state_dict.py 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632
  1. # mypy: allow-untyped-defs
  2. import contextlib
  3. import functools
  4. import gc
  5. import warnings
  6. from collections.abc import Callable, Generator, Iterable
  7. from dataclasses import asdict, dataclass, field
  8. from itertools import chain
  9. from typing import Any, cast, no_type_check, Union
  10. import torch
  11. import torch.distributed as dist
  12. import torch.nn as nn
  13. from torch.distributed._shard.sharded_tensor import ShardedTensor
  14. from torch.distributed._state_dict_utils import (
  15. _broadcast_state_dict,
  16. _distribute_state_dict,
  17. _flatten_state_dict,
  18. _gather_state_dict,
  19. _offload_state_dict_to_cpu,
  20. _unflatten_state_dict,
  21. )
  22. from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import (
  23. _CHECKPOINT_PREFIX,
  24. )
  25. from torch.distributed.fsdp import (
  26. FullOptimStateDictConfig,
  27. FullStateDictConfig,
  28. FullyShardedDataParallel as FSDP,
  29. OptimStateDictConfig,
  30. ShardedOptimStateDictConfig,
  31. ShardedStateDictConfig,
  32. StateDictConfig,
  33. StateDictType,
  34. )
  35. from torch.distributed.fsdp._common_utils import (
  36. _get_module_fsdp_state_if_fully_sharded_module,
  37. FSDP_WRAPPED_MODULE,
  38. )
  39. from torch.distributed.tensor import DTensor
  40. from torch.nn.modules.module import _IncompatibleKeys
  41. from torch.nn.parallel import DistributedDataParallel as DDP
  42. from torch.utils._pytree import tree_map_only
  43. __all__ = [
  44. "FQNS_T",
  45. "PrimitiveType",
  46. "ValueType",
  47. "DictValueType",
  48. "ListDictValueType",
  49. "OptimizerStateType",
  50. "StateDictOptions",
  51. "get_model_state_dict",
  52. "get_optimizer_state_dict",
  53. "get_state_dict",
  54. "set_model_state_dict",
  55. "set_optimizer_state_dict",
  56. "set_state_dict",
  57. ]
  58. _FLAT_PARAM = "_flat_param"
  59. _PG = "param_groups"
  60. _PARAMS = "params"
  61. _STATE = "state"
  62. FQNS_T = set[str]
  63. PrimitiveType = Union[DTensor, ShardedTensor, torch.Tensor, int, float, str]
  64. ValueType = Union[
  65. PrimitiveType, list[PrimitiveType], tuple[PrimitiveType], dict[str, "ValueType"]
  66. ]
  67. DictValueType = dict[str, ValueType]
  68. ListDictValueType = list[DictValueType]
  69. OptimizerStateType = dict[str, DictValueType | ListDictValueType]
  70. _patched_state_dict: set[Callable] = set()
  71. @contextlib.contextmanager
  72. def _gc_context():
  73. is_enabled = gc.isenabled()
  74. gc.disable()
  75. try:
  76. yield
  77. finally:
  78. if is_enabled:
  79. gc.enable()
  80. @dataclass
  81. class StateDictOptions:
  82. """
  83. This dataclass specifies how get_state_dict/set_state_dict will work.
  84. - ``full_state_dict``: if this is set to True, all the tensors in the
  85. returned state_dict will be gathered. No ShardedTensor and DTensor
  86. will be in the returned state_dict.
  87. - ``cpu_offload``: offload all the tensors to cpu. To prevent CPU OOM, if
  88. ``full_state_dict`` is also true, then only the rank0 will get the
  89. state_dict and all other ranks will get empty state_dict.
  90. - ``ignore_frozen_params``: if the value is True, the returned state_dict
  91. won't contain any frozen parameters -- the ``requires_grad`` is False.
  92. The default value is False.
  93. - ``keep_submodule_prefixes`` (deprecated): when ``submodules`` is not None, this option
  94. indicates whether to keep the submodule prefixes from the state_dict keys.
  95. or example, if the submodule is ``module.pretrain`` and the full FQN of
  96. the parameter is ``pretrain.layer1.weight`` of the param. When this option
  97. is True, the parameter's key in the returned state_dict will be
  98. ``pretrain.layer1.weight``. If the options is False, the key will be
  99. ``layer1.weight``.
  100. Note that if ``keep_submodule_prefixes`` is False, there may be conflicted
  101. FQNs, hence there should be only one submodule in ``submodules``.
  102. - ``strict``: the ``strict`` option when ``set_state_dict`` calls
  103. model.load_state_dict().
  104. - ``broadcast_from_rank0``: when the option is True, rank0 should receive a
  105. full state_dict and will broadcast the tensors in the state_dict/
  106. optim_state_dict one by one to other ranks. Other ranks will receive
  107. the tensors and shard according to the local shards in the model and
  108. optimizer. ``full_state_dict`` must be set to True when using this option.
  109. This option currently only supports DTensor, not the legacy ShardedTensor.
  110. """
  111. full_state_dict: bool = False
  112. cpu_offload: bool = False
  113. ignore_frozen_params: bool = False
  114. keep_submodule_prefixes: bool = True
  115. strict: bool = True
  116. broadcast_from_rank0: bool = False
  117. flatten_optimizer_state_dict: bool = False
  118. dsd_fqn_modifiers: str = "_fqn_modifiers"
  119. @dataclass
  120. class _StateDictInfo(StateDictOptions):
  121. fqn_param_mapping: dict[
  122. str | torch.Tensor,
  123. FQNS_T | torch.Tensor,
  124. ] = field(default_factory=dict)
  125. shared_params_mapping: dict[
  126. str | torch.Tensor,
  127. FQNS_T | torch.Tensor,
  128. ] = field(default_factory=dict)
  129. submodule_prefixes: set[str] = field(default_factory=set)
  130. handle_model: bool = True
  131. handle_optim: bool = True
  132. fsdp_context: Callable = contextlib.nullcontext
  133. fsdp_modules: list[nn.Module] = field(default_factory=list)
  134. def _get_fqns(
  135. model: nn.Module,
  136. name: str,
  137. dsd_fqn_modifiers: str = "_fqn_modifiers",
  138. skip_ddp_prefix: bool = True,
  139. skip_compiler_prefix: bool = True,
  140. ) -> FQNS_T:
  141. """
  142. This API is used to convert the name of a parameter to the FQNs. For FSDP
  143. without `use_orig_params`, the name of FlatParameter can be mapped to
  144. multiple original parameters. As a result, the return type of this function
  145. is `set[str]`.
  146. Args:
  147. module (nn.Module): the root model.
  148. name (str): the name
  149. skip_ddp_prefix (bool): whether to skip DDP's `module` prefix
  150. Returns:
  151. The canonical FQNs based on the model traversal.
  152. """
  153. # Remove the checkpoint prefix, if it exists.
  154. name = name.replace(_CHECKPOINT_PREFIX, "")
  155. if "." not in name:
  156. return {name}
  157. obj_names = name.split(".")
  158. fqn_obj_names = []
  159. curr_obj = model
  160. for i, curr_obj_name in enumerate(obj_names):
  161. if isinstance(curr_obj, DDP):
  162. if curr_obj_name != "module":
  163. raise AssertionError(f"Expected 'module', got '{curr_obj_name}'")
  164. curr_obj = curr_obj.module
  165. if not skip_ddp_prefix:
  166. fqn_obj_names.append(curr_obj_name)
  167. elif isinstance(curr_obj, FSDP):
  168. if i < len(obj_names) - 1 and obj_names[i + 1] == _FLAT_PARAM:
  169. prefix = ".".join(fqn_obj_names)
  170. flat_param = getattr(curr_obj, _FLAT_PARAM)
  171. if prefix:
  172. prefix = f"{prefix}."
  173. return {f"{prefix}{fqn}" for fqn in flat_param._fqns}
  174. curr_obj = getattr(curr_obj, FSDP_WRAPPED_MODULE)
  175. if curr_obj_name != FSDP_WRAPPED_MODULE:
  176. # pyrefly: ignore [bad-argument-type]
  177. fqn_obj_names.append(curr_obj_name)
  178. curr_obj = getattr(curr_obj, curr_obj_name)
  179. elif isinstance(curr_obj, torch._dynamo.eval_frame.OptimizedModule):
  180. if curr_obj_name != "_orig_mod":
  181. raise AssertionError(f"Expected '_orig_mod', got '{curr_obj_name}'")
  182. curr_obj = curr_obj._orig_mod
  183. if not skip_compiler_prefix:
  184. fqn_obj_names.append(curr_obj_name)
  185. else:
  186. # In some modules, _fqn_modifiers would not shown in the state_dict keys,
  187. # skip them in the fqn to ensure load stat dict successfully for them.
  188. if hasattr(curr_obj, dsd_fqn_modifiers):
  189. if removed_fqn := getattr(curr_obj, dsd_fqn_modifiers)().get(
  190. curr_obj_name
  191. ):
  192. if hasattr(curr_obj, removed_fqn):
  193. curr_obj = getattr(curr_obj, removed_fqn)
  194. # pyrefly: ignore [bad-argument-type]
  195. fqn_obj_names.append(curr_obj_name)
  196. if curr_obj_name == nn.modules.module._EXTRA_STATE_KEY_SUFFIX:
  197. if i != len(obj_names) - 1:
  198. raise RuntimeError("Expect `_extra_state` to be the last obj name")
  199. else:
  200. curr_obj = getattr(curr_obj, curr_obj_name)
  201. return {".".join(fqn_obj_names).replace(_CHECKPOINT_PREFIX, "")}
  202. class _EXTRA_STATE:
  203. pass
  204. def _iterate_valid_model_state(model, dsd_fqn_modifiers="_fqn_modifiers"):
  205. visited_modules: set[nn.Module] = set()
  206. def recurse(module: nn.Module, curr_fqn: str) -> Generator:
  207. visited_modules.add(module)
  208. curr_fqn = f"{curr_fqn}." if curr_fqn else ""
  209. for name, submodule in module.named_children():
  210. if submodule in visited_modules:
  211. continue
  212. # if user have state_dict_hooks in their model, they can add the state_dict key changes
  213. # at dsd_fqn_modifiers in input to align with the function of state_dict_hook
  214. if (
  215. hasattr(module, dsd_fqn_modifiers)
  216. and name in getattr(module, dsd_fqn_modifiers)().values()
  217. ):
  218. # skip _fqn_modifiers here thus remove the last `.` added
  219. new_fqn = curr_fqn[:-1]
  220. else:
  221. new_fqn = f"{curr_fqn}{name}"
  222. yield from recurse(submodule, new_fqn)
  223. for name, obj in chain(
  224. module.named_buffers(recurse=False), module.named_parameters(recurse=False)
  225. ):
  226. if name in module._non_persistent_buffers_set:
  227. continue
  228. new_fqn = f"{curr_fqn}{name}"
  229. yield new_fqn, obj
  230. if (
  231. getattr(module.__class__, "get_extra_state", nn.Module.get_extra_state)
  232. != nn.Module.get_extra_state
  233. ):
  234. new_fqn = f"{curr_fqn}{nn.modules.module._EXTRA_STATE_KEY_SUFFIX}"
  235. yield new_fqn, _EXTRA_STATE()
  236. yield from recurse(model, "")
  237. def _verify_options(
  238. model: nn.Module,
  239. optims: tuple[torch.optim.Optimizer, ...],
  240. optim_only: bool,
  241. *,
  242. submodules: set[nn.Module] | None = None,
  243. options: StateDictOptions | None = None,
  244. ) -> _StateDictInfo:
  245. """
  246. Verify the model and options passed by the user and generates _StateDictInfo.
  247. """
  248. if submodules:
  249. warnings.warn(
  250. "Getting submodules only model/optim state_dict is deprecated and "
  251. "will be removed in 2.5. This feature can be achieved by manually "
  252. "filtering out the state_dict returned from get_state_dict.",
  253. FutureWarning,
  254. stacklevel=2,
  255. )
  256. if optim_only and not optims:
  257. raise RuntimeError(
  258. "Optimizers are not passed in but optim_only is set to True."
  259. )
  260. options = options or StateDictOptions()
  261. fqn_param_mapping: dict[str | torch.Tensor, set[str] | torch.Tensor] = {}
  262. shared_params_mapping: dict[str | torch.Tensor, set[str] | torch.Tensor] = {}
  263. for name, param in _iterate_valid_model_state(model):
  264. if isinstance(param, _EXTRA_STATE):
  265. continue
  266. fqns = _get_fqns(model, name)
  267. fqn = fqn_param_mapping.get(param)
  268. if fqn is not None:
  269. cast(set[str], fqn_param_mapping[param]).update(fqns)
  270. shared_params_mapping[param] = fqn_param_mapping[param]
  271. else:
  272. # We need to do copy as _get_fqns is lru_cached
  273. fqn_param_mapping[param] = fqns.copy()
  274. for fqn in fqns:
  275. if not isinstance(param, _EXTRA_STATE):
  276. fqn_param_mapping[fqn] = param
  277. for param_, fqns_ in list(shared_params_mapping.items()):
  278. for fqn in fqns_:
  279. shared_params_mapping[fqn] = cast(torch.Tensor, param_)
  280. submodule_prefixes: set[str] = set()
  281. if submodules:
  282. submodules = set(submodules)
  283. for name, module in model.named_modules():
  284. if module not in submodules:
  285. continue
  286. fqns = _get_fqns(model, name)
  287. if len(fqns) != 1:
  288. raise AssertionError("Submodule FQN should only have 1 instance")
  289. submodule_prefixes.update(f"{fqn}." for fqn in fqns)
  290. if options.broadcast_from_rank0 and not options.full_state_dict:
  291. raise ValueError(
  292. "full_state_dict must be True when broadcast_from_rank0 is True."
  293. )
  294. fsdp_modules = FSDP.fsdp_modules(model)
  295. state_dict_config: StateDictConfig
  296. optim_state_dict_config: OptimStateDictConfig
  297. fsdp_context: Callable
  298. if fsdp_modules:
  299. # FSDP API only work if at least one FSDP instance exists.
  300. if options.full_state_dict:
  301. state_dict_config = FullStateDictConfig(
  302. offload_to_cpu=options.cpu_offload, rank0_only=options.cpu_offload
  303. )
  304. optim_state_dict_config = FullOptimStateDictConfig(
  305. offload_to_cpu=options.cpu_offload,
  306. rank0_only=(options.cpu_offload or options.broadcast_from_rank0),
  307. )
  308. state_dict_type = StateDictType.FULL_STATE_DICT
  309. else:
  310. state_dict_config = ShardedStateDictConfig(
  311. offload_to_cpu=options.cpu_offload,
  312. )
  313. optim_state_dict_config = ShardedOptimStateDictConfig(
  314. offload_to_cpu=options.cpu_offload,
  315. )
  316. state_dict_type = StateDictType.SHARDED_STATE_DICT
  317. @contextlib.contextmanager
  318. def fsdp_state_dict_type_without_warning(
  319. module,
  320. state_dict_type,
  321. state_dict_config,
  322. optim_state_dict_config,
  323. ):
  324. with warnings.catch_warnings():
  325. warnings.filterwarnings(
  326. "ignore", message="FSDP.state_dict_type", category=FutureWarning
  327. )
  328. with FSDP.state_dict_type(
  329. module=module,
  330. state_dict_type=state_dict_type,
  331. state_dict_config=state_dict_config,
  332. optim_state_dict_config=optim_state_dict_config,
  333. ):
  334. yield
  335. fsdp_context = functools.partial(
  336. fsdp_state_dict_type_without_warning,
  337. module=model,
  338. state_dict_type=state_dict_type,
  339. state_dict_config=state_dict_config,
  340. optim_state_dict_config=optim_state_dict_config,
  341. )
  342. else:
  343. fsdp_context = contextlib.nullcontext
  344. return _StateDictInfo(
  345. **asdict(options),
  346. fqn_param_mapping=fqn_param_mapping,
  347. shared_params_mapping=shared_params_mapping,
  348. submodule_prefixes=submodule_prefixes,
  349. fsdp_context=fsdp_context,
  350. fsdp_modules=cast(list[nn.Module], fsdp_modules),
  351. handle_model=not optim_only,
  352. handle_optim=(len(optims) > 0),
  353. )
  354. def _verify_state_dict(
  355. model_state_dict: dict[str, ValueType],
  356. optim_state_dict: OptimizerStateType,
  357. info: _StateDictInfo,
  358. ) -> None:
  359. for module in info.fsdp_modules:
  360. fsdp_state = _get_module_fsdp_state_if_fully_sharded_module(module)
  361. if fsdp_state is None:
  362. raise AssertionError("Expected a fsdp_state with a fsdp module.")
  363. # Verify if the model_state_dict and optim_state_dict are valid. This API
  364. # should give the users an explicit error message to debug or report.
  365. if (
  366. info.handle_model
  367. and not model_state_dict
  368. and not info.submodule_prefixes
  369. and not info.ignore_frozen_params
  370. and not (info.cpu_offload and info.full_state_dict)
  371. and info.strict
  372. and not info.broadcast_from_rank0
  373. ):
  374. raise RuntimeError(
  375. "The option indicates that model state_dict is required to save "
  376. "or load, but model state_dict is empty."
  377. f"rank = {dist.get_rank()=}."
  378. )
  379. if info.handle_optim:
  380. if (
  381. not optim_state_dict
  382. and not (info.cpu_offload and info.full_state_dict)
  383. and (not info.broadcast_from_rank0)
  384. ):
  385. raise RuntimeError(
  386. "The option indicates that model state_dict is required to save, "
  387. f"or load but optim state_dict is empty. {optim_state_dict}"
  388. )
  389. for key in model_state_dict:
  390. if _FLAT_PARAM in key:
  391. raise RuntimeError(
  392. f"{key} contains {_FLAT_PARAM}. This can happen if the model "
  393. "is not the root module."
  394. )
  395. def _state_dict_fn(obj: nn.Module | torch.optim.Optimizer, api: str) -> Callable:
  396. call = getattr(obj, api)
  397. if call in _patched_state_dict:
  398. call = functools.partial(getattr(obj.__class__, api), self=obj)
  399. return call
  400. def _maybe_full_or_cpu_state_dict(
  401. state_dict: dict[str, Any], info: _StateDictInfo
  402. ) -> dict[str, Any]:
  403. if info.full_state_dict:
  404. ranks_only = (
  405. ()
  406. if (not info.cpu_offload or not torch.distributed.is_initialized())
  407. else (0,)
  408. )
  409. return _gather_state_dict(
  410. state_dict, cpu_offload=info.cpu_offload, ranks_only=ranks_only
  411. )
  412. elif info.cpu_offload:
  413. return _offload_state_dict_to_cpu(state_dict)
  414. else:
  415. return state_dict
  416. @torch.no_grad()
  417. def _get_model_state_dict(
  418. model: nn.Module, info: _StateDictInfo
  419. ) -> dict[str, ValueType]:
  420. if not info.handle_model:
  421. return {}
  422. with info.fsdp_context():
  423. state_dict = _state_dict_fn(model, "state_dict")()
  424. for key in list(state_dict.keys()):
  425. fqns = _get_fqns(model, key)
  426. if len(fqns) != 1:
  427. raise AssertionError(
  428. f"Expected 1 FQN for key '{key}', got {len(fqns)}: {fqns}"
  429. )
  430. fqn = next(iter(fqns))
  431. if fqn != key:
  432. # As we only support FSDP, DDP, and TP, the only cases are
  433. # wrapper-based DDP and compiler. Verify if the assumption
  434. # is correct.
  435. def verify(key, fqn) -> bool:
  436. if len(fqn) >= len(key):
  437. return False
  438. fqn_split = fqn.split(".")
  439. key_split = key.split(".")
  440. fqn_idx = 0
  441. for key_idx, key_name in enumerate(key_split):
  442. if key_name == fqn_split[fqn_idx]:
  443. fqn_idx += 1
  444. if fqn_idx == len(fqn_split):
  445. return key_idx == len(key_split) - 1
  446. elif key_name in ("module", "_orig_mod"):
  447. continue
  448. else:
  449. return False
  450. return True
  451. if not verify(key, fqn):
  452. raise RuntimeError(f"An unexpected key, {key}, exists. FQN is {fqn}")
  453. state_dict[fqn] = state_dict.pop(key)
  454. if info.submodule_prefixes:
  455. new_state_dict: dict[str, ValueType] = {}
  456. # TODO: make this faster.
  457. for fqn in state_dict:
  458. for prefix in info.submodule_prefixes:
  459. if not fqn.startswith(prefix):
  460. continue
  461. if info.keep_submodule_prefixes:
  462. new_state_dict[fqn] = state_dict[fqn]
  463. else:
  464. new_fqn = fqn[len(prefix) :]
  465. new_state_dict[new_fqn] = state_dict[fqn]
  466. state_dict = new_state_dict
  467. if info.ignore_frozen_params:
  468. for key, param in model.named_parameters():
  469. if param.requires_grad:
  470. continue
  471. fqns = _get_fqns(model, key)
  472. for fqn in fqns:
  473. state_dict.pop(fqn)
  474. return _maybe_full_or_cpu_state_dict(state_dict, info)
  475. @torch.no_grad()
  476. def _load_model_state_dict(
  477. model: nn.Module,
  478. state_dict: dict[str, ValueType],
  479. info: _StateDictInfo,
  480. ) -> _IncompatibleKeys:
  481. if not info.handle_model or (not state_dict and not info.broadcast_from_rank0):
  482. return _IncompatibleKeys({}, {})
  483. local_state_dict = {}
  484. for key, value in _iterate_valid_model_state(model, info.dsd_fqn_modifiers):
  485. fqns = _get_fqns(model, key, info.dsd_fqn_modifiers)
  486. fqns_with_prefix = _get_fqns(
  487. model,
  488. key,
  489. info.dsd_fqn_modifiers,
  490. skip_ddp_prefix=False,
  491. skip_compiler_prefix=False,
  492. )
  493. for fqn, fqn_with_prefix in zip(fqns, fqns_with_prefix):
  494. if (
  495. not info.broadcast_from_rank0 or dist.get_rank() == 0
  496. ) and fqn != fqn_with_prefix:
  497. load_value = state_dict.pop(fqn, None)
  498. if load_value is None:
  499. if info.strict:
  500. raise RuntimeError(f"Missing key: {fqn}.")
  501. else:
  502. state_dict[fqn_with_prefix] = load_value
  503. local_state_dict[fqn_with_prefix] = value
  504. assign = False
  505. if info.broadcast_from_rank0 or info.full_state_dict:
  506. devices = set()
  507. for value in local_state_dict.values():
  508. if torch.is_tensor(value) and value.dim() > 0:
  509. devices.add(value.device)
  510. # In lora state_dict, there could be multiple devices, with meta device inside.
  511. # Take the other device in the broadcast/distribtue, and set assign to True
  512. if torch.device("meta") in devices:
  513. devices.remove(torch.device("meta"))
  514. assign = True
  515. if len(devices) == 0:
  516. devices.add(dist.distributed_c10d._get_pg_default_device())
  517. elif len(devices) > 1:
  518. raise ValueError("Multiple devices found")
  519. if info.broadcast_from_rank0:
  520. _broadcast_state_dict(
  521. state_dict,
  522. local_state_dict,
  523. device=devices.pop(),
  524. strict=info.strict,
  525. cpu_offload=info.cpu_offload,
  526. )
  527. elif info.full_state_dict:
  528. _distribute_state_dict(state_dict, local_state_dict, device=devices.pop())
  529. state_dict.update(local_state_dict)
  530. with info.fsdp_context():
  531. return cast(
  532. _IncompatibleKeys,
  533. _state_dict_fn(model, "load_state_dict")(
  534. state_dict=state_dict, strict=info.strict, assign=assign
  535. ),
  536. )
  537. def _init_optim_state(optim: torch.optim.Optimizer) -> None:
  538. """
  539. Initialize optim states by calling the step() with zero grads.
  540. """
  541. if optim.state:
  542. # The optimizer state is initialized.
  543. return
  544. # There are some stateless optimizers like SGD. These optimizer will
  545. # not return in the above condition. So if gradients exist, we should also
  546. # return. If gradients do not exist, the following initialization should
  547. # not disturb SGD because the gradients and lr are both zero.
  548. for param_group in optim.param_groups:
  549. for param in param_group[_PARAMS]:
  550. if param.grad is not None:
  551. return
  552. for param_group in optim.param_groups:
  553. for param in param_group[_PARAMS]:
  554. if param.requires_grad:
  555. param.grad = torch.zeros_like(param)
  556. # Some optimizers will update parameters regardless of grads due to lr, so
  557. # make lr to zero when calling `step()`.
  558. lrs = []
  559. for param_group in optim.param_groups:
  560. if "lr" in param_group:
  561. lrs.append(param_group["lr"])
  562. param_group["lr"] = (
  563. torch.tensor(0.0)
  564. if isinstance(param_group["lr"], torch.Tensor)
  565. else 0.0
  566. )
  567. optim.step(closure=None)
  568. # Whether to recover the "lr" should not matter too much as we will
  569. # restore checkpointing later.
  570. for param_group in optim.param_groups:
  571. if "lr" in param_group:
  572. param_group["lr"] = lrs.pop(0)
  573. optim.zero_grad(set_to_none=True)
  574. def _flatten_optim_state_dict(state_dict: OptimizerStateType) -> dict[str, ValueType]:
  575. """
  576. This API flattens the optimizer state_dict to support optimizer resharding for
  577. MPMD, e.g., pipeline parallelism.
  578. Without the API, the original optimizer state_dict looks like:
  579. {
  580. "state": {
  581. "layer1.weight": {
  582. "step": 10, "exp_avg": SomeTensor, "exp_avg_sq": SomeTensor
  583. },
  584. "layer2.weight": {
  585. "step": 10, "exp_avg": SomeTensor, "exp_avg_sq": SomeTensor
  586. },
  587. },
  588. "param_groups": [
  589. {
  590. "lr": 0.0,
  591. "betas": (0.9, 0.95), ...,
  592. "params": ["layer1.weight", "layer2.weight"]
  593. }
  594. ]
  595. }
  596. With this API, the optimizer state_dict looks like:
  597. {
  598. "state.layer1.weight.step": 10,
  599. "state.layer2.weight.step": 10,
  600. "state.layer1.weight.exp_avg": SomeTensor,
  601. "state.layer2.weight.exp_avg": SomeTensor,
  602. "state.layer1.weight.exp_avg_sq": SomeTensor,
  603. "state.layer2.weight.exp_avg_sq": SomeTensor,
  604. "param_groups.layer1.weight.lr": 0.1,
  605. "param_groups.layer2.weight.lr": 0.1,
  606. "param_groups.layer1.weight.betas": (0.9, 0.95),
  607. "param_groups.layer2.weight.betas": (0.9, 0.95),
  608. }
  609. The "state" section supports arbitrary levels of nesting for optimizers like Shampoo.
  610. """
  611. def _flatten_state_nested_dict(
  612. nested_dict: dict[str, Any], prefix: str
  613. ) -> dict[str, ValueType]:
  614. """
  615. Recursively flatten a nested dictionary with dot-separated keys.
  616. Args:
  617. nested_dict: The dictionary to flatten
  618. prefix: The prefix to prepend to all keys
  619. Returns:
  620. Flattened dictionary with dot-separated keys
  621. """
  622. flattened: dict[str, ValueType] = {}
  623. for key, value in nested_dict.items():
  624. # Convert all keys to strings for flattening
  625. str_key = str(key)
  626. full_key = f"{prefix}.{str_key}" if prefix else str_key
  627. if isinstance(value, dict):
  628. # Recursively flatten nested dictionaries
  629. flattened.update(_flatten_state_nested_dict(value, full_key))
  630. else:
  631. # Base case: store the value with the flattened key
  632. _raise_if_type_not_supported(value)
  633. flattened[full_key] = value
  634. return flattened
  635. def _raise_if_type_not_supported(v):
  636. if not isinstance(v, (torch.Tensor, int, float, dict)):
  637. raise NotImplementedError(
  638. "Flattening optimizer state_dict only supports "
  639. "tensor, int, float, dict states now. "
  640. f"Type is {type(v)}."
  641. )
  642. ret: dict[str, ValueType] = {}
  643. # Handle the "state" section with recursive flattening
  644. for fqn, state in cast(DictValueType, state_dict[_STATE]).items():
  645. state_prefix = f"{_STATE}.{fqn}"
  646. ret.update(
  647. _flatten_state_nested_dict(cast(dict[str, Any], state), state_prefix)
  648. )
  649. # Handle the "param_groups" section with two-level flattening
  650. for param_group in cast(ListDictValueType, state_dict[_PG]):
  651. fqns = param_group.pop(_PARAMS)
  652. for fqn in cast(list[str], fqns):
  653. for k, v in param_group.items():
  654. ret[f"{_PG}.{fqn}.{k}"] = v
  655. return ret
  656. def _unflatten_optim_state_dict(
  657. optim: torch.optim.Optimizer,
  658. state_dict: dict[str, ValueType],
  659. info: _StateDictInfo,
  660. ) -> OptimizerStateType:
  661. """
  662. This API unflattens the state_dict generated by _flatten_optim_state_dict().
  663. Supports arbitrary levels of nesting in the state section through recursive reconstruction.
  664. See the docstring of _flatten_optim_state_dict() for more detail.
  665. """
  666. def _reconstruct_nested_dict(
  667. flattened_key: str, flattened_dict: dict[str, ValueType]
  668. ) -> dict[str, ValueType]:
  669. """
  670. Reconstructs a potentially nested value from flattened keys.
  671. For non-nested values, returns the value directly.
  672. For nested values, reconstructs the nested structure with string keys.
  673. """
  674. # Create the prefix to search for nested keys
  675. # e.g., if flattened_key is "state.layer1.weight", prefix becomes "state.layer1.weight."
  676. prefix = f"{flattened_key}."
  677. # Initialize an empty dictionary to build our nested structure
  678. nested_dict: dict[str, Any] = {}
  679. # Iterate through all keys in the flattened dictionary
  680. for key, value in flattened_dict.items():
  681. # Check if this key is nested under our target key
  682. # e.g., "state.layer1.weight.exp_avg" starts with "state.layer1.weight."
  683. if not key.startswith(prefix):
  684. # Skip keys that don't belong to this nested structure
  685. continue
  686. # Remove the prefix to get just the nested part
  687. # e.g., "state.layer1.weight.exp_avg" -> "exp_avg"
  688. remaining_key = key[len(prefix) :]
  689. # Split the remaining key into parts to build the nested structure
  690. # e.g., "step" -> ["step"] or "momentum_buffer" -> ["momentum_buffer"]
  691. parts = remaining_key.split(".")
  692. # Start at the root of our new nested dictionary
  693. current = nested_dict
  694. # Navigate through or create the nested dictionary structure
  695. # For each part except the last one (which will hold the value)
  696. for part in parts[:-1]:
  697. # Create the nested dictionary if it doesn't exist yet
  698. if part not in current:
  699. current[part] = {}
  700. # Move deeper into the nested structure
  701. assert isinstance(current[part], dict)
  702. current = current[part]
  703. # Set the value at the final level using the last part as the key
  704. # e.g., current["exp_avg"] = tensor(...)
  705. current[parts[-1]] = value
  706. # Return the reconstructed nested dictionary (empty dict if no keys matched at all)
  707. return nested_dict
  708. state: DictValueType = {}
  709. pg_state: ListDictValueType = []
  710. return_osd: OptimizerStateType = {_STATE: state, _PG: pg_state}
  711. for param_group in optim.param_groups:
  712. pg_state.append({_PARAMS: []})
  713. for param in param_group[_PARAMS]:
  714. for fqn in info.fqn_param_mapping[param]:
  715. # If a parameter is shared, only one of the FQN will be used.
  716. # So we need to verify which if this fqn is actually used in
  717. # the state_dict.
  718. if fqn in info.shared_params_mapping:
  719. in_params = False
  720. for k in param_group:
  721. if k == _PARAMS:
  722. continue
  723. flatten_key = f"{_PG}.{fqn}.{k}"
  724. if flatten_key in state_dict:
  725. in_params = True
  726. break
  727. else:
  728. in_params = True
  729. if not in_params:
  730. continue
  731. params = pg_state[-1][_PARAMS]
  732. if not isinstance(params, list):
  733. raise AssertionError(f"Expected list, got {type(params)}")
  734. params.append(fqn)
  735. # Only add state if param requires grad
  736. if not param.requires_grad:
  737. continue
  738. # Reconstruct state for this parameter
  739. state[fqn] = {}
  740. for state_name in optim.state[param]:
  741. flattened_state_key = f"{_STATE}.{fqn}.{state_name}"
  742. if flattened_state_key not in state_dict:
  743. # Try to reconstruct the value
  744. reconstructed_value = _reconstruct_nested_dict(
  745. flattened_state_key, state_dict
  746. )
  747. cast(DictValueType, state[fqn])[state_name] = (
  748. reconstructed_value
  749. )
  750. else:
  751. # Existing keys mean no nesting, directly use the value.
  752. cast(DictValueType, state[fqn])[state_name] = state_dict[
  753. flattened_state_key
  754. ]
  755. first_param_fqn = cast(list[str], pg_state[-1][_PARAMS])[0]
  756. for k in param_group:
  757. if k == _PARAMS:
  758. continue
  759. value = state_dict[f"{_PG}.{first_param_fqn}.{k}"]
  760. if k not in pg_state[-1]:
  761. pg_state[-1][k] = value
  762. elif pg_state[-1][k] != value:
  763. raise RuntimeError(
  764. "All the parameters in the same parameter group should have "
  765. f"the same saved param_group value. But {first_param_fqn}.{k} "
  766. f"is {value} while other(s) is {pg_state[-1][k]}."
  767. )
  768. return return_osd
  769. @torch.no_grad()
  770. def _get_optim_state_dict(
  771. model: nn.Module,
  772. optimizers: tuple[torch.optim.Optimizer, ...],
  773. info: _StateDictInfo,
  774. ) -> OptimizerStateType:
  775. if not info.handle_optim:
  776. return {}
  777. optim_state_dict: OptimizerStateType = {_STATE: {}, _PG: []}
  778. for optim in optimizers:
  779. _init_optim_state(optim)
  780. osd = _state_dict_fn(optim, "state_dict")()
  781. if info.fsdp_modules:
  782. with info.fsdp_context():
  783. osd = FSDP.optim_state_dict(model, optim, osd)
  784. # We need to specially handle FlatParameter FSDP as
  785. # FlatParameter FSDP converts the FQNs.
  786. # There are no easy ways to do this conversion systematically.
  787. # We can only use a string replacement without correctness check.
  788. if not osd:
  789. continue
  790. for k in list(osd[_STATE].keys()):
  791. if "_orig_mod" in k:
  792. osd[_STATE][k.replace("_orig_mod.", "")] = osd[_STATE].pop(k)
  793. for g in osd[_PG]:
  794. params = [k.replace("_orig_mod.", "") for k in g[_PARAMS]]
  795. g[_PARAMS] = params
  796. else:
  797. params = list(chain.from_iterable(g[_PARAMS] for g in optim.param_groups))
  798. param_pid_mapping = dict(zip(params, range(len(params))))
  799. fqn_pid_mapping = {}
  800. for key, param in model.named_parameters():
  801. fqns = _get_fqns(model, key)
  802. if len(fqns) != 1:
  803. raise AssertionError(
  804. f"Expected 1 FQN for key '{key}', got {len(fqns)}"
  805. )
  806. fqn = next(iter(fqns))
  807. if param not in param_pid_mapping:
  808. continue
  809. # pyrefly: ignore [bad-index]
  810. pid = param_pid_mapping[param]
  811. fqn_pid_mapping[fqn] = pid
  812. # pyrefly: ignore [unsupported-operation]
  813. fqn_pid_mapping[pid] = fqn
  814. # Only convert top-level parameter IDs to FQNs, preserve nested key types
  815. for key in list(osd[_STATE].keys()):
  816. fqn = fqn_pid_mapping[key]
  817. # Move the entire state dict value (which may contain nested integer keys)
  818. # without modifying its internal structure
  819. osd[_STATE][fqn] = osd[_STATE].pop(key)
  820. for group in osd[_PG]:
  821. group[_PARAMS] = [fqn_pid_mapping[pid] for pid in group[_PARAMS]]
  822. if not osd:
  823. continue
  824. cast(DictValueType, optim_state_dict[_STATE]).update(osd[_STATE])
  825. cast(ListDictValueType, optim_state_dict[_PG]).extend(osd[_PG])
  826. if info.flatten_optimizer_state_dict:
  827. optim_state_dict = cast(
  828. OptimizerStateType, _flatten_optim_state_dict(optim_state_dict)
  829. )
  830. return _maybe_full_or_cpu_state_dict(optim_state_dict, info)
  831. def _split_optim_state_dict(
  832. model: nn.Module,
  833. optim: torch.optim.Optimizer,
  834. optim_state_dict: OptimizerStateType,
  835. info: _StateDictInfo,
  836. ) -> OptimizerStateType:
  837. """
  838. Extract the corresponding optim state_dict from ``optim_state_dict`` for
  839. ``optim`` and return the result optim state_dict.
  840. Args:
  841. model (nn.Module): the root model.
  842. optim (torch.optim.Optimizer): the optimizer.
  843. optim_state_dict (Dict[str, ValueType]): the superset optim state_dict that
  844. contains the optim state_dict of ``optim``.
  845. info (_StateDictInfo): state dict information.
  846. Returns:
  847. The optim state_dict of ``optim``.
  848. """
  849. state: DictValueType = {}
  850. pg_state: ListDictValueType = []
  851. return_osd: OptimizerStateType = {_STATE: state, _PG: pg_state}
  852. pg_mapping: dict[int, int] = {}
  853. if all(isinstance(k, int) for k in cast(DictValueType, optim_state_dict[_STATE])):
  854. return optim_state_dict
  855. for param_group in optim.param_groups:
  856. pg_state.append({_PARAMS: []})
  857. for param in param_group[_PARAMS]:
  858. for fqn in info.fqn_param_mapping[param]:
  859. if fqn in info.shared_params_mapping:
  860. in_params = False
  861. for loaded_param_group in cast(
  862. ListDictValueType, optim_state_dict[_PG]
  863. ):
  864. if fqn in cast(list[str], loaded_param_group[_PARAMS]):
  865. in_params = True
  866. break
  867. else:
  868. in_params = True
  869. if not in_params:
  870. continue
  871. params = pg_state[-1][_PARAMS]
  872. if not isinstance(params, list):
  873. raise AssertionError(f"Expected list, got {type(params)}")
  874. params.append(fqn)
  875. if param.requires_grad:
  876. if fqn in cast(DictValueType, optim_state_dict[_STATE]):
  877. state[fqn] = cast(DictValueType, optim_state_dict[_STATE])[fqn]
  878. elif info.strict:
  879. raise RuntimeError(
  880. f"Missing optimizer state for parameter '{fqn}' in checkpoint. "
  881. "The parameter requires gradients but has no saved optimizer state. "
  882. "To load anyway, use StateDictOptions(strict=False)."
  883. )
  884. for loaded_param_group in cast(
  885. ListDictValueType, optim_state_dict[_PG]
  886. ):
  887. if fqn in cast(list[str], loaded_param_group[_PARAMS]):
  888. pg_mapping[id(loaded_param_group)] = len(return_osd[_PG]) - 1
  889. if len(param_group[_PARAMS]) == 0:
  890. # Param_group with empty params.
  891. ret = []
  892. for loaded_param_group in cast(ListDictValueType, optim_state_dict[_PG]):
  893. if len(cast(list[str], loaded_param_group[_PARAMS])) == 0:
  894. ret.append(loaded_param_group)
  895. if len(ret) != 1:
  896. raise ValueError(
  897. "There are param groups that have zero parameters. "
  898. "In such a case, DSD only support exactly one param group "
  899. "with zero parameters."
  900. "But the loaded state_dict has zero or more than one param groups "
  901. "that have zero parameters."
  902. )
  903. if len(optim_state_dict[_PG]) != len(optim.param_groups):
  904. raise ValueError(
  905. "When there is a parameter group that has zero parameters, "
  906. "multiple optimizers are not supported."
  907. )
  908. pg_mapping[id(loaded_param_group)] = len(return_osd[_PG]) - 1
  909. for param_group in cast(ListDictValueType, optim_state_dict[_PG]):
  910. pg_idx = pg_mapping.get(id(param_group), -1)
  911. if pg_idx == -1:
  912. continue
  913. for key, value in param_group.items():
  914. if key == _PARAMS:
  915. continue
  916. # TODO: check if value is the same if exists.
  917. pg_state[pg_idx][key] = value
  918. return return_osd
  919. @torch.no_grad()
  920. def _load_optim_state_dict(
  921. model: nn.Module,
  922. optimizers: tuple[torch.optim.Optimizer, ...],
  923. state_dict: OptimizerStateType,
  924. info: _StateDictInfo,
  925. ) -> None:
  926. if not info.handle_optim:
  927. return
  928. for optim in optimizers:
  929. _init_optim_state(optim)
  930. if state_dict:
  931. if _STATE in state_dict:
  932. optim_state_dict = _split_optim_state_dict(
  933. model, optim, state_dict, info
  934. )
  935. else:
  936. optim_state_dict = _unflatten_optim_state_dict(
  937. optim, cast(dict[str, ValueType], state_dict), info
  938. )
  939. else:
  940. optim_state_dict = {}
  941. if info.fsdp_modules:
  942. # We need to specially handle FlatParameter FSDP as
  943. # FlatParameter FSDP converts the FQNs.
  944. for original_fqn, _ in model.named_parameters():
  945. fqns = _get_fqns(model, original_fqn)
  946. fqns_with_compiler = _get_fqns(
  947. model, original_fqn, skip_compiler_prefix=False
  948. )
  949. if fqns == fqns_with_compiler:
  950. continue
  951. if len(fqns) != 1:
  952. raise AssertionError(
  953. f"Expected 1 FQN for '{original_fqn}', got {len(fqns)}"
  954. )
  955. fqn = fqns.pop()
  956. fqn_with_compiler = fqns_with_compiler.pop()
  957. for g in optim_state_dict[_PG]:
  958. val = cast(dict[str, Any], g)
  959. params = [
  960. key.replace(fqn, fqn_with_compiler) for key in val[_PARAMS]
  961. ]
  962. val[_PARAMS] = params
  963. osd_state = cast(DictValueType, optim_state_dict[_STATE])
  964. for k in list(osd_state.keys()):
  965. if fqn in k:
  966. osd_state[k.replace(fqn, fqn_with_compiler)] = osd_state.pop(k)
  967. with info.fsdp_context():
  968. optim_state_dict = FSDP.optim_state_dict_to_load(
  969. model, optim, optim_state_dict
  970. )
  971. elif info.full_state_dict:
  972. info.full_state_dict = False
  973. local_state_dict = _get_optim_state_dict(model, (optim,), info)
  974. info.full_state_dict = True
  975. device = None
  976. def _device(t):
  977. if t.dim() > 0:
  978. nonlocal device
  979. if device is None:
  980. device = t.device
  981. elif device != t.device:
  982. raise ValueError("Device mismatch")
  983. return t
  984. _ = tree_map_only(torch.Tensor, _device, local_state_dict)
  985. if device is None:
  986. raise AssertionError("Expected device to be set")
  987. flatten_osd, osd_mapping = _flatten_state_dict(optim_state_dict)
  988. flatten_local_osd, local_osd_mapping = _flatten_state_dict(local_state_dict)
  989. if info.broadcast_from_rank0:
  990. _broadcast_state_dict(flatten_osd, flatten_local_osd, device=device)
  991. else:
  992. _distribute_state_dict(flatten_osd, flatten_local_osd, device=device)
  993. # The modifications listed seek to address the problem where optim might possess
  994. # dissimilar parameters in comparison to optim_state_dict. This is achieved by
  995. # incorporating differential parameters within local, which may result in optim
  996. # having additional parameters ultimately.
  997. for optim_key in flatten_osd:
  998. if optim_key not in flatten_local_osd:
  999. if optim_key not in osd_mapping:
  1000. raise AssertionError(
  1001. f"Expected key '{optim_key}' in osd_mapping"
  1002. )
  1003. flatten_local_osd[optim_key] = flatten_osd[optim_key]
  1004. local_osd_mapping[optim_key] = osd_mapping[optim_key]
  1005. optim_state_dict = _unflatten_state_dict(
  1006. flatten_local_osd, local_osd_mapping
  1007. )
  1008. for pg in optim_state_dict[_PG]:
  1009. if _PARAMS not in pg:
  1010. cast(dict[str, ValueType], pg)[_PARAMS] = []
  1011. # Note that we do not have to convert the FQN back to param id here if
  1012. # order in optim.param_groups[idx][_PARAMS] is the same as the one in
  1013. # optim_state_dict[_PG][idx][_PARAMS].
  1014. _state_dict_fn(optim, "load_state_dict")(state_dict=optim_state_dict)
  1015. def get_model_state_dict(
  1016. model: nn.Module,
  1017. *,
  1018. submodules: set[nn.Module] | None = None,
  1019. options: StateDictOptions | None = None,
  1020. ) -> dict[str, ValueType]:
  1021. """
  1022. Return the model state_dict of ``model``.
  1023. See ``get_state_dict`` for the detail usage.
  1024. Args:
  1025. model (nn.Module): the nn.Module to the model.
  1026. submodules (deprecated): Optional[set[nn.Module]]: only return the model parameters
  1027. that belong to the submodules.
  1028. options (StateDictOptions): the options to control how
  1029. model state_dict and optimizer state_dict should be returned. See
  1030. `StateDictOptions` for the details.
  1031. Returns:
  1032. The state_dict for ``model``.
  1033. :rtype: typing.Dict[str, ValueType]
  1034. """
  1035. with _gc_context():
  1036. info = _verify_options(
  1037. model,
  1038. (),
  1039. optim_only=False,
  1040. submodules=submodules,
  1041. options=options,
  1042. )
  1043. model_state_dict = _get_model_state_dict(model, info)
  1044. _verify_state_dict(model_state_dict, {}, info)
  1045. return model_state_dict
  1046. def get_optimizer_state_dict(
  1047. model: nn.Module,
  1048. optimizers: torch.optim.Optimizer | Iterable[torch.optim.Optimizer],
  1049. *,
  1050. submodules: set[nn.Module] | None = None,
  1051. options: StateDictOptions | None = None,
  1052. ) -> OptimizerStateType:
  1053. """
  1054. Return the combined state_dict for optimizers.
  1055. See ``get_state_dict`` for the detail usage.
  1056. Args:
  1057. model (nn.Module): the nn.Module to the model.
  1058. optimizers (Union[None, Optimizer, Iterable[Optimizer]]):
  1059. The optimizers that are used to optimize ``model``.
  1060. submodules (deprecated): Optional[set[nn.Module]]: only return the model parameters
  1061. that belong to the submodules.
  1062. options (StateDictOptions): the options to control how
  1063. model state_dict and optimizer state_dict should be returned. See
  1064. `StateDictOptions` for the details.
  1065. Returns:
  1066. The state_dict for ``optimizers``.
  1067. :rtype: OptimizerStateType
  1068. """
  1069. with _gc_context():
  1070. optimizers = (
  1071. (optimizers,)
  1072. if isinstance(optimizers, torch.optim.Optimizer)
  1073. else tuple(optimizers)
  1074. )
  1075. info = _verify_options(
  1076. model,
  1077. optimizers,
  1078. optim_only=True,
  1079. submodules=submodules,
  1080. options=options,
  1081. )
  1082. optim_state_dict = _get_optim_state_dict(model, optimizers, info)
  1083. _verify_state_dict({}, optim_state_dict, info)
  1084. return optim_state_dict
  1085. def get_state_dict(
  1086. model: nn.Module,
  1087. optimizers: torch.optim.Optimizer | Iterable[torch.optim.Optimizer],
  1088. *,
  1089. submodules: set[nn.Module] | None = None,
  1090. options: StateDictOptions | None = None,
  1091. ) -> tuple[dict[str, ValueType], OptimizerStateType]:
  1092. """
  1093. Return the model state_dict and optimizers state_dict.
  1094. ``get_state_dict`` can process any module that is parallelized by PyTorch
  1095. FSDP/fully_shard, DDP/replicate, tensor_parallel/parallelize_module, and any
  1096. combination of these parallelisms. The main functions of ``get_state_dict``
  1097. are: 1.) returning a model and optimizer state_dict that can be resharded
  1098. with a different number of trainers and/or different parallelisms.
  1099. 2.) hiding the parallelism-specific state_dict APIs. Users don't have to call
  1100. these APIs.
  1101. 3.) sanity checking the result state_dict.
  1102. The keys of the result state dictionary are the canonical FQNs (Fully
  1103. Qualified Names). A canonical FQN refers to the FQN based on a parameter's
  1104. position in an nn.Module hierarchy. More specifically, a canonical FQN to a
  1105. parameter is the FQN returned by ``module.named_parameters()`` or
  1106. ``module.named_buffers()`` when the module is not distributed by any
  1107. parallelisms. Since the optimizer internally uses parameter IDs to represent
  1108. a parameter, there will be a conversion from the parameter IDs to the
  1109. canonical FQNs when calling this API.
  1110. ``get_state_dict`` can also process a module that is not parallelized. In
  1111. such a case, ``get_state_dict`` only performs one function -- converting the
  1112. optimizer parameter IDs to the canonical FQNs.
  1113. Example:
  1114. >>> # xdoctest: +SKIP
  1115. >>> import torch
  1116. >>> from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
  1117. >>> from torch.nn.parallel import DistributedDataParallel as DDP
  1118. >>> from torch.distributed.checkpoint.state_dict import get_state_dict
  1119. >>> fsdp_model = FSDP(copy.deepcopy(model))
  1120. >>> fsdp_optim = torch.optim.Adam(model.parameters(), lr=1e-3)
  1121. >>> ddp_model = DDP(copy.deepcopy(model))
  1122. >>> ddp_optim = torch.optim.Adam(model.parameters(), lr=1e-3)
  1123. >>> ddp_state_dict, ddp_optim_state_dict = get_state_dict(ddp_model, ddp_optim)
  1124. >>> fsdp_state_dict, fsdp_optim_state_dict = get_state_dict(
  1125. ... fsdp_model, fsdp_optim
  1126. ... )
  1127. >>> # if we simply call ddp_model.state_dict() and fsdp_model.state_dict(),
  1128. >>> # the asserts will fail.
  1129. >>> assert ddp_state_dict == fsdp_state_dict
  1130. >>> assert ddp_optim_state == fsdp_optim_state_dict
  1131. Args:
  1132. model (nn.Module): the nn.Module to the model.
  1133. optimizers (Union[None, Optimizer, Iterable[Optimizer]]):
  1134. The optimizers that are used to optimize ``model``.
  1135. submodules (deprecated): Optional[set[nn.Module]]: only return the model parameters
  1136. that belong to the submodules.
  1137. options (StateDictOptions): the options to control how
  1138. model state_dict and optimizer state_dict should be returned. See
  1139. `StateDictOptions` for the details.
  1140. Returns:
  1141. ``Tuple`` that contain model state_dict and optimizer state_dict.
  1142. :rtype: typing.Tuple[typing.Dict[str, ValueType], OptimizerStateType]
  1143. """
  1144. with _gc_context():
  1145. optimizers = (
  1146. (optimizers,)
  1147. if isinstance(optimizers, torch.optim.Optimizer)
  1148. else tuple(optimizers)
  1149. )
  1150. info = _verify_options(
  1151. model,
  1152. optimizers,
  1153. optim_only=False,
  1154. submodules=submodules,
  1155. options=options,
  1156. )
  1157. model_state_dict = _get_model_state_dict(model, info)
  1158. optim_state_dict = _get_optim_state_dict(model, optimizers, info)
  1159. _verify_state_dict(model_state_dict, optim_state_dict, info)
  1160. return model_state_dict, optim_state_dict
  1161. def _unflatten_model_state_dict(
  1162. model: nn.Module,
  1163. state_dict: dict[nn.Module, dict[str, ValueType]] | dict[str, ValueType],
  1164. ) -> dict[str, ValueType]:
  1165. if not state_dict:
  1166. return {}
  1167. if isinstance(next(iter(state_dict.keys())), nn.Module):
  1168. warnings.warn(
  1169. "Passing model_state_dict as a ``Dict[nn.Module, Dict[str, Any]]``"
  1170. "is deprecated and will be removed in 2.5. If you need this "
  1171. "feature, please preprocessing the model_state_dict to achieve the "
  1172. "same functionality.",
  1173. FutureWarning,
  1174. stacklevel=2,
  1175. )
  1176. cast_state_dict = cast(dict[nn.Module, dict[str, ValueType]], state_dict)
  1177. new_state_dict: dict[str, ValueType] = {}
  1178. for submodule, sub_state_dict in cast_state_dict.items():
  1179. for name, m in model.named_modules():
  1180. if m != submodule:
  1181. continue
  1182. fqns = _get_fqns(model, name)
  1183. if len(fqns) != 1:
  1184. raise AssertionError(
  1185. "FQNs for a submodule should only have 1 element"
  1186. )
  1187. prefix = f"{next(iter(fqns))}."
  1188. new_state_dict.update(
  1189. {prefix + subfqn: value for subfqn, value in sub_state_dict.items()}
  1190. )
  1191. return new_state_dict
  1192. else:
  1193. return cast(dict[str, ValueType], state_dict)
  1194. def set_model_state_dict(
  1195. model: nn.Module,
  1196. model_state_dict: dict[str, ValueType],
  1197. *,
  1198. options: StateDictOptions | None = None,
  1199. ) -> _IncompatibleKeys:
  1200. """Load the model state_dict.
  1201. The counterpart of ``get_model_state_dict`` to set the state_dict to the
  1202. model. See ``set_state_dict`` for the detail usage.
  1203. Args:
  1204. model (nn.Module): the nn.Module to the model.
  1205. model_state_dict: (Dict[str, ValueType]):
  1206. the model state_dict to load. If the key of the ``model_state_dict``
  1207. is nn.Module, the key is a submodule of ``model`` and the value should
  1208. be the state_dict of the submodule. When loading the state_dict,
  1209. the prefix of the submodule will be append to the state_dict.
  1210. options (StateDictOptions): the options to control how
  1211. model state_dict and optimizer state_dict should be loaded. See
  1212. `StateDictOptions` for the details.
  1213. Returns:
  1214. ``NamedTuple`` with ``missing_keys`` and ``unexpected_keys`` fields:
  1215. * **missing_keys** is a list of str containing the missing keys
  1216. * **unexpected_keys** is a list of str containing the unexpected keys
  1217. :type model_state_dict: typing.Dict[str, ValueType]
  1218. """
  1219. model_state_dict: dict[str, ValueType] = _unflatten_model_state_dict(
  1220. model, model_state_dict
  1221. )
  1222. with _gc_context():
  1223. info = _verify_options(model, (), optim_only=False, options=options)
  1224. _verify_state_dict(model_state_dict, {}, info)
  1225. return _load_model_state_dict(model, model_state_dict, info)
  1226. def set_optimizer_state_dict(
  1227. model: nn.Module,
  1228. optimizers: torch.optim.Optimizer | Iterable[torch.optim.Optimizer],
  1229. optim_state_dict: OptimizerStateType,
  1230. *,
  1231. options: StateDictOptions | None = None,
  1232. ) -> None:
  1233. """Load the optimizers state_dict.
  1234. The counterpart of ``get_optimizer_state_dict`` to set the state_dict to the
  1235. optimizers. See ``set_state_dict`` for the detail usage.
  1236. WARN: ``set_optimizer_state_dict`` can only be called before ``backward()`` or after
  1237. ``step()`` is called on the optimizers. Otherwise, the optimizer states won't be
  1238. initialized correctly.
  1239. Args:
  1240. model (nn.Module): the nn.Module to the model.
  1241. optimizers (Union[Optimizer, Iterable[Optimizer]]):
  1242. The optimizers that are used to optimize ``model``.
  1243. optim_state_dict: OptimizerStateType:
  1244. the optimizer state_dict to load.
  1245. options (StateDictOptions): the options to control how
  1246. model state_dict and optimizer state_dict should be loaded. See
  1247. `StateDictOptions` for the details.
  1248. Returns:
  1249. None
  1250. :type optim_state_dict: typing.OptimizerStateType
  1251. """
  1252. with _gc_context():
  1253. optimizers = (
  1254. (optimizers,)
  1255. if isinstance(optimizers, torch.optim.Optimizer)
  1256. else tuple(optimizers)
  1257. )
  1258. info = _verify_options(model, optimizers, optim_only=True, options=options)
  1259. _verify_state_dict({}, optim_state_dict, info)
  1260. _load_optim_state_dict(model, optimizers, optim_state_dict, info)
  1261. def set_state_dict(
  1262. model: nn.Module,
  1263. optimizers: torch.optim.Optimizer | Iterable[torch.optim.Optimizer],
  1264. *,
  1265. model_state_dict: dict[str, ValueType],
  1266. optim_state_dict: OptimizerStateType,
  1267. options: StateDictOptions | None = None,
  1268. ) -> _IncompatibleKeys:
  1269. """Load the model state_dict and optimizers state_dict.
  1270. The counterpart of ``get_state_dict`` to set the state_dict to the model and
  1271. optimizers. The given ``model_state_dict`` and ``optim_state_dict`` do not
  1272. have to be returned by ``get_state_dict`` but must meet the following
  1273. requirements: 1) all FQNs are canonical FQNs as defined in ``get_state_dict``,
  1274. 2) if a tensor is sharded, it must be either a ShardedTensor or DTensor,
  1275. 3) optimizer state_dict cannot contain the parameter IDs; the keys should be
  1276. the canonical FQNs.
  1277. WARN: ``set_state_dict`` can only be called before ``backward()`` or after ``step()``
  1278. is called on the optimizers. Otherwise, the optimizer states won't be initialized
  1279. correctly.
  1280. Args:
  1281. model (nn.Module): the nn.Module to the model.
  1282. optimizers (Union[Optimizer, Iterable[Optimizer]]):
  1283. The optimizers that are used to optimize ``model``.
  1284. model_state_dict: (Union[Dict[nn.Module, Dict[str, ValueType]], Dict[str, ValueType]]):
  1285. the model state_dict to load. If the key of the ``model_state_dict``
  1286. is nn.Module, the key is a submodule of ``model`` and the value should
  1287. be the state_dict of the submodule. When loading the state_dict,
  1288. the prefix of the submodule will be append to the state_dict.
  1289. optim_state_dict: OptimizerStateType:
  1290. the optimizer state_dict to load.
  1291. options (StateDictOptions): the options to control how
  1292. model state_dict and optimizer state_dict should be loaded. See
  1293. `StateDictOptions` for the details.
  1294. Returns:
  1295. ``NamedTuple`` with ``missing_keys`` and ``unexpected_keys`` fields:
  1296. * **missing_keys** is a list of str containing the missing keys of the model state_dict.
  1297. * **unexpected_keys** is a list of str containing the unexpected keys of the model state_dict.
  1298. :type model_state_dict: typing.Dict[str, ValueType]
  1299. :type optim_state_dict: typing.OptimizerStateType
  1300. """
  1301. model_state_dict: dict[str, ValueType] = _unflatten_model_state_dict(
  1302. model, model_state_dict
  1303. )
  1304. with _gc_context():
  1305. optimizers = (
  1306. (optimizers,)
  1307. if isinstance(optimizers, torch.optim.Optimizer)
  1308. else tuple(optimizers)
  1309. )
  1310. info = _verify_options(
  1311. model, optimizers, optim_only=not model_state_dict, options=options
  1312. )
  1313. _verify_state_dict(model_state_dict, optim_state_dict, info)
  1314. _load_optim_state_dict(model, optimizers, optim_state_dict, info)
  1315. return _load_model_state_dict(model, model_state_dict, info)
  1316. # TODO: correct the state_dict function signature.
  1317. # TODO: this API is not yet fully tested. Make it private
  1318. @no_type_check
  1319. def _patch_model_state_dict(
  1320. model: nn.Module,
  1321. *,
  1322. options: StateDictOptions | None = None,
  1323. ) -> None:
  1324. """Patch the ``state_dict`` and ``load_state_dict`` attributes of ``model``.
  1325. Patch the ``state_dict`` and ``load_state_dict`` attributes of ``model`` to
  1326. be a partial function to call ``get_state_dict`` and ``set_state_dict``.
  1327. Example:
  1328. from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
  1329. from torch.distributed.checkpoint.state_dict import patch_model_state_dict
  1330. model = fsdp(model)
  1331. patch_model_state_dict(model)
  1332. Args:
  1333. model (nn.Module): the nn.Module to the model.
  1334. options (StateDictOptions): the options to control how
  1335. model state_dict and optimizer state_dict should be loaded. See
  1336. `StateDictOptions` for the details.
  1337. Returns:
  1338. None
  1339. """
  1340. _state_dict_call = functools.partial(
  1341. get_model_state_dict,
  1342. model=model,
  1343. options=options,
  1344. )
  1345. def state_dict_call():
  1346. return _state_dict_call()
  1347. model.state_dict = state_dict_call
  1348. _load_state_dict_call = functools.partial(
  1349. set_model_state_dict,
  1350. model=model,
  1351. options=options,
  1352. )
  1353. def load_state_dict_call(state_dict: dict[str, Any]):
  1354. _load_state_dict_call(model_state_dict=state_dict)
  1355. model.load_state_dict = load_state_dict_call
  1356. _patched_state_dict.add(state_dict_call)
  1357. _patched_state_dict.add(load_state_dict_call)
  1358. # TODO: correct the load_state_dict function signature.
  1359. # TODO: this API is not yet fully tested. Make it private
  1360. @no_type_check
  1361. def _patch_optimizer_state_dict(
  1362. model: nn.Module,
  1363. *,
  1364. optimizers: tuple[torch.optim.Optimizer, ...],
  1365. options: StateDictOptions | None = None,
  1366. ) -> None:
  1367. """Patch the ``state_dict`` and ``load_state_dict`` attributes of ``optimizers``.
  1368. Patch the ``state_dict`` and ``load_state_dict`` attributes of ``optimizers`` to
  1369. be a partial function to call ``get_state_dict`` and ``set_state_dict``.
  1370. Note that if there are multiple optimizers, all of the optimizers will be patched.
  1371. So users only need to call one of the state_dict() to get the full result.
  1372. Example:
  1373. from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
  1374. from torch.distributed.checkpoint.state_dict import patch_model_state_dict
  1375. model = fsdp(model)
  1376. patch_model_state_dict(model)
  1377. Args:
  1378. model (nn.Module): the nn.Module to the model.
  1379. options (StateDictOptions): the options to control how
  1380. model state_dict and optimizer state_dict should be loaded. See
  1381. `StateDictOptions` for the details.
  1382. Returns:
  1383. None
  1384. """
  1385. _state_dict_call = functools.partial(
  1386. get_optimizer_state_dict,
  1387. model=model,
  1388. optimizers=optimizers,
  1389. options=options,
  1390. )
  1391. def state_dict_call():
  1392. return _state_dict_call()
  1393. _load_state_dict_call = functools.partial(
  1394. set_optimizer_state_dict,
  1395. model=model,
  1396. optimizers=optimizers,
  1397. options=options,
  1398. )
  1399. def load_state_dict_call(state_dict: dict[str, Any]):
  1400. _load_state_dict_call(optim_state_dict=state_dict)
  1401. _patched_state_dict.add(state_dict_call)
  1402. _patched_state_dict.add(load_state_dict_call)
  1403. optimizers = (
  1404. (optimizers,)
  1405. if isinstance(optimizers, torch.optim.Optimizer)
  1406. else tuple(optimizers)
  1407. )
  1408. for optim in optimizers:
  1409. optim.state_dict = state_dict_call
  1410. optim.load_state_dict = load_state_dict_call