zero_to_fp32.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. #!/usr/bin/env python
  2. # Copyright (c) Microsoft Corporation.
  3. # SPDX-License-Identifier: Apache-2.0
  4. # DeepSpeed Team
  5. # This script extracts fp32 consolidated weights from a zero 1, 2 and 3 DeepSpeed checkpoints. It gets
  6. # copied into the top level checkpoint dir, so the user can easily do the conversion at any point in
  7. # the future. Once extracted, the weights don't require DeepSpeed and can be used in any
  8. # application.
  9. #
  10. # example: python zero_to_fp32.py . pytorch_model.bin
  11. import argparse
  12. import torch
  13. import glob
  14. import math
  15. import os
  16. import re
  17. from collections import OrderedDict
  18. from dataclasses import dataclass
  19. # while this script doesn't use deepspeed to recover data, since the checkpoints are pickled with
  20. # DeepSpeed data structures it has to be available in the current python environment.
  21. from deepspeed.utils import logger
  22. from deepspeed.checkpoint.constants import (DS_VERSION, OPTIMIZER_STATE_DICT, SINGLE_PARTITION_OF_FP32_GROUPS,
  23. FP32_FLAT_GROUPS, ZERO_STAGE, PARTITION_COUNT, PARAM_SHAPES, BUFFER_NAMES,
  24. FROZEN_PARAM_SHAPES, FROZEN_PARAM_FRAGMENTS)
  25. @dataclass
  26. class zero_model_state:
  27. buffers: dict()
  28. param_shapes: dict()
  29. shared_params: list
  30. ds_version: int
  31. frozen_param_shapes: dict()
  32. frozen_param_fragments: dict()
  33. debug = 0
  34. # load to cpu
  35. device = torch.device('cpu')
  36. def atoi(text):
  37. return int(text) if text.isdigit() else text
  38. def natural_keys(text):
  39. '''
  40. alist.sort(key=natural_keys) sorts in human order
  41. http://nedbatchelder.com/blog/200712/human_sorting.html
  42. (See Toothy's implementation in the comments)
  43. '''
  44. return [atoi(c) for c in re.split(r'(\d+)', text)]
  45. def get_model_state_file(checkpoint_dir, zero_stage):
  46. if not os.path.isdir(checkpoint_dir):
  47. raise FileNotFoundError(f"Directory '{checkpoint_dir}' doesn't exist")
  48. # there should be only one file
  49. if zero_stage <= 2:
  50. file = os.path.join(checkpoint_dir, "mp_rank_00_model_states.pt")
  51. elif zero_stage == 3:
  52. file = os.path.join(checkpoint_dir, "zero_pp_rank_0_mp_rank_00_model_states.pt")
  53. if not os.path.exists(file):
  54. raise FileNotFoundError(f"can't find model states file at '{file}'")
  55. return file
  56. def get_checkpoint_files(checkpoint_dir, glob_pattern):
  57. # XXX: need to test that this simple glob rule works for multi-node setup too
  58. ckpt_files = sorted(glob.glob(os.path.join(checkpoint_dir, glob_pattern)), key=natural_keys)
  59. if len(ckpt_files) == 0:
  60. raise FileNotFoundError(f"can't find {glob_pattern} files in directory '{checkpoint_dir}'")
  61. return ckpt_files
  62. def get_optim_files(checkpoint_dir):
  63. return get_checkpoint_files(checkpoint_dir, "*_optim_states.pt")
  64. def get_model_state_files(checkpoint_dir):
  65. return get_checkpoint_files(checkpoint_dir, "*_model_states.pt")
  66. def parse_model_states(files):
  67. zero_model_states = []
  68. for file in files:
  69. state_dict = torch.load(file, map_location=device)
  70. if BUFFER_NAMES not in state_dict:
  71. raise ValueError(f"{file} is not a model state checkpoint")
  72. buffer_names = state_dict[BUFFER_NAMES]
  73. if debug:
  74. print("Found buffers:", buffer_names)
  75. # recover just the buffers while restoring them to fp32 if they were saved in fp16
  76. buffers = {k: v.float() for k, v in state_dict["module"].items() if k in buffer_names}
  77. param_shapes = state_dict[PARAM_SHAPES]
  78. # collect parameters that are included in param_shapes
  79. param_names = []
  80. for s in param_shapes:
  81. for name in s.keys():
  82. param_names.append(name)
  83. # update with frozen parameters
  84. frozen_param_shapes = state_dict.get(FROZEN_PARAM_SHAPES, None)
  85. if frozen_param_shapes is not None:
  86. if debug:
  87. print(f"Found frozen_param_shapes: {frozen_param_shapes}")
  88. param_names += list(frozen_param_shapes.keys())
  89. # handle shared params
  90. shared_params = [[k, v] for k, v in state_dict["shared_params"].items()]
  91. ds_version = state_dict.get(DS_VERSION, None)
  92. frozen_param_fragments = state_dict.get(FROZEN_PARAM_FRAGMENTS, None)
  93. z_model_state = zero_model_state(buffers=buffers,
  94. param_shapes=param_shapes,
  95. shared_params=shared_params,
  96. ds_version=ds_version,
  97. frozen_param_shapes=frozen_param_shapes,
  98. frozen_param_fragments=frozen_param_fragments)
  99. zero_model_states.append(z_model_state)
  100. return zero_model_states
  101. def parse_optim_states(files, ds_checkpoint_dir):
  102. total_files = len(files)
  103. state_dicts = []
  104. for f in files:
  105. state_dict = torch.load(f, map_location=device)
  106. # immediately discard the potentially huge 2 optimizer states as we only care for fp32 master weights
  107. # and also handle the case where it was already removed by another helper script
  108. state_dict["optimizer_state_dict"].pop("optimizer_state_dict", None)
  109. state_dicts.append(state_dict)
  110. if not ZERO_STAGE in state_dicts[0][OPTIMIZER_STATE_DICT]:
  111. raise ValueError(f"{files[0]} is not a zero checkpoint")
  112. zero_stage = state_dicts[0][OPTIMIZER_STATE_DICT][ZERO_STAGE]
  113. world_size = state_dicts[0][OPTIMIZER_STATE_DICT][PARTITION_COUNT]
  114. # For ZeRO-2 each param group can have different partition_count as data parallelism for expert
  115. # parameters can be different from data parallelism for non-expert parameters. So we can just
  116. # use the max of the partition_count to get the dp world_size.
  117. if type(world_size) is list:
  118. world_size = max(world_size)
  119. if world_size != total_files:
  120. raise ValueError(
  121. f"Expected {world_size} of '*_optim_states.pt' under '{ds_checkpoint_dir}' but found {total_files} files. "
  122. "Possibly due to an overwrite of an old checkpoint, or a checkpoint didn't get saved by one or more processes."
  123. )
  124. # the groups are named differently in each stage
  125. if zero_stage <= 2:
  126. fp32_groups_key = SINGLE_PARTITION_OF_FP32_GROUPS
  127. elif zero_stage == 3:
  128. fp32_groups_key = FP32_FLAT_GROUPS
  129. else:
  130. raise ValueError(f"unknown zero stage {zero_stage}")
  131. if zero_stage <= 2:
  132. fp32_flat_groups = [state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key] for i in range(len(state_dicts))]
  133. elif zero_stage == 3:
  134. # if there is more than one param group, there will be multiple flattened tensors - one
  135. # flattened tensor per group - for simplicity merge them into a single tensor
  136. #
  137. # XXX: could make the script more memory efficient for when there are multiple groups - it
  138. # will require matching the sub-lists of param_shapes for each param group flattened tensor
  139. fp32_flat_groups = [
  140. torch.cat(state_dicts[i][OPTIMIZER_STATE_DICT][fp32_groups_key], 0) for i in range(len(state_dicts))
  141. ]
  142. return zero_stage, world_size, fp32_flat_groups
  143. def _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir):
  144. """
  145. Returns fp32 state_dict reconstructed from ds checkpoint
  146. Args:
  147. - ``ds_checkpoint_dir``: path to the deepspeed checkpoint folder (where the optimizer files are)
  148. """
  149. print(f"Processing zero checkpoint '{ds_checkpoint_dir}'")
  150. optim_files = get_optim_files(ds_checkpoint_dir)
  151. zero_stage, world_size, fp32_flat_groups = parse_optim_states(optim_files, ds_checkpoint_dir)
  152. print(f"Detected checkpoint of type zero stage {zero_stage}, world_size: {world_size}")
  153. model_files = get_model_state_files(ds_checkpoint_dir)
  154. zero_model_states = parse_model_states(model_files)
  155. print(f'Parsing checkpoint created by deepspeed=={zero_model_states[0].ds_version}')
  156. if zero_stage <= 2:
  157. return _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states)
  158. elif zero_stage == 3:
  159. return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states)
  160. def _zero2_merge_frozen_params(state_dict, zero_model_states):
  161. if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
  162. return
  163. frozen_param_shapes = zero_model_states[0].frozen_param_shapes
  164. frozen_param_fragments = zero_model_states[0].frozen_param_fragments
  165. if debug:
  166. num_elem = sum(s.numel() for s in frozen_param_shapes.values())
  167. print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
  168. wanted_params = len(frozen_param_shapes)
  169. wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
  170. avail_numel = sum([p.numel() for p in frozen_param_fragments.values()])
  171. print(f'Frozen params: Have {avail_numel} numels to process.')
  172. print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
  173. total_params = 0
  174. total_numel = 0
  175. for name, shape in frozen_param_shapes.items():
  176. total_params += 1
  177. unpartitioned_numel = shape.numel()
  178. total_numel += unpartitioned_numel
  179. state_dict[name] = frozen_param_fragments[name]
  180. if debug:
  181. print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
  182. print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
  183. def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
  184. param_shapes = zero_model_states[0].param_shapes
  185. # Reconstruction protocol:
  186. #
  187. # XXX: document this
  188. if debug:
  189. for i in range(world_size):
  190. for j in range(len(fp32_flat_groups[0])):
  191. print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
  192. # XXX: memory usage doubles here (zero2)
  193. num_param_groups = len(fp32_flat_groups[0])
  194. merged_single_partition_of_fp32_groups = []
  195. for i in range(num_param_groups):
  196. merged_partitions = [sd[i] for sd in fp32_flat_groups]
  197. full_single_fp32_vector = torch.cat(merged_partitions, 0)
  198. merged_single_partition_of_fp32_groups.append(full_single_fp32_vector)
  199. avail_numel = sum(
  200. [full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
  201. if debug:
  202. wanted_params = sum([len(shapes) for shapes in param_shapes])
  203. wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes])
  204. # not asserting if there is a mismatch due to possible padding
  205. print(f"Have {avail_numel} numels to process.")
  206. print(f"Need {wanted_numel} numels in {wanted_params} params.")
  207. # params
  208. # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
  209. # out-of-core computing solution
  210. total_numel = 0
  211. total_params = 0
  212. for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups):
  213. offset = 0
  214. avail_numel = full_single_fp32_vector.numel()
  215. for name, shape in shapes.items():
  216. unpartitioned_numel = shape.numel()
  217. total_numel += unpartitioned_numel
  218. total_params += 1
  219. if debug:
  220. print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
  221. state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape)
  222. offset += unpartitioned_numel
  223. # Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and
  224. # avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex
  225. # paddings performed in the code it's almost impossible to predict the exact numbers w/o the
  226. # live optimizer object, so we are checking that the numbers are within the right range
  227. align_to = 2 * world_size
  228. def zero2_align(x):
  229. return align_to * math.ceil(x / align_to)
  230. if debug:
  231. print(f"original offset={offset}, avail_numel={avail_numel}")
  232. offset = zero2_align(offset)
  233. avail_numel = zero2_align(avail_numel)
  234. if debug:
  235. print(f"aligned offset={offset}, avail_numel={avail_numel}")
  236. # Sanity check
  237. if offset != avail_numel:
  238. raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
  239. print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
  240. def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states):
  241. state_dict = OrderedDict()
  242. # buffers
  243. buffers = zero_model_states[0].buffers
  244. state_dict.update(buffers)
  245. if debug:
  246. print(f"added {len(buffers)} buffers")
  247. _zero2_merge_frozen_params(state_dict, zero_model_states)
  248. _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
  249. # recover shared parameters
  250. for pair in zero_model_states[0].shared_params:
  251. if pair[1] in state_dict:
  252. state_dict[pair[0]] = state_dict[pair[1]]
  253. return state_dict
  254. def zero3_partitioned_param_info(unpartitioned_numel, world_size):
  255. remainder = unpartitioned_numel % world_size
  256. padding_numel = (world_size - remainder) if remainder else 0
  257. partitioned_numel = math.ceil(unpartitioned_numel / world_size)
  258. return partitioned_numel, padding_numel
  259. def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states):
  260. if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
  261. return
  262. if debug:
  263. for i in range(world_size):
  264. num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values())
  265. print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
  266. frozen_param_shapes = zero_model_states[0].frozen_param_shapes
  267. wanted_params = len(frozen_param_shapes)
  268. wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
  269. avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size
  270. print(f'Frozen params: Have {avail_numel} numels to process.')
  271. print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
  272. total_params = 0
  273. total_numel = 0
  274. for name, shape in zero_model_states[0].frozen_param_shapes.items():
  275. total_params += 1
  276. unpartitioned_numel = shape.numel()
  277. total_numel += unpartitioned_numel
  278. param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states)
  279. state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
  280. partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
  281. if debug:
  282. print(
  283. f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
  284. )
  285. print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
  286. def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
  287. param_shapes = zero_model_states[0].param_shapes
  288. avail_numel = fp32_flat_groups[0].numel() * world_size
  289. # Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each
  290. # param, re-consolidating each param, while dealing with padding if any
  291. # merge list of dicts, preserving order
  292. param_shapes = {k: v for d in param_shapes for k, v in d.items()}
  293. if debug:
  294. for i in range(world_size):
  295. print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
  296. wanted_params = len(param_shapes)
  297. wanted_numel = sum(shape.numel() for shape in param_shapes.values())
  298. # not asserting if there is a mismatch due to possible padding
  299. avail_numel = fp32_flat_groups[0].numel() * world_size
  300. print(f"Trainable params: Have {avail_numel} numels to process.")
  301. print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
  302. # params
  303. # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
  304. # out-of-core computing solution
  305. offset = 0
  306. total_numel = 0
  307. total_params = 0
  308. for name, shape in param_shapes.items():
  309. unpartitioned_numel = shape.numel()
  310. total_numel += unpartitioned_numel
  311. total_params += 1
  312. partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
  313. if debug:
  314. print(
  315. f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
  316. )
  317. # XXX: memory usage doubles here
  318. state_dict[name] = torch.cat(
  319. tuple(fp32_flat_groups[i].narrow(0, offset, partitioned_numel) for i in range(world_size)),
  320. 0).narrow(0, 0, unpartitioned_numel).view(shape)
  321. offset += partitioned_numel
  322. offset *= world_size
  323. # Sanity check
  324. if offset != avail_numel:
  325. raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
  326. print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
  327. def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states):
  328. state_dict = OrderedDict()
  329. # buffers
  330. buffers = zero_model_states[0].buffers
  331. state_dict.update(buffers)
  332. if debug:
  333. print(f"added {len(buffers)} buffers")
  334. _zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
  335. _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
  336. # recover shared parameters
  337. for pair in zero_model_states[0].shared_params:
  338. if pair[1] in state_dict:
  339. state_dict[pair[0]] = state_dict[pair[1]]
  340. return state_dict
  341. def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag=None):
  342. """
  343. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with
  344. ``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example
  345. via a model hub.
  346. Args:
  347. - ``checkpoint_dir``: path to the desired checkpoint folder
  348. - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in 'latest' file. e.g., ``global_step14``
  349. Returns:
  350. - pytorch ``state_dict``
  351. Note: this approach may not work if your application doesn't have sufficient free CPU memory and
  352. you may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with
  353. the checkpoint.
  354. A typical usage might be ::
  355. from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
  356. # do the training and checkpoint saving
  357. state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu
  358. model = model.cpu() # move to cpu
  359. model.load_state_dict(state_dict)
  360. # submit to model hub or save the model to share with others
  361. In this example the ``model`` will no longer be usable in the deepspeed context of the same
  362. application. i.e. you will need to re-initialize the deepspeed engine, since
  363. ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
  364. If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
  365. """
  366. if tag is None:
  367. latest_path = os.path.join(checkpoint_dir, 'latest')
  368. if os.path.isfile(latest_path):
  369. with open(latest_path, 'r') as fd:
  370. tag = fd.read().strip()
  371. else:
  372. raise ValueError(f"Unable to find 'latest' file at {latest_path}")
  373. ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
  374. if not os.path.isdir(ds_checkpoint_dir):
  375. raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
  376. return _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir)
  377. def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir, output_file, tag=None):
  378. """
  379. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be
  380. loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
  381. Args:
  382. - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
  383. - ``output_file``: path to the pytorch fp32 state_dict output file (e.g. path/pytorch_model.bin)
  384. - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
  385. """
  386. state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
  387. print(f"Saving fp32 state dict to {output_file}")
  388. torch.save(state_dict, output_file)
  389. def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None):
  390. """
  391. 1. Put the provided model to cpu
  392. 2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict``
  393. 3. Load it into the provided model
  394. Args:
  395. - ``model``: the model object to update
  396. - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
  397. - ``tag``: checkpoint tag used as a unique identifier for checkpoint. If not provided will attempt to load tag in the file named ``latest`` in the checkpoint folder, e.g., ``global_step14``
  398. Returns:
  399. - ``model`: modified model
  400. Make sure you have plenty of CPU memory available before you call this function. If you don't
  401. have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it
  402. conveniently placed for you in the checkpoint folder.
  403. A typical usage might be ::
  404. from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
  405. model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir)
  406. # submit to model hub or save the model to share with others
  407. Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context
  408. of the same application. i.e. you will need to re-initialize the deepspeed engine, since
  409. ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
  410. """
  411. logger.info(f"Extracting fp32 weights")
  412. state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
  413. logger.info(f"Overwriting model with fp32 weights")
  414. model = model.cpu()
  415. model.load_state_dict(state_dict, strict=False)
  416. return model
  417. if __name__ == "__main__":
  418. parser = argparse.ArgumentParser()
  419. parser.add_argument("checkpoint_dir",
  420. type=str,
  421. help="path to the desired checkpoint folder, e.g., path/checkpoint-12")
  422. parser.add_argument(
  423. "output_file",
  424. type=str,
  425. help="path to the pytorch fp32 state_dict output file (e.g. path/checkpoint-12/pytorch_model.bin)")
  426. parser.add_argument("-t",
  427. "--tag",
  428. type=str,
  429. default=None,
  430. help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1")
  431. parser.add_argument("-d", "--debug", action='store_true', help="enable debug")
  432. args = parser.parse_args()
  433. debug = args.debug
  434. convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir, args.output_file, tag=args.tag)