zero_to_fp32.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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, exclude_frozen_parameters):
  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. exclude_frozen_parameters)
  159. elif zero_stage == 3:
  160. return _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
  161. exclude_frozen_parameters)
  162. def _zero2_merge_frozen_params(state_dict, zero_model_states):
  163. if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
  164. return
  165. frozen_param_shapes = zero_model_states[0].frozen_param_shapes
  166. frozen_param_fragments = zero_model_states[0].frozen_param_fragments
  167. if debug:
  168. num_elem = sum(s.numel() for s in frozen_param_shapes.values())
  169. print(f'rank 0: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
  170. wanted_params = len(frozen_param_shapes)
  171. wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
  172. avail_numel = sum([p.numel() for p in frozen_param_fragments.values()])
  173. print(f'Frozen params: Have {avail_numel} numels to process.')
  174. print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
  175. total_params = 0
  176. total_numel = 0
  177. for name, shape in frozen_param_shapes.items():
  178. total_params += 1
  179. unpartitioned_numel = shape.numel()
  180. total_numel += unpartitioned_numel
  181. state_dict[name] = frozen_param_fragments[name]
  182. if debug:
  183. print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
  184. print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
  185. def _has_callable(obj, fn):
  186. attr = getattr(obj, fn, None)
  187. return callable(attr)
  188. def _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
  189. param_shapes = zero_model_states[0].param_shapes
  190. # Reconstruction protocol:
  191. #
  192. # XXX: document this
  193. if debug:
  194. for i in range(world_size):
  195. for j in range(len(fp32_flat_groups[0])):
  196. print(f"{FP32_FLAT_GROUPS}[{i}][{j}].shape={fp32_flat_groups[i][j].shape}")
  197. # XXX: memory usage doubles here (zero2)
  198. num_param_groups = len(fp32_flat_groups[0])
  199. merged_single_partition_of_fp32_groups = []
  200. for i in range(num_param_groups):
  201. merged_partitions = [sd[i] for sd in fp32_flat_groups]
  202. full_single_fp32_vector = torch.cat(merged_partitions, 0)
  203. merged_single_partition_of_fp32_groups.append(full_single_fp32_vector)
  204. avail_numel = sum(
  205. [full_single_fp32_vector.numel() for full_single_fp32_vector in merged_single_partition_of_fp32_groups])
  206. if debug:
  207. wanted_params = sum([len(shapes) for shapes in param_shapes])
  208. wanted_numel = sum([sum(shape.numel() for shape in shapes.values()) for shapes in param_shapes])
  209. # not asserting if there is a mismatch due to possible padding
  210. print(f"Have {avail_numel} numels to process.")
  211. print(f"Need {wanted_numel} numels in {wanted_params} params.")
  212. # params
  213. # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
  214. # out-of-core computing solution
  215. total_numel = 0
  216. total_params = 0
  217. for shapes, full_single_fp32_vector in zip(param_shapes, merged_single_partition_of_fp32_groups):
  218. offset = 0
  219. avail_numel = full_single_fp32_vector.numel()
  220. for name, shape in shapes.items():
  221. unpartitioned_numel = shape.numel() if _has_callable(shape, 'numel') else math.prod(shape)
  222. total_numel += unpartitioned_numel
  223. total_params += 1
  224. if debug:
  225. print(f"{name} full shape: {shape} unpartitioned numel {unpartitioned_numel} ")
  226. state_dict[name] = full_single_fp32_vector.narrow(0, offset, unpartitioned_numel).view(shape)
  227. offset += unpartitioned_numel
  228. # Z2 started to align to 2*world_size to improve nccl performance. Therefore both offset and
  229. # avail_numel can differ by anywhere between 0..2*world_size. Due to two unrelated complex
  230. # paddings performed in the code it's almost impossible to predict the exact numbers w/o the
  231. # live optimizer object, so we are checking that the numbers are within the right range
  232. align_to = 2 * world_size
  233. def zero2_align(x):
  234. return align_to * math.ceil(x / align_to)
  235. if debug:
  236. print(f"original offset={offset}, avail_numel={avail_numel}")
  237. offset = zero2_align(offset)
  238. avail_numel = zero2_align(avail_numel)
  239. if debug:
  240. print(f"aligned offset={offset}, avail_numel={avail_numel}")
  241. # Sanity check
  242. if offset != avail_numel:
  243. raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
  244. print(f"Reconstructed fp32 state dict with {total_params} params {total_numel} elements")
  245. def _get_fp32_state_dict_from_zero2_checkpoint(world_size, fp32_flat_groups, zero_model_states,
  246. exclude_frozen_parameters):
  247. state_dict = OrderedDict()
  248. # buffers
  249. buffers = zero_model_states[0].buffers
  250. state_dict.update(buffers)
  251. if debug:
  252. print(f"added {len(buffers)} buffers")
  253. if not exclude_frozen_parameters:
  254. _zero2_merge_frozen_params(state_dict, zero_model_states)
  255. _zero2_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
  256. # recover shared parameters
  257. for pair in zero_model_states[0].shared_params:
  258. if pair[1] in state_dict:
  259. state_dict[pair[0]] = state_dict[pair[1]]
  260. return state_dict
  261. def zero3_partitioned_param_info(unpartitioned_numel, world_size):
  262. remainder = unpartitioned_numel % world_size
  263. padding_numel = (world_size - remainder) if remainder else 0
  264. partitioned_numel = math.ceil(unpartitioned_numel / world_size)
  265. return partitioned_numel, padding_numel
  266. def _zero3_merge_frozen_params(state_dict, world_size, zero_model_states):
  267. if zero_model_states[0].frozen_param_shapes is None or len(zero_model_states[0].frozen_param_shapes) == 0:
  268. return
  269. if debug:
  270. for i in range(world_size):
  271. num_elem = sum(s.numel() for s in zero_model_states[i].frozen_param_fragments.values())
  272. print(f'rank {i}: {FROZEN_PARAM_SHAPES}.numel = {num_elem}')
  273. frozen_param_shapes = zero_model_states[0].frozen_param_shapes
  274. wanted_params = len(frozen_param_shapes)
  275. wanted_numel = sum(s.numel() for s in frozen_param_shapes.values())
  276. avail_numel = sum([p.numel() for p in zero_model_states[0].frozen_param_fragments.values()]) * world_size
  277. print(f'Frozen params: Have {avail_numel} numels to process.')
  278. print(f'Frozen params: Need {wanted_numel} numels in {wanted_params} params')
  279. total_params = 0
  280. total_numel = 0
  281. for name, shape in zero_model_states[0].frozen_param_shapes.items():
  282. total_params += 1
  283. unpartitioned_numel = shape.numel()
  284. total_numel += unpartitioned_numel
  285. param_frags = tuple(model_state.frozen_param_fragments[name] for model_state in zero_model_states)
  286. state_dict[name] = torch.cat(param_frags, 0).narrow(0, 0, unpartitioned_numel).view(shape)
  287. partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
  288. if debug:
  289. print(
  290. f"Frozen params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
  291. )
  292. print(f"Reconstructed Frozen fp32 state dict with {total_params} params {total_numel} elements")
  293. def _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states):
  294. param_shapes = zero_model_states[0].param_shapes
  295. avail_numel = fp32_flat_groups[0].numel() * world_size
  296. # Reconstruction protocol: For zero3 we need to zip the partitions together at boundary of each
  297. # param, re-consolidating each param, while dealing with padding if any
  298. # merge list of dicts, preserving order
  299. param_shapes = {k: v for d in param_shapes for k, v in d.items()}
  300. if debug:
  301. for i in range(world_size):
  302. print(f"{FP32_FLAT_GROUPS}[{i}].shape={fp32_flat_groups[i].shape}")
  303. wanted_params = len(param_shapes)
  304. wanted_numel = sum(shape.numel() for shape in param_shapes.values())
  305. # not asserting if there is a mismatch due to possible padding
  306. avail_numel = fp32_flat_groups[0].numel() * world_size
  307. print(f"Trainable params: Have {avail_numel} numels to process.")
  308. print(f"Trainable params: Need {wanted_numel} numels in {wanted_params} params.")
  309. # params
  310. # XXX: for huge models that can't fit into the host's RAM we will have to recode this to support
  311. # out-of-core computing solution
  312. offset = 0
  313. total_numel = 0
  314. total_params = 0
  315. for name, shape in param_shapes.items():
  316. unpartitioned_numel = shape.numel()
  317. total_numel += unpartitioned_numel
  318. total_params += 1
  319. partitioned_numel, partitioned_padding_numel = zero3_partitioned_param_info(unpartitioned_numel, world_size)
  320. if debug:
  321. print(
  322. f"Trainable params: {total_params} {name} full shape: {shape} partition0 numel={partitioned_numel} partitioned_padding_numel={partitioned_padding_numel}"
  323. )
  324. # XXX: memory usage doubles here
  325. state_dict[name] = torch.cat(
  326. tuple(fp32_flat_groups[i].narrow(0, offset, partitioned_numel) for i in range(world_size)),
  327. 0).narrow(0, 0, unpartitioned_numel).view(shape)
  328. offset += partitioned_numel
  329. offset *= world_size
  330. # Sanity check
  331. if offset != avail_numel:
  332. raise ValueError(f"consumed {offset} numels out of {avail_numel} - something is wrong")
  333. print(f"Reconstructed Trainable fp32 state dict with {total_params} params {total_numel} elements")
  334. def _get_fp32_state_dict_from_zero3_checkpoint(world_size, fp32_flat_groups, zero_model_states,
  335. exclude_frozen_parameters):
  336. state_dict = OrderedDict()
  337. # buffers
  338. buffers = zero_model_states[0].buffers
  339. state_dict.update(buffers)
  340. if debug:
  341. print(f"added {len(buffers)} buffers")
  342. if not exclude_frozen_parameters:
  343. _zero3_merge_frozen_params(state_dict, world_size, zero_model_states)
  344. _zero3_merge_trainable_params(state_dict, world_size, fp32_flat_groups, zero_model_states)
  345. # recover shared parameters
  346. for pair in zero_model_states[0].shared_params:
  347. if pair[1] in state_dict:
  348. state_dict[pair[0]] = state_dict[pair[1]]
  349. return state_dict
  350. def get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag=None, exclude_frozen_parameters=False):
  351. """
  352. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated state_dict that can be loaded with
  353. ``load_state_dict()`` and used for training without DeepSpeed or shared with others, for example
  354. via a model hub.
  355. Args:
  356. - ``checkpoint_dir``: path to the desired checkpoint folder
  357. - ``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``
  358. - ``exclude_frozen_parameters``: exclude frozen parameters
  359. Returns:
  360. - pytorch ``state_dict``
  361. Note: this approach may not work if your application doesn't have sufficient free CPU memory and
  362. you may need to use the offline approach using the ``zero_to_fp32.py`` script that is saved with
  363. the checkpoint.
  364. A typical usage might be ::
  365. from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
  366. # do the training and checkpoint saving
  367. state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) # already on cpu
  368. model = model.cpu() # move to cpu
  369. model.load_state_dict(state_dict)
  370. # submit to model hub or save the model to share with others
  371. In this example the ``model`` will no longer be usable in the deepspeed context of the same
  372. application. i.e. you will need to re-initialize the deepspeed engine, since
  373. ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
  374. If you want it all done for you, use ``load_state_dict_from_zero_checkpoint`` instead.
  375. """
  376. if tag is None:
  377. latest_path = os.path.join(checkpoint_dir, 'latest')
  378. if os.path.isfile(latest_path):
  379. with open(latest_path, 'r') as fd:
  380. tag = fd.read().strip()
  381. else:
  382. raise ValueError(f"Unable to find 'latest' file at {latest_path}")
  383. ds_checkpoint_dir = os.path.join(checkpoint_dir, tag)
  384. if not os.path.isdir(ds_checkpoint_dir):
  385. raise FileNotFoundError(f"Directory '{ds_checkpoint_dir}' doesn't exist")
  386. return _get_fp32_state_dict_from_zero_checkpoint(ds_checkpoint_dir, exclude_frozen_parameters)
  387. def convert_zero_checkpoint_to_fp32_state_dict(checkpoint_dir, output_file, tag=None, exclude_frozen_parameters=False):
  388. """
  389. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict`` file that can be
  390. loaded with ``torch.load(file)`` + ``load_state_dict()`` and used for training without DeepSpeed.
  391. Args:
  392. - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
  393. - ``output_file``: path to the pytorch fp32 state_dict output file (e.g. path/pytorch_model.bin)
  394. - ``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``
  395. - ``exclude_frozen_parameters``: exclude frozen parameters
  396. """
  397. state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag, exclude_frozen_parameters)
  398. print(f"Saving fp32 state dict to {output_file}")
  399. torch.save(state_dict, output_file)
  400. def load_state_dict_from_zero_checkpoint(model, checkpoint_dir, tag=None):
  401. """
  402. 1. Put the provided model to cpu
  403. 2. Convert ZeRO 2 or 3 checkpoint into a single fp32 consolidated ``state_dict``
  404. 3. Load it into the provided model
  405. Args:
  406. - ``model``: the model object to update
  407. - ``checkpoint_dir``: path to the desired checkpoint folder. (one that contains the tag-folder, like ``global_step14``)
  408. - ``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``
  409. Returns:
  410. - ``model`: modified model
  411. Make sure you have plenty of CPU memory available before you call this function. If you don't
  412. have enough use the ``zero_to_fp32.py`` utility to do the conversion. You will find it
  413. conveniently placed for you in the checkpoint folder.
  414. A typical usage might be ::
  415. from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint
  416. model = load_state_dict_from_zero_checkpoint(trainer.model, checkpoint_dir)
  417. # submit to model hub or save the model to share with others
  418. Note, that once this was run, the ``model`` will no longer be usable in the deepspeed context
  419. of the same application. i.e. you will need to re-initialize the deepspeed engine, since
  420. ``model.load_state_dict(state_dict)`` will remove all the deepspeed magic from it.
  421. """
  422. logger.info(f"Extracting fp32 weights")
  423. state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir, tag)
  424. logger.info(f"Overwriting model with fp32 weights")
  425. model = model.cpu()
  426. model.load_state_dict(state_dict, strict=False)
  427. return model
  428. if __name__ == "__main__":
  429. parser = argparse.ArgumentParser()
  430. parser.add_argument("checkpoint_dir",
  431. type=str,
  432. help="path to the desired checkpoint folder, e.g., path/checkpoint-12")
  433. parser.add_argument(
  434. "output_file",
  435. type=str,
  436. help="path to the pytorch fp32 state_dict output file (e.g. path/checkpoint-12/pytorch_model.bin)")
  437. parser.add_argument("-t",
  438. "--tag",
  439. type=str,
  440. default=None,
  441. help="checkpoint tag used as a unique identifier for checkpoint. e.g., global_step1")
  442. parser.add_argument("--exclude_frozen_parameters", action='store_true', help="exclude frozen parameters")
  443. parser.add_argument("-d", "--debug", action='store_true', help="enable debug")
  444. args = parser.parse_args()
  445. debug = args.debug
  446. convert_zero_checkpoint_to_fp32_state_dict(args.checkpoint_dir,
  447. args.output_file,
  448. tag=args.tag,
  449. exclude_frozen_parameters=args.exclude_frozen_parameters)