_optim_utils.py 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741
  1. import copy
  2. import functools
  3. import warnings
  4. from dataclasses import dataclass
  5. from typing import (
  6. Any,
  7. cast,
  8. Dict,
  9. Iterable,
  10. Iterator,
  11. List,
  12. NamedTuple,
  13. Optional,
  14. Sequence,
  15. Set,
  16. Tuple,
  17. Union,
  18. )
  19. import torch
  20. import torch.distributed as dist
  21. import torch.distributed.fsdp._traversal_utils as traversal_utils
  22. import torch.nn as nn
  23. from torch.distributed._shard.sharded_tensor import ShardedTensor
  24. from torch.distributed.fsdp._common_utils import (
  25. _apply_to_modules,
  26. _FSDPState,
  27. _get_module_fsdp_state_if_fully_sharded_module,
  28. _get_param_to_fqns,
  29. _module_handles,
  30. clean_tensor_name,
  31. )
  32. from torch.distributed.fsdp._fsdp_extensions import _ext_chunk_tensor
  33. from torch.distributed.fsdp._runtime_utils import _clear_grads_if_needed, _lazy_init
  34. from torch.distributed.fsdp._shard_utils import _gather_state_dict
  35. from torch.distributed.fsdp.api import ShardingStrategy
  36. from torch.distributed.fsdp.flat_param import FlatParameter, FlatParamHandle
  37. @dataclass
  38. class FSDPParamInfo:
  39. state: _FSDPState
  40. flat_param: FlatParameter
  41. param_indices: Dict[str, int]
  42. def sorted_items(dictionary: Dict[str, Any]) -> Iterator[Tuple[str, Any]]:
  43. keys = sorted(dictionary.keys())
  44. for k in keys:
  45. yield k, dictionary[k]
  46. class _ConsolidatedOptimState:
  47. """
  48. This holds the consolidated optimizer state on the target rank. Positive-
  49. dimension tensor state is communicated across ranks, while zero-dimension
  50. tensor state and non-tensor state is taken directly from the target rank.
  51. PyTorch version 1.12 moved to using zero-dimension tensors for scalar
  52. values, but user implemented optimizers may still use float (i.e. a
  53. non-tensor). Thus, we support both and handle them identically.
  54. Attributes:
  55. tensor_state (Dict[str, torch.Tensor]): Mapping from positive-dimension
  56. tensor state name to the unsharded flattened tensor representing
  57. the state.
  58. zero_dim_tensor_state (Dict[str, torch.Tensor]): Mapping from zero-
  59. dimension tensor state name to its value.
  60. non_tensor_state (Dict[str, Any]): Mapping from non-tensor state
  61. name to its value.
  62. """
  63. tensor_state: Dict[str, torch.Tensor] = {}
  64. zero_dim_tensor_state: Dict[str, torch.Tensor] = {}
  65. non_tensor_state: Dict[str, Any] = {}
  66. class _PosDimTensorInfo(NamedTuple):
  67. """
  68. Meatadata for positive-dimension tensors used internally for
  69. :meth:`scatter_full_optim_state_dict`.
  70. Attributes:
  71. shape (torch.Size): Sharded tensor shape (which is equal to the
  72. unsharded tensor shape if the tensor is optimizer state for a
  73. non-FSDP parameter and is hence not sharded).
  74. dtype (torch.dtype): Data type of the tensor.
  75. """
  76. shape: torch.Size
  77. dtype: torch.dtype
  78. class _OptimStateKey(NamedTuple):
  79. """
  80. This represents an optimizer state key that may be used commonly across
  81. ranks. It is based on the unflattened parameter names rather than parameter
  82. IDs to make it indepenendent of each rank's own optimizer construction.
  83. """
  84. unflat_param_names: Tuple[str, ...]
  85. is_fsdp_managed: bool
  86. def _unflatten_optim_state(
  87. fsdp_param_info: FSDPParamInfo,
  88. flat_param_state: Dict[str, Any],
  89. to_save: bool,
  90. shard_state: bool,
  91. ) -> List[Dict[str, Any]]:
  92. """
  93. Unflattens the optimizer state, consisting of the "state" part and the
  94. "param_groups" part. Unflattening the "state" part involves consolidating
  95. the state on the target rank and remapping from flattened to unflattened
  96. parameter IDs, and the "param_groups" part only involves remapping from
  97. flattened to unflattened parameter IDs.
  98. Args:
  99. fsdp_param_info (FSDPParamInfo): The fsdp state and the target flatten
  100. parameter.
  101. flat_param_state (Dict[str, Any]): Entry for the flattened parameter
  102. in the "state" part of the optimizer state dict.
  103. to_save (bool): Whether to save the state on this rank.
  104. Returns:
  105. List[Dict[str, Any]]: A :class:`list` holding the entries in the
  106. "state" part of the optimizer state dict corresponding to the
  107. unflattened parameters comprising the flattened parameter if on the
  108. target rank or an empty :class:`list` otherwise. The final optimizer
  109. state dict will need to map these entries using the proper unflattened
  110. parameter IDs.
  111. """
  112. assert (
  113. not shard_state or to_save
  114. ), "If ``shard_state`` is True, ``to_save`` has to be True."
  115. consolidated_state = _communicate_optim_state(
  116. fsdp_param_info,
  117. flat_param_state,
  118. )
  119. if to_save:
  120. unflat_param_state = _unflatten_communicated_optim_state(
  121. fsdp_param_info,
  122. consolidated_state,
  123. shard_state,
  124. )
  125. for optim_state in unflat_param_state:
  126. for key in list(optim_state.keys()):
  127. state = optim_state[key]
  128. if isinstance(state, torch.Tensor):
  129. optim_state[key] = state.cpu()
  130. return unflat_param_state
  131. else:
  132. return []
  133. def _is_zero_dim_tensor(x: Any) -> bool:
  134. return torch.is_tensor(x) and x.dim() == 0
  135. def _communicate_optim_state(
  136. fsdp_param_info: FSDPParamInfo,
  137. flat_param_state: Dict[str, Any],
  138. ) -> _ConsolidatedOptimState:
  139. """
  140. Communicates the optimizer state for a flattened parameter across ranks.
  141. All ranks will hold the entire non-sharded optimizer state on GPU.
  142. If ``N`` is the number of tensor optimizer states in the optimizer state
  143. dict, then the communication complexity is 0 if ``N = 0`` and ``N + 1``
  144. otherwise (where the plus 1 comes from all-gathering the padding per rank).
  145. Args:
  146. fsdp_param_info (FSDPParamInfo): The fsdp state and the target flatten
  147. parameter.
  148. flat_param_state (Dict[str, Any]): The entry in the "state" part of the
  149. optimizer state dict corresponding to the flattened parameter.
  150. Returns:
  151. ConsolidatedOptimState: Consolidated optimizer state for the target
  152. flattened parameter.
  153. """
  154. fsdp_state = fsdp_param_info.state
  155. flat_param = fsdp_param_info.flat_param
  156. state = _ConsolidatedOptimState()
  157. tensor_state, zero_dim_tensor_state, non_tensor_state = (
  158. state.tensor_state,
  159. state.zero_dim_tensor_state,
  160. state.non_tensor_state,
  161. )
  162. for state_name, value in sorted_items(flat_param_state):
  163. # Positive-dimension tensor state: communicate across ranks
  164. if torch.is_tensor(value) and value.dim() > 0:
  165. # If the parameter is not sharded, then neither is the
  166. # positive-dimension tensor state, so no need to communicate it --
  167. # we take the target rank's value
  168. if (
  169. fsdp_state.world_size == 1
  170. or fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD
  171. ):
  172. tensor_state[state_name] = value
  173. continue
  174. if not value.is_cuda:
  175. value = value.to(fsdp_state.compute_device)
  176. # Assume that positive-dimension tensor optimizer state
  177. # has the same shape as the sharded flattened parameter
  178. buffer_size = flat_param._full_param_padded.size() # type: ignore[attr-defined]
  179. tensor_buffer = value.new_zeros(*buffer_size)
  180. dist.all_gather_into_tensor(
  181. tensor_buffer, value, group=fsdp_state.process_group
  182. )
  183. torch.cuda.synchronize()
  184. unpadded_numel = cast(
  185. nn.Parameter, flat_param._unpadded_unsharded_size
  186. ).numel()
  187. tensor_state[state_name] = tensor_buffer[:unpadded_numel]
  188. # Zero-dimension tensor state and non-tensor state: take this rank's
  189. # value directly
  190. else:
  191. if _is_zero_dim_tensor(value):
  192. zero_dim_tensor_state[state_name] = value
  193. else:
  194. non_tensor_state[state_name] = value
  195. return state
  196. def _unflatten_communicated_optim_state(
  197. fsdp_param_info: FSDPParamInfo,
  198. state: _ConsolidatedOptimState,
  199. shard_state: bool,
  200. ) -> List[Dict[str, Any]]:
  201. """
  202. Unflattens the communicated optimizer state (given by ``tensor_state``,
  203. ``non_tensor_state``, and ``zero_dim_tensor_state``) for a single flattened
  204. parameter. This should only be called on the target rank.
  205. Args:
  206. fsdp_param_info (FSDPParamInfo): The fsdp state and the target flatten
  207. parameter.
  208. state (_ConsolidatedOptimState): Consolidated optimizer state.
  209. Returns:
  210. List[Dict[str, Any]]: A :class:`list` holding the entries in the
  211. "state" part of the optimizer state dict corresponding to the
  212. unflattened parameters comprising the flattened parameter. The final
  213. optimizer state dict will need to map these entries using the proper
  214. unflattened parameter IDs.
  215. """
  216. fsdp_state = fsdp_param_info.state
  217. flat_param = fsdp_param_info.flat_param
  218. unflat_param_state: List[Dict[str, Any]] = []
  219. flat_param_views: Dict[str, Iterator] = {}
  220. num_unflat_params = flat_param._num_params
  221. tensor_state, zero_dim_tensor_state, non_tensor_state = (
  222. state.tensor_state,
  223. state.zero_dim_tensor_state,
  224. state.non_tensor_state,
  225. )
  226. for _ in range(num_unflat_params):
  227. unflat_state_param = {}
  228. # Add positive-dimension tensor state: unflatten with views
  229. for state_name, flat_tensor in sorted_items(tensor_state):
  230. views_generated = state_name in flat_param_views
  231. if not views_generated:
  232. views = FlatParamHandle._get_unflat_views(flat_param, flat_tensor)
  233. flat_param_views[state_name] = views
  234. else:
  235. views = flat_param_views[state_name]
  236. optim_state: Union[torch.Tensor, ShardedTensor] = next(views)
  237. if shard_state:
  238. assert fsdp_state.process_group is not None
  239. optim_state = _ext_chunk_tensor(
  240. optim_state,
  241. fsdp_state.rank,
  242. fsdp_state.world_size,
  243. torch.cuda.device_count(),
  244. fsdp_state.process_group,
  245. )
  246. unflat_state_param[state_name] = optim_state
  247. # Add zero-dimension tensor state: take the target rank's value
  248. for state_name, zero_dim_tensor in sorted_items(zero_dim_tensor_state):
  249. unflat_state_param[state_name] = zero_dim_tensor
  250. # Add non-tensor state: take the target rank's value
  251. for state_name, non_tensor in sorted_items(non_tensor_state):
  252. unflat_state_param[state_name] = non_tensor
  253. unflat_param_state.append(unflat_state_param)
  254. return unflat_param_state
  255. def _flatten_optim_state_dict(
  256. optim_state_dict: Dict[str, Any],
  257. model: nn.Module,
  258. shard_state: bool,
  259. use_orig_params: bool = False,
  260. optim: Optional[torch.optim.Optimizer] = None,
  261. ) -> Dict[str, Any]:
  262. """
  263. Flattens the full optimizer state dict, still keying by unflattened
  264. parameter names. If ``shard_state=True``, then FSDP-managed
  265. ``FlatParameter`` 's optimizer states are sharded, and otherwise, they are
  266. kept unsharded.
  267. If ``use_orig_params`` is True, each rank will have all FSDP-managed
  268. parameters but some of these parameters may be empty due to the sharding.
  269. For a regular optim.Optimizer, states for those empty parameters will
  270. not be initialized. So, when aggregating the FQNs across ranks, no assert
  271. will be raised on a rank even if it does not have all the states -- it is
  272. valid and FSDP know how to aggregate them. However, FSDP has to ignore
  273. handling those parameters that are not managed by FSDP and do not exist on
  274. the local rank -- it is managed by other parallelism and FSDP does not
  275. know ho to handle/aggregate them.
  276. Note that ``_flatten_tensor_optim_state`` does not need ``optim`` to
  277. flatten/shard the state. However, NamedOptimizer and KeyedOptimizer require
  278. all the states even if the corresponding parameters are empty. To this end,
  279. ``optim`` will be used to to get the initial state of the empty parameters.
  280. ``optim`` should only be non-None if the ``optim` is KeyedOptimizer or
  281. NamedOptimizer.
  282. Returns:
  283. Dict[str, Any]: The flattened optimizer state dict.
  284. """
  285. unflat_osd = optim_state_dict
  286. if "state" not in unflat_osd or "param_groups" not in unflat_osd:
  287. raise ValueError(
  288. '`optim_state_dict` must have the keys "state" and '
  289. '"param_groups" to be a valid optimizer state dict'
  290. )
  291. param_to_fqns = _get_param_to_fqns(model)
  292. fqn_to_fsdp_param_info = _get_fqn_to_fsdp_param_info(model)
  293. # Construct the "state" part
  294. flat_osd_state: Dict[Union[_OptimStateKey, str], Any] = {}
  295. unflat_osd_state = unflat_osd["state"]
  296. all_state_keys = set(unflat_osd_state.keys())
  297. # local_state_dict is used to construct states of empty parameters.
  298. # This should only be used if is_named_optimizer=True.
  299. local_state_dict: Dict[str, Any] = {}
  300. local_state_clean_fqns: Dict[str, str] = {}
  301. if optim is not None:
  302. local_state_dict = optim.state_dict()["state"]
  303. for fqn in local_state_dict.keys():
  304. clean_fqn = clean_tensor_name(fqn)
  305. local_state_clean_fqns[clean_fqn] = fqn
  306. for param, unflat_param_names in param_to_fqns.items():
  307. fqn = unflat_param_names[0]
  308. if fqn not in unflat_osd_state:
  309. continue
  310. all_state_keys.difference_update(unflat_param_names)
  311. if fqn in fqn_to_fsdp_param_info:
  312. fsdp_param_info = fqn_to_fsdp_param_info[fqn]
  313. if use_orig_params:
  314. assert (
  315. shard_state
  316. ), "If use_orig_params is True, shard_state must be True."
  317. flat_state = _shard_orig_param_state(
  318. fsdp_param_info,
  319. fqn,
  320. unflat_osd_state[fqn],
  321. )
  322. else:
  323. flat_state = _flatten_optim_state(
  324. fsdp_param_info,
  325. unflat_osd_state,
  326. unflat_param_names,
  327. shard_state,
  328. )
  329. key = _OptimStateKey(tuple(unflat_param_names), True)
  330. # Only include non-empty states since as expected by
  331. # `torch.optim.Optimizer` s unless the optimizer is KeyedOptimizer
  332. # or NamedOptimizer.
  333. if flat_state:
  334. flat_osd_state[key] = flat_state
  335. elif optim is not None: # NamedOptimizer or KeyedOptimizer case.
  336. assert len(unflat_param_names) == 1
  337. local_wrapped_fqn = local_state_clean_fqns.get(fqn, "")
  338. if local_wrapped_fqn:
  339. flat_osd_state[key] = copy.deepcopy(
  340. local_state_dict[local_wrapped_fqn]
  341. )
  342. else: # do not flatten non-FSDP parameters' states
  343. assert len(unflat_param_names) == 1
  344. key = _OptimStateKey(tuple(unflat_param_names), False)
  345. flat_osd_state[key] = copy.copy(unflat_osd_state[fqn])
  346. # Handle user-defined state, states that are not accosiated with parameters.
  347. for key in all_state_keys:
  348. flat_osd_state[key] = copy.copy(unflat_osd_state[key])
  349. # Construct the "param_groups" part -- copy as is since it will be
  350. # rekeyed later according to the target rank's optimizer
  351. flat_osd_param_groups = copy.deepcopy(unflat_osd["param_groups"])
  352. return {"state": flat_osd_state, "param_groups": flat_osd_param_groups}
  353. def _flatten_optim_state(
  354. fsdp_param_info: FSDPParamInfo,
  355. unflat_osd_state: Dict[str, Dict[str, Any]],
  356. unflat_param_names: List[str],
  357. shard_state: bool,
  358. ) -> Dict[str, Any]:
  359. """
  360. Flattens the optimizer state in ``full_optim_state_dict`` for a single
  361. flattened parameter in ``fsdp_param_info`` corresponding to the unflattened
  362. parameter names in ``unflat_param_names``.
  363. Args:
  364. unflat_osd_state (Dict[str, Dict[str, Any]]): The "state" part of the
  365. optimizer state dict corresponding to the unflattened parameters.
  366. unflat_param_names (List[str]): A :class:`list` of unflattened
  367. parameter names corresponding to the flattened parameter
  368. ``flat_param``.
  369. fsdp_param_info (FSDPParamInfo): The fsdp state and the target flatten
  370. parameter.
  371. shard_state (bool): Whether to shard flattened positive-dimension
  372. tensor state; if ``False``, then the full flattened tensor is
  373. kept in the returned :class:`dict.
  374. Returns:
  375. Dict[str, Any]: A :class:`dict` mapping state names to their values for
  376. a particular flattened parameter. The sharded optimizer state dict's
  377. "state" part will map a key to this returned value.
  378. """
  379. fsdp_state = fsdp_param_info.state
  380. flat_param = fsdp_param_info.flat_param
  381. num_unflat_params = len(unflat_param_names)
  382. assert num_unflat_params > 0, (
  383. "Expects at least one unflattened parameter corresponding to the "
  384. "flattened parameter"
  385. )
  386. unflat_param_shapes = flat_param._shapes
  387. num_unflat_param_shapes = len(unflat_param_shapes)
  388. assert (
  389. num_unflat_params == num_unflat_param_shapes
  390. ), f"Expects {num_unflat_params} shapes but got {num_unflat_param_shapes}"
  391. # Check if these unflattened parameters have any optimizer state
  392. has_state = [
  393. bool(unflat_param_name in unflat_osd_state)
  394. for unflat_param_name in unflat_param_names
  395. ]
  396. # If none of the unflattened parameters comprising this flattened parameter
  397. # have any state, then we do not want an entry in the optimizer state dict
  398. if not any(has_state):
  399. return {} # no need to flatten any state
  400. # There may still be some unflattened parameters with state and some
  401. # without
  402. unflat_param_states = [
  403. _gather_state_dict(
  404. unflat_osd_state[unflat_param_name], pg=fsdp_state.process_group
  405. )
  406. if unflat_param_name in unflat_osd_state
  407. else None
  408. for unflat_param_name in unflat_param_names
  409. ]
  410. # Check that the unflattened parameters have the same state names
  411. state_names = None
  412. for unflat_param_state in unflat_param_states:
  413. if unflat_param_state is None:
  414. continue
  415. if state_names is None:
  416. state_names = set(unflat_param_state.keys())
  417. else:
  418. if state_names != set(unflat_param_state.keys()):
  419. raise ValueError(
  420. "Differing optimizer state names for the unflattened "
  421. f"parameters: {unflat_param_names}"
  422. )
  423. assert state_names is not None
  424. # Flatten the state
  425. flat_state: Dict[str, Any] = {}
  426. for state_name in state_names:
  427. state_values = [
  428. unflat_param_state[state_name] if unflat_param_state is not None else None
  429. for unflat_param_state in unflat_param_states
  430. ]
  431. non_none_state_values = [v for v in state_values if v is not None]
  432. are_pos_dim_tensors = are_zero_dim_tensors = are_non_tensors = True
  433. for v in non_none_state_values:
  434. are_pos_dim_tensors &= torch.is_tensor(v) and v.dim() > 0
  435. are_zero_dim_tensors &= _is_zero_dim_tensor(v)
  436. are_non_tensors &= not torch.is_tensor(v)
  437. types = {type(v) for v in non_none_state_values}
  438. if len(types) != 1 or not (
  439. are_pos_dim_tensors or are_zero_dim_tensors or are_non_tensors
  440. ):
  441. raise ValueError(
  442. f"Differing optimizer state types for state {state_name}, "
  443. f"values {non_none_state_values}, and unflattened parameter "
  444. f"names {unflat_param_names}"
  445. )
  446. if are_pos_dim_tensors:
  447. flat_tensor = _flatten_tensor_optim_state(
  448. state_name,
  449. state_values,
  450. unflat_param_names,
  451. unflat_param_shapes,
  452. flat_param,
  453. )
  454. if shard_state:
  455. # Shard the flattened tensor immediately to minimize max memory
  456. # usage
  457. sharded_flat_tensor, _ = FlatParamHandle._get_shard(
  458. flat_tensor,
  459. fsdp_state.rank,
  460. fsdp_state.world_size,
  461. )
  462. flat_state[state_name] = sharded_flat_tensor
  463. else:
  464. flat_state[state_name] = flat_tensor
  465. elif are_zero_dim_tensors:
  466. flat_state[state_name] = _flatten_zero_dim_tensor_optim_state(
  467. state_name,
  468. state_values,
  469. unflat_param_names,
  470. )
  471. else:
  472. assert are_non_tensors
  473. flat_state[state_name] = _flatten_non_tensor_optim_state(
  474. state_name,
  475. state_values,
  476. unflat_param_names,
  477. )
  478. return flat_state
  479. def _flatten_tensor_optim_state(
  480. state_name: str,
  481. pos_dim_tensors: List[torch.Tensor],
  482. unflat_param_names: List[str],
  483. unflat_param_shapes: Sequence[torch.Size],
  484. flat_param: FlatParameter,
  485. ) -> torch.Tensor:
  486. """
  487. Flattens the positive-dimension tensor optimizer state given by the values
  488. ``tensors`` for the state ``state_name`` for a single flattened parameter
  489. ``flat_param`` corresponding to the unflattened parameter names
  490. ``unflat_param_names`` and unflatted parameter shapes
  491. ``unflat_param_shapes``. This flattens each unflattened parameter's tensor
  492. state into one tensor.
  493. NOTE: We use zero tensors for any unflattened parameters without state
  494. since some value is required to fill those entries. This assumes that the
  495. zero tensor is mathematically equivalent to having no state, which is true
  496. for Adam's "exp_avg" and "exp_avg_sq" but may not be true for all
  497. optimizers.
  498. Args:
  499. state_name (str): Optimizer state name.
  500. pos_dim_tensors (List[torch.Tensor]): Positive-dimension tensor
  501. optimizer state values for the unflattened parameters corresponding
  502. to the single flattened parameter.
  503. unflat_param_names (List[str]): A :class:`list` of unflattened
  504. parameter names corresponding to the single flattened parameter.
  505. unflat_param_shapes (List[torch.Size]): Unflattened parameter shapes
  506. corresponding to the single flattened parameter.
  507. flat_param (FlatParameter): The flattened parameter.
  508. Returns:
  509. torch.Tensor: A flattened tensor containing the optimizer state
  510. corresponding to ``state_name`` constructed by concatenating the
  511. unflattened parameter tensor states in ``pos_dim_tensors`` (using zero
  512. tensors for any unflattened parameters without the state).
  513. """
  514. non_none_tensors = [t for t in pos_dim_tensors if t is not None]
  515. # Check that all are tensors with the same dtype
  516. dtypes = {t.dtype for t in non_none_tensors}
  517. if len(dtypes) != 1:
  518. raise ValueError(
  519. "All unflattened parameters comprising a single flattened "
  520. "parameter must have positive-dimension tensor state with the "
  521. f"same dtype but got dtypes {dtypes} for state {state_name} and "
  522. f"unflattened parameter names {unflat_param_names}"
  523. )
  524. dtype = next(iter(dtypes))
  525. # Check that each tensor state matches its parameter's shape
  526. for tensor, shape in zip(pos_dim_tensors, unflat_param_shapes):
  527. if tensor is None and len(shape) == 0:
  528. raise ValueError("Flattening a zero-dimension parameter is not supported")
  529. elif tensor is not None and tensor.shape != shape:
  530. raise ValueError(
  531. "Tensor optimizer state does not have same shape as its "
  532. f"parameter: {tensor.shape} {shape}"
  533. )
  534. # Flatten the tensor states: we do not need to add any padding since the
  535. # flattened optimizer state tensor sharded via `_get_shard()`, which pads
  536. # the shard as needed (just like for the flattened parameter)
  537. cpu_device = torch.device("cpu")
  538. tensors = [
  539. torch.flatten(state_value.to(cpu_device))
  540. if state_value is not None
  541. else torch.flatten(
  542. torch.zeros(
  543. size=shape,
  544. dtype=dtype,
  545. device=cpu_device,
  546. )
  547. )
  548. for state_value, shape in zip(pos_dim_tensors, unflat_param_shapes)
  549. ]
  550. flat_tensor = torch.cat(tensors)
  551. flat_param_shape = flat_param._unpadded_unsharded_size # type: ignore[attr-defined]
  552. assert flat_tensor.shape == flat_param_shape, (
  553. f"tensor optim state: {flat_tensor.shape} "
  554. f"flattened parameter: {flat_param_shape}"
  555. )
  556. return flat_tensor
  557. def _flatten_zero_dim_tensor_optim_state(
  558. state_name: str,
  559. zero_dim_tensors: List[torch.Tensor],
  560. unflat_param_names: List[str],
  561. ) -> torch.Tensor:
  562. """
  563. Flattens the zero-dimension tensor optimizer state given by the values
  564. ``zero_dim_tensors`` for the state ``state_name`` for a single flattened
  565. parameter corresponding to the unflattened parameter names
  566. ``unflat_param_names`` by enforcing that all tensors are the same and using
  567. that common value.
  568. NOTE: The requirement that the tensors are the same across all unflattened
  569. parameters comprising the flattened parameter is needed to maintain the
  570. invariant that FSDP performs the same computation as its non-sharded
  571. equivalent. This means that none of the unflattened parameters can be
  572. missing this state since imposing a value may differ from having no value.
  573. For example, for Adam's "step", no value means maximum bias correction,
  574. while having some positive value means less bias correction.
  575. Args:
  576. state_name (str): Optimizer state name.
  577. zero_dim_tensors (List[torch.Tensor]): Zero-dimension optimizer state
  578. for the unflattened parameters corresponding to the single
  579. flattened parameter.
  580. unflat_param_names (List[str]): A :class:`list` of unflattened
  581. parameter names corresponding to the single flattened parameter.
  582. Returns:
  583. torch.Tensor: A zero-dimensional tensor giving the value of the state
  584. ``state_name`` for all unflattened parameters corresponding to the
  585. names ``unflat_param_names``.
  586. """
  587. non_none_tensors = [t for t in zero_dim_tensors if t is not None]
  588. # Enforce that all have the same value and dtype
  589. values_set = {t.item() if t is not None else None for t in zero_dim_tensors}
  590. dtypes = {t.dtype if t is not None else None for t in zero_dim_tensors}
  591. if (
  592. len(non_none_tensors) != len(zero_dim_tensors)
  593. or len(values_set) != 1
  594. or len(dtypes) != 1
  595. ):
  596. raise ValueError(
  597. "All unflattened parameters comprising a single flattened "
  598. "parameter must have scalar state with the same value and dtype "
  599. f"but got values {values_set} and dtypes {dtypes} for state "
  600. f"{state_name} and unflattened parameter names "
  601. f"{unflat_param_names}"
  602. )
  603. value = next(iter(values_set))
  604. dtype = next(iter(dtypes))
  605. return torch.tensor(value, dtype=dtype, device=torch.device("cpu"))
  606. def _flatten_non_tensor_optim_state(
  607. state_name: str,
  608. non_tensors: List[Any],
  609. unflat_param_names: List[str],
  610. ) -> Any:
  611. """
  612. Flattens the non-tensor optimizer state given by the values ``non_tensors``
  613. for the state ``state_name`` for a single flattened parameter corresponding
  614. to the unflattened parameter names ``unflat_param_names`` by enforcing that
  615. all values are the same and using that common value.
  616. See the note in :func:`_flatten_zero_dim_tensor_optim_state`.
  617. Args:
  618. state_name (str): Optimizer state name.
  619. non_tensors (List[Any]): Non-tensor optimizer state for the unflattened
  620. parameters corresponding to the single flattened parameter.
  621. unflat_param_names (List[str]): A :class:`list` of unflattened
  622. parameter names corresponding to the single flattened parameter.
  623. Returns:
  624. Any: A non-tensor giving the value of the state ``state_name`` for all
  625. unflattened parameters corresponding to the names
  626. ``unflat_param_names``.
  627. """
  628. non_none_non_tensors = [nt for nt in non_tensors if nt is not None]
  629. # Enforce that all have the same value (same type already checked)
  630. non_tensor_set = set(non_tensors)
  631. if len(non_none_non_tensors) != len(non_tensors) or len(non_tensor_set) != 1:
  632. raise ValueError(
  633. "All unflattened parameters comprising a single flattened "
  634. "parameter must have scalar state with the same value and dtype "
  635. f"but got values {non_tensor_set} for state {state_name} and "
  636. f"unflattened parameter names {unflat_param_names}"
  637. )
  638. non_tensor = next(iter(non_tensor_set))
  639. return non_tensor
  640. def _process_pos_dim_tensor_state(
  641. flat_optim_state_dict: Dict[str, Any],
  642. world_size: int,
  643. ) -> Dict[str, Any]:
  644. """
  645. Processes positive-dimension tensor states in ``flat_optim_state_dict`` by
  646. replacing them with metadata. This is done so the processed optimizer state
  647. dict can be broadcast from rank 0 to all ranks without copying those tensor
  648. states, and thus, this is meant to only be called on rank 0.
  649. Args:
  650. flat_optim_state_dict (Dict[str, Any]): Flattened optimizer state dict
  651. with the positive-dimension tensor states unsharded.
  652. Returns:
  653. Dict[str, Any]: The flattened optimizer state dict with positive-
  654. dimension tensor states replaced by metadata.
  655. """
  656. flat_osd = flat_optim_state_dict # alias
  657. no_tensor_osd: Dict[str, Any] = {"state": {}}
  658. for key, param_state in flat_osd["state"].items():
  659. no_tensor_osd["state"][key] = {}
  660. for state_name, value in sorted_items(param_state):
  661. is_pos_dim_tensor_state = torch.is_tensor(value) and value.dim() > 0
  662. if not is_pos_dim_tensor_state:
  663. no_tensor_osd["state"][key][state_name] = value
  664. continue
  665. if key.is_fsdp_managed: # FSDP parameter
  666. sharded_size = FlatParamHandle._get_sharded_size(
  667. value, rank=0, world_size=world_size
  668. )
  669. assert len(sharded_size) == 1, f"{sharded_size}"
  670. info = _PosDimTensorInfo(sharded_size, value.dtype)
  671. else: # non-FSDP parameter
  672. info = _PosDimTensorInfo(value.shape, value.dtype)
  673. no_tensor_osd["state"][key][state_name] = info
  674. no_tensor_osd["param_groups"] = flat_osd["param_groups"]
  675. return no_tensor_osd
  676. def _broadcast_processed_optim_state_dict(
  677. processed_optim_state_dict: Optional[Dict[str, Any]],
  678. rank: int,
  679. group,
  680. ) -> Dict[str, Any]:
  681. """
  682. Broadcasts the processed optimizer state dict from rank 0 to all ranks.
  683. Args:
  684. processed_optim_state_dict (Optional[Dict[str, Any]]): The flattened
  685. optimizer state dict with positive-dimension tensor states replaced
  686. with metadata if on rank 0; ignored otherwise.
  687. Returns:
  688. Dict[str, Any]: The processed optimizer state dict.
  689. """
  690. # Broadcast the two data structures rank 0 to all ranks
  691. obj_list = [processed_optim_state_dict] if rank == 0 else [None]
  692. dist.broadcast_object_list(obj_list, src=0, group=group)
  693. processed_optim_state_dict = obj_list[0] # type: ignore[assignment]
  694. assert processed_optim_state_dict is not None
  695. # Keep zero-dimension tensors on CPU
  696. return processed_optim_state_dict
  697. def _broadcast_pos_dim_tensor_states(
  698. processed_optim_state_dict: Dict[str, Any],
  699. flat_optim_state_dict: Optional[Dict[str, Any]],
  700. rank: int,
  701. world_size: int,
  702. group,
  703. broadcast_device: torch.device,
  704. ) -> Dict[str, Any]:
  705. """
  706. Takes ``processed_optim_state_dict``, which has metadata in place of
  707. positive-dimension tensor states, and broadcasts those tensor states from
  708. rank 0 to all ranks. For tensor states corresponding to FSDP parameters,
  709. rank 0 shards the tensor and broadcasts shard-by-shard, and for tensor
  710. states corresponding to non-FSDP parameters, rank 0 broadcasts the full
  711. tensor.
  712. Args:
  713. processed_optim_state_dict (Dict[str, Any]): The flattened optimizer
  714. state dict with positive-dimension tensor states replaced with
  715. metadata; this should be returned by
  716. :meth:`_process_pos_dim_tensor_state` and non-empty on all ranks.
  717. flat_optim_state_dict (Optional[Dict[str, Any]]): The flattened
  718. unsharded optimizer state dict with the actual positive-dimension
  719. tensor states if on rank 0; ignored on nonzero ranks.
  720. Returns:
  721. Dict[str, Any]: The optimizer state dict with the positive-dimension
  722. tensor state correctly populated via ``broadcast()`` s from rank 0.
  723. """
  724. assert (
  725. rank != 0 or flat_optim_state_dict is not None
  726. ), "Expects rank 0 to pass in the flattened optimizer state dict"
  727. no_tensor_osd = processed_optim_state_dict # alias
  728. flat_osd = flat_optim_state_dict # alias
  729. for key, param_state in no_tensor_osd["state"].items():
  730. for state_name, value in sorted_items(param_state):
  731. is_pos_dim_tensor_state = isinstance(value, _PosDimTensorInfo)
  732. if not is_pos_dim_tensor_state:
  733. continue
  734. if rank == 0:
  735. assert flat_osd is not None
  736. unsharded_tensor = flat_osd["state"][key][state_name]
  737. else:
  738. unsharded_tensor = None
  739. shape, dtype = value.shape, value.dtype
  740. if key.is_fsdp_managed: # FSDP parameter
  741. _broadcast_sharded_pos_dim_tensor_state(
  742. unsharded_tensor,
  743. param_state,
  744. state_name,
  745. shape,
  746. dtype,
  747. broadcast_device,
  748. rank,
  749. world_size,
  750. group,
  751. ) # modify `param_state` destructively
  752. else: # non-FSDP parameter
  753. _broadcast_unsharded_pos_dim_tensor_state(
  754. unsharded_tensor,
  755. param_state,
  756. state_name,
  757. shape,
  758. dtype,
  759. broadcast_device,
  760. rank,
  761. group,
  762. ) # modify `param_state` destructively
  763. return no_tensor_osd
  764. def _broadcast_sharded_pos_dim_tensor_state(
  765. unsharded_tensor: Optional[torch.Tensor],
  766. param_state: Dict[str, Any],
  767. state_name: str,
  768. shape: torch.Size,
  769. dtype: torch.dtype,
  770. broadcast_device: torch.device,
  771. rank: int,
  772. world_size: int,
  773. group,
  774. ) -> None:
  775. """
  776. Broadcasts positive-dimension tensor state for the state ``state_name``
  777. corresponding to an FSDP parameter shard-by-shard, only to be saved on the
  778. relevant rank. This modifies ``param_state`` destructively.
  779. Args:
  780. unsharded_tensor (Optional[torch.Tensor]): Unsharded tensor from which
  781. to broadcast shards if on rank 0; ignored otherwise.
  782. shape (torch.Size): Shape of the sharded tensor; same on all ranks.
  783. """
  784. get_shard: Optional[functools.partial[Tuple[torch.Tensor, int]]] = None
  785. if rank == 0:
  786. assert (
  787. unsharded_tensor is not None
  788. ), "Expects rank 0 to pass in the unsharded tensor"
  789. get_shard = functools.partial(
  790. FlatParamHandle._get_shard,
  791. unsharded_tensor,
  792. )
  793. for target_rank in range(1, world_size):
  794. if rank == 0:
  795. assert get_shard is not None
  796. sharded_tensor = get_shard(target_rank, world_size)[0].to(broadcast_device)
  797. else:
  798. sharded_tensor = torch.zeros(
  799. shape,
  800. requires_grad=False,
  801. dtype=dtype,
  802. device=broadcast_device,
  803. )
  804. dist.broadcast(sharded_tensor, src=0, group=group)
  805. # Only keep the shard on the target rank and keep it on the broadcast
  806. # device, which is typically GPU
  807. if rank == target_rank:
  808. param_state[state_name] = sharded_tensor
  809. else:
  810. del sharded_tensor
  811. # Lastly, shard on rank 0
  812. if rank != 0:
  813. return
  814. param_state[state_name] = get_shard(0, world_size)[0].to(broadcast_device) # type: ignore[misc]
  815. def _broadcast_unsharded_pos_dim_tensor_state(
  816. unsharded_tensor: Optional[torch.Tensor],
  817. param_state: Dict[str, Any],
  818. state_name: str,
  819. shape: torch.Size,
  820. dtype: torch.dtype,
  821. broadcast_device: torch.device,
  822. rank: int,
  823. group,
  824. ) -> None:
  825. """
  826. Broadcasts positive-dimension tensor state for the state ``state_name``
  827. corresponding to an unsharded non-FSDP parameter from rank 0 to all ranks.
  828. This modifies ``param_state`` destructively.
  829. Args:
  830. unsharded_tensor (Optional[torch.Tensor]): Unsharded tensor to
  831. broadcast if on rank 0; ignored otherwise.
  832. """
  833. if rank == 0:
  834. assert (
  835. unsharded_tensor is not None
  836. ), "Expects rank 0 to pass in the unsharded tensor"
  837. assert (
  838. shape == unsharded_tensor.shape
  839. ), f"Shape mismatch: {shape} {unsharded_tensor.shape}"
  840. assert (
  841. dtype == unsharded_tensor.dtype
  842. ), f"dtype mismatch: {dtype} {unsharded_tensor.dtype}"
  843. unsharded_tensor = unsharded_tensor.to(broadcast_device)
  844. else:
  845. unsharded_tensor = torch.zeros(
  846. shape,
  847. requires_grad=False,
  848. dtype=dtype,
  849. device=broadcast_device,
  850. )
  851. dist.broadcast(unsharded_tensor, src=0, group=group)
  852. # Keep the tensor on the broadcast device, which is typically GPU
  853. param_state[state_name] = unsharded_tensor
  854. def _rekey_sharded_optim_state_dict(
  855. sharded_osd: Dict[str, Any],
  856. model: nn.Module,
  857. optim: torch.optim.Optimizer,
  858. optim_input: Optional[
  859. Union[
  860. List[Dict[str, Any]],
  861. Iterable[nn.Parameter],
  862. ]
  863. ],
  864. using_optim_input: bool,
  865. is_named_optimizer: bool = False,
  866. ) -> Dict[str, Any]:
  867. """
  868. Rekeys the optimizer state dict from unflattened parameter names to
  869. flattened parameter IDs according to the calling rank's ``optim``, which
  870. may be different across ranks. In particular, the unflattened parameter
  871. names are represented as :class:`_OptimStateKey` s.
  872. """
  873. param_to_fqns = _get_param_to_fqns(model)
  874. flat_param_to_fqn = _get_flat_param_to_fqn(model)
  875. param_to_param_key: Dict[nn.Parameter, Union[int, str]] = cast(
  876. Dict[nn.Parameter, Union[int, str]],
  877. (
  878. _get_param_to_param_id_from_optim_input(model, optim_input)
  879. if using_optim_input
  880. else _get_param_to_param_key(
  881. optim, model, is_named_optimizer, param_to_fqns, flat_param_to_fqn
  882. )
  883. ),
  884. )
  885. # All parameter keys in `param_to_param_key` should be in
  886. # `param_to_fqns` -- strict inequality follows when not all parameters are
  887. # passed to the optimizer
  888. assert len(param_to_param_key) <= len(param_to_fqns)
  889. unflat_param_names_to_flat_param_key: Dict[
  890. Tuple[str, ...], Union[int, str]
  891. ] = {} # for "state"
  892. unflat_param_name_to_flat_param_key: Dict[
  893. str, Union[int, str]
  894. ] = {} # for "param_groups"
  895. for param, unflat_param_names in param_to_fqns.items():
  896. if param not in param_to_param_key:
  897. # This parameter was not passed to the optimizer
  898. continue
  899. flat_param_key = param_to_param_key[param]
  900. unflat_param_names_to_flat_param_key[tuple(unflat_param_names)] = flat_param_key
  901. for unflat_param_name in unflat_param_names:
  902. unflat_param_name_to_flat_param_key[unflat_param_name] = flat_param_key
  903. sharded_osd_state = sharded_osd["state"]
  904. rekeyed_osd_state: Dict[Union[str, int], Any] = {}
  905. for key, param_state in sharded_osd_state.items():
  906. if isinstance(key, str):
  907. rekeyed_osd_state[key] = param_state
  908. continue
  909. flat_param_key = unflat_param_names_to_flat_param_key.get(
  910. key.unflat_param_names, key.unflat_param_names
  911. )
  912. rekeyed_osd_state[flat_param_key] = param_state
  913. rekeyed_osd_param_groups: List[Dict[str, Any]] = []
  914. for unflat_param_group in sharded_osd["param_groups"]:
  915. flat_param_group = copy.deepcopy(unflat_param_group)
  916. flat_param_keys = sorted(
  917. {
  918. unflat_param_name_to_flat_param_key[unflat_param_name]
  919. for unflat_param_name in unflat_param_group["params"]
  920. }
  921. )
  922. flat_param_group["params"] = flat_param_keys
  923. rekeyed_osd_param_groups.append(flat_param_group)
  924. return {"state": rekeyed_osd_state, "param_groups": rekeyed_osd_param_groups}
  925. def _get_param_id_to_param_from_optim_input(
  926. model: nn.Module,
  927. optim_input: Optional[
  928. Union[
  929. List[Dict[str, Any]],
  930. Iterable[nn.Parameter],
  931. ]
  932. ] = None,
  933. ) -> Dict[int, nn.Parameter]:
  934. """
  935. Constructs a mapping from parameter IDs to parameters. This may be used
  936. both for models with ``FlatParameter`` s and without.
  937. NOTE: This method is only preserved for backward compatibility. The method
  938. :meth:`_get_param_key_to_param` is the preferred code path that does not
  939. rely on ``optim_input``.
  940. NOTE: We critically assume that, whether the optimizer input is a list of
  941. parameters or a list of parameter groups, :class:`torch.optim.Optimizer`
  942. enumerates the parameter IDs in order. In other words, for a parameter list
  943. input, the parameter IDs should be in that list order, and for a parameter
  944. groups input, the parameter IDs should be in order within each parameter
  945. group and in order across parameter groups.
  946. Args:
  947. model (nn.Module): Model whose parameters are passed into the
  948. optimizer.
  949. optim_input (Optional[Union[List[Dict[str, Any]],
  950. Iterable[nn.Parameter]]]): Input passed into the optimizer
  951. representing either a :class:`list` of parameter groups or an
  952. iterable of parameters; if ``None``, then this method assumes the
  953. input was ``model.parameters()``. (Default: ``None``)
  954. Returns:
  955. List[nn.Parameter]: Mapping from parameter IDs to parameters,
  956. where the parameter ID is implicitly the index in the :class:`list`.
  957. """
  958. # Assume the standard case of passing `model.parameters()` to the optimizer
  959. # if `optim_input` is not specified
  960. if optim_input is None:
  961. return {pid: param for pid, param in enumerate(model.parameters())}
  962. try:
  963. params = cast(List[nn.Parameter], list(optim_input))
  964. except TypeError as e:
  965. raise TypeError(
  966. "Optimizer input should be an iterable of Tensors or dicts, "
  967. f"but got {optim_input}"
  968. ) from e
  969. if len(params) == 0:
  970. raise ValueError("Optimizer input should not be empty")
  971. # Check if the optimizer input represents tensors or parameter groups
  972. all_tensors = True
  973. all_dicts = True
  974. for param in params:
  975. all_tensors &= isinstance(param, torch.Tensor)
  976. all_dicts &= isinstance(param, dict)
  977. if not all_tensors and not all_dicts:
  978. raise TypeError("Optimizer input should be an iterable of Tensors or dicts")
  979. if all_tensors:
  980. return {pid: param for pid, param in enumerate(params)}
  981. assert all_dicts
  982. param_id_to_param: List[nn.Parameter] = []
  983. for param_group in params:
  984. has_params_key = "params" in param_group # type: ignore[operator]
  985. assert has_params_key, (
  986. 'A parameter group should map "params" to a list of the '
  987. "parameters in the group"
  988. )
  989. for param in param_group["params"]: # type: ignore[index]
  990. # Implicitly map `flat_param_id` (current length of the list) to
  991. # `param`
  992. param_id_to_param.append(param)
  993. return {pid: param for pid, param in enumerate(param_id_to_param)}
  994. def _get_flat_param_to_fqn(model: torch.nn.Module) -> Dict[nn.Parameter, str]:
  995. def module_fn(module, prefix, flat_param_to_fqn):
  996. for param_name, param in module.named_parameters(recurse=False):
  997. if type(param) is not FlatParameter:
  998. continue
  999. fqn = clean_tensor_name(prefix + param_name)
  1000. flat_param_to_fqn[param] = fqn
  1001. def return_fn(flat_param_to_fqn):
  1002. return flat_param_to_fqn
  1003. flat_param_to_fqn_ret: Dict[torch.nn.Parameter, str] = {}
  1004. return _apply_to_modules(
  1005. model,
  1006. module_fn,
  1007. return_fn,
  1008. [fqn for fqn, _ in model.named_parameters()],
  1009. flat_param_to_fqn_ret,
  1010. )
  1011. def _get_param_key_to_param(
  1012. optim: torch.optim.Optimizer,
  1013. model: Optional[nn.Module] = None,
  1014. is_named_optimizer: bool = False,
  1015. param_to_fqns: Optional[Dict[nn.Parameter, List[str]]] = None,
  1016. flat_param_to_fqn: Optional[Dict[nn.Parameter, str]] = None,
  1017. ) -> Dict[Union[int, str], nn.Parameter]:
  1018. """
  1019. Constructs a mapping from parameter keys to parameters. For the regular
  1020. optimizers, the keys are parameter IDs. For NamedOptimizer, the keys
  1021. are FQNs. This API may be used both for models with ``FlatParameter`` s and
  1022. without.
  1023. """
  1024. clean_fqn_to_curr_fqn: Dict[str, str] = {}
  1025. if is_named_optimizer:
  1026. assert (
  1027. param_to_fqns is not None and flat_param_to_fqn is not None
  1028. ), "The optimizer is a NamedOptimizer, `param_to_fqns` must not be None."
  1029. assert model is not None
  1030. for key, _ in model.named_parameters():
  1031. clean_fqn_to_curr_fqn[clean_tensor_name(key)] = key
  1032. param_key_to_param: Dict[Union[str, int], nn.Parameter] = {}
  1033. pid = 0
  1034. for param_group in optim.param_groups:
  1035. if is_named_optimizer:
  1036. for param in param_group["params"]:
  1037. assert flat_param_to_fqn is not None
  1038. if param in flat_param_to_fqn:
  1039. # FlatParameter case
  1040. key = flat_param_to_fqn[param]
  1041. else:
  1042. assert param_to_fqns is not None
  1043. # use_orig_params case
  1044. assert len(param_to_fqns[param]) == 1
  1045. key = param_to_fqns[param][0]
  1046. key = clean_fqn_to_curr_fqn[key]
  1047. param_key_to_param[key] = param
  1048. else:
  1049. for param in param_group["params"]:
  1050. param_key_to_param[pid] = param
  1051. pid += 1
  1052. return param_key_to_param
  1053. def _get_param_to_param_key(
  1054. optim: torch.optim.Optimizer,
  1055. model: Optional[nn.Module] = None,
  1056. is_named_optimizer: bool = False,
  1057. param_to_fqns: Optional[Dict[nn.Parameter, List[str]]] = None,
  1058. flat_param_to_fqn: Optional[Dict[nn.Parameter, str]] = None,
  1059. ) -> Dict[nn.Parameter, Union[int, str]]:
  1060. """
  1061. Constructs the inverse mapping of :func:`_get_param_key_to_param`. This API
  1062. only supports the case where `optim` is a regular optimizer, not NamedOptimizer.
  1063. So the parameter keys will be parameter id.
  1064. """
  1065. param_id_to_param = _get_param_key_to_param(
  1066. optim, model, is_named_optimizer, param_to_fqns, flat_param_to_fqn
  1067. )
  1068. return {param: param_id for param_id, param in param_id_to_param.items()}
  1069. def _get_param_to_param_id_from_optim_input(
  1070. model: nn.Module,
  1071. optim_input: Optional[
  1072. Union[
  1073. List[Dict[str, Any]],
  1074. Iterable[nn.Parameter],
  1075. ]
  1076. ] = None,
  1077. ) -> Dict[nn.Parameter, int]:
  1078. """Constructs the inverse mapping of :func:`_get_param_id_to_param_from_optim_input`."""
  1079. param_id_to_param = _get_param_id_to_param_from_optim_input(model, optim_input)
  1080. return {param: param_id for param_id, param in param_id_to_param.items()}
  1081. def _check_missing_keys_on_rank(
  1082. r0_optim_state_keys: List[_OptimStateKey],
  1083. optim_state_key_to_param_key: Dict[_OptimStateKey, Union[str, int]],
  1084. param_key_to_param: Dict[Union[str, int], nn.Parameter],
  1085. group: Optional[dist.ProcessGroup],
  1086. ) -> None:
  1087. # Ensure that all ranks have at least the optimizer states needed by
  1088. # rank 0's optimizer
  1089. missing_keys: List[_OptimStateKey] = []
  1090. for r0_optim_state_key in r0_optim_state_keys:
  1091. if r0_optim_state_key not in optim_state_key_to_param_key:
  1092. # A parameter from rank 0's optimizer does not exist for this
  1093. # rank's optimizer
  1094. missing_keys.append(r0_optim_state_key)
  1095. continue
  1096. param_key = optim_state_key_to_param_key[r0_optim_state_key]
  1097. if isinstance(param_key, int):
  1098. assert param_key >= 0 and param_key < len(
  1099. param_key_to_param
  1100. ), "Check the `param_key_to_param` construction"
  1101. device = torch.device("cuda", torch.cuda.current_device())
  1102. num_missing = torch.tensor([len(missing_keys)], dtype=torch.int32, device=device)
  1103. dist.all_reduce(num_missing, group=group)
  1104. if num_missing.item() > 0:
  1105. obj_list = [None for _ in range(dist.get_world_size(group))]
  1106. dist.all_gather_object(obj_list, missing_keys, group=group)
  1107. error_msg = (
  1108. "FSDP currently requires each rank to have at least the "
  1109. "optimizer states needed by rank 0's optimizer but some ranks "
  1110. "are missing some of those states"
  1111. )
  1112. for rank, keys in enumerate(obj_list):
  1113. keys = cast(List[_OptimStateKey], keys)
  1114. if len(keys) > 0:
  1115. error_msg += (
  1116. f"\nRank {rank} is missing states for the parameters: "
  1117. f"{[key.unflat_param_names for key in keys]}"
  1118. )
  1119. raise RuntimeError(error_msg)
  1120. def _map_param_key_to_optim_keys(
  1121. optim_state_dict: Dict[str, Any],
  1122. group: Optional[dist.ProcessGroup],
  1123. param_key_to_param: Dict[Union[int, str], nn.Parameter],
  1124. param_to_fqns: Dict[nn.Parameter, List[str]],
  1125. fqn_to_fsdp_param_info: Dict[str, FSDPParamInfo],
  1126. merge_keys: bool = False,
  1127. ) -> Tuple[List[_OptimStateKey], Dict[_OptimStateKey, Union[int, str]]]:
  1128. """
  1129. Construct the local mapping between the ``_OptimStateKey`` and parameter keys
  1130. and all the ``_OptimStateKey`` across ranks. If ``merge_keys`` is False, rank0
  1131. must contain all the ``_OptimStateKey``, an exception will be raised otherwise.
  1132. Note that ``merge_keys`` should equal to ``use_orig_params``.
  1133. """
  1134. rank = dist.get_rank(group)
  1135. optim_state_key_to_param_key: Dict[_OptimStateKey, Union[int, str]] = {} # local
  1136. all_optim_state_keys: List[_OptimStateKey] = []
  1137. for param_key, param in param_key_to_param.items():
  1138. # Do not include parameters without state to avoid empty mappings
  1139. # just like in normal `torch.optim.Optimizer.state_dict()`
  1140. if param_key not in optim_state_dict["state"]:
  1141. continue
  1142. fqns = param_to_fqns[param]
  1143. is_fsdp_managed = isinstance(param, FlatParameter)
  1144. if is_fsdp_managed:
  1145. assert fqns[0] in fqn_to_fsdp_param_info, (
  1146. fqns[0],
  1147. list(fqn_to_fsdp_param_info.keys()),
  1148. )
  1149. is_fsdp_managed = fqns[0] in fqn_to_fsdp_param_info
  1150. optim_state_key = _OptimStateKey(
  1151. unflat_param_names=tuple(fqns),
  1152. is_fsdp_managed=is_fsdp_managed,
  1153. )
  1154. if rank == 0 or merge_keys:
  1155. all_optim_state_keys.append(optim_state_key)
  1156. optim_state_key_to_param_key[optim_state_key] = param_key
  1157. if merge_keys:
  1158. all_keys: List[List[_OptimStateKey]] = [
  1159. [] for _ in range(dist.get_world_size(group))
  1160. ]
  1161. dist.all_gather_object(all_keys, all_optim_state_keys, group=group)
  1162. merge_all_optim_state_keys = [
  1163. key for local_keys in all_keys for key in local_keys
  1164. ]
  1165. all_optim_state_keys = sorted(set(merge_all_optim_state_keys))
  1166. else:
  1167. key_obj_list: List[Optional[List[_OptimStateKey]]] = (
  1168. [all_optim_state_keys] if rank == 0 else [None]
  1169. )
  1170. dist.broadcast_object_list(key_obj_list, src=0, group=group)
  1171. assert key_obj_list[0] is not None
  1172. all_optim_state_keys = key_obj_list[0]
  1173. _check_missing_keys_on_rank(
  1174. all_optim_state_keys,
  1175. optim_state_key_to_param_key,
  1176. param_key_to_param,
  1177. group,
  1178. )
  1179. return all_optim_state_keys, optim_state_key_to_param_key
  1180. def _unflatten_param_groups(
  1181. state_dict: Dict[str, Any],
  1182. param_key_to_param: Dict[Union[int, str], nn.Parameter],
  1183. param_to_fqns: Dict[nn.Parameter, List[str]],
  1184. ) -> List[Dict[str, Any]]:
  1185. param_groups: List[Dict[str, Any]] = []
  1186. for flat_param_group in state_dict["param_groups"]:
  1187. unflat_param_group = copy.deepcopy(flat_param_group)
  1188. param_group_params = [
  1189. param_key_to_param[flat_param_key]
  1190. for flat_param_key in flat_param_group["params"]
  1191. ]
  1192. nested_unflat_param_names = [
  1193. param_to_fqns[param] for param in param_group_params
  1194. ]
  1195. unflat_param_group["params"] = [
  1196. unflat_param_name
  1197. for unflat_param_names in nested_unflat_param_names
  1198. for unflat_param_name in unflat_param_names
  1199. ] # flatten the list of lists
  1200. param_groups.append(unflat_param_group)
  1201. return param_groups
  1202. def _is_named_optimizer(optim_state_dict: Dict[str, Any]) -> bool:
  1203. state = optim_state_dict.get("state", None)
  1204. if not state:
  1205. # If we cannot find a state, assume it is not NamedOptimizer as
  1206. # NamedOptimizer has eagerly initialization.
  1207. return False
  1208. try:
  1209. key = next(iter(state.keys()))
  1210. except Exception as e:
  1211. raise Exception(optim_state_dict) from e
  1212. return isinstance(key, str)
  1213. def _optim_state_dict(
  1214. model: nn.Module,
  1215. optim: torch.optim.Optimizer,
  1216. optim_state_dict: Dict[str, Any],
  1217. optim_input: Optional[
  1218. Union[
  1219. List[Dict[str, Any]],
  1220. Iterable[nn.Parameter],
  1221. ]
  1222. ],
  1223. rank0_only: bool,
  1224. shard_state: bool,
  1225. group: Optional[dist.ProcessGroup],
  1226. using_optim_input: bool,
  1227. use_orig_params: bool = False,
  1228. ) -> Dict[str, Any]:
  1229. """
  1230. Consolidates the optimizer state and returns it as a :class:`dict`
  1231. following the convention of :meth:`torch.optim.Optimizer.state_dict`,
  1232. i.e. with keys ``"state"`` and ``"param_groups"``.
  1233. The flattened parameters in ``FSDP`` modules contained in ``model``
  1234. are mapped back to their unflattened parameters.
  1235. Parameter keys are not well-defined. For a regular optimizer, the optimizer
  1236. state_dict contains a mapping from parameter IDs to parameter states.
  1237. Parameter IDs are the order of parameters in ``optim.param_groups()`` across
  1238. all the groups. This API also allows user to pass ``optim_input`` for the
  1239. mapping between parameters and parameter IDs. Using ``optim_input`` is being
  1240. deprecated.
  1241. If the optimizer is a ``NamedOptimizer``, the optimizer state_dict does not
  1242. contain parameter IDs mapping but a mapping from parameter FQNs to parameter
  1243. states. This API finds the mapping from FQNs to parameters if the optimizer
  1244. is a ``NamedOptimizer``.
  1245. If ``use_orig_params`` is True, each rank will have all FSDP-managed
  1246. parameters but some of these parameters may be empty due to the sharding.
  1247. For a regular optim.Optimizer, states for those empty parameters will
  1248. not be initialized. So, when aggregating the FQNs across ranks, no assert
  1249. will be raised on a rank even if it does not have all the states -- it is
  1250. valid and FSDP know how to aggregate them. However, FSDP has to ignore
  1251. handling those parameters that are not managed by FSDP and do not exist on
  1252. the local rank -- it is managed by other parallelism and FSDP does not
  1253. know ho to handle/aggregate them.
  1254. Args:
  1255. model (nn.Module): Root module (which may or may not be a
  1256. :class:`FullyShardedDataParallel` instance) whose parameters
  1257. were passed into the optimizer ``optim``.
  1258. optim (torch.optim.Optimizer): Optimizer for ``model`` 's
  1259. parameters.
  1260. rank0_only (bool): If ``True``, saves the populated :class:`dict`
  1261. only on rank 0; if ``False``, saves it on all ranks. (Default:
  1262. ``True``)
  1263. shard_state (bool): If ``True``, shard and distribute all
  1264. non-zero-dimension states.
  1265. Returns:
  1266. Dict[str, Any]: A :class:`dict` containing the optimizer state for
  1267. ``model`` 's original unflattened parameters and including keys
  1268. "state" and "param_groups" following the convention of
  1269. :meth:`torch.optim.Optimizer.state_dict`. If ``rank0_only=False``,
  1270. then nonzero ranks return an empty :class:`dict`.
  1271. """
  1272. _clear_grads_if_needed(traversal_utils._get_fsdp_handles(model))
  1273. to_save = not rank0_only or (dist.get_rank(group) == 0 or shard_state)
  1274. fsdp_osd: Dict[str, Any] = {"state": {}, "param_groups": []} if to_save else {}
  1275. fsdp_osd_state: Dict[str, Any] = fsdp_osd["state"] if to_save else {}
  1276. param_to_fqns = _get_param_to_fqns(model)
  1277. flat_param_to_fqn = _get_flat_param_to_fqn(model)
  1278. is_named_optimizer = _is_named_optimizer(optim_state_dict)
  1279. param_key_to_param = cast(
  1280. Dict[Union[int, str], nn.Parameter],
  1281. (
  1282. _get_param_id_to_param_from_optim_input(model, optim_input)
  1283. if using_optim_input
  1284. else _get_param_key_to_param(
  1285. optim, model, is_named_optimizer, param_to_fqns, flat_param_to_fqn
  1286. )
  1287. ),
  1288. )
  1289. fqn_to_fsdp_param_info = _get_fqn_to_fsdp_param_info(model)
  1290. all_optim_state_keys, optim_state_key_to_param_key = _map_param_key_to_optim_keys(
  1291. optim_state_dict,
  1292. group,
  1293. param_key_to_param,
  1294. param_to_fqns,
  1295. fqn_to_fsdp_param_info,
  1296. merge_keys=use_orig_params,
  1297. )
  1298. # Iterate in rank 0's flattened parameter ID order to ensure aligned
  1299. # all-gathers across ranks
  1300. for optim_state_key in all_optim_state_keys:
  1301. param_key: Union[str, int, None] = optim_state_key_to_param_key.get(
  1302. optim_state_key, None
  1303. )
  1304. if param_key is None:
  1305. assert use_orig_params, (
  1306. "If use_orig_params is False, we must be able to find the "
  1307. f"corresponding param id. {optim_state_key} {param_key}"
  1308. )
  1309. if not optim_state_key.is_fsdp_managed:
  1310. continue
  1311. if optim_state_key.is_fsdp_managed:
  1312. # If there are multiple unflat_param_names (not use_orig_params),
  1313. # they share the same FSDPParamInfo. So the first unflat_param_name
  1314. # is sufficient to fetch the FSDPParamInfo.
  1315. fqn = optim_state_key.unflat_param_names[0]
  1316. fsdp_param_info = fqn_to_fsdp_param_info[fqn]
  1317. if use_orig_params:
  1318. state = (
  1319. {} if param_key is None else optim_state_dict["state"][param_key]
  1320. )
  1321. unflat_state = [
  1322. _gather_orig_param_state(
  1323. fsdp_param_info,
  1324. fqn,
  1325. state,
  1326. shard_state,
  1327. )
  1328. ]
  1329. else:
  1330. unflat_state = _unflatten_optim_state(
  1331. fsdp_param_info,
  1332. optim_state_dict["state"][param_key],
  1333. to_save,
  1334. shard_state,
  1335. )
  1336. if to_save:
  1337. assert len(unflat_state) == len(optim_state_key.unflat_param_names)
  1338. for unflat_param_name, unflat_param_state in zip(
  1339. optim_state_key.unflat_param_names,
  1340. unflat_state,
  1341. ):
  1342. fsdp_osd_state[unflat_param_name] = unflat_param_state
  1343. elif to_save:
  1344. assert len(optim_state_key.unflat_param_names) == 1
  1345. unflat_param_name = optim_state_key.unflat_param_names[0]
  1346. fsdp_osd_state[unflat_param_name] = copy.copy(
  1347. optim_state_dict["state"][param_key]
  1348. )
  1349. for state_name, value in sorted_items(fsdp_osd_state[unflat_param_name]):
  1350. if torch.is_tensor(value):
  1351. fsdp_osd_state[unflat_param_name][state_name] = value.cpu()
  1352. if to_save:
  1353. flat_param_fqns = set(flat_param_to_fqn.values())
  1354. for key, value in optim_state_dict["state"].items():
  1355. if key in fsdp_osd_state:
  1356. continue
  1357. if key in flat_param_fqns:
  1358. continue
  1359. if key in param_key_to_param:
  1360. continue
  1361. # This key is not recognized by FSDP. It may be a user-defined state
  1362. # or some parameters state that FSDP is unable to map from
  1363. # ``optim.param_groups``.
  1364. warnings.warn(
  1365. f"Found a optim state, {key}, that FSDP cannot process. FSDP "
  1366. "will directly copy everything to the returned state_dict. In "
  1367. "most cases, this is a user-defined state that is not "
  1368. "associated with any particular parameter. Another possible "
  1369. "case is this state is managed by DMP. Otherwise, there may "
  1370. " be a mismatched assumption of optim_state_dict of this mode."
  1371. )
  1372. fsdp_osd_state[key] = value
  1373. fsdp_osd["param_groups"] = _unflatten_param_groups(
  1374. optim_state_dict, param_key_to_param, param_to_fqns
  1375. )
  1376. return fsdp_osd
  1377. def _get_fqn_to_fsdp_param_info(model: nn.Module) -> Dict[str, FSDPParamInfo]:
  1378. """
  1379. Construct the mapping from a param's fqn to its corresponding ``FSDPParamInfo``
  1380. if the param is managed by FSDP. ``FlatParameter._fqns`` only stores the first
  1381. FQN of a shared parameter. So the keys in the mapping are guaranteed to map
  1382. to unique parameters.
  1383. """
  1384. def module_fn(module, prefix, fqn_to_param_info):
  1385. fsdp_state = _get_module_fsdp_state_if_fully_sharded_module(module)
  1386. if fsdp_state is None:
  1387. return
  1388. _lazy_init(fsdp_state, module)
  1389. handles = _module_handles(fsdp_state, module)
  1390. if not handles:
  1391. return
  1392. flat_param = handles[0].flat_param
  1393. fsdp_param_info = FSDPParamInfo(fsdp_state, flat_param, {})
  1394. for idx, local_fqn in enumerate(flat_param._fqns):
  1395. fqn = clean_tensor_name(prefix + local_fqn)
  1396. if fqn in fqn_to_param_info:
  1397. assert fqn_to_param_info[fqn].flat_param == flat_param
  1398. fqn_to_param_info[fqn] = fsdp_param_info
  1399. fsdp_param_info.param_indices[fqn] = idx
  1400. def return_fn(fqn_to_param_info):
  1401. return fqn_to_param_info
  1402. fqn_to_param_info: Dict[str, FSDPParamInfo] = {}
  1403. # FlatParameter._fqns stores the local fqn, starting from the root of the
  1404. # FSDP. Using _apply_to_modules() with model (may not be the FSDP root
  1405. # module) allows us to construct the global fqn.
  1406. return _apply_to_modules(
  1407. model,
  1408. module_fn,
  1409. return_fn,
  1410. [fqn for fqn, _ in model.named_parameters()],
  1411. fqn_to_param_info,
  1412. )
  1413. @dataclass
  1414. class StateInfo:
  1415. tensors: Dict[str, _PosDimTensorInfo]
  1416. scalar_tensors: Dict[str, torch.Tensor]
  1417. non_tensors: Dict[str, Any]
  1418. @dataclass
  1419. class AllGatherInfo:
  1420. tensors: List[torch.Tensor]
  1421. numels: List[int]
  1422. work: Optional[dist.Work]
  1423. def _all_gather_optim_state(
  1424. fsdp_state: _FSDPState, optim_state: Dict[str, Any]
  1425. ) -> Dict[str, Any]:
  1426. """
  1427. All-gathering state from all the ranks. This API is slow as it uses
  1428. ``all_gather_object``. However, optim state_dict is not in the critical path.
  1429. We can fuse the communication across differnt state if the performance
  1430. becomes a problem.
  1431. """
  1432. # Allgather the scalar tensor state, non-tensor states and tensors metadata.
  1433. processed_state = StateInfo({}, {}, {})
  1434. for state_name, value in sorted_items(optim_state):
  1435. if torch.is_tensor(value):
  1436. if value.dim() == 0:
  1437. # Ensure that `step` is on CPU.
  1438. processed_state.scalar_tensors[state_name] = value.cpu()
  1439. else:
  1440. processed_state.tensors[state_name] = _PosDimTensorInfo(
  1441. value.shape, value.dtype
  1442. )
  1443. else:
  1444. processed_state.non_tensors = value
  1445. object_list: List[StateInfo] = [
  1446. processed_state for _ in range(fsdp_state.world_size)
  1447. ]
  1448. dist.all_gather_object(object_list, processed_state)
  1449. # Convert the gathered, pre-proccessed state of each rank to the original one.
  1450. gathered_state: Dict[str, Any] = {}
  1451. all_tensor_states = sorted(
  1452. {n for state in object_list for n in state.tensors.keys()}
  1453. )
  1454. empty_ranks: Set[int] = set()
  1455. for name in all_tensor_states:
  1456. numels = []
  1457. dtype = torch.float
  1458. _empty_ranks: Set[int] = set()
  1459. for rank, object_state in enumerate(object_list):
  1460. numels.append(0)
  1461. info = object_state.tensors.get(name, None)
  1462. if info is not None:
  1463. numels[-1] = info.shape.numel()
  1464. dtype = info.dtype
  1465. if numels[-1] == 0:
  1466. _empty_ranks.add(rank)
  1467. empty_func = functools.partial(
  1468. torch.empty, dtype=dtype, device=fsdp_state.compute_device
  1469. )
  1470. if empty_ranks:
  1471. assert empty_ranks == _empty_ranks
  1472. empty_ranks = _empty_ranks
  1473. local_state = optim_state.get(name, empty_func(0))
  1474. local_state = local_state.to(fsdp_state.compute_device)
  1475. tensors = [
  1476. empty_func(numel) if rank != fsdp_state.rank else local_state
  1477. for rank, numel in enumerate(numels)
  1478. ]
  1479. work = dist.all_gather(
  1480. tensors, local_state, group=fsdp_state.process_group, async_op=True
  1481. )
  1482. gathered_state[name] = AllGatherInfo(tensors, numels, work)
  1483. for rank, object_state in enumerate(object_list):
  1484. if rank in empty_ranks:
  1485. continue
  1486. for name, non_tensor_value in object_state.non_tensors.items():
  1487. curr_non_tensor_value = gathered_state.get(name, None)
  1488. assert (
  1489. curr_non_tensor_value is None
  1490. or curr_non_tensor_value == non_tensor_value
  1491. ), f"Different ranks have different values for {name}."
  1492. gathered_state[name] = non_tensor_value
  1493. for name, scalar_tensor_value in object_state.scalar_tensors.items():
  1494. curr_scalar_tensor_value = gathered_state.get(name, None)
  1495. assert curr_scalar_tensor_value is None or torch.equal(
  1496. scalar_tensor_value, curr_scalar_tensor_value
  1497. ), f"Different ranks have different values for {name}."
  1498. gathered_state[name] = scalar_tensor_value
  1499. for name, value in list(gathered_state.items()):
  1500. if not isinstance(value, AllGatherInfo):
  1501. continue
  1502. assert value.work is not None
  1503. value.work.wait()
  1504. gathered_state[name] = torch.cat(
  1505. [
  1506. rank_tensor[:rank_numel]
  1507. for rank_tensor, rank_numel in zip(value.tensors, value.numels)
  1508. if rank_numel > 0
  1509. ]
  1510. )
  1511. return gathered_state
  1512. def _gather_orig_param_state(
  1513. fsdp_param_info: FSDPParamInfo,
  1514. fqn: str,
  1515. optim_state: Dict[str, Any],
  1516. shard_state: bool,
  1517. ) -> Dict[str, Any]:
  1518. """
  1519. Gather the optimizer state for the original parameter with the name ``fqn``.
  1520. This API should only be used when ``use_orig_params`` is True.
  1521. """
  1522. fsdp_state = fsdp_param_info.state
  1523. assert (
  1524. fsdp_state._use_orig_params
  1525. ), "_gather_orig_param_state only support use_orig_params=True case"
  1526. flat_param = fsdp_param_info.flat_param
  1527. param_idx = fsdp_param_info.param_indices[fqn]
  1528. if (
  1529. fsdp_state.world_size == 1
  1530. or fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD
  1531. ):
  1532. return optim_state
  1533. gathered_state = _all_gather_optim_state(fsdp_state, optim_state)
  1534. # Unflatten state values.
  1535. for state_name, value in list(gathered_state.items()):
  1536. if not torch.is_tensor(value) or value.dim() == 0:
  1537. continue
  1538. value = value[: flat_param._numels[param_idx]].reshape(
  1539. flat_param._shapes[param_idx]
  1540. )
  1541. if shard_state:
  1542. assert fsdp_state.process_group is not None
  1543. value = _ext_chunk_tensor(
  1544. value,
  1545. fsdp_state.rank,
  1546. fsdp_state.world_size,
  1547. torch.cuda.device_count(),
  1548. fsdp_state.process_group,
  1549. )
  1550. value = value.cpu()
  1551. gathered_state[state_name] = value
  1552. return gathered_state
  1553. def _shard_orig_param_state(
  1554. fsdp_param_info: FSDPParamInfo,
  1555. fqn: str,
  1556. optim_state: Dict[str, Any],
  1557. ) -> Dict[str, Any]:
  1558. """
  1559. Shard the optimizer state for the original parameter with the name ``fqn``.
  1560. This API should only be used when ``use_orig_params`` is True.
  1561. """
  1562. if not optim_state:
  1563. return {}
  1564. fsdp_state = fsdp_param_info.state
  1565. flat_param = fsdp_param_info.flat_param
  1566. param_idx = fsdp_param_info.param_indices[fqn]
  1567. optim_state = _gather_state_dict(optim_state, fsdp_state.process_group)
  1568. start, end = flat_param._shard_indices # type: ignore[attr-defined]
  1569. if not (start <= param_idx <= end and flat_param._shard_param_offsets): # type: ignore[attr-defined]
  1570. return {}
  1571. param_start, param_end = flat_param._shard_param_offsets[param_idx - start] # type: ignore[attr-defined]
  1572. # Flatten and shard the state.
  1573. new_optim_state: Dict[str, Any] = {}
  1574. for state_name, value in optim_state.items():
  1575. if torch.is_tensor(value) and value.dim() > 0:
  1576. value = value.flatten()[param_start : param_end + 1]
  1577. new_optim_state[state_name] = value
  1578. return new_optim_state