ZTWHHH commited on
Commit
2ef691d
·
verified ·
1 Parent(s): 9b09b53

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. vllm/lib/python3.10/site-packages/torch/distributed/_tools/__init__.py +5 -0
  2. vllm/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/__init__.cpython-310.pyc +0 -0
  3. vllm/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/fsdp2_mem_tracker.cpython-310.pyc +0 -0
  4. vllm/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/mem_tracker.cpython-310.pyc +0 -0
  5. vllm/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/memory_tracker.cpython-310.pyc +0 -0
  6. vllm/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/mod_tracker.cpython-310.pyc +0 -0
  7. vllm/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/runtime_estimator.cpython-310.pyc +0 -0
  8. vllm/lib/python3.10/site-packages/torch/distributed/_tools/fsdp2_mem_tracker.py +610 -0
  9. vllm/lib/python3.10/site-packages/torch/distributed/_tools/mem_tracker.py +943 -0
  10. vllm/lib/python3.10/site-packages/torch/distributed/_tools/memory_tracker.py +295 -0
  11. vllm/lib/python3.10/site-packages/torch/distributed/_tools/mod_tracker.py +238 -0
  12. vllm/lib/python3.10/site-packages/torch/distributed/_tools/runtime_estimator.py +527 -0
  13. vllm/lib/python3.10/site-packages/torch/distributed/checkpoint/__init__.py +14 -0
  14. vllm/lib/python3.10/site-packages/torch/distributed/checkpoint/_dedup_save_plans.py +60 -0
  15. vllm/lib/python3.10/site-packages/torch/distributed/checkpoint/_dedup_tensors.py +62 -0
  16. vllm/lib/python3.10/site-packages/torch/distributed/checkpoint/_storage_utils.py +49 -0
  17. vllm/lib/python3.10/site-packages/torch/distributed/checkpoint/_traverse.py +208 -0
  18. vllm/lib/python3.10/site-packages/torch/distributed/checkpoint/filesystem.py +765 -0
  19. vllm/lib/python3.10/site-packages/torch/distributed/checkpoint/metadata.py +182 -0
  20. vllm/lib/python3.10/site-packages/torch/distributed/checkpoint/planner.py +417 -0
  21. vllm/lib/python3.10/site-packages/torch/distributed/checkpoint/state_dict.py +1422 -0
  22. vllm/lib/python3.10/site-packages/torch/distributed/fsdp/__init__.py +39 -0
  23. vllm/lib/python3.10/site-packages/torch/distributed/fsdp/__pycache__/_trace_utils.cpython-310.pyc +0 -0
  24. vllm/lib/python3.10/site-packages/torch/distributed/fsdp/__pycache__/_unshard_param_utils.cpython-310.pyc +0 -0
  25. vllm/lib/python3.10/site-packages/torch/distributed/fsdp/_common_utils.py +558 -0
  26. vllm/lib/python3.10/site-packages/torch/distributed/fsdp/_debug_utils.py +157 -0
  27. vllm/lib/python3.10/site-packages/torch/distributed/fsdp/_exec_order_utils.py +365 -0
  28. vllm/lib/python3.10/site-packages/torch/distributed/fsdp/_flat_param.py +0 -0
  29. vllm/lib/python3.10/site-packages/torch/distributed/fsdp/_fsdp_extensions.py +179 -0
  30. vllm/lib/python3.10/site-packages/torch/distributed/fsdp/_init_utils.py +1200 -0
  31. vllm/lib/python3.10/site-packages/torch/distributed/fsdp/_limiter_utils.py +33 -0
  32. vllm/lib/python3.10/site-packages/torch/distributed/fsdp/_optim_utils.py +2091 -0
  33. vllm/lib/python3.10/site-packages/torch/distributed/fsdp/_runtime_utils.py +1638 -0
  34. vllm/lib/python3.10/site-packages/torch/distributed/fsdp/_shard_utils.py +137 -0
  35. vllm/lib/python3.10/site-packages/torch/distributed/fsdp/_state_dict_utils.py +924 -0
  36. vllm/lib/python3.10/site-packages/torch/distributed/fsdp/_trace_utils.py +238 -0
  37. vllm/lib/python3.10/site-packages/torch/distributed/fsdp/_traversal_utils.py +113 -0
  38. vllm/lib/python3.10/site-packages/torch/distributed/fsdp/_unshard_param_utils.py +336 -0
  39. vllm/lib/python3.10/site-packages/torch/distributed/fsdp/api.py +410 -0
  40. vllm/lib/python3.10/site-packages/torch/distributed/fsdp/fully_sharded_data_parallel.py +0 -0
  41. vllm/lib/python3.10/site-packages/torch/distributed/fsdp/sharded_grad_scaler.py +396 -0
  42. vllm/lib/python3.10/site-packages/torch/distributed/fsdp/wrap.py +608 -0
  43. vllm/lib/python3.10/site-packages/torch/distributed/nn/__pycache__/functional.cpython-310.pyc +0 -0
  44. vllm/lib/python3.10/site-packages/torch/distributed/rpc/internal.py +285 -0
  45. vllm/lib/python3.10/site-packages/torch/distributed/tensor/__pycache__/__init__.cpython-310.pyc +0 -0
  46. vllm/lib/python3.10/site-packages/torch/distributed/tensor/__pycache__/_api.cpython-310.pyc +0 -0
  47. vllm/lib/python3.10/site-packages/torch/distributed/tensor/__pycache__/_collective_utils.cpython-310.pyc +0 -0
  48. vllm/lib/python3.10/site-packages/torch/distributed/tensor/__pycache__/_dtensor_spec.cpython-310.pyc +0 -0
  49. vllm/lib/python3.10/site-packages/torch/distributed/tensor/__pycache__/_op_schema.cpython-310.pyc +0 -0
  50. vllm/lib/python3.10/site-packages/torch/distributed/tensor/__pycache__/_redistribute.cpython-310.pyc +0 -0
vllm/lib/python3.10/site-packages/torch/distributed/_tools/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from .fsdp2_mem_tracker import FSDPMemTracker
2
+ from .mem_tracker import MemTracker
3
+ from .memory_tracker import MemoryTracker
4
+ from .mod_tracker import ModTracker
5
+ from .runtime_estimator import RuntimeEstimator
vllm/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (432 Bytes). View file
 
vllm/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/fsdp2_mem_tracker.cpython-310.pyc ADDED
Binary file (19 kB). View file
 
vllm/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/mem_tracker.cpython-310.pyc ADDED
Binary file (32 kB). View file
 
vllm/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/memory_tracker.cpython-310.pyc ADDED
Binary file (10.4 kB). View file
 
vllm/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/mod_tracker.cpython-310.pyc ADDED
Binary file (9.26 kB). View file
 
vllm/lib/python3.10/site-packages/torch/distributed/_tools/__pycache__/runtime_estimator.cpython-310.pyc ADDED
Binary file (16.9 kB). View file
 
vllm/lib/python3.10/site-packages/torch/distributed/_tools/fsdp2_mem_tracker.py ADDED
@@ -0,0 +1,610 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from copy import deepcopy
2
+ from datetime import timedelta
3
+ from functools import partial, wraps
4
+ from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple, Type, Union
5
+
6
+ import torch
7
+ import torch.distributed as dist
8
+ from torch import nn, optim
9
+ from torch._guards import active_fake_mode
10
+ from torch.distributed._composable.fsdp import FSDPModule
11
+ from torch.distributed._composable.fsdp._fsdp_param_group import FSDPParamGroup
12
+ from torch.distributed._tools.mem_tracker import _RefType, _State, MemTracker
13
+ from torch.distributed.distributed_c10d import (
14
+ _IllegalWork,
15
+ ProcessGroup,
16
+ ReduceOp,
17
+ Work,
18
+ )
19
+ from torch.futures import Future
20
+ from torch.utils._python_dispatch import TorchDispatchMode
21
+ from torch.utils._pytree import tree_map_only
22
+ from torch.utils.weak import WeakIdKeyDictionary, weakref
23
+
24
+
25
+ _TOTAL_KEY = "Total"
26
+
27
+ __all__ = ["FSDPMemTracker"]
28
+
29
+
30
+ class _FSDPRefType(_RefType):
31
+ """
32
+ Enumerates categories of memory usage in FSDP modules, including parameters, gradients, activations,
33
+ and optimizer states.
34
+
35
+ Attributes:
36
+ SHARDED_PARAM (str): Memory usage of sharded parameters.
37
+ UNSHARDED_PARAM (str): Memory usage of unsharded parameters.
38
+ SHARDED_GRAD (str): Memory usage of sharded gradients corresponding to the sharded parameters.
39
+ UNSHARDED_GRAD (str): Memory usage of unsharded gradients corresponding to the unsharded parameters.
40
+ ACT (str): Memory usage of activations and tensors from forward and AC recomputation.
41
+ TEMP (str): Memory usage of temporary tensors during the backward pass including gradients of activations.
42
+ ALL_GATHER (str): Memory usage of all_gather output tensor.
43
+ REDUCE_SCATTER (str): Memory usage of reduce_scatter input tensor.
44
+ OPT (str): Memory usage of tensors storing optimizer states.
45
+ INP (str): Memory usage of input tensors.
46
+ """
47
+
48
+ SHARDED_PARAM = "Sharded Param"
49
+ UNSHARDED_PARAM = "Unsharded Param"
50
+ BUFFER = "Buffer"
51
+ SHARDED_GRAD = "Sharded Grad"
52
+ UNSHARDED_GRAD = "Unsharded Grad"
53
+ ACT = "Activation"
54
+ TEMP = "Temp"
55
+ ALL_GATHER = "All Gather"
56
+ REDUCE_SCATTER = "Reduce Scatter"
57
+ OPT = "OptState"
58
+ INP = "Inputs"
59
+
60
+
61
+ class _SavedFSDPMethods(NamedTuple):
62
+ pre_backward: Callable
63
+ post_backward: Callable
64
+
65
+
66
+ class _SavedCollectives(NamedTuple):
67
+ all_gather_into_tensor: Callable
68
+ reduce_scatter_tensor: Callable
69
+ all_reduce: Callable
70
+ barrier: Callable
71
+
72
+
73
+ class _FSDPModState(_State):
74
+ """
75
+ Enumerates the states of FSDP modules during the forward and backward passes.
76
+ """
77
+
78
+ BEF_PRE_FW = "Before Pre-Forward"
79
+ AFT_PRE_FW = "After Pre-Forward"
80
+ BEF_POST_FW = "Before Post-Forward"
81
+ AFT_POST_FW = "After Post-Forward"
82
+ BEF_PRE_BW = "Before Pre-Backward"
83
+ AFT_PRE_BW = "After Pre-Backward"
84
+ BEF_POST_BW = "Before Post-Backward"
85
+ AFT_POST_BW = "After Post-Backward"
86
+ PRE_FW_AC = "Pre-Forward AC"
87
+ POST_FW_AC = "Post-Forward AC"
88
+ PEAK_FW = "Peak Forward"
89
+ PEAK_BW = "Peak Backward"
90
+
91
+
92
+ class _FSDPModMemStats:
93
+ """
94
+ A class to store the memory statistics of an FSDP module.
95
+
96
+ Args:
97
+ mod_fqn (str): The fully qualified name of the FSDP module.
98
+
99
+ Attributes:
100
+ snapshots (Dict[_FSDPModState, Dict[torch.device, Dict[str, int]]]): A dictionary of memory snapshots
101
+ of the module at different states as defined by ``_FSDPModState``. Each key is a device, and
102
+ each value is another dictionary with keys as memory reference types defined by ``_FSDPRefType`` and
103
+ values as the memory consumed in bytes.
104
+
105
+ """
106
+
107
+ def __init__(self, mod_fqn: str) -> None:
108
+ self.mod_fqn = mod_fqn
109
+ self.local_peak: Dict[torch.device, int] = {}
110
+ self.snapshots: Dict[
111
+ _FSDPModState, List[Dict[torch.device, Dict[str, int]]]
112
+ ] = {}
113
+
114
+
115
+ class FSDPMemTracker(MemTracker):
116
+ """
117
+ A ``TorchDispatchMode`` based context manager that extends ``torch.distributed._tools.mem_tracker.MemTracker`` to track
118
+ and categorize the peak memory and module-wise memory usage of FSDP modules.
119
+
120
+ It tracks the peak memory usage across all the devices of all the FSDP modules in the module tree and categorizes
121
+ the tensor memory usage as defined by ``_FSDPRefType``. Further, it captures memory `snapshots` at different stages of
122
+ the module execution defined by ``_FSDPModState``.
123
+
124
+ Attributes:
125
+ memory_tracking: A weakref key dictionary to store the memory statistics of each module. Each key is a reference
126
+ to a module, and each value is a ``_FSDPModMemStats`` object that stores the memory statistics of the module.
127
+
128
+ Args:
129
+ mod (torch.nn.Module): The root FSDP module to be tracked.
130
+ optm (torch.optim.Optimizer, optional): The optimizer to be tracked.
131
+
132
+ Note: Please refer to ``torch.distributed._tools.mem_tracker.MemTracker`` to learn about the limitations.
133
+
134
+ Example usage
135
+
136
+ .. code-block:: python
137
+
138
+ module = ...
139
+ optimizer = ...
140
+ inp = ...
141
+ fmt = FSDPMemTracker(module, optimizer)
142
+ fmt.track_inputs((inp,))
143
+ with fmt:
144
+ optimizer.zero_grad()
145
+ loss = module(inp)
146
+ print("After Forward:")
147
+ fmt.display_snapshot("current")
148
+ loss.backward()
149
+ optimizer.step()
150
+ fmt.display_snapshot("peak")
151
+ fmt.display_modulewise_snapshots(depth = 3, units = "MB")
152
+
153
+ """
154
+
155
+ def __init__(
156
+ self,
157
+ mod: torch.nn.Module,
158
+ optm: Optional[torch.optim.Optimizer] = None,
159
+ ) -> None:
160
+ super().__init__()
161
+ assert isinstance(mod, FSDPModule), "FSDPMemTracker only supports FSDP modules"
162
+ self._root_mod = mod
163
+ self._optm = optm
164
+ self._in_fake_mode: bool = False
165
+ self._fsdp_mod_to_saved_methods: WeakIdKeyDictionary = WeakIdKeyDictionary()
166
+ self._saved_collectives: _SavedCollectives
167
+ self._ref_class: Type[_RefType] = _FSDPRefType
168
+
169
+ def _instrument_fsdp_sharded_params_grads(
170
+ self, fsdp_param_group: FSDPParamGroup
171
+ ) -> None:
172
+ # Track sharded params and grads after initilization
173
+ for fsdp_param in fsdp_param_group.fsdp_params:
174
+ self._update_and_maybe_create_winfos(
175
+ fsdp_param.sharded_param,
176
+ _FSDPRefType.SHARDED_PARAM,
177
+ )
178
+ sharded_grad = fsdp_param.sharded_param.grad
179
+ if sharded_grad is not None:
180
+ self._update_and_maybe_create_winfos(
181
+ sharded_grad,
182
+ _FSDPRefType.SHARDED_GRAD,
183
+ )
184
+
185
+ def _fsdp_state_pre_forward(
186
+ self,
187
+ fsdp_mod: FSDPModule,
188
+ orig_fsdp_state_pre_fw: Callable,
189
+ ) -> Callable:
190
+ # We capture memory snapshots before and after ``FSDPState._pre_forward`` to attribute the `unsharded` params
191
+ # and `all_gather` buffers. There are three cases:
192
+ # Case 1: If the module is not in the ``memory_tracking`` dictionary, create a new ``_FSDPModMemStats``
193
+ # instance for the module and add it to the ``memory_tracking`` dictionary.
194
+ # Case 2: If the module is already in the ``memory_tracking`` dictionary and we are in backward, this means
195
+ # we are in the AC region. We check if this is the top most module in the AC region. If it is,
196
+ # we store a weak reference and set the flag ``_in_ac`` to True.
197
+ # Case 3: If the module is already in the ``memory_tracking`` dictionary and we are in forward, this means
198
+ # this module is called for the second time. If it is a root module, that means we are in the next
199
+ # iteration and we error out. If it is not a root module, that means it's a submodule that is being
200
+ # used multiple times in the same iteration, which we allow and track.
201
+ # For Case 1 and 3, we also initialiaze the ``local_peak`` and ``PEAK_FW`` snapshot for the module.
202
+ # For Case 2 we only capture 1 snapshot after ``FSDPState._pre_forward`` runs because it is a no-op.
203
+ @wraps(orig_fsdp_state_pre_fw)
204
+ def inner(*args: Any, **kwargs: Any) -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
205
+ mod_fqn = self._mod_tracker.get_known_fqn(fsdp_mod)
206
+ assert mod_fqn is not None
207
+ if fsdp_mod not in self.memory_tracking:
208
+ mod_stat = _FSDPModMemStats(mod_fqn)
209
+ self.memory_tracking[fsdp_mod] = mod_stat
210
+ snapshot = self.get_tracker_snapshot()
211
+ mod_stat.local_peak = {
212
+ dev: dev_snap[_TOTAL_KEY] for dev, dev_snap in snapshot.items()
213
+ }
214
+ mod_stat.snapshots.setdefault(_FSDPModState.PEAK_FW, []).append(
215
+ snapshot
216
+ )
217
+ mod_stat.snapshots.setdefault(_FSDPModState.BEF_PRE_FW, []).append(
218
+ deepcopy(snapshot)
219
+ )
220
+ elif not self._mod_tracker.is_bw:
221
+ parents = self._mod_tracker.parents - {mod_fqn}
222
+ if len(parents) == 1 and "Global" in parents:
223
+ raise NotImplementedError(
224
+ "FSDPMemTracker does not support memory tracking for multiple iterative calls."
225
+ " Either use ``reset_mod_stats`` to clear module memory stats for the previous iteration"
226
+ " or file a github issue if you need this feature."
227
+ )
228
+
229
+ args, kwargs = orig_fsdp_state_pre_fw(*args, **kwargs)
230
+
231
+ fsdp_state = fsdp_mod._get_fsdp_state()
232
+ if fsdp_param_group := fsdp_state._fsdp_param_group:
233
+ for fsdp_param in fsdp_param_group.fsdp_params:
234
+ self._update_and_maybe_create_winfos(
235
+ fsdp_param.unsharded_param,
236
+ _FSDPRefType.UNSHARDED_PARAM,
237
+ )
238
+ mod_stat = self.memory_tracking[fsdp_mod]
239
+ if self._mod_tracker.is_bw:
240
+ state = _FSDPModState.PRE_FW_AC
241
+ if self._ac_mod is None:
242
+ self._ac_mod = weakref.ref(fsdp_mod)
243
+ self._in_ac = True
244
+ else:
245
+ state = _FSDPModState.AFT_PRE_FW
246
+ mod_stat.snapshots.setdefault(state, []).append(self.get_tracker_snapshot())
247
+ return args, kwargs
248
+
249
+ return inner
250
+
251
+ def _fsdp_state_post_forward(
252
+ self,
253
+ fsdp_mod: FSDPModule,
254
+ orig_fsdp_state_post_fw: Callable,
255
+ ) -> Callable:
256
+ # We capture memory snapshots before and after ``FSDPState._post_forward`` to capture the resharded state
257
+ # if ``reshard_after_forward`` is not ``False``. There are two cases:
258
+ # Case 1: This is called in backward, which means we are in the AC region. If this is the top most module
259
+ # in the AC region, we set the flag ``_in_ac`` to False.
260
+ # Case 2: This is called in forward.
261
+ @wraps(orig_fsdp_state_post_fw)
262
+ def inner(*args: Any, **kwargs: Any) -> Any:
263
+ mod_stat = self.memory_tracking[fsdp_mod]
264
+ if self._mod_tracker.is_bw:
265
+ state = _FSDPModState.POST_FW_AC
266
+ if self._ac_mod is not None and self._ac_mod() is fsdp_mod:
267
+ self._ac_mod = None
268
+ self._in_ac = False
269
+ else:
270
+ state = _FSDPModState.BEF_POST_FW
271
+ mod_stat.snapshots.setdefault(state, []).append(self.get_tracker_snapshot())
272
+
273
+ output = orig_fsdp_state_post_fw(*args, **kwargs)
274
+
275
+ if not self._mod_tracker.is_bw:
276
+ mod_stat.snapshots.setdefault(_FSDPModState.AFT_POST_FW, []).append(
277
+ self.get_tracker_snapshot()
278
+ )
279
+ return output
280
+
281
+ return inner
282
+
283
+ def _fsdp_param_group_pre_backward(
284
+ self,
285
+ fsdp_mod: FSDPModule,
286
+ orig_fsdp_param_group_pre_backward: Callable,
287
+ ) -> Callable:
288
+ # We capture memory snapshots before and after ``FSDPParamGroup.pre_backward`` to capture the pre-fetching
289
+ # and unsharding of params. We also initialize ``local_peak`` and ``PEAK_BW`` snapshot for the module.
290
+ @wraps(orig_fsdp_param_group_pre_backward)
291
+ def inner(*args: Any, **kwargs: Any) -> None:
292
+ mod_stat = self.memory_tracking[fsdp_mod]
293
+ snapshot = self.get_tracker_snapshot()
294
+ mod_stat.local_peak = {
295
+ dev: dev_snap[_TOTAL_KEY] for dev, dev_snap in snapshot.items()
296
+ }
297
+ mod_stat.snapshots.setdefault(_FSDPModState.PEAK_BW, []).append(snapshot)
298
+ mod_stat.snapshots.setdefault(_FSDPModState.BEF_PRE_BW, []).append(
299
+ deepcopy(snapshot)
300
+ )
301
+ orig_fsdp_param_group_pre_backward(*args, **kwargs)
302
+
303
+ mod_stat.snapshots.setdefault(_FSDPModState.AFT_PRE_BW, []).append(
304
+ self.get_tracker_snapshot()
305
+ )
306
+
307
+ return inner
308
+
309
+ def _fsdp_param_group_post_backward(
310
+ self,
311
+ fsdp_mod: FSDPModule,
312
+ orig_fsdp_param_group_post_backward: Callable,
313
+ ) -> Callable:
314
+ # We capture the memory snapshots before and after ``FSDPParamGroup.post_backward`` to track and attribute
315
+ # the `unsharded` grads before the post backward and then `sharded` grads and `reduce_scatter` buffers
316
+ # after the post backward.
317
+ @wraps(orig_fsdp_param_group_post_backward)
318
+ def inner(*args: Any, **kwargs: Any) -> None:
319
+ fsdp_state = fsdp_mod._get_fsdp_state()
320
+ if fsdp_param_group := fsdp_state._fsdp_param_group:
321
+ for fsdp_param in fsdp_param_group.fsdp_params:
322
+ unsharded_grad = fsdp_param._unsharded_param.grad
323
+ if unsharded_grad is not None:
324
+ self._update_and_maybe_create_winfos(
325
+ unsharded_grad,
326
+ _FSDPRefType.UNSHARDED_GRAD,
327
+ update_existing=True,
328
+ )
329
+
330
+ mod_stat = self.memory_tracking[fsdp_mod]
331
+ mod_stat.snapshots.setdefault(_FSDPModState.BEF_POST_BW, []).append(
332
+ self.get_tracker_snapshot()
333
+ )
334
+
335
+ orig_fsdp_param_group_post_backward(*args, **kwargs)
336
+
337
+ if fsdp_param_group := fsdp_state._fsdp_param_group:
338
+ for fsdp_param in fsdp_param_group.fsdp_params:
339
+ sharded_grad = fsdp_param.sharded_param.grad
340
+ if sharded_grad is not None:
341
+ self._update_and_maybe_create_winfos(
342
+ sharded_grad,
343
+ _FSDPRefType.SHARDED_GRAD,
344
+ )
345
+
346
+ mod_stat.snapshots.setdefault(_FSDPModState.AFT_POST_BW, []).append(
347
+ self.get_tracker_snapshot()
348
+ )
349
+
350
+ return inner
351
+
352
+ def _instrument_fsdp_module(self) -> None:
353
+ # We uninstall the existing `FSDPState._pre_forward` and `FSDPState._post_forward` hooks and install
354
+ # our own hooks that wrap them. We choose this over monkey-patching `FSDPParamGroup.pre_forward` and
355
+ # `FSDPParamGroup.post_forward` because during AC these won't be called.
356
+ # TODO(@sanketpurandare): This will need to be modified after this PR (https://github.com/pytorch/pytorch/pull/127786)
357
+ # lands. For backward we monkey-patch the `FSDPParamGroup.pre_backward` and `FSDPParamGroup.post_backward`.
358
+ for module in self._root_mod.modules():
359
+ if isinstance(module, FSDPModule):
360
+ fsdp_state = module._get_fsdp_state()
361
+ if fsdp_param_group := fsdp_state._fsdp_param_group:
362
+ self._instrument_fsdp_sharded_params_grads(fsdp_param_group)
363
+ fsdp_state._pre_forward_hook_handle.remove()
364
+ fsdp_state._post_forward_hook_handle.remove()
365
+ fsdp_state._pre_forward_hook_handle = (
366
+ module.register_forward_pre_hook(
367
+ self._fsdp_state_pre_forward(
368
+ module, fsdp_state._pre_forward
369
+ ),
370
+ prepend=True,
371
+ with_kwargs=True,
372
+ )
373
+ )
374
+ fsdp_state._post_forward_hook_handle = module.register_forward_hook(
375
+ self._fsdp_state_post_forward(module, fsdp_state._post_forward),
376
+ prepend=False,
377
+ always_call=True,
378
+ )
379
+ self._fsdp_mod_to_saved_methods[module] = _SavedFSDPMethods(
380
+ fsdp_param_group.pre_backward,
381
+ fsdp_param_group.post_backward,
382
+ )
383
+ fsdp_param_group.pre_backward = self._fsdp_param_group_pre_backward( # type: ignore[assignment]
384
+ module, fsdp_param_group.pre_backward
385
+ )
386
+ fsdp_param_group.post_backward = ( # type: ignore[assignment]
387
+ self._fsdp_param_group_post_backward(
388
+ module, fsdp_param_group.post_backward
389
+ )
390
+ )
391
+
392
+ for buffer in self._root_mod.buffers():
393
+ self._update_and_maybe_create_winfos(
394
+ buffer,
395
+ _FSDPRefType.BUFFER,
396
+ )
397
+
398
+ def _instrument_optimizer(self) -> None:
399
+ # Register a hook on the optimizer step to track the optimizer states.
400
+ # The pre-hook is to set the flag ``_in_opt`` to True. The post-hook unsets the flag,
401
+ # and also tracks any optimizer states that are created during the optimizer step.
402
+ if self._optm is not None:
403
+ self._track_optimizer_states(_FSDPRefType.OPT, self._optm)
404
+
405
+ def _opt_step_pre_hook(
406
+ optimizer: optim.Optimizer, args: Any, kwargs: Any
407
+ ) -> None:
408
+ self._in_opt = True
409
+
410
+ def _opt_step_post_hook(
411
+ optimizer: optim.Optimizer, args: Any, kwargs: Any
412
+ ) -> None:
413
+ self._track_optimizer_states(_FSDPRefType.OPT, optimizer)
414
+ self._in_opt = False
415
+
416
+ self._optimizer_hook_handles = (
417
+ self._optm.register_step_pre_hook(_opt_step_pre_hook),
418
+ self._optm.register_step_post_hook(_opt_step_post_hook),
419
+ )
420
+
421
+ def _register_module_and_optimizer_hooks(self) -> None:
422
+ self._instrument_fsdp_module()
423
+ self._instrument_optimizer()
424
+
425
+ def _deregister_module_and_optimizer_hooks(self) -> None:
426
+ for (
427
+ fsdp_mod,
428
+ saved_methods,
429
+ ) in self._fsdp_mod_to_saved_methods.items():
430
+ fsdp_state = fsdp_mod._get_fsdp_state()
431
+ fsdp_state._pre_forward_hook_handle.remove()
432
+ fsdp_state._post_forward_hook_handle.remove()
433
+ fsdp_state._pre_forward_hook_handle = fsdp_mod.register_forward_pre_hook(
434
+ fsdp_state._pre_forward, prepend=True, with_kwargs=True
435
+ )
436
+ fsdp_state._post_forward_hook_handle = fsdp_mod.register_forward_hook(
437
+ fsdp_state._post_forward, prepend=False
438
+ )
439
+ if fsdp_param_group := fsdp_state._fsdp_param_group:
440
+ fsdp_param_group.pre_backward = saved_methods.pre_backward
441
+ fsdp_param_group.post_backward = saved_methods.post_backward
442
+ self._fsdp_mod_to_saved_methods.clear()
443
+
444
+ if self._optimizer_hook_handles is not None:
445
+ for handle in self._optimizer_hook_handles:
446
+ handle.remove()
447
+ self._optimizer_hook_handles = None
448
+
449
+ def _instrument_and_maybe_bypass_collectives(self) -> None:
450
+ # Monkey-patching collectives is required because they do not work with `FakeTensorMode`
451
+ # It's also easier to track `all_gather` and `reduce_scatter` buffers faithfully.
452
+ self._saved_collectives = _SavedCollectives(
453
+ dist.all_gather_into_tensor,
454
+ dist.reduce_scatter_tensor,
455
+ dist.all_reduce,
456
+ dist.barrier,
457
+ )
458
+
459
+ class FakeWork(Work):
460
+ def __init__(self) -> None:
461
+ super().__init__()
462
+
463
+ def get_future(self) -> Future:
464
+ future: Future = Future()
465
+ future.set_result(None)
466
+ return future
467
+
468
+ def wait(self, timeout: Optional[timedelta] = None) -> bool:
469
+ return True
470
+
471
+ @wraps(dist.all_gather_into_tensor)
472
+ def all_gather_into_tensor(
473
+ output_tensor: torch.Tensor,
474
+ input_tensor: torch.Tensor,
475
+ group: Union[ProcessGroup, None] = None,
476
+ async_op: bool = False,
477
+ ) -> Union[Work, _IllegalWork, None]:
478
+ self._update_and_maybe_create_winfos(
479
+ output_tensor,
480
+ _FSDPRefType.ALL_GATHER,
481
+ update_existing=True,
482
+ )
483
+
484
+ if self._in_fake_mode:
485
+ if async_op:
486
+ return FakeWork()
487
+ return None
488
+ else:
489
+ return self._saved_collectives.all_gather_into_tensor(
490
+ output_tensor, input_tensor, group, async_op
491
+ )
492
+
493
+ @wraps(dist.reduce_scatter_tensor)
494
+ def reduce_scatter_tensor(
495
+ output: torch.Tensor,
496
+ input: torch.Tensor,
497
+ op: ReduceOp.RedOpType = dist.ReduceOp.SUM,
498
+ group: Union[ProcessGroup, None] = None,
499
+ async_op: bool = False,
500
+ ) -> Union[Work, _IllegalWork, None]:
501
+ self._update_and_maybe_create_winfos(
502
+ input,
503
+ _FSDPRefType.REDUCE_SCATTER,
504
+ update_existing=True,
505
+ )
506
+
507
+ if self._in_fake_mode:
508
+ if async_op:
509
+ return FakeWork()
510
+ return None
511
+ else:
512
+ return self._saved_collectives.reduce_scatter_tensor(
513
+ output, input, op, group, async_op
514
+ )
515
+
516
+ @wraps(dist.all_reduce)
517
+ def all_reduce(
518
+ tensor: torch.Tensor,
519
+ op: ReduceOp.RedOpType = dist.ReduceOp.SUM,
520
+ group: Union[ProcessGroup, None] = None,
521
+ async_op: bool = False,
522
+ ) -> Union[Work, _IllegalWork, None]:
523
+ if self._in_fake_mode:
524
+ if async_op:
525
+ return FakeWork()
526
+ return None
527
+ else:
528
+ return self._saved_collectives.all_reduce(tensor, op, group, async_op)
529
+
530
+ @wraps(dist.barrier)
531
+ def barrier(
532
+ group: Union[ProcessGroup, None] = dist.GroupMember.WORLD,
533
+ async_op: bool = False,
534
+ device_ids: Union[List[int], None] = None,
535
+ ) -> Union[Work, None]:
536
+ if self._in_fake_mode:
537
+ return None
538
+ else:
539
+ return self._saved_collectives.barrier(group, async_op, device_ids)
540
+
541
+ dist.all_gather_into_tensor = all_gather_into_tensor
542
+ dist.reduce_scatter_tensor = reduce_scatter_tensor
543
+ dist.all_reduce = all_reduce
544
+ dist.barrier = barrier
545
+
546
+ def _restore_collectives(self) -> None:
547
+ dist.all_gather_into_tensor = self._saved_collectives.all_gather_into_tensor
548
+ dist.reduce_scatter_tensor = self._saved_collectives.reduce_scatter_tensor
549
+ dist.all_reduce = self._saved_collectives.all_reduce
550
+ dist.barrier = self._saved_collectives.barrier
551
+ del self._saved_collectives
552
+
553
+ def track_inputs(self, inputs: Tuple[Any, ...]) -> None:
554
+ """
555
+ This is used to track the input tensors to the model and annotate them as ``Inputs``.
556
+ Args:
557
+ inputs (Tuple[Any]): A tuple containing the input data. This can include tensors
558
+ as well as other data types. Only tensors will be tracked.
559
+ """
560
+
561
+ def _track_inputs(t: torch.Tensor) -> None:
562
+ self._update_and_maybe_create_winfos(
563
+ t,
564
+ _FSDPRefType.INP,
565
+ )
566
+
567
+ tree_map_only(torch.Tensor, _track_inputs, inputs)
568
+
569
+ def track_external(
570
+ self, *external: Union[nn.Module, optim.Optimizer, torch.Tensor]
571
+ ) -> None:
572
+ """This is no-op for ``FSDPMemTracker``"""
573
+
574
+ def __enter__(self) -> "FSDPMemTracker":
575
+ self._in_fake_mode = True if active_fake_mode() else False
576
+ self._register_module_and_optimizer_hooks()
577
+ self._instrument_and_maybe_bypass_collectives()
578
+ self._track_resize()
579
+ self._peak_mem_snap = self.get_tracker_snapshot()
580
+ self._peak_mem = {
581
+ dev: dev_snap[_TOTAL_KEY] for dev, dev_snap in self._peak_mem_snap.items()
582
+ }
583
+ self._mod_tracker.__enter__()
584
+ TorchDispatchMode.__enter__(self)
585
+ return self
586
+
587
+ def __exit__(self, *args: Any) -> None:
588
+ self._deregister_module_and_optimizer_hooks()
589
+ self._restore_collectives()
590
+ self._restore_resize()
591
+ TorchDispatchMode.__exit__(self, *args)
592
+ self._mod_tracker.__exit__(*args)
593
+
594
+ def __torch_dispatch__(self, func, types, args=..., kwargs=None): # type: ignore[no-untyped-def]
595
+ res = func(*args, **kwargs or {})
596
+ # If we are tracking an optimizer state, we use the optimizer reference type.
597
+ # If we are in backward region and not in AC region, we use the backward reference type.
598
+ # Else we use the forward reference type.
599
+ if self._in_opt:
600
+ reftype = _FSDPRefType.OPT
601
+ elif self._mod_tracker.is_bw and not self._in_ac:
602
+ reftype = _FSDPRefType.TEMP
603
+ else:
604
+ reftype = _FSDPRefType.ACT
605
+ tree_map_only(torch.Tensor, partial(self._track, reftype), res)
606
+ peak_state = (
607
+ _FSDPModState.PEAK_BW if self._mod_tracker.is_bw else _FSDPModState.PEAK_FW
608
+ )
609
+ self._update_peak_stats(peak_state)
610
+ return res
vllm/lib/python3.10/site-packages/torch/distributed/_tools/mem_tracker.py ADDED
@@ -0,0 +1,943 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import re
4
+ import warnings
5
+ from copy import deepcopy
6
+ from enum import auto, Enum
7
+ from functools import partial, wraps
8
+ from typing import (
9
+ Any,
10
+ Callable,
11
+ Dict,
12
+ List,
13
+ Optional,
14
+ Set,
15
+ Tuple,
16
+ Type,
17
+ TYPE_CHECKING,
18
+ Union,
19
+ )
20
+ from typing_extensions import Self
21
+
22
+ import torch
23
+ from torch import nn, optim
24
+ from torch.distributed._tools.mod_tracker import ModTracker
25
+ from torch.optim.optimizer import (
26
+ register_optimizer_step_post_hook,
27
+ register_optimizer_step_pre_hook,
28
+ )
29
+ from torch.utils._python_dispatch import (
30
+ is_traceable_wrapper_subclass,
31
+ TorchDispatchMode,
32
+ )
33
+ from torch.utils._pytree import tree_flatten, tree_map_only
34
+ from torch.utils.weak import WeakIdKeyDictionary, weakref
35
+
36
+
37
+ if TYPE_CHECKING:
38
+ from torch.utils.hooks import RemovableHandle
39
+
40
+ # This value is hard-coded here:
41
+ # https://github.com/pytorch/pytorch/blob/5fba5d83f0703ff8077ab65448a998e9ad6598fd/c10/cuda/CUDACachingAllocator.cpp#L117
42
+ _PYTORCH_MIN_ALLOCATE = (
43
+ 2**9 if int(os.environ.get("PYTORCH_NO_CUDA_MEMORY_CACHING", 0)) == 0 else 1
44
+ )
45
+ _TOTAL_KEY = "Total"
46
+
47
+ __all__ = ["MemTracker"]
48
+
49
+
50
+ class _RefType(str, Enum):
51
+ """Base Class for defining memory reference types, categorizing tensors based on their usage within a model."""
52
+
53
+
54
+ class _State(str, Enum):
55
+ """Base Class for defining module state to capture snapshots ."""
56
+
57
+
58
+ class _MemRefType(_RefType):
59
+ """
60
+ An enum to define memory reference types, categorizing tensors based on their usage within a model.
61
+
62
+ - PARAM: Tensors registered as nn.Parameter within modules.
63
+ - BUFFER: Tensors registered as nn.Buffer within modules.
64
+ - GRAD: Gradients associated with parameters.
65
+ - ACT: Tensors produced during the forward pass and recomputation in activation checkpointing.
66
+ - TMP: Temporary memory used during the backward pass, including gradients of activations.
67
+ - OPT: Tensors holding optimizer states.
68
+ - OTH: Tensors registered via `track_external` that do not fit the above categories.
69
+ """
70
+
71
+ PARAM = "Parameter"
72
+ BUFFER = "Buffer"
73
+ GRAD = "Gradient"
74
+ ACT = "Activation"
75
+ TEMP = "Temp"
76
+ OPT = "Optstate"
77
+ OTH = "Other"
78
+
79
+
80
+ class _ModState(_State):
81
+ """
82
+ An enum to define the state of a module.
83
+
84
+ - PRE_FW: The module is about to run the forward pass.
85
+ - POST_FW: The module has finished running the forward pass.
86
+ - PEAK_FW: The module has reached the peak memory usage during the forward pass.
87
+ - PRE_BW: The module is about to run the backward pass.
88
+ - PRE_FW_AC: The module is about to run the forward pass with activation checkpointing.
89
+ - POST_FW_AC: The module has finished running the forward pass with activation checkpointing.
90
+ - POST_BW: The module has finished running the backward pass.
91
+ - PEAK_BW: The module has reached the peak memory usage during the backward pass.
92
+ """
93
+
94
+ PRE_FW = "Pre-Forward"
95
+ POST_FW = "Post-Forward"
96
+ PEAK_FW = "Peak-Forward"
97
+ PRE_BW = "Pre-Backward"
98
+ PRE_FW_AC = "Pre-Forward-AC"
99
+ POST_FW_AC = "Post-Forward-AC"
100
+ POST_BW = "Post-Backward"
101
+ PEAK_BW = "Peak-Backward"
102
+
103
+
104
+ class _ModMemStats:
105
+ """
106
+ A class to store the memory statistics of a module.
107
+
108
+ Args:
109
+ mod_fqn (str): The fully qualified name of the module.
110
+ Attributes:
111
+ mod_fqn (str): The fully qualified name of the module.
112
+ parameter_mem (int): The memory usage of the parameters of the module.
113
+ buffer_mem (int): The memory usage of the buffers of the module.
114
+ input_mem (int): The memory usage of the inputs to the module.
115
+ output_mem (int): The memory usage of the outputs from the module.
116
+ snapshots (Dict[_ModState, Dict[torch.device, Dict[str, int]]]): A dictionary of memory snapshots
117
+ of the module at different states defined by ``_ModState``.
118
+ Note:
119
+ The memory snapshot is stored as a dictionary - Dict[torch.device, Dict[str, int]], where each key is a device,
120
+ and each value is another dictionary with keys as memory reference types defined by `_MemRefType` and
121
+ values as the memory consumed in bytes.
122
+ """
123
+
124
+ def __init__(self, mod_fqn: str):
125
+ self.mod_fqn = mod_fqn
126
+ self.parameter_mem: int
127
+ self.buffer_mem: int
128
+ self.input_mem: int
129
+ self.output_mem: int
130
+ self.local_peak: Dict[torch.device, int] = {}
131
+ self.snapshots: Dict[_ModState, List[Dict[torch.device, Dict[str, int]]]] = {}
132
+
133
+
134
+ class _WeakRefInfo:
135
+ """
136
+ Manages memory statistics and device attributes for tensor storages.
137
+ """
138
+
139
+ def __init__(
140
+ self, size: int, element_size: int, device: torch.device, reftype: _RefType
141
+ ) -> None:
142
+ """
143
+ Initializes the ``_WeakRefInfo`` object with tensor storage properties.
144
+
145
+ Args:
146
+ size (int): The number of elements in the tensor storage.
147
+ element_size (int): The size of each element in the tensor storage.
148
+ device (torch.device): The device on which the tensor is allocated.
149
+ reftype (_RefType): The reference type of the tensor.
150
+ """
151
+ self.size = size
152
+ self.element_size = element_size
153
+ self.reftype = reftype
154
+ self.device = device
155
+ self.mem_consumed = self._calculate_mem_consumed()
156
+
157
+ def _calculate_mem_consumed(self) -> int:
158
+ """
159
+ Calculates the memory consumed by the tensor storage, considering device-specific allocation rules.
160
+
161
+ Returns:
162
+ int: The memory consumed in bytes.
163
+ """
164
+ mem = self.size * self.element_size
165
+ if self.device.type == "cuda":
166
+ return math.ceil((mem) / _PYTORCH_MIN_ALLOCATE) * _PYTORCH_MIN_ALLOCATE
167
+ return mem
168
+
169
+ def update_mem_consumed(self, st: torch.UntypedStorage) -> int:
170
+ """
171
+ Updates and returns the memory consumed if the storage size has changed.
172
+
173
+ Args:
174
+ st (torch.UntypedStorage): The tensor storage to check for size updates.
175
+
176
+ Returns:
177
+ int: The updated memory consumed in bytes.
178
+ """
179
+ if st.size() != self.size:
180
+ self.size = st.size()
181
+ self.mem_consumed = self._calculate_mem_consumed()
182
+ return self.mem_consumed
183
+
184
+ @staticmethod
185
+ def get_untyped_storages(t: torch.Tensor) -> Set[torch.UntypedStorage]:
186
+ """
187
+ Recursively extracts untyped storages from a tensor or its subclasses.
188
+
189
+ Args:
190
+ t (torch.Tensor): The tensor to extract storages from.
191
+
192
+ Returns:
193
+ Set[torch.UntypedStorage]: A set of untyped storages.
194
+ """
195
+ unflattened_tensors = [t]
196
+ flattened_tensor_storages = set()
197
+ while len(unflattened_tensors) > 0:
198
+ obj = unflattened_tensors.pop()
199
+ if is_traceable_wrapper_subclass(obj):
200
+ attrs, _ = obj.__tensor_flatten__() # type: ignore[attr-defined]
201
+ unflattened_tensors.extend([getattr(obj, attr) for attr in attrs])
202
+ else:
203
+ if not hasattr(obj, "untyped_storage"):
204
+ warnings.warn(
205
+ f"Expected a tensor or a traceable wrapper-subclass of tensor, but got {type(obj)}",
206
+ category=UserWarning,
207
+ stacklevel=2,
208
+ )
209
+ else:
210
+ flattened_tensor_storages.add(obj.untyped_storage())
211
+ return flattened_tensor_storages
212
+
213
+ @classmethod
214
+ def create_winfo(
215
+ cls,
216
+ st: torch.UntypedStorage,
217
+ device: torch.device,
218
+ reftype: _RefType,
219
+ callback: Optional[Callable[[Self, weakref.ref], Any]] = None,
220
+ ) -> Tuple[Self, weakref.ref]:
221
+ """
222
+ Creates a new ``_WeakRefInfo`` instance and a weak reference to a ``torch.UntypedStorage`` object,
223
+ optionally attaching a callback to the weak reference.
224
+
225
+ Args:
226
+ st (torch.UntypedStorage): The storage object for which to create the weak reference info.
227
+ device (torch.device): The device associated with the storage object.
228
+ reftype (_RefType): The type of reference, used to categorize the storage.
229
+ callback (Optional[Callable[[Self, weakref.ref]]]): A callback function that is called when
230
+ the storage object is about to be finalized (garbage collected). The callback function
231
+ should accept two arguments: the ``_WeakRefInfo`` instance and the weak reference to the storage.
232
+ Returns:
233
+ Tuple[Self, weakref.ref]: A tuple containing the newly created ``_WeakRefInfo`` instance and the
234
+ weak reference to the storage object. The weak reference may have an attached callback if provided.
235
+ """
236
+
237
+ winfo = cls(st.size(), st.element_size(), device, reftype)
238
+ w_st = weakref.ref(st, partial(callback, winfo) if callback else None)
239
+ return winfo, w_st
240
+
241
+
242
+ def _get_mem_divisor(units: str) -> int:
243
+ unit_dict = {"B": 1, "KiB": 2**10, "MiB": 2**20, "GiB": 2**30}
244
+ if units in unit_dict:
245
+ return unit_dict[units]
246
+ else:
247
+ raise ValueError(
248
+ f"Unsupported unit: {units}. Supported units are: {', '.join(unit_dict.keys())}"
249
+ )
250
+
251
+
252
+ def _rounding_fn(value: int, divisor: int, precision: int) -> Union[float, int]:
253
+ return value if divisor == 1 else round(value / divisor, precision)
254
+
255
+
256
+ def _print_snapshot(snapshot: Dict[torch.device, Dict[str, int]], units: str) -> None:
257
+ if len(snapshot) == 0:
258
+ print("No memory tracked.")
259
+ return
260
+ divisor = _get_mem_divisor(units)
261
+ for dev, dev_snap in snapshot.items():
262
+ if _rounding_fn(dev_snap[_TOTAL_KEY], divisor, 2) <= 0:
263
+ continue
264
+ print(
265
+ f"Device: {dev}",
266
+ *(
267
+ f"\t{k}: {_rounding_fn(v, divisor, 2)} {units}"
268
+ for k, v in dev_snap.items()
269
+ ),
270
+ sep="\n",
271
+ )
272
+
273
+
274
+ def _print_snapshot_tabular(
275
+ snapshot: Dict[torch.device, Dict[str, int]], units: str
276
+ ) -> None:
277
+ if len(snapshot) == 0:
278
+ print("No memory tracked.")
279
+ return
280
+ try:
281
+ from tabulate import tabulate
282
+ except ImportError as err:
283
+ raise ImportError(
284
+ "Please install tabulate to use the tabulate option."
285
+ ) from err
286
+ divisor = _get_mem_divisor(units)
287
+ table_data = []
288
+ key_list = list(next(iter(snapshot.values())).keys())
289
+ headers = ["Device"] + [f"{key}" for key in key_list]
290
+
291
+ for dev, dev_snap in snapshot.items():
292
+ if _rounding_fn(dev_snap[_TOTAL_KEY], divisor, 2) <= 0:
293
+ continue
294
+ row = [str(dev)]
295
+ row.extend(f"{_rounding_fn(v, divisor, 2)} {units}" for v in dev_snap.values())
296
+ table_data.append(row)
297
+ print(tabulate(table_data, headers=headers, tablefmt="rst"))
298
+
299
+
300
+ def _print_state_snapshots(
301
+ snapshots: Dict[_State, List[Dict[torch.device, Dict[str, int]]]], units: str
302
+ ) -> None:
303
+ for state, snapshot_list in snapshots.items():
304
+ print(f"{state}")
305
+ for i, snapshot in enumerate(snapshot_list):
306
+ print(f"# {i + 1}:")
307
+ _print_snapshot(snapshot, units)
308
+ print()
309
+
310
+
311
+ def _print_state_snapshots_tabular(
312
+ snapshots: Dict[_State, List[Dict[torch.device, Dict[str, int]]]], units: str
313
+ ) -> None:
314
+ try:
315
+ from tabulate import tabulate
316
+ except ImportError as err:
317
+ raise ImportError(
318
+ "Please install tabulate to use the tabulate option."
319
+ ) from err
320
+
321
+ table_data = []
322
+ last_state_call = None
323
+ divisor = _get_mem_divisor(units)
324
+ for state, snapshot_list in snapshots.items():
325
+ for i, snapshot in enumerate(snapshot_list):
326
+ state_call = f"{state} # {i + 1}"
327
+ for dev, dev_snap in snapshot.items():
328
+ if _rounding_fn(dev_snap[_TOTAL_KEY], divisor, 2) <= 0:
329
+ continue
330
+ row = {
331
+ "State & Call": (
332
+ state_call if state_call != last_state_call else ""
333
+ ),
334
+ "Device": str(dev),
335
+ }
336
+ last_state_call = state_call
337
+ for k, v in dev_snap.items():
338
+ row[f"{k}"] = f"{_rounding_fn(v, divisor, 2)} {units}"
339
+ table_data.append(row)
340
+ print(tabulate(table_data, headers="keys", tablefmt="rst"))
341
+
342
+
343
+ class _UpdateType(Enum):
344
+ # These are used for tracking updates to the continuouly maintained memory snapshot.
345
+ # ADD - When a new tensor storage is tracked
346
+ # DEL - When a tensor storage is about to be finalized (garbage collected).
347
+ # REF - When a tensor reference is updated, for instance, the gradients are marked as
348
+ # generic backward reference types until the grad_hook categorizes them as gradients.
349
+ # SIZE - When a tensor's storage is resized.
350
+ ADD = auto()
351
+ DEL = auto()
352
+ REF = auto()
353
+ SIZE = auto()
354
+
355
+
356
+ class MemTracker(TorchDispatchMode):
357
+ """
358
+ A TorchDispatchMode to track, categorize and attribute the tensor memory created or accessed within its context.
359
+
360
+ It categorizes the tracked tensors as parameters, buffers, activations, gradients, temporary memory and optimizer states
361
+ as defined by ``_MemRefType`` within its context. It captures memory `snapshots` for the modules, called within its context,
362
+ at various states defined by ``_ModState``.
363
+
364
+ Attributes:
365
+ memory_tracking: A weakref key dictionary to store the memory statistics of each module. Each key
366
+ is a reference to a module, and each value is a ``_ModMemStats`` object that stores the memory
367
+ statistics of the module.
368
+
369
+ Note:
370
+ The MemTracker should be used as a context manager. The modules, optimizers, and any other tensors created within
371
+ the context of MemTracker will be tracked by default. Any tensors or stateful objects such as modules, optimizers etc.
372
+ that need to be tracked but are created outside the MemTracker should be registered using the `track_external` method.
373
+ The `track_external` method should be called before the MemTracker is used. Any tensors created outside the ``MemTracker``
374
+ and not supplied to the `track_external` method will not be tracked by the ``MemTracker``.
375
+
376
+ Example usage:
377
+
378
+ .. code-block:: python
379
+
380
+ module = ...
381
+ optimizer = ...
382
+ inp = ...
383
+ mem_tracker = MemTracker()
384
+ mem_tracker.track_external(module, optimizer, inp)
385
+ with mem_tracker as mt:
386
+ loss = module(inp)
387
+ print("After Forward:")
388
+ mt.display_snapshot("current")
389
+ loss.backward()
390
+ optimizer.step()
391
+ optimizer.zero_grad()
392
+ mt.display_snapshot("peak")
393
+ mt.display_modulewise_snapshots(depth = 3, units = "MiB")
394
+
395
+ Known Limitations:
396
+ - The ``MemTracker`` does not track memory for tensors that bypass the ``TorchDispatchMode`` ex. under ``no_dispatch``.
397
+ - Resizing tensor storages directly by using non-Tensor methods other than using ``torch.Untyped_Storage.resize_``
398
+ is not tracked. File a Github issue if you have use-cases for this.
399
+ - If the tensors are not traceable or wrappable subclasses of ``torch.Tensor``, then the tracker does not know how to
400
+ track their storages. File a Github issue if you have use-cases for this.
401
+ - During AC in the backward pass there might be misattribution between activation and temp memory, but the peak memory
402
+ will be tracked accurately. This will be fixed in the next update by hooking intricately with ``torch.uitls.checkpoint``.
403
+ """
404
+
405
+ def __init__(self) -> None:
406
+ self.memory_tracking = WeakIdKeyDictionary()
407
+ self._curr_mem_snap: Dict[torch.device, Dict[str, int]] = {}
408
+ self._peak_mem: Dict[torch.device, int] = {}
409
+ self._peak_mem_snap: Dict[torch.device, Dict[str, int]] = {}
410
+ self._param_to_grad_hook_handles = WeakIdKeyDictionary()
411
+ self._optimizer_hook_handles: Optional[
412
+ Tuple[RemovableHandle, RemovableHandle]
413
+ ] = None
414
+ # Dictionary to store the ``_WeakRefInfo`` instances corresponding to each tensor's storage.
415
+ self._WINFO = WeakIdKeyDictionary()
416
+ self._mod_tracker = ModTracker()
417
+ # This is a general memory tracker which can be used with any ``_RefType`` subclass
418
+ self._ref_class: Type[_RefType] = _MemRefType
419
+ # Flags to track if we are in the AC region or optimizer step region
420
+ self._in_opt: bool = False
421
+ self._in_ac: bool = False
422
+ # Weak references to the topmost AC module currently active
423
+ self._ac_mod: Optional[weakref.ref] = None
424
+ self._orig_resize = torch.UntypedStorage.resize_
425
+
426
+ def _update_snap(
427
+ self,
428
+ u_type: _UpdateType,
429
+ winfo: _WeakRefInfo,
430
+ old_mem_consumed: Optional[int] = None,
431
+ old_reftype: Optional[_RefType] = None,
432
+ ) -> None:
433
+ # Initialize a flag to track if the total memory might drop to zero after updates.
434
+ maybe_zero = False
435
+ # Ensure the device entry exists in the current memory snapshot, initializing if necessary.
436
+ dev_snap = self._curr_mem_snap.setdefault(
437
+ winfo.device, dict.fromkeys(self._ref_class, 0)
438
+ )
439
+ dev_snap.setdefault(_TOTAL_KEY, 0)
440
+ # Handle different types of updates based on the update type (`u_type`).
441
+ if u_type == _UpdateType.ADD:
442
+ # Increase the memory consumed for the specific reference type and update the total.
443
+ dev_snap[winfo.reftype] += winfo.mem_consumed
444
+ dev_snap[_TOTAL_KEY] += winfo.mem_consumed
445
+ elif u_type == _UpdateType.DEL:
446
+ # Decrease the memory consumed for the specific reference type and reduce the total.
447
+ dev_snap[winfo.reftype] -= winfo.mem_consumed
448
+ dev_snap[_TOTAL_KEY] -= winfo.mem_consumed
449
+ maybe_zero = True
450
+ elif u_type == _UpdateType.REF:
451
+ assert old_reftype is not None
452
+ # Adjust memory consumption between two reference types within the same device.
453
+ dev_snap[old_reftype] -= winfo.mem_consumed
454
+ dev_snap[winfo.reftype] += winfo.mem_consumed
455
+ elif u_type == _UpdateType.SIZE:
456
+ assert old_mem_consumed is not None
457
+ # Adjust the memory consumed for a reference type due to a change in size.
458
+ change = winfo.mem_consumed - old_mem_consumed
459
+ dev_snap[winfo.reftype] += change
460
+ dev_snap[_TOTAL_KEY] += change
461
+ maybe_zero = True
462
+ else:
463
+ raise ValueError(f"Invalid update type: {u_type}")
464
+ # Check if the total memory for the device has dropped to zero.
465
+ if maybe_zero:
466
+ if self._curr_mem_snap[winfo.device][_TOTAL_KEY] == 0:
467
+ # Remove the device entry from the memory snapshot if the total memory is zero.
468
+ del self._curr_mem_snap[winfo.device]
469
+
470
+ def _update_and_maybe_create_winfos(
471
+ self,
472
+ t: torch.Tensor,
473
+ reftype: _RefType,
474
+ update_existing: bool = False,
475
+ ) -> Set[_WeakRefInfo]:
476
+ sts = _WeakRefInfo.get_untyped_storages(t)
477
+ winfos = set()
478
+ for st in sts:
479
+ # Attempt to retrieve existing ``_WeakRefInfo`` and its weak reference from the tracking dictionary.
480
+ winfo, _ = self._WINFO.get(st, (None, None))
481
+ if winfo is not None:
482
+ # If ``_WeakRefInfo`` exists, check if the reference type needs to be updated.
483
+ old_reftype = winfo.reftype
484
+ if old_reftype != reftype:
485
+ # Update the reference type and apply changes via ``_update_snap``.
486
+ winfo.reftype = reftype
487
+ self._update_snap(_UpdateType.REF, winfo, old_reftype=old_reftype)
488
+ winfos.add(winfo)
489
+ elif update_existing:
490
+ # If no existing ``_WeakRefInfo`` is found and update_existing is True, raise an error.
491
+ raise KeyError("No existing winfo found")
492
+ else:
493
+ # If no existing _WeakRefInfo is found and update_existing is False, create a new ``_WeakRefInfo``.
494
+ winfo, w_st = _WeakRefInfo.create_winfo(
495
+ st, t.device, reftype, self._delete_callback
496
+ )
497
+ # Store the new ``_WeakRefInfo`` and its weak reference in the tracking dictionary.
498
+ self._WINFO[st] = (winfo, w_st)
499
+ # Update the snapshot for the newly added ``_WeakRefInfo``.
500
+ if winfo.mem_consumed > 0:
501
+ self._update_snap(_UpdateType.ADD, winfo)
502
+ winfos.add(winfo)
503
+ return winfos
504
+
505
+ def _delete_callback(self, winfo: _WeakRefInfo, w_st: weakref.ref) -> None:
506
+ # Callback to be called when the storage object corresponding to the ``_WeakRefInfo``
507
+ # instance is about to be finalized.
508
+ if winfo.mem_consumed > 0:
509
+ self._update_snap(_UpdateType.DEL, winfo)
510
+
511
+ def _track_resize(self) -> None:
512
+ # Need to monkey-patch this because ``torch.UntypedStorage.resize_`` is not captured
513
+ # by ``TorchDispatchMode``.
514
+ @wraps(self._orig_resize)
515
+ def resize_(st: torch.UntypedStorage, size: int) -> None:
516
+ self._orig_resize(st, size)
517
+ winfo, _ = self._WINFO.get(st, (None, None))
518
+ if winfo is not None and winfo.size != st.size():
519
+ old_mem_consumed = winfo.mem_consumed
520
+ winfo.update_mem_consumed(st)
521
+ self._update_snap(
522
+ _UpdateType.SIZE, winfo, old_mem_consumed=old_mem_consumed
523
+ )
524
+
525
+ torch.UntypedStorage.resize_ = resize_ # type: ignore[method-assign, assignment]
526
+
527
+ def _restore_resize(self) -> None:
528
+ torch.UntypedStorage.resize_ = self._orig_resize # type: ignore[method-assign]
529
+
530
+ def _update_peak_stats(self, peak_state: _State) -> None:
531
+ # We first capture the current memory snapshot of the current tracker state then,
532
+ # We step through each of the modules we have tracked so far in ``memory_tracking``
533
+ # and check if it is currently active by querying ``_mod_tracker.parents``
534
+ # If it is active, we update the per device peak memory usage for the module
535
+ # corresponding to the ``_State`` which can be ``PEAK_FW`` or ``PEAK_BW``.
536
+ curr_snap = self._curr_mem_snap
537
+
538
+ for mod_stats in self.memory_tracking.values():
539
+ if mod_stats.mod_fqn in self._mod_tracker.parents:
540
+ if peak_state in mod_stats.snapshots:
541
+ for dev, dev_snap in curr_snap.items():
542
+ if mod_stats.local_peak.get(dev, 0) < dev_snap[_TOTAL_KEY]:
543
+ mod_stats.local_peak[dev] = dev_snap[_TOTAL_KEY]
544
+ mod_stats.snapshots[peak_state][-1][dev] = deepcopy(
545
+ dev_snap
546
+ )
547
+
548
+ for dev, dev_snap in curr_snap.items():
549
+ if self._peak_mem.get(dev, 0) < dev_snap[_TOTAL_KEY]:
550
+ self._peak_mem[dev] = dev_snap[_TOTAL_KEY]
551
+ self._peak_mem_snap[dev] = deepcopy(dev_snap)
552
+
553
+ def _track(self, reftype: _RefType, t: torch.Tensor) -> None:
554
+ # Get the storages of the tensor and check if we have already tracked them.
555
+ # If yes, then check if the storage size has changed and update the current snapshot.
556
+ # Else create a new ``_WeakRefInfo`` instance and add it to the dictionary.
557
+ sts = _WeakRefInfo.get_untyped_storages(t)
558
+ for st in sts:
559
+ winfo, _ = self._WINFO.get(st, (None, None))
560
+ if winfo is not None:
561
+ if winfo.size != st.size():
562
+ old_mem_consumed = winfo.mem_consumed
563
+ winfo.update_mem_consumed(st)
564
+ self._update_snap(
565
+ _UpdateType.SIZE, winfo, old_mem_consumed=old_mem_consumed
566
+ )
567
+ return
568
+ else:
569
+ winfo, w_st = _WeakRefInfo.create_winfo(
570
+ st, t.device, reftype, self._delete_callback
571
+ )
572
+ self._WINFO[st] = (winfo, w_st)
573
+ # Update the current snapshot for the newly added ``_WeakRefInfo``.
574
+ if winfo.mem_consumed > 0:
575
+ self._update_snap(_UpdateType.ADD, winfo)
576
+
577
+ def get_tracker_snapshot(
578
+ self, type: str = "current"
579
+ ) -> Dict[torch.device, Dict[str, int]]:
580
+ """
581
+ Capture a snapshot of the memory usage breakdown per device, based on the specified type.
582
+
583
+ Args:
584
+ type (str): The type of snapshot to capture. Can be "current" for the current memory usage or "peak" for the
585
+ peak memory usage. Defaults to "current".
586
+ Returns:
587
+ Dict[torch.device, Dict[str, int]]: A dictionary where each key is a torch.device, and each value is another
588
+ dictionary. This inner dictionary has keys representing memory reference
589
+ types as defined in ``_MemRefType`` and values representing the amount of
590
+ memory consumed in bytes.
591
+ Raises:
592
+ ValueError: If an invalid type is specified.
593
+ """
594
+ if type == "current":
595
+ return deepcopy(self._curr_mem_snap)
596
+ elif type == "peak":
597
+ return deepcopy(self._peak_mem_snap)
598
+ else:
599
+ raise ValueError(f"Invalid type {type}")
600
+
601
+ def _track_module_params_and_buffers(
602
+ self, module: nn.Module, install_grad_hooks: bool = True
603
+ ) -> Tuple[int, int]:
604
+ # Track the parameters and buffers of the module if not already tracked.
605
+ # If the parameters have gradients, track the gradients as well.
606
+ # If install_grad_hooks is True, install a gradient hook on the parameters
607
+ # to track the gradients, if it has not already been installed.
608
+ # Return the total memory consumed by the parameters and buffers.
609
+ def _grad_hook(grad: torch.Tensor) -> None:
610
+ self._update_and_maybe_create_winfos(
611
+ grad,
612
+ _MemRefType.GRAD,
613
+ )
614
+
615
+ param_memory = 0
616
+ for param in module.parameters():
617
+ winfos = self._update_and_maybe_create_winfos(
618
+ param,
619
+ _MemRefType.PARAM,
620
+ )
621
+ param_memory += sum(winfo.mem_consumed for winfo in winfos)
622
+ if param.grad is not None:
623
+ self._update_and_maybe_create_winfos(
624
+ param.grad,
625
+ _MemRefType.GRAD,
626
+ )
627
+ if (
628
+ self._param_to_grad_hook_handles.get(param, None) is None
629
+ and install_grad_hooks
630
+ ):
631
+ grad_hook_handle = param.register_hook(_grad_hook)
632
+ post_acc_grad_hook_handle = param.register_post_accumulate_grad_hook(
633
+ lambda p: (_grad_hook(p.grad))
634
+ )
635
+ self._param_to_grad_hook_handles[param] = (
636
+ grad_hook_handle,
637
+ post_acc_grad_hook_handle,
638
+ )
639
+ buffer_memory = 0
640
+ for buffer in module.buffers():
641
+ winfos = self._update_and_maybe_create_winfos(
642
+ buffer,
643
+ _MemRefType.BUFFER,
644
+ )
645
+ buffer_memory += sum(winfo.mem_consumed for winfo in winfos)
646
+ return (param_memory, buffer_memory)
647
+
648
+ def _track_inputs_or_outputs(self, args: Any) -> int:
649
+ # Calculate the memory consumed by the inputs or outputs of the module.
650
+ input_or_output_memory = 0
651
+
652
+ def add_inps_or_outs(t: torch.Tensor) -> None:
653
+ nonlocal input_or_output_memory
654
+ sts = _WeakRefInfo.get_untyped_storages(t)
655
+ for st in sts:
656
+ winfo, _ = self._WINFO.get(st, (None, None))
657
+ if winfo is not None:
658
+ input_or_output_memory += winfo.mem_consumed
659
+
660
+ tree_map_only(torch.Tensor, add_inps_or_outs, args)
661
+ return input_or_output_memory
662
+
663
+ def _pre_fw_hook(self, module: nn.Module, inputs: Any) -> None:
664
+ # This is installed as a pre-fwd user hook with ``ModTracker.`` Based on the following cases we
665
+ # set the state and capture the memory snapshot for the module.
666
+ # Case 1: If the module is not in the ``memory_tracking`` dictionary, we track the parameters, buffers,
667
+ # input and output memory of the module. Create a new ``_ModMemStats`` instance for the module
668
+ # and add it to the ``memory_tracking`` dictionary.
669
+ # Case 2: If the module is already in the ``memory_tracking`` dictionary and we are in backward, this means
670
+ # we are in the AC region. We check if this is the top most module in the AC region. If it is,
671
+ # we store a weak reference and set the flag ``_in_ac`` to True.
672
+ # Case 3: If the module is already in the ``memory_tracking`` dictionary and we are in forward, this means
673
+ # this module is called for the second time. If it is a root module, that means we are in the next
674
+ # iteration and we error out. If it is not a root module, that means it's a submodule that is being
675
+ # used multiple times in the same iteration, which we allow and track.
676
+ # For Case 1 and 3, we also initialiaze the ``local_peak`` and ``PEAK_FW`` snapshot for the module.
677
+ mod_name = self._mod_tracker.get_known_fqn(module)
678
+ assert mod_name is not None
679
+ if module not in self.memory_tracking:
680
+ mod_stats = _ModMemStats(mod_name)
681
+ param_mem, buffer_mem = self._track_module_params_and_buffers(
682
+ module, install_grad_hooks=True
683
+ )
684
+ input_mem = self._track_inputs_or_outputs(inputs)
685
+ mod_stats.parameter_mem = param_mem
686
+ mod_stats.buffer_mem = buffer_mem
687
+ mod_stats.input_mem = input_mem
688
+ self.memory_tracking[module] = mod_stats
689
+ state = _ModState.PRE_FW
690
+
691
+ elif self._mod_tracker.is_bw:
692
+ mod_stats = self.memory_tracking[module]
693
+ state = _ModState.PRE_FW_AC
694
+ if self._ac_mod is None:
695
+ self._ac_mod = weakref.ref(module)
696
+ self._in_ac = True
697
+ else:
698
+ parents = set(self._mod_tracker.parents) - {mod_name}
699
+ if len(parents) == 1 and "Global" in parents:
700
+ raise NotImplementedError(
701
+ "MemTracker does not support memory tracking for multiple iterative calls."
702
+ " Either use ``reset_mod_stats`` to clear module memory stats for the previous iteration"
703
+ " or file a github issue if you need this feature."
704
+ )
705
+ mod_stats = self.memory_tracking[module]
706
+ state = _ModState.PRE_FW
707
+ input_mem = self._track_inputs_or_outputs(inputs)
708
+ mod_stats.input_mem = input_mem
709
+
710
+ mem_snapshot = self.get_tracker_snapshot()
711
+ if state == _ModState.PRE_FW:
712
+ mod_stats.local_peak = {
713
+ dev: dev_snap[_TOTAL_KEY] for dev, dev_snap in mem_snapshot.items()
714
+ }
715
+ mod_stats.snapshots.setdefault(_ModState.PEAK_FW, []).append(mem_snapshot)
716
+ mod_stats.snapshots.setdefault(state, []).append(deepcopy(mem_snapshot))
717
+
718
+ def _post_fw_hook(self, module: nn.Module, inputs: Any, outputs: Any) -> None:
719
+ # This is installed as a post-fwd user hook with ``ModTracker``. Based on the following cases we
720
+ # set the state and capture the memory snapshot for the module.
721
+ # Case 1: This is called in backward, which means we are in the AC region. If this is the top most module
722
+ # in the AC region, we set the flag ``_in_ac`` to False.
723
+ # Case 2: This is called in forward so we calculate the output memory
724
+ # of the module and update its mod_stats.
725
+ mod_stats = self.memory_tracking[module]
726
+ if self._mod_tracker.is_bw:
727
+ state = _ModState.POST_FW_AC
728
+ if self._ac_mod is not None and self._ac_mod() is module:
729
+ self._ac_mod = None
730
+ self._in_ac = False
731
+ else:
732
+ state = _ModState.POST_FW
733
+ output_mem = self._track_inputs_or_outputs(outputs)
734
+ mod_stats.output_mem = output_mem
735
+ mod_stats.snapshots.setdefault(state, []).append(self.get_tracker_snapshot())
736
+
737
+ def _pre_bw_hook(self, module: nn.Module, args: Any) -> None:
738
+ # This is installed as a pre-bwd user hook with ``ModTracker``. We set the state and capture the
739
+ # snapshot for the module. We also initialize the ``local_peak`` and ``PEAK_BW`` snapshot for it.
740
+ # If the module is None, we skip the hook.
741
+ # This can happen since this installed inside a multi-grad hook on the module's output tensors
742
+ # and the module itself may not be alive during backward.
743
+ if module is None:
744
+ warnings.warn("Module is None. Skipping PRE_BW hook.", stacklevel=2)
745
+ return
746
+ mod_stats = self.memory_tracking[module]
747
+ mem_snapshot = self.get_tracker_snapshot()
748
+ mod_stats.local_peak = {
749
+ dev: dev_snap[_TOTAL_KEY] for dev, dev_snap in mem_snapshot.items()
750
+ }
751
+ mod_stats.snapshots.setdefault(_ModState.PEAK_BW, []).append(mem_snapshot)
752
+ mod_stats.snapshots.setdefault(_ModState.PRE_BW, []).append(
753
+ deepcopy(mem_snapshot)
754
+ )
755
+
756
+ def _post_bw_hook(self, module: nn.Module, args: Any) -> None:
757
+ # This is installed as a post-bwd user hook with ``ModTracker``. We set the state and capture the
758
+ # snapshot for the module if it is not None.
759
+ # This can happen since this installed inside a multi-grad hook on the module's input tensors
760
+ # and the module itself may not be alive during backward.
761
+ if module is None:
762
+ warnings.warn("Module is None. Skipping POST_BW hook.", stacklevel=2)
763
+ return
764
+ mod_stats = self.memory_tracking[module]
765
+ mod_stats.snapshots.setdefault(_ModState.POST_BW, []).append(
766
+ self.get_tracker_snapshot()
767
+ )
768
+
769
+ def _track_optimizer_states(
770
+ self, reftype: _RefType, optimizer: optim.Optimizer
771
+ ) -> None:
772
+ for states in optimizer.state.values():
773
+ for val in states.values():
774
+ if isinstance(val, torch.Tensor):
775
+ self._update_and_maybe_create_winfos(
776
+ val,
777
+ reftype,
778
+ )
779
+
780
+ def _register_global_optimizer_hook(self) -> None:
781
+ # Register a hook on the optimizer step to track the optimizer states.
782
+ # The pre-hook is to set the flag ``_in_opt`` to True. The post-hook unsets the flag,
783
+ # and also tracks any optimizer states that are created during the optimizer step.
784
+ def _opt_step_pre_hook(
785
+ optimizer: optim.Optimizer, args: Any, kwargs: Any
786
+ ) -> None:
787
+ self._in_opt = True
788
+
789
+ def _opt_step_post_hook(
790
+ optimizer: optim.Optimizer, args: Any, kwargs: Any
791
+ ) -> None:
792
+ self._track_optimizer_states(_MemRefType.OPT, optimizer)
793
+ self._in_opt = False
794
+
795
+ self._optimizer_hook_handles = (
796
+ register_optimizer_step_pre_hook(_opt_step_pre_hook),
797
+ register_optimizer_step_post_hook(_opt_step_post_hook),
798
+ )
799
+
800
+ def _deregister_param_and_optimizer_hooks(self) -> None:
801
+ for (
802
+ grad_hook_handle,
803
+ post_acc_grad_hook_handle,
804
+ ) in self._param_to_grad_hook_handles.values():
805
+ grad_hook_handle.remove()
806
+ post_acc_grad_hook_handle.remove()
807
+ self._param_to_grad_hook_handles.clear()
808
+
809
+ if self._optimizer_hook_handles is not None:
810
+ for handle in self._optimizer_hook_handles:
811
+ handle.remove()
812
+ self._optimizer_hook_handles = None
813
+
814
+ def track_external(
815
+ self, *external: Union[nn.Module, optim.Optimizer, torch.Tensor]
816
+ ) -> None:
817
+ """
818
+ Track tensors and stateful objects like modules, optimizers etc. that are created outside the MemTracker.
819
+
820
+ This method should be called before the ``MemTracker`` is used. Any tensors that are not module parameters, buffers,
821
+ gradients activations, or optimizer states will be categorized as ``Other``. If you want them categorized with a
822
+ custom name, please file a GitHub issue. Any tensors created outside the MemTracker and not supplied to this
823
+ method will not be be tracked by ``MemTracker``.
824
+
825
+ Args:
826
+ *external (Union[nn.Module, optim.Optimizer, torch.Tensor]): The external modules, optimizers, and
827
+ tensors to be tracked.
828
+ """
829
+ flat_external, _ = tree_flatten(external)
830
+ for obj in flat_external:
831
+ if isinstance(obj, torch.Tensor):
832
+ self._update_and_maybe_create_winfos(
833
+ obj,
834
+ _MemRefType.OTH,
835
+ )
836
+ elif isinstance(obj, torch.nn.Module):
837
+ self._track_module_params_and_buffers(obj, install_grad_hooks=False)
838
+ elif isinstance(obj, optim.Optimizer):
839
+ self._track_optimizer_states(_MemRefType.OPT, obj)
840
+ else:
841
+ raise TypeError(
842
+ f"Object of type {type(obj)} is not supported for tracking. "
843
+ f"Only stateful objects like modules, optimizers, and tensors are supported."
844
+ )
845
+
846
+ def display_snapshot(
847
+ self, type: str = "current", units: str = "B", tabulate: bool = False
848
+ ) -> None:
849
+ """
850
+ Display the memory usage breakdown snapshot of the tracker based on the specified type and units.
851
+
852
+ Keyword args:
853
+ type (str): The type of snapshot to display. Can be "current" for the current memory usage or "peak" for the
854
+ peak memory usage. Defaults to "current".
855
+ units (str): The units to use for displaying memory usage. Defaults to "B". Supports ["B", "KiB", "MiB", "GiB"].
856
+ tabulate (bool): Whether to display the snapshot in a tabular format. Defaults to False.
857
+ """
858
+ snapshot = self.get_tracker_snapshot(type)
859
+ if tabulate:
860
+ _print_snapshot_tabular(snapshot, units)
861
+ else:
862
+ _print_snapshot(snapshot, units)
863
+
864
+ def display_modulewise_snapshots(
865
+ self, depth: int = 2, units: str = "B", tabulate: bool = False
866
+ ) -> None:
867
+ """
868
+ Print per device memory breakdown snapshot for each module called within MemTracker.
869
+
870
+ Snapshots are displayed for the states defined by ``_ModState``.
871
+ The module hierarchy is displayed up to the specified depth.
872
+
873
+ Keyword Args:
874
+ depth (int, optional): The depth of the module hierarchy to display. Defaults to 2.
875
+ units (str, optional): The units to use for memory tracking. Defaults to "B". Supports ["B", "KiB", "MiB", "GiB"].
876
+ tabulate (bool, optional): Whether to display the snapshot in a tabular format. Defaults to False.
877
+ """
878
+
879
+ def natural_sort_key(s: str) -> List[Union[int, str]]:
880
+ return [
881
+ int(text) if text.isdigit() else text.lower()
882
+ for text in re.split("([0-9]+)", s)
883
+ ]
884
+
885
+ for mod_stats in sorted(
886
+ self.memory_tracking.values(),
887
+ key=lambda m_stats: natural_sort_key(m_stats.mod_fqn),
888
+ ):
889
+ mod_fqn = mod_stats.mod_fqn
890
+ mod_depth = mod_fqn.count(".") + 1
891
+ if mod_depth > depth:
892
+ continue
893
+ print(f"Module: {mod_fqn}")
894
+ if tabulate:
895
+ _print_state_snapshots_tabular(mod_stats.snapshots, units)
896
+ else:
897
+ _print_state_snapshots(mod_stats.snapshots, units)
898
+
899
+ def reset_mod_stats(self) -> None:
900
+ """
901
+ Reset all the module memory stats. Clears ``memory_tracking`` dictionary.
902
+ """
903
+ self.memory_tracking.clear()
904
+
905
+ def __enter__(self) -> "MemTracker":
906
+ self._register_global_optimizer_hook()
907
+ self._mod_tracker.register_user_hooks(
908
+ self._pre_fw_hook,
909
+ self._post_fw_hook,
910
+ self._pre_bw_hook,
911
+ self._post_bw_hook,
912
+ )
913
+ self._track_resize()
914
+ self._peak_mem_snap = self.get_tracker_snapshot()
915
+ self._peak_mem = {
916
+ dev: dev_snap[_TOTAL_KEY] for dev, dev_snap in self._peak_mem_snap.items()
917
+ }
918
+ self._mod_tracker.__enter__()
919
+ super().__enter__()
920
+ return self
921
+
922
+ def __exit__(self, *args: Any) -> None:
923
+ self._deregister_param_and_optimizer_hooks()
924
+ self._mod_tracker.clear_user_hooks()
925
+ self._restore_resize()
926
+ super().__exit__(*args)
927
+ self._mod_tracker.__exit__(*args)
928
+
929
+ def __torch_dispatch__(self, func, types, args=(), kwargs=None): # type: ignore[no-untyped-def]
930
+ res = func(*args, **kwargs or {})
931
+ # If we are tracking an optimizer state, we use the optimizer reference type.
932
+ # If we are in backward region and not in AC region, we use the backward reference type.
933
+ # Else we use the forward reference type.
934
+ if self._in_opt:
935
+ reftype = _MemRefType.OPT
936
+ elif self._mod_tracker.is_bw and not self._in_ac:
937
+ reftype = _MemRefType.TEMP
938
+ else:
939
+ reftype = _MemRefType.ACT
940
+ tree_map_only(torch.Tensor, partial(self._track, reftype), res)
941
+ peak_state = _ModState.PEAK_BW if self._mod_tracker.is_bw else _ModState.PEAK_FW
942
+ self._update_peak_stats(peak_state)
943
+ return res
vllm/lib/python3.10/site-packages/torch/distributed/_tools/memory_tracker.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import operator
3
+ import pickle
4
+ from collections import defaultdict
5
+ from itertools import chain
6
+ from typing import Any, Callable, Dict, List, no_type_check, Sequence, TYPE_CHECKING
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ from torch.utils._python_dispatch import TorchDispatchMode
11
+
12
+
13
+ if TYPE_CHECKING:
14
+ from torch.utils.hooks import RemovableHandle
15
+
16
+
17
+ BYTES_PER_MB = 1024 * 1024.0
18
+
19
+
20
+ class MemoryProfileDispatchMode(TorchDispatchMode):
21
+ """Run in ``TorchDispatchMode`` to get memory stats at operator level."""
22
+
23
+ def __init__(self, memory_tracker) -> None:
24
+ self.memory_tracker = memory_tracker
25
+
26
+ def __torch_dispatch__(self, func, types, args=..., kwargs=None):
27
+ rs = func(*args, **kwargs)
28
+ if func == torch.ops.aten.detach.default:
29
+ return rs
30
+ func_name: str = (
31
+ self.memory_tracker._cur_module_name
32
+ + "."
33
+ + func.__name__
34
+ + "_"
35
+ + str(self.memory_tracker._operator_names[func.__name__])
36
+ )
37
+ self.memory_tracker._operator_names[func.__name__] = (
38
+ self.memory_tracker._operator_names[func.__name__] + 1
39
+ )
40
+ self.memory_tracker._record_memory_stats(func_name)
41
+
42
+ return rs
43
+
44
+
45
+ class MemoryTracker:
46
+ """
47
+ Collect and plot the memory stats at operator level.
48
+
49
+ Includes ``memories_allocated``, ``memories_active`` and ``memories_reserved``.
50
+ It also prints a summary for the top 20 operators that generate the most memories.
51
+
52
+ Example usage:
53
+
54
+ >>> # xdoctest: +SKIP(failing)
55
+ >>> net.cuda()
56
+ >>> input = input.cuda()
57
+
58
+ >>> mem_tracker = MemoryTracker()
59
+ >>> mem_tracker.start_monitor(net)
60
+
61
+ >>> net.zero_grad(True)
62
+ >>> loss = net(input)
63
+ >>> if isinstance(loss, dict):
64
+ >>> loss = loss['out']
65
+ >>> loss.sum().backward()
66
+ >>> net.zero_grad(set_to_none=True)
67
+
68
+ >>> mem_tracker.stop()
69
+ >>> mem_tracker.summary()
70
+ >>> mem_tracker.show_traces()
71
+ """
72
+
73
+ def __init__(self) -> None:
74
+ torch._C._log_api_usage_once("torch.distributed.memory_tracker")
75
+ self._hooks: List[RemovableHandle] = []
76
+ self._operator_names: Dict[str, int] = defaultdict(int)
77
+ self.memories_allocated: Dict[int, Dict[str, float]] = defaultdict()
78
+ self.memories_active: Dict[int, Dict[str, float]] = defaultdict()
79
+ self.memories_reserved: Dict[int, Dict[str, float]] = defaultdict()
80
+ self._markers: Dict[str, int] = defaultdict(int)
81
+ self._cur_module_name: str = ""
82
+ self._op_index: int = 0
83
+ self._num_cuda_retries: int = 0
84
+
85
+ @no_type_check
86
+ def start_monitor(self, root_module: nn.Module) -> None:
87
+ """
88
+ Register module hooks and entering ``MemoryProfileDispatchMode``.
89
+
90
+ This enables operator level memory stats can be tracked during module runtime.
91
+ """
92
+ self._clear_state()
93
+ root_module.__setattr__("_memory_tracker_is_root", True)
94
+ for name, m in root_module.named_modules():
95
+ if m is not root_module:
96
+ m.__setattr__("_memory_tracker_is_root", False)
97
+ # fused_proxy_group does not support hooks
98
+ if ".fused_proxy_grouped_embedding_bag" in name:
99
+ continue
100
+ # hook ordering with other hooks added by users is not managed, so
101
+ # the memory stats tracked here may not completely accurate.
102
+ h1 = m.register_forward_pre_hook(self._create_pre_forward_hook(name))
103
+ h2 = m.register_forward_hook(self._create_post_forward_hook(name))
104
+ # it does not work well with jagged tensor somehow, the root cause is not
105
+ # clear and remove it for now as it does not really capture important info.
106
+ # h3 = m.register_backward_hook(self._create_backward_hook(name))
107
+ self._hooks.extend([h1, h2])
108
+ torch.cuda.empty_cache()
109
+ assert getattr(self, "profile_mode", None) is None
110
+ self.profile_mode = MemoryProfileDispatchMode(self)
111
+ self.profile_mode.__enter__()
112
+
113
+ @no_type_check
114
+ def stop(self) -> None:
115
+ """
116
+ Remove module hooks and exit ``MemoryProfileDispatchMode`` to stop tracking memory stats at operator level.
117
+
118
+ Get some aggregated stats when the memory_tracker() is enabled, like cuda ``num_alloc_retries``.
119
+ """
120
+ self._num_cuda_retries = torch.cuda.memory_stats().get("num_alloc_retries", 0)
121
+
122
+ for h in self._hooks:
123
+ h.remove()
124
+ self._hooks.clear()
125
+ assert getattr(self, "profile_mode", None) is not None
126
+ self.profile_mode.__exit__(None, None, None)
127
+ self.profile_mode = None
128
+
129
+ @no_type_check
130
+ def summary(self, top: int = 20) -> None:
131
+ """
132
+ Print out the top operators that generate the most memories.
133
+
134
+ The number of the top operators can be configured.
135
+ """
136
+ op_diff: Dict[str, float] = defaultdict(float)
137
+ op_name, previous_allocated_memory = self.memories_allocated[0]
138
+ for i in range(1, self._op_index):
139
+ op_name, current_allocated_memory = self.memories_allocated[i]
140
+ op_diff[op_name] = current_allocated_memory - previous_allocated_memory
141
+ previous_allocated_memory = current_allocated_memory
142
+
143
+ print("------------------------------------------------")
144
+ print(f"The number of cuda retries are: {self._num_cuda_retries}")
145
+ print(f"Top {top} ops that generates memory are:")
146
+ for k, v in sorted(op_diff.items(), key=operator.itemgetter(1), reverse=True)[
147
+ :top
148
+ ]:
149
+ print(f"{k}: {v}MB")
150
+ print("------------------------------------------------")
151
+
152
+ @no_type_check
153
+ def show_traces(self, path: str = "") -> None:
154
+ import matplotlib.pyplot as plt
155
+
156
+ def _plot_figure(x, y_values, labels):
157
+ min_val = min(list(chain(*y_values))) * 0.999
158
+ max_val = max(list(chain(*y_values))) * 1.001
159
+ plt.figure()
160
+ for y, label in zip(y_values, labels):
161
+ plt.plot(x, y, label=label)
162
+ plt.xlabel("# Operator Calls")
163
+ plt.ylabel("Memory (MB)")
164
+ plt.legend()
165
+ for marker_name, marker in self._markers.items():
166
+ if marker_name == "fw_bw_boundary":
167
+ plt.plot(
168
+ [marker, marker],
169
+ [min_val, max_val],
170
+ "r",
171
+ lw=2,
172
+ label=marker_name,
173
+ )
174
+ else:
175
+ plt.plot(
176
+ [marker, marker],
177
+ [min_val, max_val],
178
+ "k-",
179
+ lw=2,
180
+ label=marker_name,
181
+ )
182
+
183
+ if path != "":
184
+ self.load(path)
185
+
186
+ y_1 = [gb for (name, gb) in self.memories_allocated.values()]
187
+ y_2 = [gb for (name, gb) in self.memories_active.values()]
188
+ y_3 = [gb for (name, gb) in self.memories_reserved.values()]
189
+ x = list(range(len(y_1)))
190
+ # Split figures when there is big difference between
191
+ # "reserved_memory" and "allocated_memory" or "active_memory".
192
+ _plot_figure(
193
+ x,
194
+ [list(y_1), list(y_2), list(y_3)],
195
+ ["allocated_memory", "active_memory", "reserved_memory"],
196
+ )
197
+ _plot_figure(x, [list(y_1)], ["allocated_memory"])
198
+ _plot_figure(x, [list(y_2)], ["active_memory"])
199
+ _plot_figure(x, [list(y_3)], ["reserved_memory"])
200
+
201
+ def save_stats(self, path: str) -> None:
202
+ """Save the stats using pickle during runtime if users want to plot the traces in other places like notebook."""
203
+ stats = {
204
+ "memories_allocated": self.memories_allocated,
205
+ "memories_active": self.memories_active,
206
+ "memories_reserved": self.memories_reserved,
207
+ "markers": self._markers,
208
+ "num_alloc_retries": self._num_cuda_retries,
209
+ }
210
+
211
+ with open(path, "wb") as f:
212
+ pickle.dump(stats, f, pickle.HIGHEST_PROTOCOL)
213
+
214
+ def load(self, path: str) -> None:
215
+ """Load the pickled memory stats to plot the traces or print the summary."""
216
+ with open(path, "rb") as f:
217
+ stats = pickle.load(f)
218
+
219
+ self.memories_allocated = stats["memories_allocated"]
220
+ self.memories_active = stats["memories_active"]
221
+ self.memories_reserved = stats["memories_reserved"]
222
+ self._markers = stats["markers"]
223
+ self._num_cuda_retries = stats["num_alloc_retries"]
224
+
225
+ def _create_pre_forward_hook(self, name: str) -> Callable:
226
+ """Prefix operator name with current module and 'forward', and insert 'fw_start' marker at forward pass start."""
227
+
228
+ def _pre_forward_hook(module: nn.Module, inputs: Any) -> None:
229
+ self._cur_module_name = f"{name}.forward"
230
+ if (
231
+ hasattr(module, "_memory_tracker_is_root")
232
+ and module._memory_tracker_is_root
233
+ ):
234
+ self._add_marker("fw_start")
235
+
236
+ return _pre_forward_hook
237
+
238
+ def _create_post_forward_hook(self, name: str) -> Callable:
239
+ """Insert the marker 'fw_bw_boundary' at the boundary of forward and backward pass."""
240
+
241
+ def _post_forward_hook(
242
+ module: nn.Module,
243
+ inputs: Sequence[torch.Tensor],
244
+ outputs: Sequence[torch.Tensor],
245
+ ) -> None:
246
+ if (
247
+ hasattr(module, "_memory_tracker_is_root")
248
+ and module._memory_tracker_is_root
249
+ ):
250
+ self._add_marker("fw_bw_boundary")
251
+
252
+ return _post_forward_hook
253
+
254
+ def _create_backward_hook(self, name: str) -> Callable:
255
+ """Insert the current module name with backward prefix for the operator name."""
256
+
257
+ def _backward_hook(
258
+ module: nn.Module, grad_input: torch.Tensor, grad_output: torch.Tensor
259
+ ) -> None:
260
+ self._cur_module_name = f"{name}.backward"
261
+
262
+ return _backward_hook
263
+
264
+ @no_type_check
265
+ def _record_memory_stats(self, fn_name: str) -> None:
266
+ """
267
+ Record current memory allocated, current memory active and current memory reserved.
268
+
269
+ The memory stats dict is indexed with ``self._op_index``.
270
+ """
271
+ memory_allocated: float = torch.cuda.memory_allocated() / BYTES_PER_MB
272
+ memory_reserved: float = torch.cuda.memory_reserved() / BYTES_PER_MB
273
+ memory_active: float = (
274
+ torch.cuda.memory_stats().get("active_bytes.all.current", 0) / BYTES_PER_MB
275
+ )
276
+ self.memories_allocated[self._op_index] = (fn_name, memory_allocated)
277
+ self.memories_reserved[self._op_index] = (fn_name, memory_reserved)
278
+ self.memories_active[self._op_index] = (fn_name, memory_active)
279
+ self._op_index += 1
280
+
281
+ def _add_marker(self, marker_name: str) -> None:
282
+ """Set the marker's x-axis value."""
283
+ marker_val = len(self.memories_allocated.values())
284
+ self._markers[marker_name] = marker_val
285
+
286
+ def _clear_state(self) -> None:
287
+ """Clear states when start_monitor() is called."""
288
+ self._operator_names.clear()
289
+ self.memories_allocated.clear()
290
+ self.memories_active.clear()
291
+ self.memories_reserved.clear()
292
+ self._markers.clear()
293
+ self._cur_module_name = ""
294
+ self._op_index = 0
295
+ self._num_cuda_retries = 0
vllm/lib/python3.10/site-packages/torch/distributed/_tools/mod_tracker.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import warnings
3
+ import weakref
4
+ from typing import Callable, Optional, Set
5
+
6
+ import torch
7
+ from torch.autograd.graph import register_multi_grad_hook
8
+ from torch.nn.modules.module import (
9
+ register_module_forward_hook,
10
+ register_module_forward_pre_hook,
11
+ )
12
+ from torch.utils._pytree import tree_flatten
13
+
14
+
15
+ __all__ = ["ModTracker"]
16
+
17
+
18
+ class ModTracker:
19
+ """
20
+ ``ModTracker`` is a context manager that tracks the nn.Module hierarchy during execution
21
+ so that other system can query which Module is currently being executed (or its backward is being
22
+ executed).
23
+
24
+ You can access the ``parents`` attribute on this context manager to get the set of all the
25
+ Modules currently being executed via their fqn (fully qualified name, also used as the key within
26
+ the state_dict).
27
+ You can access the ``is_bw`` attribute to know if you are currently running in backward or not.
28
+
29
+ Note that ``parents`` is never empty and always contains the "Global" key. The ``is_bw`` flag
30
+ will remain ``True`` after the forward until another Module is executed. If you need it to be
31
+ more accurate, please submit an issue requesting this. Adding a map from fqn to the module instance
32
+ is possible but not done yet, please submit an issue requesting this if you need it.
33
+
34
+ Example usage
35
+
36
+ .. code-block:: python
37
+
38
+ mod = torch.nn.Linear(2, 2)
39
+
40
+ with ModTracker() as tracker:
41
+ # Access anything during the forward pass
42
+ def my_linear(m1, m2, bias):
43
+ print(f"Current modules: {tracker.parents}")
44
+ return torch.mm(m1, m2.t()) + bias
45
+ torch.nn.functional.linear = my_linear
46
+
47
+ mod(torch.rand(2, 2))
48
+
49
+ """
50
+
51
+ parents: Set[str]
52
+ """
53
+ A Set containing the fqn for each module currently running their forward
54
+ """
55
+
56
+ def __init__(self):
57
+ self.parents = {"Global"}
58
+ self._active_module_cnt = {}
59
+ self._known_modules: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary()
60
+ self._seen_modules: weakref.WeakSet = weakref.WeakSet()
61
+ self._has_callback = False
62
+ self._user_pre_fw_hook = None
63
+ self._user_post_fw_hook = None
64
+ self._user_pre_bw_hook = None
65
+ self._user_post_bw_hook = None
66
+
67
+ def _maybe_set_engine_callback(self):
68
+ # This assumes no concurrent calls to backward
69
+ if self._has_callback:
70
+ return
71
+
72
+ def callback():
73
+ self.parents = {"Global"}
74
+ self._has_callback = False
75
+
76
+ torch.autograd.Variable._execution_engine.queue_callback(callback)
77
+ self._has_callback = True
78
+
79
+ @property
80
+ def is_bw(self):
81
+ """
82
+ A boolean marking if this is currently running during the backward pass or not
83
+ """
84
+ return torch._C._current_graph_task_id() != -1
85
+
86
+ def get_known_fqn(self, mod):
87
+ """
88
+ Return the fqn for the given module if it is known to the ``ModTracker``, otherwise ``None``.
89
+ """
90
+ return self._known_modules.get(mod, None)
91
+
92
+ def register_user_hooks(
93
+ self,
94
+ pre_fw_hook: Optional[Callable] = None,
95
+ post_fw_hook: Optional[Callable] = None,
96
+ pre_bw_hook: Optional[Callable] = None,
97
+ post_bw_hook: Optional[Callable] = None,
98
+ ):
99
+ """
100
+ Registers user-specified hooks to be called before/after the forward/backward pass for each
101
+ module tracked by the ``ModTracker``. One or more can be ``None``.
102
+ Args:
103
+ pre_fw_hook (Callable, optional): A hook to be called before the forward pass for the
104
+ module. It should have the following signature:
105
+ pre_fw_hook (module, input) -> None
106
+ post_fw_hook (Callable, optional): A hook to be called after the forward pass for the
107
+ module. It should have the following signature:
108
+ post_fw_hook (module, input, output) -> None
109
+ pre_bw_hook (Callable, optional): A multi-grad hook to be called on all the outputs of
110
+ the module that require gradients. It should have the following signature:
111
+ pre_bw_hook (module, grad_output) -> None
112
+ post_bw_hook (Callable, optional): A multi-grad hook to be called on all the inputs of
113
+ the module that require gradients. It should have the following signature:
114
+ post_bw_hook (module, grad_input) -> None
115
+ Raises:
116
+ AssertionError: If a new hook is provided when one is already registered.
117
+ Note:
118
+ If the module is not alive during the backward pass, the pre_bw_hook and post_bw_hook will
119
+ will receive None as the module argument.
120
+ The module fqn will be present in the ``parents`` attribute when each of the hooks is called.
121
+ Hooks are intended to be used as markers only not to modify the inputs/outputs.
122
+ """
123
+
124
+ def set_hook(hook, user_hook, hook_name):
125
+ if hook is not None and user_hook is not None:
126
+ raise AssertionError(
127
+ f"Only one {hook_name} can be registered at a time"
128
+ f" Clear the existing hook by calling ``clear_user_hooks`` before registering a new one"
129
+ )
130
+ return hook
131
+
132
+ self._user_pre_fw_hook = set_hook(
133
+ pre_fw_hook, self._user_pre_fw_hook, "pre_fw_hook"
134
+ )
135
+ self._user_post_fw_hook = set_hook(
136
+ post_fw_hook, self._user_post_fw_hook, "post_fw_hook"
137
+ )
138
+ self._user_pre_bw_hook = set_hook(
139
+ pre_bw_hook, self._user_pre_bw_hook, "pre_bw_hook"
140
+ )
141
+ self._user_post_bw_hook = set_hook(
142
+ post_bw_hook, self._user_post_bw_hook, "post_bw_hook"
143
+ )
144
+
145
+ def clear_user_hooks(self):
146
+ """
147
+ Clears the user specified hooks registered with ``register_user_hooks``
148
+ """
149
+ self._user_pre_fw_hook = None
150
+ self._user_post_fw_hook = None
151
+ self._user_pre_bw_hook = None
152
+ self._user_post_bw_hook = None
153
+
154
+ def _get_mod_name(self, mod):
155
+ if mod not in self._known_modules:
156
+ self._known_modules[mod] = type(mod).__name__
157
+ mod_name = self._known_modules[mod]
158
+ if mod not in self._seen_modules:
159
+ for name, submod in mod.named_children():
160
+ self._known_modules[submod] = f"{mod_name}.{name}"
161
+ self._get_mod_name(submod)
162
+ self._seen_modules.add(mod)
163
+ return mod_name
164
+
165
+ def _get_append_fn(self, w_mod, name, is_bw):
166
+ def fn(*args):
167
+ if is_bw:
168
+ self._maybe_set_engine_callback()
169
+ if name in self.parents and not self.is_bw:
170
+
171
+ def custom_formatwarning(msg, category, filename, lineno, line=None):
172
+ return f"{filename}:{lineno}: {category.__name__}: {msg} \n"
173
+
174
+ warnings.formatwarning = custom_formatwarning
175
+ warnings.warn(
176
+ "The module hierarchy tracking maybe be messed up."
177
+ " Please file a bug to PyTorch, if it is the case."
178
+ )
179
+ if name not in self.parents:
180
+ self._active_module_cnt[name] = 1
181
+ self.parents.add(name)
182
+ else:
183
+ self._active_module_cnt[name] += 1
184
+
185
+ if self._user_pre_bw_hook is not None and is_bw:
186
+ self._user_pre_bw_hook(w_mod(), args)
187
+
188
+ return fn
189
+
190
+ def _get_pop_fn(self, w_mod, name, is_bw):
191
+ def fn(*args):
192
+ if self._user_post_bw_hook is not None and is_bw:
193
+ self._user_post_bw_hook(w_mod(), args)
194
+ if name in self.parents:
195
+ self._active_module_cnt[name] -= 1
196
+ if self._active_module_cnt[name] == 0:
197
+ self.parents.remove(name)
198
+ elif not self.is_bw:
199
+ # Due to some input/output not requiring gradients, we cannot enforce
200
+ # proper nesting in backward
201
+ raise RuntimeError(
202
+ "The Module hierarchy tracking is wrong. Report a bug to PyTorch"
203
+ )
204
+
205
+ return fn
206
+
207
+ def _fw_pre_hook(self, mod, input):
208
+ name = self._get_mod_name(mod)
209
+ w_mod = weakref.ref(mod)
210
+ self._get_append_fn(w_mod, name, False)()
211
+ if self._user_pre_fw_hook is not None:
212
+ self._user_pre_fw_hook(mod, input)
213
+ args, _ = tree_flatten(input)
214
+ tensors = [a for a in args if isinstance(a, torch.Tensor) and a.requires_grad]
215
+ if not self.is_bw and tensors:
216
+ register_multi_grad_hook(tensors, self._get_pop_fn(w_mod, name, True))
217
+
218
+ def _fw_post_hook(self, mod, input, output):
219
+ name = self._get_mod_name(mod)
220
+ w_mod = weakref.ref(mod)
221
+ if self._user_post_fw_hook is not None:
222
+ self._user_post_fw_hook(mod, input, output)
223
+ self._get_pop_fn(w_mod, name, False)()
224
+ args, _ = tree_flatten(output)
225
+ tensors = [a for a in args if isinstance(a, torch.Tensor) and a.requires_grad]
226
+ if not self.is_bw and tensors:
227
+ register_multi_grad_hook(tensors, self._get_append_fn(w_mod, name, True))
228
+
229
+ def __enter__(self):
230
+ self._fw_pre_handle = register_module_forward_pre_hook(self._fw_pre_hook)
231
+ self._fw_post_handle = register_module_forward_hook(
232
+ self._fw_post_hook, always_call=True
233
+ )
234
+ return self
235
+
236
+ def __exit__(self, *args):
237
+ self._fw_pre_handle.remove()
238
+ self._fw_post_handle.remove()
vllm/lib/python3.10/site-packages/torch/distributed/_tools/runtime_estimator.py ADDED
@@ -0,0 +1,527 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Owner(s): ["module: unknown"]
2
+ import math
3
+ import os
4
+ from collections import defaultdict
5
+ from typing import Any, Callable, Dict, List, Set, Tuple
6
+ from typing_extensions import Self
7
+
8
+ import torch
9
+ import torch.utils._pytree as pytree
10
+ from torch._guards import active_fake_mode
11
+ from torch._inductor.utils import get_device_tflops, get_gpu_dram_gbps
12
+ from torch._subclasses.fake_tensor import FakeTensorMode
13
+ from torch.distributed._tools.mod_tracker import ModTracker
14
+ from torch.utils._mode_utils import no_dispatch
15
+ from torch.utils._python_dispatch import TorchDispatchMode
16
+ from torch.utils.flop_counter import flop_registry
17
+
18
+
19
+ aten = torch.ops.aten
20
+
21
+ # This value is hard-coded here:
22
+ # https://github.com/pytorch/pytorch/blob/5fba5d83f0703ff8077ab65448a998e9ad6598fd/c10/cuda/CUDACachingAllocator.cpp#L117
23
+ _PYTORCH_MIN_ALLOCATE = (
24
+ 2**9 if int(os.environ.get("PYTORCH_NO_CUDA_MEMORY_CACHING", 0)) == 0 else 1
25
+ )
26
+
27
+ # No fall-back kernel needed/exists for view ops
28
+ _VIEW_OPS = {
29
+ aten.lift_fresh,
30
+ aten.t,
31
+ aten.transpose,
32
+ aten.view,
33
+ aten.detach,
34
+ aten._unsafe_view,
35
+ aten.split,
36
+ aten.adjoint,
37
+ aten.as_strided,
38
+ aten.diagonal,
39
+ aten.expand,
40
+ aten.expand_as,
41
+ aten.movedim,
42
+ aten.permute,
43
+ aten.select,
44
+ aten.squeeze,
45
+ aten.mT,
46
+ aten.mH,
47
+ aten.real,
48
+ aten.imag,
49
+ aten.view_as,
50
+ aten.unflatten,
51
+ aten.unfold,
52
+ aten.unbind,
53
+ aten.unsqueeze,
54
+ aten.vsplit,
55
+ aten.hsplit,
56
+ aten.split_with_sizes,
57
+ aten.swapaxes,
58
+ aten.swapdims,
59
+ aten.chunk,
60
+ }
61
+ # We can ignore benchmarking tensor create ops
62
+ _CREATE_OPS = {
63
+ aten.randint,
64
+ aten.randn,
65
+ aten.rand,
66
+ aten.randn_like,
67
+ aten.rand_like,
68
+ aten.randint_like,
69
+ aten.arange,
70
+ aten.ones_like,
71
+ aten.zeros_like,
72
+ }
73
+
74
+ _IGNORE_OPS = _VIEW_OPS | _CREATE_OPS
75
+
76
+ __all__ = ["RuntimeEstimator"]
77
+
78
+
79
+ class RuntimeEstimator(TorchDispatchMode):
80
+ """
81
+ Estimates the GPU runtime in milliseconds using various estimation methods under the ``FakeTensorMode``.
82
+
83
+ This class provides a ``TorchDispatchMode`` based context manager that can be used to estimate the eager
84
+ runtime of PyTorch functions. It supports two estimation modes, benchmarking (`operator-level-benchmark`) and
85
+ roofline cost modeling (`operator-level-cost-model`).
86
+ For modules executed under this context manager, it agggregates the forward and backward operation runtimes
87
+ and also records their execution orders.
88
+
89
+ Attributes:
90
+ mod_runtimes (Dict[str, Dict[str, float]]): A dictionary of module runtimes. The key to the outer dictionary
91
+ is the fully qualified name (FQN) of the module. For each module the forward and backward runtimes of the
92
+ operations are aggregated in the inner dictionary keyed by 'fw' and 'bw'.
93
+ mod_fw_pre_order (List[str]): List of module FQNs in pre-forward execution order.
94
+ mod_bw_pre_order (List[str]): List of module FQNs in pre-backward execution order.
95
+ mod_fw_post_order (List[str]): List of module FQNs in post-forward execution order.
96
+ mod_bw_post_order (List[str]): List of module FQNs in post-backward execution order.
97
+ total_runtime (float): The total estimated runtime in milliseconds.
98
+
99
+ Note:
100
+ 1) The benchmarking estimate mode will execute kernels on GPU and assumes that every operation can run in
101
+ isolation without causing an OOM error. It is also designed to be used only under ``FakeTensorMode``.
102
+ 2) Currently wrapper tensor sub-classes such as ``DTensor`` won't produce correct estimates. We plan to support
103
+ them in future PRs.
104
+ 3) We only estimate the compute time, if your code has communication, it will not be considered. Again, we will
105
+ support this in future PRs.
106
+
107
+ Example usage:
108
+
109
+ .. code-block:: python
110
+
111
+ runtime_estimator = RuntimeEstimator()
112
+ with FakeTensorMode():
113
+ module = ...
114
+ optimizer = ...
115
+ inp = ...
116
+ with runtime_estimator(estimate_mode_type="operator-level-cost-model"):
117
+ loss = module(inp)
118
+ loss.backward()
119
+ optimizer.step()
120
+ optimizer.zero_grad()
121
+ runtime_estimator.display_modulewise_stats()
122
+ """
123
+
124
+ _float_types: Set[torch.dtype] = {
125
+ torch.float16,
126
+ torch.bfloat16,
127
+ torch.float32,
128
+ torch.float64,
129
+ }
130
+ _no_fallback_kernel: Set[torch._ops._OpNamespace] = set()
131
+ fake_mode: FakeTensorMode
132
+
133
+ def __init__(self) -> None:
134
+ super().__init__()
135
+ self._estimate: Callable
136
+ self._estimate_mode_type: str
137
+ self._mod_tracker = ModTracker()
138
+ self.mod_runtimes: Dict[str, Dict[str, float]] = defaultdict(
139
+ lambda: defaultdict(lambda: 0.0)
140
+ )
141
+ self.mod_fw_pre_order: List[str] = []
142
+ self.mod_bw_pre_order: List[str] = []
143
+ self.mod_fw_post_order: List[str] = []
144
+ self.mod_bw_post_order: List[str] = []
145
+ self.total_runtime: float = 0.0
146
+
147
+ # Adapted from: https://github.com/pytorch/pytorch/blob/9b902b3ee3bd608a19543362b66bf06c373dd374/torch/_subclasses/fake_tensor.py#L1969 # noqa: PGH004,B950
148
+ # NB: returns fake tensors
149
+ @classmethod
150
+ def _maybe_run_and_benchmark_fallback_kernel( # type: ignore[no-untyped-def]
151
+ cls,
152
+ func,
153
+ args,
154
+ kwargs,
155
+ orig_not_implemented_exception,
156
+ ):
157
+ """
158
+ Runs and benchmarks a fallback kernel for a given function.
159
+
160
+ Args:
161
+ func (Callable): The function to benchmark.
162
+ args (Tuple): The arguments to pass to the function.
163
+ kwargs (Dict[str, Any]): The keyword arguments to pass to the function.
164
+ orig_not_implemented_exception (Exception): The original exception to raise if the fallback kernel
165
+ is not implemented.
166
+
167
+ Returns:
168
+ Tuple[Any, float]: A tuple containing the result of the function and
169
+ the mean operation time in milliseconds.
170
+ """
171
+ # these should all be supported, just to be safe
172
+ # avoid fallback for operators which inplace modify metadata
173
+ # because the input fake tensors would be umodified
174
+ if torch.Tag.inplace_view in func.tags: # type: ignore[attr-defined]
175
+ raise orig_not_implemented_exception
176
+
177
+ inp_impls = {}
178
+ flat_args, args_spec = pytree.tree_flatten((args, kwargs))
179
+ # Don't use in_kernel_invocation_manager(fake_mode) as we want to do
180
+ # REAL compute (not with meta device)
181
+ with no_dispatch():
182
+
183
+ def to_real_tensor(e): # type: ignore[no-untyped-def]
184
+ if cls.fake_mode.is_our_fake(e):
185
+ if e.dtype in cls._float_types:
186
+ out = torch.rand_like(e, device=e.fake_device)
187
+ else:
188
+ out = torch.ones_like(e, device=e.fake_device)
189
+ if e.is_sparse:
190
+ out._coalesced_(e.is_coalesced())
191
+ inp_impls[id(out)] = e
192
+ return out
193
+ return e
194
+
195
+ flat_args = [to_real_tensor(a) for a in flat_args]
196
+ args, kwargs = pytree.tree_unflatten(flat_args, args_spec)
197
+ r = func(*args, **kwargs)
198
+ warmup_iters, actual_iters = 2, 3
199
+ for _ in range(warmup_iters):
200
+ func(*args, **kwargs)
201
+ start_event = torch.cuda.Event(enable_timing=True)
202
+ end_event = torch.cuda.Event(enable_timing=True)
203
+ start_event.record(torch.cuda.current_stream())
204
+ for _ in range(actual_iters):
205
+ func(*args, **kwargs)
206
+ end_event.record(torch.cuda.current_stream())
207
+ torch.cuda.synchronize()
208
+ cuda_time = start_event.elapsed_time(end_event)
209
+ mean_op_time = cuda_time / actual_iters
210
+
211
+ storages = set()
212
+
213
+ for e in flat_args:
214
+ if isinstance(e, torch.Tensor):
215
+ if not e.is_sparse:
216
+ storages.add(e._typed_storage()._cdata)
217
+
218
+ # TODO: also check metadata change on inputs
219
+ # proper aliasing/metadata relationship between outputs and inputs will
220
+ # not be set up, bc of conversion to device, unless we can reuse an
221
+ # input impl
222
+
223
+ def map_out(e): # type: ignore[no-untyped-def]
224
+ if id(e) not in inp_impls and (
225
+ isinstance(e, torch.Tensor)
226
+ and not e.is_sparse
227
+ and e._typed_storage()._cdata in storages
228
+ ):
229
+ raise orig_not_implemented_exception
230
+
231
+ if isinstance(e, torch.Tensor):
232
+ if id(e) in inp_impls:
233
+ return inp_impls[id(e)]
234
+ else:
235
+ return cls.fake_mode.fake_tensor_converter.from_real_tensor(
236
+ cls.fake_mode, e
237
+ )
238
+ else:
239
+ return e
240
+
241
+ return (pytree.tree_map(map_out, r), mean_op_time)
242
+
243
+ @classmethod
244
+ def _benchmark_estimate(cls, func, args, kwargs) -> Tuple[Any, float]: # type: ignore[no-untyped-def]
245
+ """
246
+ Estimates the runtime of a function using benchmarking.
247
+
248
+ Args:
249
+ func: The function to estimate.
250
+ args: The arguments to pass to the function.
251
+ kwargs: The keyword arguments to pass to the function.
252
+ res: The result of the function.
253
+
254
+ Returns:
255
+ Tuple[Any, float]: A tuple containing the result of the function and
256
+ the mean operation time in milliseconds.
257
+ """
258
+ assert isinstance(
259
+ cls.fake_mode, FakeTensorMode
260
+ ), "Initialize/Assign FakeTensorMode before using this function"
261
+ mean_op_time = 0.0
262
+ if func._overloadpacket not in _VIEW_OPS:
263
+ try:
264
+ res, mean_op_time = cls._maybe_run_and_benchmark_fallback_kernel(
265
+ func,
266
+ args,
267
+ kwargs,
268
+ NotImplementedError,
269
+ )
270
+ return (res, mean_op_time)
271
+ except NotImplementedError:
272
+ cls._no_fallback_kernel.add(func._overloadpacket)
273
+ res = func(*args, **kwargs or {})
274
+ return (res, mean_op_time)
275
+
276
+ # Adapted from: https://github.com/pytorch/pytorch/blob/9b902b3ee3bd608a19543362b66bf06c373dd374/torch/_inductor/scheduler.py#L589 # noqa: PGH004,B950
277
+ @classmethod
278
+ def _roofline_estimate(cls, func, args, kwargs) -> Tuple[Any, float]: # type: ignore[no-untyped-def]
279
+ """
280
+ Estimates the runtime of a function using a roofline cost model.
281
+
282
+ Args:
283
+ func: The function to estimate.
284
+ args: The arguments to pass to the function.
285
+ kwargs: The keyword arguments to pass to the function.
286
+ out: The output of the function.
287
+
288
+ Returns:
289
+ Tuple[Any, float]: A tuple containing the result of the function and
290
+ the mean operation time in milliseconds.
291
+ """
292
+ assert (
293
+ torch.cuda.is_available()
294
+ ), "Roofline estimation needs to access CUDA capabilities to make estimations"
295
+
296
+ def get_num_bytes(t: torch.Tensor) -> int:
297
+ """
298
+ Calculates the memory consumption of a tensor.
299
+
300
+ Args:
301
+ t (torch.Tensor): The input tensor.
302
+
303
+ Returns:
304
+ int: The memory consumption of the tensor in bytes.
305
+ """
306
+ num_bytes = t.untyped_storage().nbytes()
307
+ mem_consumed = (
308
+ math.ceil(num_bytes / _PYTORCH_MIN_ALLOCATE) * _PYTORCH_MIN_ALLOCATE
309
+ )
310
+ return mem_consumed
311
+
312
+ def get_compute_time(func_packet, args, kwargs, out, out_dtypes) -> float: # type: ignore[no-untyped-def]
313
+ """
314
+ Estimates the compute time of an aten operator.
315
+
316
+ Args:
317
+ func_packet: The operator overload packet.
318
+ args: The arguments to the operator.
319
+ kwargs: The keyword arguments to the operator.
320
+ out: The output of the operator.
321
+ out_dtypes: The output data types.
322
+
323
+ Returns:
324
+ float: The estimated compute time in nanoseconds.
325
+ """
326
+ if func_packet in flop_registry:
327
+ assert (
328
+ len(out_dtypes) == 1
329
+ ), f"Only support single out dtype got {out_dtypes} for {func_packet}"
330
+ dtype = out_dtypes.pop()
331
+ # This actually gives peta-FLOPs/s hence multiply by 1e15 to get the FLOPs/s
332
+ peak_gpu_flops = get_device_tflops(dtype) * 1e15
333
+ # We can expect to achieve 75% of theoretical peak flops
334
+ factor = 0.75
335
+ peak_empirical_flops = factor * peak_gpu_flops
336
+ flop_count_func = flop_registry[func_packet]
337
+ # We divide by a factor of 2 to get the MACs (multiply and accumulate)
338
+ flop_count = flop_count_func(*args, **kwargs, out_val=out) / 2
339
+ # We multiply by 1e9 to get the time in nano seconds
340
+ compute_time = (flop_count / peak_empirical_flops) * 1e9
341
+ return compute_time
342
+ return 0.0
343
+
344
+ def get_transfer_time(flat_args_kwargs, flat_outs) -> float: # type: ignore[no-untyped-def]
345
+ """
346
+ Estimates the memory transfer time of input and output tensors.
347
+
348
+ Args:
349
+ flat_args_kwargs (List[torch.Tensor]): The flat list of arguments and keyword arguments.
350
+ flat_outs (List[torch.Tensor]): The flat list of outputs.
351
+
352
+ Returns:
353
+ float: The estimated memory transfer time in nanoseconds.
354
+ """
355
+ gpu_memory_bandwidth = get_gpu_dram_gbps()
356
+ read_bytes = sum(
357
+ get_num_bytes(t)
358
+ for t in flat_args_kwargs
359
+ if isinstance(t, torch.Tensor)
360
+ )
361
+ write_bytes = sum(
362
+ get_num_bytes(t) for t in flat_outs if isinstance(t, torch.Tensor)
363
+ )
364
+ counted_bytes = read_bytes + write_bytes
365
+ # The GPU memory bandwidth is in GB/s so the transfer time is in nanoseconds
366
+ transfer_time = counted_bytes / gpu_memory_bandwidth
367
+ return transfer_time
368
+
369
+ # Roofline Cost Model Explanation
370
+
371
+ # The roofline cost model estimates the execution time of an operator based on
372
+ # the device's empirical maximum FLOPs/sec (pi) and device DRAM bandwidth (beta).
373
+
374
+ # Variables:
375
+ # - pi: Maximum empirical FLOPs/sec of the device
376
+ # - beta: Maximum empirical device DRAM bandwidth (bytes/sec) of the device
377
+ # - I: Arithmetic intensity of the operator (FLOPs/bytes)
378
+ # - op_flops: FLOPs required by the operator
379
+ # - op_bytes: Bytes transferred to and from DRAM for the operator
380
+
381
+ # Calculation Steps:
382
+ # 1. Calculate arithmetic intensity: I = op_flops / op_bytes
383
+ # 2. Calculate estimated FLOPs/sec: est_flops_sec = min(pi, beta * I)
384
+ # 3. Calculate estimated operator time: estimated_op_time = op_flops / est_flops_sec
385
+ # This simplifies to: estimated_op_time = max(op_flops / pi, op_flops / (beta * I))
386
+ # Further simplifying: estimated_op_time = max(op_flops / pi, op_bytes / beta)
387
+
388
+ # Simplified Formulas:
389
+ # - compute_time = op_flops / pi
390
+ # - transfer_time = op_bytes / beta
391
+ # - estimated_op_time = max(compute_time, transfer_time)
392
+
393
+ kwargs = kwargs if kwargs else {}
394
+ out = func(*args, **kwargs)
395
+ op_time = 0.0
396
+ func_packet = func._overloadpacket
397
+ if func_packet not in _IGNORE_OPS:
398
+ flat_args_kwargs, args_spec = pytree.tree_flatten((args, kwargs))
399
+ flat_outs, out_spec = pytree.tree_flatten(out)
400
+ transfer_time = get_transfer_time(flat_args_kwargs, flat_outs)
401
+
402
+ out_dtypes = {
403
+ t.dtype
404
+ for t in flat_outs
405
+ if isinstance(t, torch.Tensor) and t.dtype in cls._float_types
406
+ }
407
+
408
+ args, kwargs = pytree.tree_unflatten(flat_args_kwargs, args_spec)
409
+ out = pytree.tree_unflatten(flat_outs, out_spec)
410
+
411
+ compute_time = get_compute_time(func_packet, args, kwargs, out, out_dtypes)
412
+ # We get the estimated time as the max of the transfer time and
413
+ # compute time. We divide by 1e6 to get the time in ms
414
+ op_time = max(transfer_time, compute_time) / 1e6
415
+
416
+ return (out, op_time)
417
+
418
+ def display_modulewise_stats(self, depth: int = 2) -> None:
419
+ """
420
+ Displays module-wise statistics collected by ``RuntimeEstimator``.
421
+
422
+ Prints the pre-forward and pre-backward execution orders.
423
+ Displays the module-wise forward and backward runtimes in milliseconds.
424
+
425
+ Args:
426
+ depth (int): The maximum depth of module hierarchy to display (default to 2).
427
+ """
428
+ print("Pre-Forward Execution Order: ")
429
+ for mod_fqn in self.mod_fw_pre_order:
430
+ mod_depth = mod_fqn.count(".") + 1
431
+ if mod_depth > depth:
432
+ continue
433
+ print(mod_fqn)
434
+ print("Pre-Backward Execution Order: ")
435
+ for mod_fqn in self.mod_bw_pre_order:
436
+ mod_depth = mod_fqn.count(".") + 1
437
+ if mod_depth > depth:
438
+ continue
439
+ print(mod_fqn)
440
+ for mod_fqn, runtimes in self.mod_runtimes.items():
441
+ mod_depth = mod_fqn.count(".") + 1
442
+ if mod_depth > depth:
443
+ continue
444
+ print(
445
+ f"{mod_fqn} fw: {runtimes.get('fw', 0.0):.3f}ms bw: {runtimes.get('bw', 0.0):.3f}ms"
446
+ )
447
+
448
+ def __torch_dispatch__(self, func, types, args=..., kwargs=None): # type: ignore[no-untyped-def]
449
+ # TODO: @sanketpurandare: Flatten tensors by desugaring the tensor subclasses
450
+ # TODO: @sanketpurandare: Add logic for incorporating communication time
451
+ res, op_time = self._estimate(func, args, kwargs)
452
+ for par in self._mod_tracker.parents:
453
+ if self._mod_tracker.is_bw:
454
+ self.mod_runtimes[par]["bw"] += op_time
455
+ else:
456
+ self.mod_runtimes[par]["fw"] += op_time
457
+ self.total_runtime += op_time
458
+ return res
459
+
460
+ def __call__(self, estimate_mode_type: str) -> Self:
461
+ """
462
+ Sets the estimate mode type.
463
+
464
+ Currently supported modes:
465
+ - "operator-level-benchmark": Estimates runtime using operator benchmarking.
466
+ - "operator-level-cost-model": Estimates runtime using roofline cost model.
467
+
468
+ Args:
469
+ estimate_mode_type (str): The type of estimate mode to use.
470
+
471
+ Returns:
472
+ RuntimeEstimator: The runtime estimator instance.
473
+
474
+ Raises:
475
+ NotImplementedError: If the estimate mode type is not supported.
476
+ """
477
+ if estimate_mode_type == "operator-level-benchmark":
478
+ self._estimate = RuntimeEstimator._benchmark_estimate
479
+ elif estimate_mode_type == "operator-level-cost-model":
480
+ self._estimate = RuntimeEstimator._roofline_estimate
481
+ else:
482
+ raise NotImplementedError(
483
+ f"estimate_mode_type {estimate_mode_type} not supported"
484
+ )
485
+ self._estimate_mode_type = estimate_mode_type
486
+ return self
487
+
488
+ def __enter__(self) -> Self:
489
+ fake_mode = active_fake_mode()
490
+ assert isinstance(
491
+ fake_mode, FakeTensorMode
492
+ ), "No FakeTensorMode found, designed to used under FakeTensorMode"
493
+ RuntimeEstimator.fake_mode = fake_mode
494
+ self.total_runtime = 0.0
495
+ self.mod_runtimes = defaultdict(lambda: defaultdict(lambda: 0.0))
496
+ self.mod_fw_pre_order.clear()
497
+ self.mod_bw_pre_order.clear()
498
+ self.mod_fw_post_order.clear()
499
+ self.mod_bw_post_order.clear()
500
+ self._mod_tracker.register_user_hooks(
501
+ pre_fw_hook=lambda mod, inp: self.mod_fw_pre_order.append(
502
+ self._mod_tracker.get_known_fqn(mod)
503
+ ),
504
+ pre_bw_hook=lambda mod, g_out: self.mod_bw_pre_order.append(
505
+ self._mod_tracker.get_known_fqn(mod)
506
+ ),
507
+ post_fw_hook=lambda mod, inp, out: self.mod_fw_post_order.append(
508
+ self._mod_tracker.get_known_fqn(mod)
509
+ ),
510
+ post_bw_hook=lambda mod, g_inp: self.mod_bw_post_order.append(
511
+ self._mod_tracker.get_known_fqn(mod)
512
+ ),
513
+ )
514
+ self._mod_tracker.__enter__()
515
+ super().__enter__()
516
+ return self
517
+
518
+ def __exit__(self, *args: Any) -> None:
519
+ print(
520
+ f"Estimated ({self._estimate_mode_type})"
521
+ f"total_time: {self.total_runtime:.3f} ms"
522
+ )
523
+ if len(self._no_fallback_kernel) > 0:
524
+ print("no_fallback_kernel: ", list(self._no_fallback_kernel))
525
+ super().__exit__(*args)
526
+ self._mod_tracker.clear_user_hooks()
527
+ self._mod_tracker.__exit__()
vllm/lib/python3.10/site-packages/torch/distributed/checkpoint/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .api import CheckpointException
2
+ from .default_planner import DefaultLoadPlanner, DefaultSavePlanner
3
+ from .filesystem import FileSystemReader, FileSystemWriter
4
+ from .metadata import (
5
+ BytesStorageMetadata,
6
+ ChunkStorageMetadata,
7
+ Metadata,
8
+ TensorStorageMetadata,
9
+ )
10
+ from .optimizer import load_sharded_optimizer_state_dict
11
+ from .planner import LoadPlan, LoadPlanner, ReadItem, SavePlan, SavePlanner, WriteItem
12
+ from .state_dict_loader import load, load_state_dict
13
+ from .state_dict_saver import async_save, save, save_state_dict
14
+ from .storage import StorageReader, StorageWriter
vllm/lib/python3.10/site-packages/torch/distributed/checkpoint/_dedup_save_plans.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+ import dataclasses
3
+ from collections import defaultdict
4
+ from typing import Dict, List, Set, TYPE_CHECKING
5
+
6
+ from torch.distributed.checkpoint.planner import SavePlan, WriteItem
7
+
8
+
9
+ if TYPE_CHECKING:
10
+ from torch.distributed.checkpoint.metadata import MetadataIndex
11
+
12
+ __all__ = ["dedup_save_plans"]
13
+
14
+
15
+ def dedup_save_plans(
16
+ all_plans: List[SavePlan],
17
+ save_to_lowest_rank: bool = False,
18
+ ) -> List[SavePlan]:
19
+ """
20
+ Removes duplicate entries from appearing on multiple SavePlans. For each duplicate across
21
+ a set of SavePlans, only the smallest SavePlan in terms of planned storage keeps the entry.
22
+ """
23
+
24
+ write_item_to_plan_indices: Dict[MetadataIndex, Set[int]] = defaultdict(set)
25
+ write_item_idx_to_write_item: Dict[MetadataIndex, WriteItem] = {}
26
+ for plan_idx, plan in enumerate(all_plans):
27
+ for write_item in plan.items:
28
+ # map each write item to its plan
29
+ write_item_to_plan_indices[write_item.index].add(plan_idx)
30
+ write_item_idx_to_write_item[write_item.index] = write_item
31
+
32
+ # put item in the plan with the smallest size and remove it from the other plan_indices
33
+ to_remove: List[Set] = [set() for _ in range(len(all_plans))]
34
+ plan_to_size = [0] * len(all_plans)
35
+ for write_item_idx, plan_indices in write_item_to_plan_indices.items():
36
+ if save_to_lowest_rank:
37
+ select_plan_idx = min(plan_indices)
38
+ else:
39
+ select_plan_idx = min(
40
+ plan_indices, key=lambda plan_idx: plan_to_size[plan_idx]
41
+ )
42
+
43
+ write_item = write_item_idx_to_write_item[write_item_idx]
44
+ # essentially ignores the storage size of anything that is not a tensor, since
45
+ # we don't know how much storage they represent
46
+ plan_to_size[select_plan_idx] += write_item.tensor_storage_size() or 1
47
+
48
+ plan_indices.remove(select_plan_idx)
49
+ for plan_idx in plan_indices:
50
+ to_remove[plan_idx].add(write_item_idx)
51
+
52
+ for plan_idx, remove_set in enumerate(to_remove):
53
+ new_items = [
54
+ write_item
55
+ for write_item in all_plans[plan_idx].items
56
+ if write_item.index not in remove_set
57
+ ]
58
+ all_plans[plan_idx] = dataclasses.replace(all_plans[plan_idx], items=new_items)
59
+
60
+ return all_plans
vllm/lib/python3.10/site-packages/torch/distributed/checkpoint/_dedup_tensors.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+ import dataclasses
3
+ import logging
4
+ from typing import Dict, List, TYPE_CHECKING
5
+
6
+ from torch.distributed.checkpoint.planner import SavePlan
7
+
8
+
9
+ if TYPE_CHECKING:
10
+ from torch.distributed.checkpoint.metadata import MetadataIndex
11
+
12
+ __all__ = ["dedup_tensors"]
13
+
14
+
15
+ def init_logger() -> logging.Logger:
16
+ logger = logging.getLogger(__name__)
17
+ level = logging.INFO
18
+ logger.setLevel(level)
19
+ console = logging.StreamHandler()
20
+ formatter = logging.Formatter(
21
+ "%(asctime)s %(filename)s:%(lineno)s %(levelname)s p:%(processName)s t:%(threadName)s: %(message)s"
22
+ )
23
+ console.setFormatter(formatter)
24
+ console.setLevel(level)
25
+ logger.addHandler(console)
26
+ logger.propagate = False
27
+ return logger
28
+
29
+
30
+ logger = init_logger()
31
+
32
+
33
+ # TODO add docstring for dedup_tensors
34
+ def dedup_tensors(all_plans: List[SavePlan]) -> List[SavePlan]:
35
+ all_plans = list(all_plans)
36
+ key_to_plan: Dict[MetadataIndex, List[int]] = {}
37
+ for plan_idx, plan in enumerate(all_plans):
38
+ for write_item in plan.items:
39
+ key_to_plan.setdefault(write_item.index, []).append(plan_idx)
40
+
41
+ replicated_items = {k: v for k, v in key_to_plan.items() if len(v) > 1}
42
+
43
+ # Remove duplicates by always keeping the first entry.
44
+ # Compute the per-rank remove set.
45
+ plan_to_keys: Dict[int, List[MetadataIndex]] = {}
46
+ for key, plans in replicated_items.items():
47
+ for plan_idx in plans[1:]:
48
+ plan_to_keys.setdefault(plan_idx, []).append(key)
49
+ if len(plan_to_keys) > 0:
50
+ logger.info("Duplicate keys to remove: %s", plan_to_keys)
51
+
52
+ for plan_idx, keys in plan_to_keys.items():
53
+ key_set = set(keys)
54
+ # rewrite items and remove elements
55
+ new_items = [
56
+ write_item
57
+ for write_item in all_plans[plan_idx].items
58
+ if write_item.index not in key_set
59
+ ]
60
+ all_plans[plan_idx] = dataclasses.replace(all_plans[plan_idx], items=new_items)
61
+
62
+ return all_plans
vllm/lib/python3.10/site-packages/torch/distributed/checkpoint/_storage_utils.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import List, Type, Union
3
+
4
+ from .filesystem import FileSystemReader, FileSystemWriter
5
+ from .storage import StorageReader, StorageWriter
6
+
7
+
8
+ def _storage_setup(
9
+ storage: Union[StorageReader, StorageWriter, None],
10
+ checkpoint_id: Union[str, os.PathLike, None],
11
+ reader: bool = False,
12
+ ) -> Union[None, StorageReader, StorageWriter]:
13
+ if storage:
14
+ if checkpoint_id is not None:
15
+ storage.reset(checkpoint_id)
16
+ return storage
17
+
18
+ if not checkpoint_id:
19
+ raise RuntimeError(
20
+ "`checkpoint_id` must be specificed if "
21
+ "storage_reader/storage_writer is None."
22
+ )
23
+
24
+ targets: List[Type[Union[StorageReader, StorageWriter]]] = []
25
+ if reader:
26
+ targets = [
27
+ FileSystemReader,
28
+ ]
29
+ else:
30
+ targets = [
31
+ FileSystemWriter,
32
+ ]
33
+ try:
34
+ from ._fsspec_filesystem import FsspecReader, FsspecWriter
35
+
36
+ targets.append(FsspecReader if reader else FsspecWriter)
37
+ except Exception:
38
+ pass
39
+
40
+ for target in targets:
41
+ if target.validate_checkpoint_id(checkpoint_id):
42
+ storage = target(checkpoint_id) # type: ignore[call-arg]
43
+ storage.reset(checkpoint_id)
44
+ return storage
45
+
46
+ raise RuntimeError(
47
+ "Cannot detect which StorageReader or StorageWriter to use. "
48
+ "Please specify the storage_reader/storage_writer."
49
+ )
vllm/lib/python3.10/site-packages/torch/distributed/checkpoint/_traverse.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+ from typing import (
3
+ Callable,
4
+ cast,
5
+ Collection,
6
+ List,
7
+ Mapping,
8
+ MutableMapping,
9
+ Optional,
10
+ Tuple,
11
+ TypeVar,
12
+ Union,
13
+ )
14
+
15
+ import torch
16
+ from torch.distributed._shard.sharded_tensor.api import ShardedTensor
17
+ from torch.distributed.checkpoint.metadata import STATE_DICT_TYPE
18
+ from torch.distributed.tensor import DTensor
19
+
20
+
21
+ PATH_ITEM = Union[str, int]
22
+ OBJ_PATH = Tuple[PATH_ITEM, ...]
23
+ T = TypeVar("T")
24
+
25
+ STATE_DICT_ITEM = object
26
+ CONTAINER_TYPE = MutableMapping[PATH_ITEM, STATE_DICT_ITEM]
27
+
28
+ __all__ = ["traverse_state_dict", "set_element", "get_element", "print_tensor"]
29
+
30
+
31
+ def _keep_visiting_tensors(value: STATE_DICT_ITEM) -> bool:
32
+ return isinstance(value, torch.Tensor)
33
+
34
+
35
+ # TODO: update docstring for traverse.py
36
+ def traverse_state_dict(
37
+ state_dict: STATE_DICT_TYPE,
38
+ visitor: Callable[[OBJ_PATH, STATE_DICT_ITEM], None],
39
+ keep_traversing: Callable[[STATE_DICT_ITEM], bool] = _keep_visiting_tensors,
40
+ ) -> None:
41
+ """
42
+ Invoke ``visitor`` for each value recursively in ``state_dict``.
43
+ Mapping will be traversed and ``visitor`` will be applied to the leaf elements.
44
+ ``visitor`` will only be applied to elements in a list or a tuple, if the
45
+ container contains tensors or mappings.
46
+ """
47
+
48
+ def _is_terminal(value: STATE_DICT_ITEM) -> bool:
49
+ values: Collection[STATE_DICT_ITEM]
50
+ if isinstance(value, Mapping):
51
+ return False
52
+ elif isinstance(value, list):
53
+ values = value
54
+ else:
55
+ return True
56
+
57
+ for entry in values:
58
+ if isinstance(entry, (Mapping, list)) and not _is_terminal(entry):
59
+ return False
60
+ if keep_traversing is not None and keep_traversing(entry):
61
+ return False
62
+ return True
63
+
64
+ def _traverse_obj(path: OBJ_PATH, value: STATE_DICT_ITEM) -> None:
65
+ if isinstance(value, Mapping):
66
+ for k, v in value.items():
67
+ _traverse_obj(path + (str(k),), v)
68
+ elif _is_terminal(value):
69
+ visitor(path, value)
70
+ elif isinstance(value, (list, tuple)):
71
+ for i, v in enumerate(value):
72
+ _traverse_obj(path + (i,), v)
73
+
74
+ for key, value in state_dict.items():
75
+ _traverse_obj((str(key),), value)
76
+
77
+
78
+ def traverse_state_dict_v_2_3(
79
+ state_dict: STATE_DICT_TYPE,
80
+ visitor: Callable[[OBJ_PATH, STATE_DICT_ITEM], None],
81
+ keep_traversing: Callable[[STATE_DICT_ITEM], bool] = _keep_visiting_tensors,
82
+ ) -> None:
83
+ """
84
+ Traversal is short-circuited when if finds a collection for which ``keep_visiting_tensors`` evaluates
85
+ to false for all elements.
86
+ By default, all collections with at least one ``torch.Tensor`` element are traversed.
87
+ Visitor takes a path argument that is a tuple of the keys used to reach it.
88
+ """
89
+
90
+ # a value is terminal if it has no other containers values inside it
91
+ def _is_terminal(value: STATE_DICT_ITEM) -> bool:
92
+ values: Collection[STATE_DICT_ITEM]
93
+ if isinstance(value, Mapping):
94
+ values = value.values()
95
+ elif isinstance(value, list):
96
+ values = value
97
+ else:
98
+ return True
99
+
100
+ for entry in values:
101
+ if isinstance(entry, (Mapping, list)) and not _is_terminal(entry):
102
+ return False
103
+ if keep_traversing is not None and keep_traversing(entry):
104
+ return False
105
+ return True
106
+
107
+ def _traverse_obj(path: OBJ_PATH, value: STATE_DICT_ITEM) -> None:
108
+ if _is_terminal(value):
109
+ visitor(path, value)
110
+ elif isinstance(value, Mapping):
111
+ for k, v in value.items():
112
+ _traverse_obj(path + (str(k),), v)
113
+ elif isinstance(value, list):
114
+ for i, v in enumerate(value):
115
+ _traverse_obj(path + (i,), v)
116
+
117
+ for key, value in state_dict.items():
118
+ _traverse_obj((str(key),), value)
119
+
120
+
121
+ def set_element(
122
+ root_dict: STATE_DICT_TYPE, path: OBJ_PATH, value: STATE_DICT_ITEM
123
+ ) -> None:
124
+ """Set ``value`` in ``root_dict`` along the ``path`` object path."""
125
+ cur_container = cast(CONTAINER_TYPE, root_dict)
126
+
127
+ def extend_list(lst: List[STATE_DICT_ITEM], idx: int) -> None:
128
+ while len(lst) <= idx:
129
+ lst.append(None)
130
+
131
+ for i in range(1, len(path)):
132
+ prev_key = path[i - 1]
133
+ key = path[i]
134
+ def_val = cast(STATE_DICT_ITEM, {} if type(key) == str else [])
135
+
136
+ if isinstance(cur_container, Mapping):
137
+ cur_container = cast(
138
+ CONTAINER_TYPE, cur_container.setdefault(prev_key, def_val)
139
+ )
140
+ else:
141
+ extend_list(cur_container, prev_key)
142
+ if cur_container[prev_key] is None:
143
+ cur_container[prev_key] = def_val
144
+ cur_container = cur_container[prev_key]
145
+
146
+ key = path[-1]
147
+ if type(key) == int:
148
+ extend_list(cast(List[STATE_DICT_ITEM], cur_container), key)
149
+
150
+ cur_container[key] = value
151
+
152
+
153
+ def get_element(
154
+ root_dict: STATE_DICT_TYPE,
155
+ path: OBJ_PATH,
156
+ default_value: Optional[T] = None,
157
+ ) -> Optional[T]:
158
+ """Retrieve the value at ``path``from ``root_dict``, returning ``default_value`` if not found."""
159
+ cur_value = cast(CONTAINER_TYPE, root_dict)
160
+ for part in path:
161
+ if type(part) is int:
162
+ if not isinstance(cur_value, list) or len(cur_value) < part:
163
+ return default_value
164
+ elif not isinstance(cur_value, Mapping) or part not in cur_value:
165
+ return default_value
166
+
167
+ cur_value = cast(CONTAINER_TYPE, cur_value[part])
168
+ return cast(Optional[T], cur_value)
169
+
170
+
171
+ def _print_nested(
172
+ value: STATE_DICT_ITEM,
173
+ prefix: str = "",
174
+ print_fun: Callable[[str], None] = print,
175
+ ) -> None:
176
+ if type(value) is ShardedTensor:
177
+ print_fun(f"{prefix} ShardedTensor size: {value.size()}")
178
+ for shard in value.local_shards():
179
+ _print_nested(
180
+ shard.tensor,
181
+ f"{shard.metadata.shard_offsets} ",
182
+ print_fun=print_fun,
183
+ )
184
+ elif type(value) is (DTensor):
185
+ print_fun(f"{prefix} DistributedTensor size: {value.size()}")
186
+ # TODO: add local offset for _local_tensor in print_nested.
187
+ _print_nested(
188
+ value._local_tensor,
189
+ print_fun=print_fun,
190
+ )
191
+ elif isinstance(value, torch.Tensor):
192
+ print_fun(f"{prefix} Tensor size: {value.size()}")
193
+ else:
194
+ print_fun(f"{prefix} Type: {type(value)}")
195
+
196
+
197
+ def print_tensor(
198
+ path: OBJ_PATH,
199
+ value: STATE_DICT_ITEM,
200
+ print_fun: Callable[[str], None] = print,
201
+ ) -> None:
202
+ """
203
+ Use this callback with traverse_state_dict to print its content.
204
+
205
+ By default the content is printed using the builtin ``print`` but this can
206
+ be change by passing a different ``print_fun` callable.
207
+ """
208
+ _print_nested(value, prefix=str(path), print_fun=print_fun)
vllm/lib/python3.10/site-packages/torch/distributed/checkpoint/filesystem.py ADDED
@@ -0,0 +1,765 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import collections
3
+ import dataclasses
4
+ import io
5
+ import operator
6
+ import os
7
+ import pickle
8
+ import queue
9
+ import threading
10
+ import uuid
11
+ import warnings
12
+ from abc import ABC, abstractmethod
13
+ from contextlib import contextmanager
14
+ from dataclasses import dataclass
15
+ from pathlib import Path
16
+ from typing import (
17
+ Any,
18
+ Callable,
19
+ cast,
20
+ Dict,
21
+ Generator,
22
+ IO,
23
+ Iterable,
24
+ Iterator,
25
+ List,
26
+ Optional,
27
+ Tuple,
28
+ Union,
29
+ )
30
+
31
+ import torch
32
+ from torch import Tensor
33
+ from torch._utils import _get_available_device_type, _get_device_module
34
+ from torch.distributed._shard._utils import narrow_tensor_by_index
35
+ from torch.distributed.checkpoint.metadata import (
36
+ Metadata,
37
+ MetadataIndex,
38
+ STATE_DICT_TYPE,
39
+ StorageMeta,
40
+ )
41
+ from torch.distributed.checkpoint.planner import (
42
+ LoadItemType,
43
+ LoadPlan,
44
+ LoadPlanner,
45
+ ReadItem,
46
+ SavePlan,
47
+ SavePlanner,
48
+ WriteItem,
49
+ WriteItemType,
50
+ )
51
+ from torch.distributed.checkpoint.staging import BlockingAsyncStager
52
+ from torch.distributed.checkpoint.storage import (
53
+ StorageReader,
54
+ StorageWriter,
55
+ WriteResult,
56
+ )
57
+ from torch.distributed.checkpoint.utils import _create_file_view
58
+ from torch.futures import Future
59
+
60
+
61
+ __all__ = ["FileSystemWriter", "FileSystemReader", "FileSystem", "FileSystemBase"]
62
+
63
+ _metadata_fn: str = ".metadata"
64
+
65
+
66
+ @dataclass
67
+ class _StorageInfo:
68
+ """This is the per entry storage info."""
69
+
70
+ relative_path: str
71
+ offset: int
72
+ length: int
73
+
74
+
75
+ @dataclass
76
+ class _StoragePrefix:
77
+ prefix: str
78
+
79
+
80
+ DEFAULT_SUFFIX = ".distcp"
81
+
82
+
83
+ def _generate_uuid() -> str:
84
+ return str(uuid.uuid4())
85
+
86
+
87
+ class _TensorLoader(ABC):
88
+ @abstractmethod
89
+ def add(self, size: int, obj: object) -> None:
90
+ pass
91
+
92
+ @abstractmethod
93
+ def start_loading(self) -> None:
94
+ pass
95
+
96
+ @abstractmethod
97
+ def values(self) -> Iterator[Tuple[torch.Tensor, object]]:
98
+ pass
99
+
100
+
101
+ class _SerialCpuLoader(_TensorLoader):
102
+ def __init__(self, resolve_fun: Callable) -> None:
103
+ self.resolve_fun = resolve_fun
104
+ self.items: List[Tuple[int, object]] = []
105
+
106
+ def add(self, size: int, obj: object) -> None:
107
+ self.items.append((size, obj))
108
+
109
+ def start_loading(self) -> None:
110
+ pass
111
+
112
+ def values(self) -> Iterator[Tuple[torch.Tensor, object]]:
113
+ for _, obj in self.items:
114
+ tensor = self.resolve_fun(obj).detach()
115
+ tensor = tensor.cpu()
116
+ if tensor.storage().size() != tensor.numel():
117
+ tensor = tensor.clone()
118
+ yield (
119
+ tensor,
120
+ obj,
121
+ )
122
+
123
+
124
+ class _OverlappingCpuLoader(_TensorLoader):
125
+ def __init__(
126
+ self,
127
+ resolve_fun: Callable,
128
+ stream: Optional[torch.Stream] = None,
129
+ inflight_threshhold: int = 1_000_000,
130
+ ) -> None:
131
+ self.resolve_fun = resolve_fun
132
+ self.items: List[Tuple[int, object]] = []
133
+ self.inflight_threshhold = inflight_threshhold
134
+ self.in_flight_data = 0
135
+ self.current_items: collections.deque = collections.deque()
136
+ self.idx = 0
137
+ self.started = False
138
+ self.device_type = (
139
+ stream.device_type if stream else _get_available_device_type()
140
+ )
141
+ self.device_module = _get_device_module(self.device_type)
142
+ self.stream = cast(
143
+ torch.cuda.Stream, stream or self.device_module.current_stream()
144
+ )
145
+ if self.stream != self.device_module.current_stream():
146
+ self.stream.wait_stream(self.device_module.current_stream())
147
+
148
+ @property
149
+ def _done(self) -> bool:
150
+ return self.idx >= len(self.items)
151
+
152
+ def _drain(self) -> List[Tuple[torch.Tensor, object]]:
153
+ drained = []
154
+ if self.in_flight_data >= self.inflight_threshhold:
155
+ self.stream.synchronize()
156
+ while self.in_flight_data >= self.inflight_threshhold:
157
+ val = self.current_items.popleft()
158
+ self.in_flight_data -= val[0].numel() * val[0].element_size()
159
+ drained.append(val)
160
+ return drained
161
+
162
+ def _refill(self) -> None:
163
+ with self.device_module.stream(self.stream):
164
+ while not self._done and self.in_flight_data < self.inflight_threshhold:
165
+ _, obj = self.items[self.idx]
166
+ self.idx += 1
167
+ tensor = self.resolve_fun(obj).detach()
168
+ if tensor.device.type == self.device_type:
169
+ tensor = tensor.to(device="cpu", non_blocking=True)
170
+ elif tensor.device == torch.device("cpu"):
171
+ if (
172
+ tensor.untyped_storage().size()
173
+ != tensor.numel() * tensor.itemsize
174
+ ):
175
+ # this forces the tensor to be both contiguous and with minimal storage
176
+ tensor = tensor.clone()
177
+
178
+ self.current_items.append(
179
+ (
180
+ tensor,
181
+ obj,
182
+ )
183
+ )
184
+ self.in_flight_data += tensor.numel() * tensor.element_size()
185
+
186
+ def _finish(self) -> Iterable[Tuple[torch.Tensor, object]]:
187
+ assert self._done
188
+ if len(self.current_items) > 0:
189
+ self.stream.synchronize()
190
+ return self.current_items
191
+
192
+ def add(self, size: int, obj: object) -> None:
193
+ if self.started:
194
+ raise RuntimeError("cannot add items after loading started")
195
+ self.items.append((size, obj))
196
+
197
+ def start_loading(self) -> None:
198
+ if self.started:
199
+ return
200
+ self.started = True
201
+ self.items.sort(key=operator.itemgetter(0))
202
+ self._refill()
203
+
204
+ def values(self) -> Iterator[Tuple[torch.Tensor, object]]:
205
+ self.start_loading()
206
+ while not self._done:
207
+ drained = self._drain()
208
+ self._refill()
209
+ yield from drained
210
+
211
+ yield from self._finish()
212
+
213
+
214
+ def _item_size(item: WriteItem) -> int:
215
+ size = 1
216
+ assert item.tensor_data is not None
217
+ # can't use math.prod as PT needs to support older python
218
+ for s in item.tensor_data.size:
219
+ size *= s
220
+
221
+ dtype = item.tensor_data.properties.dtype
222
+ return size * torch._utils._element_size(dtype)
223
+
224
+
225
+ def _split_by_size_and_type(bins: int, items: List[WriteItem]) -> List[List[WriteItem]]:
226
+ if bins == 1:
227
+ return [items]
228
+
229
+ bytes_w = [wi for wi in items if wi.type == WriteItemType.BYTE_IO]
230
+ tensor_w = [wi for wi in items if wi.type != WriteItemType.BYTE_IO]
231
+
232
+ buckets: List[List[WriteItem]] = [[] for _ in range(bins)]
233
+ bucket_sizes = [0 for _ in range(bins)]
234
+
235
+ tensor_w.sort(key=_item_size, reverse=True)
236
+
237
+ for i, wi in enumerate(bytes_w):
238
+ buckets[i % bins].append(wi)
239
+
240
+ for wi in tensor_w:
241
+ # TODO replace with headq
242
+ idx = min(enumerate(bucket_sizes), key=operator.itemgetter(1))[0]
243
+ buckets[idx].append(wi)
244
+ bucket_sizes[idx] += _item_size(wi)
245
+
246
+ return buckets
247
+
248
+
249
+ def _write_item(
250
+ stream: io.IOBase,
251
+ data: Union[io.BytesIO, torch.Tensor],
252
+ write_item: WriteItem,
253
+ storage_key: str,
254
+ ) -> WriteResult:
255
+ offset = stream.tell()
256
+
257
+ if write_item.type == WriteItemType.BYTE_IO:
258
+ assert isinstance(data, io.BytesIO)
259
+ stream.write(data.getbuffer())
260
+ else:
261
+ assert isinstance(data, torch.Tensor)
262
+ assert data.device == torch.device("cpu")
263
+ torch.save(data, cast(IO[bytes], stream))
264
+ length = stream.tell() - offset
265
+
266
+ return WriteResult(
267
+ index=write_item.index,
268
+ size_in_bytes=length,
269
+ storage_data=_StorageInfo(storage_key, offset, length),
270
+ )
271
+
272
+
273
+ def _write_files_from_queue(
274
+ create_stream: Callable,
275
+ file_queue: queue.Queue,
276
+ result_queue: queue.Queue,
277
+ planner: SavePlanner,
278
+ inflight_threshhold: int,
279
+ use_fsync: bool,
280
+ thread_count: int,
281
+ ) -> None:
282
+ try:
283
+ while True:
284
+ file_name, storage_key, write_items = file_queue.get_nowait()
285
+ loader: _TensorLoader
286
+
287
+ custom_backend_name = torch._C._get_privateuse1_backend_name()
288
+ custom_device_mod = getattr(torch, custom_backend_name, None)
289
+
290
+ # TODO: Using the OverlappingCpuLoader with multiple threads creates significant
291
+ # performance degredation, observed as being related to cuda stream syncs. We
292
+ # should try to fix this and use _OverlappingCpuLoader for all threaded cases
293
+ if (
294
+ thread_count == 1
295
+ and (
296
+ torch.cuda.is_available()
297
+ or (custom_device_mod and custom_device_mod.is_available())
298
+ )
299
+ and inflight_threshhold > 0
300
+ ):
301
+ loader = _OverlappingCpuLoader(
302
+ planner.resolve_data,
303
+ inflight_threshhold=inflight_threshhold,
304
+ )
305
+ else:
306
+ loader = _SerialCpuLoader(
307
+ planner.resolve_data,
308
+ )
309
+
310
+ tensor_w = [wi for wi in write_items if wi.type != WriteItemType.BYTE_IO]
311
+ for write_item in tensor_w:
312
+ loader.add(_item_size(write_item), write_item)
313
+ loader.start_loading()
314
+
315
+ bytes_w = [wi for wi in write_items if wi.type == WriteItemType.BYTE_IO]
316
+ write_results = []
317
+
318
+ with create_stream(file_name, "wb") as stream:
319
+ for write_item in bytes_w:
320
+ data = planner.resolve_data(write_item)
321
+ write_results.append(
322
+ _write_item(stream, data, write_item, storage_key)
323
+ )
324
+
325
+ for tensor, write_item in loader.values():
326
+ assert tensor.is_cpu
327
+ write_results.append(
328
+ _write_item(stream, tensor, write_item, storage_key)
329
+ )
330
+
331
+ if use_fsync:
332
+ try:
333
+ os.fsync(stream.fileno())
334
+ except AttributeError:
335
+ os.sync()
336
+ result_queue.put(write_results)
337
+ except queue.Empty:
338
+ pass
339
+
340
+
341
+ class FileSystemBase(ABC):
342
+ @contextmanager
343
+ @abstractmethod
344
+ def create_stream(
345
+ self, path: Union[str, os.PathLike], mode: str
346
+ ) -> Generator[io.IOBase, None, None]:
347
+ ...
348
+
349
+ @abstractmethod
350
+ def concat_path(
351
+ self, path: Union[str, os.PathLike], suffix: str
352
+ ) -> Union[str, os.PathLike]:
353
+ ...
354
+
355
+ @abstractmethod
356
+ def rename(
357
+ self, path: Union[str, os.PathLike], new_path: Union[str, os.PathLike]
358
+ ) -> None:
359
+ ...
360
+
361
+ @abstractmethod
362
+ def init_path(self, path: Union[str, os.PathLike]) -> Union[str, os.PathLike]:
363
+ ...
364
+
365
+ @abstractmethod
366
+ def mkdir(self, path: Union[str, os.PathLike]) -> None:
367
+ ...
368
+
369
+ @classmethod
370
+ @abstractmethod
371
+ def validate_checkpoint_id(cls, checkpoint_id: Union[str, os.PathLike]) -> bool:
372
+ ...
373
+
374
+ @abstractmethod
375
+ def exists(self, path: Union[str, os.PathLike]) -> bool:
376
+ ...
377
+
378
+ @abstractmethod
379
+ def rm_file(self, path: Union[str, os.PathLike]) -> None:
380
+ ...
381
+
382
+
383
+ class FileSystem(FileSystemBase):
384
+ @contextmanager
385
+ def create_stream(
386
+ self, path: Union[str, os.PathLike], mode: str
387
+ ) -> Generator[io.IOBase, None, None]:
388
+ with cast(Path, path).open(mode) as stream:
389
+ yield cast(io.IOBase, stream)
390
+
391
+ def concat_path(
392
+ self, path: Union[str, os.PathLike], suffix: str
393
+ ) -> Union[str, os.PathLike]:
394
+ return cast(Path, path) / suffix
395
+
396
+ def init_path(self, path: Union[str, os.PathLike]) -> Union[str, os.PathLike]:
397
+ if not isinstance(path, Path):
398
+ path = Path(path)
399
+ return path
400
+
401
+ def rename(
402
+ self, path: Union[str, os.PathLike], new_path: Union[str, os.PathLike]
403
+ ) -> None:
404
+ cast(Path, path).rename(cast(Path, new_path))
405
+
406
+ def mkdir(self, path: Union[str, os.PathLike]) -> None:
407
+ cast(Path, path).mkdir(parents=True, exist_ok=True)
408
+
409
+ @classmethod
410
+ def validate_checkpoint_id(cls, checkpoint_id: Union[str, os.PathLike]) -> bool:
411
+ if isinstance(checkpoint_id, Path):
412
+ return True
413
+
414
+ if "://" in str(checkpoint_id):
415
+ return False
416
+
417
+ for p in Path(checkpoint_id).parents:
418
+ if p.exists() and os.access(str(p), os.W_OK):
419
+ return True
420
+
421
+ return False
422
+
423
+ def exists(self, path: Union[str, os.PathLike]) -> bool:
424
+ return cast(Path, path).exists()
425
+
426
+ def rm_file(self, path: Union[str, os.PathLike]) -> None:
427
+ cast(Path, path).unlink()
428
+
429
+
430
+ class _FileSystemWriter(StorageWriter):
431
+ """
432
+ Basic implementation of StorageWriter using file IO.
433
+
434
+ This implementation makes the following assumptions and simplifications:
435
+
436
+ * The checkpoint path is an empty or non-existing directory.
437
+ * File creation is atomic
438
+
439
+ The checkpoint consist of one file per write request plus
440
+ a `.metadata` file with the serialized metadata.
441
+
442
+ """
443
+
444
+ def __init__(
445
+ self,
446
+ path: Union[str, os.PathLike],
447
+ single_file_per_rank: bool = True,
448
+ sync_files: bool = True,
449
+ thread_count: int = 1,
450
+ per_thread_copy_ahead: int = 10_000_000,
451
+ overwrite: bool = True,
452
+ *args: Any,
453
+ **kwargs: Any,
454
+ ) -> None:
455
+ """
456
+ Initialize the writer pointing to `path`.
457
+
458
+ Args:
459
+ path: directory where the checkpoint will be written to.
460
+ single_file_per_rank: Produce one file per rank instead of one file per tensor/blob. Default to True.
461
+ sync_files : force files to be synced to permanent storage. Default to True.
462
+ thread_count: Number of IO threads to use to write. Default to 1.
463
+ per_thread_copy_ahead: How many bytes to copy from the GPU ahead of saving then. Default 10Mb.
464
+ overwrite: Whether to allow overwriting existing checkpoints. Defaults to True.
465
+
466
+ N. B. If sync_files is disabled, there's no guarantee that the checkpoint will be consistent in the case of a failure.
467
+ """
468
+ super().__init__()
469
+ self.fs = FileSystem()
470
+ self.path = self.fs.init_path(path)
471
+ self.single_file_per_rank = single_file_per_rank
472
+ self.sync_files = sync_files
473
+ self.thread_count = thread_count
474
+ self.per_thread_copy_ahead = per_thread_copy_ahead
475
+ self.save_id = _generate_uuid()
476
+ self.overwrite = overwrite
477
+
478
+ def reset(self, checkpoint_id: Union[str, os.PathLike, None] = None) -> None:
479
+ if checkpoint_id:
480
+ self.path = self.fs.init_path(checkpoint_id)
481
+ self.save_id = _generate_uuid()
482
+
483
+ def set_up_storage_writer(self, is_coordinator: bool) -> None:
484
+ pass
485
+
486
+ def prepare_local_plan(self, plan: SavePlan) -> SavePlan:
487
+ self.fs.mkdir(self.path)
488
+ if self.fs.exists(self.metadata_path):
489
+ if self.overwrite:
490
+ warnings.warn(
491
+ f"Detected an existing checkpoint in {self.metadata_path}, overwriting since {self.overwrite=}."
492
+ " Past version 2.5 of PyTorch, `overwrite` will default to False. Set this variable to True to"
493
+ " maintain this functionality or False to raise when an existing checkpoint is found."
494
+ )
495
+ else:
496
+ raise RuntimeError(f"Checkpoint already exists and {self.overwrite=}.")
497
+
498
+ return plan
499
+
500
+ def prepare_global_plan(self, plans: List[SavePlan]) -> List[SavePlan]:
501
+ new_plans = [
502
+ dataclasses.replace(plan, storage_data=_StoragePrefix(f"__{i}_"))
503
+ for i, plan in enumerate(plans)
504
+ ]
505
+ return new_plans
506
+
507
+ def write_data(
508
+ self,
509
+ plan: SavePlan,
510
+ planner: SavePlanner,
511
+ ) -> Future[List[WriteResult]]:
512
+ storage_plan: _StoragePrefix = plan.storage_data
513
+ file_count = 0
514
+
515
+ def gen_file():
516
+ nonlocal file_count
517
+ file_name = f"{storage_plan.prefix}{file_count}{DEFAULT_SUFFIX}"
518
+ file_count += 1
519
+ return file_name
520
+
521
+ file_queue: queue.Queue = queue.Queue()
522
+ if self.single_file_per_rank:
523
+ for bucket in _split_by_size_and_type(self.thread_count, plan.items):
524
+ file_name = gen_file()
525
+ path = self.fs.concat_path(self.path, file_name)
526
+ file_queue.put((path, file_name, bucket))
527
+ else:
528
+ for item in plan.items:
529
+ file_name = gen_file()
530
+ path = self.fs.concat_path(self.path, file_name)
531
+ file_queue.put((path, file_name, [item]))
532
+
533
+ result_queue: queue.Queue = queue.Queue()
534
+
535
+ threads = []
536
+ for _ in range(1, self.thread_count):
537
+ t = threading.Thread(
538
+ target=_write_files_from_queue,
539
+ args=(
540
+ self.fs.create_stream,
541
+ file_queue,
542
+ result_queue,
543
+ planner,
544
+ self.per_thread_copy_ahead,
545
+ self.sync_files,
546
+ self.thread_count,
547
+ ),
548
+ )
549
+ t.start()
550
+ threads.append(t)
551
+
552
+ _write_files_from_queue(
553
+ create_stream=self.fs.create_stream,
554
+ file_queue=file_queue,
555
+ result_queue=result_queue,
556
+ planner=planner,
557
+ inflight_threshhold=self.per_thread_copy_ahead,
558
+ use_fsync=self.sync_files,
559
+ thread_count=self.thread_count,
560
+ )
561
+
562
+ for t in threads:
563
+ t.join()
564
+
565
+ res = []
566
+ try:
567
+ while True:
568
+ res += result_queue.get_nowait()
569
+ except queue.Empty:
570
+ fut: Future[List[WriteResult]] = Future()
571
+ fut.set_result(res)
572
+ return fut
573
+
574
+ def finish(self, metadata: Metadata, results: List[List[WriteResult]]) -> None:
575
+ storage_md = {}
576
+ for wr_list in results:
577
+ storage_md.update({wr.index: wr.storage_data for wr in wr_list})
578
+ metadata.storage_data = storage_md
579
+
580
+ metadata.storage_meta = self.storage_meta()
581
+
582
+ tmp_path = cast(Path, self.fs.concat_path(self.path, f"{_metadata_fn}.tmp"))
583
+ with self.fs.create_stream(tmp_path, "wb") as metadata_file:
584
+ pickle.dump(metadata, metadata_file)
585
+ if self.sync_files:
586
+ try:
587
+ os.fsync(metadata_file.fileno())
588
+ except AttributeError:
589
+ os.sync()
590
+
591
+ # delete in-case other checkpoints were present.
592
+ if self.fs.exists(self.metadata_path):
593
+ self.fs.rm_file(self.metadata_path)
594
+
595
+ self.fs.rename(tmp_path, self.metadata_path)
596
+
597
+ def storage_meta(self) -> Optional[StorageMeta]:
598
+ return StorageMeta(checkpoint_id=self.checkpoint_id, save_id=self.save_id)
599
+
600
+ @property
601
+ def metadata_path(self) -> Union[str, os.PathLike]:
602
+ return cast(Path, self.fs.concat_path(self.path, _metadata_fn))
603
+
604
+ @property
605
+ def checkpoint_id(self) -> Union[str, os.PathLike]:
606
+ """
607
+ return the checkpoint_id that will be used to save the checkpoint.
608
+ """
609
+ return self.path
610
+
611
+ @classmethod
612
+ def validate_checkpoint_id(cls, checkpoint_id: Union[str, os.PathLike]) -> bool:
613
+ return FileSystem.validate_checkpoint_id(checkpoint_id)
614
+
615
+
616
+ class FileSystemReader(StorageReader):
617
+ def __init__(self, path: Union[str, os.PathLike]) -> None:
618
+ super().__init__()
619
+ self.fs = FileSystem()
620
+ self.path = self.fs.init_path(path)
621
+ self.storage_data: Dict[MetadataIndex, _StorageInfo] = {}
622
+ self.load_id = _generate_uuid()
623
+
624
+ def _slice_file(self, file, sinfo: _StorageInfo) -> io.IOBase:
625
+ return _create_file_view(file, sinfo.offset, sinfo.length)
626
+
627
+ def reset(self, checkpoint_id: Union[str, os.PathLike, None] = None) -> None:
628
+ self.storage_data = {}
629
+ if checkpoint_id:
630
+ self.path = self.fs.init_path(checkpoint_id)
631
+ self.load_id = _generate_uuid()
632
+
633
+ def read_data(self, plan: LoadPlan, planner: LoadPlanner) -> Future[None]:
634
+ # group requests by file
635
+ per_file: Dict[str, List[ReadItem]] = {}
636
+ for read_item in plan.items:
637
+ item_md = self.storage_data[read_item.storage_index]
638
+ path = item_md.relative_path
639
+ per_file.setdefault(path, []).append(read_item)
640
+
641
+ for relative_path, reqs in per_file.items():
642
+ new_path = self.fs.concat_path(self.path, relative_path)
643
+ with self.fs.create_stream(new_path, "rb") as stream:
644
+ # TODO sort by offset and cache the reading
645
+ for req in reqs:
646
+ item_md = self.storage_data[req.storage_index]
647
+ file_slice = self._slice_file(stream, item_md)
648
+ if req.type == LoadItemType.BYTE_IO:
649
+ read_bytes = io.BytesIO(file_slice.read(item_md.length))
650
+ read_bytes.seek(0)
651
+ planner.load_bytes(req, read_bytes)
652
+ else:
653
+ tensor = cast(
654
+ Tensor,
655
+ torch.load(
656
+ cast(IO[bytes], file_slice),
657
+ map_location="cpu",
658
+ weights_only=True,
659
+ ),
660
+ )
661
+ tensor = narrow_tensor_by_index(
662
+ tensor, req.storage_offsets, req.lengths
663
+ )
664
+ target_tensor = planner.resolve_tensor(req).detach()
665
+
666
+ assert (
667
+ target_tensor.size() == tensor.size()
668
+ ), f"req {req.storage_index} mismatch sizes {target_tensor.size()} vs {tensor.size()}"
669
+ target_tensor.copy_(tensor)
670
+ planner.commit_tensor(req, target_tensor)
671
+
672
+ fut: Future = Future()
673
+ fut.set_result(None)
674
+ return fut
675
+
676
+ # Implementing the abstract function in StorageReader
677
+ def read_metadata(self) -> Metadata:
678
+ path = self.fs.concat_path(self.path, ".metadata")
679
+ with self.fs.create_stream(path, "rb") as metadata_file:
680
+ metadata = pickle.load(metadata_file)
681
+
682
+ if getattr(metadata, "storage_meta", None) is None:
683
+ metadata.storage_meta = StorageMeta()
684
+ metadata.storage_meta.load_id = self.load_id
685
+
686
+ return metadata
687
+
688
+ def set_up_storage_reader(self, metadata: Metadata, is_coordinator: bool) -> None:
689
+ self.storage_data = metadata.storage_data
690
+ assert self.storage_data is not None
691
+
692
+ def prepare_local_plan(self, plan: LoadPlan) -> LoadPlan:
693
+ return plan
694
+
695
+ def prepare_global_plan(self, plans: List[LoadPlan]) -> List[LoadPlan]:
696
+ return plans
697
+
698
+ @property
699
+ def checkpoint_id(self) -> Union[str, os.PathLike]:
700
+ """
701
+ return the checkpoint_id that will be used to load the checkpoint.
702
+ """
703
+ return self.path
704
+
705
+ @classmethod
706
+ def validate_checkpoint_id(cls, checkpoint_id: Union[str, os.PathLike]) -> bool:
707
+ return FileSystem.validate_checkpoint_id(checkpoint_id)
708
+
709
+
710
+ class FileSystemWriter(_FileSystemWriter, BlockingAsyncStager):
711
+ """
712
+ Basic implementation of StorageWriter using file IO.
713
+
714
+ This implementation makes the following assumptions and simplifications:
715
+
716
+ * The checkpoint path is an empty or non-existing directory.
717
+ * File creation is atomic
718
+
719
+ The checkpoint consist of one file per write request plus
720
+ a `.metadata` file with the serialized metadata.
721
+
722
+ """
723
+
724
+ def __init__(
725
+ self,
726
+ path: Union[str, os.PathLike],
727
+ single_file_per_rank: bool = True,
728
+ sync_files: bool = True,
729
+ thread_count: int = 1,
730
+ per_thread_copy_ahead: int = 10_000_000,
731
+ cache_staged_state_dict: bool = False,
732
+ overwrite: bool = True,
733
+ ) -> None:
734
+ """
735
+ Initialize the writer pointing to `path`.
736
+
737
+ Args:
738
+ path: directory where the checkpoint will be written to.
739
+ single_file_per_rank: Produce one file per rank instead of one file per tensor/blob. Default to True.
740
+ sync_files : force files to be synced to permanent storage. Default to True.
741
+ thread_count: Number of IO threads to use to write. Default to 1.
742
+ per_thread_copy_ahead: How many bytes to copy from the GPU ahead of saving then. Default 10Mb.
743
+ cache_staged_state_dict: Whether to cache the staged state_dict. This option decreases staging latency
744
+ at the cost of increases memory usage. Additionally, if this parameter is set to True, it's the expectation
745
+ that the stager is maintained and re-used for multiple dcp.async_save calls. Default to False.
746
+ overwrite: Whether to allow overwriting existing checkpoints. Defaults to True.
747
+
748
+ N. B. If sync_files is disabled, there's no guarantee that the checkpoint will be consistent in the case of a failure.
749
+ """
750
+ super().__init__(
751
+ path=path,
752
+ single_file_per_rank=single_file_per_rank,
753
+ sync_files=sync_files,
754
+ thread_count=thread_count,
755
+ per_thread_copy_ahead=per_thread_copy_ahead,
756
+ cache_staged_state_dict=cache_staged_state_dict,
757
+ overwrite=overwrite,
758
+ )
759
+
760
+ def stage(self, state_dict: STATE_DICT_TYPE) -> STATE_DICT_TYPE:
761
+ """Override of AsyncStager.stage"""
762
+ # in the async case, the state dict is already on CPU, so maintaining this
763
+ # buffer makes no sense
764
+ self.per_thread_copy_ahead = 0
765
+ return super().stage(state_dict)
vllm/lib/python3.10/site-packages/torch/distributed/checkpoint/metadata.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import os
3
+ from dataclasses import dataclass, field
4
+ from enum import Enum
5
+ from typing import Any, Dict, List, Optional, Sequence, Union
6
+
7
+ import torch
8
+ from torch.distributed.checkpoint.stateful import StatefulT
9
+
10
+
11
+ __all__ = [
12
+ "ChunkStorageMetadata",
13
+ "TensorStorageMetadata",
14
+ "BytesStorageMetadata",
15
+ "Metadata",
16
+ "MetadataIndex",
17
+ "TensorProperties",
18
+ "StorageMeta",
19
+ ]
20
+
21
+
22
+ @dataclass
23
+ class ChunkStorageMetadata:
24
+ """
25
+ Each chunk is expected to have the same properties of the TensorStorageMetadata
26
+ that includes it.
27
+ """
28
+
29
+ offsets: torch.Size
30
+ sizes: torch.Size
31
+
32
+
33
+ class _MEM_FORMAT_ENCODING(Enum):
34
+ """Describe the memory format of a tensor."""
35
+
36
+ TORCH_CONTIGUOUS_FORMAT = 0
37
+ TORCH_CHANNELS_LAST = 1
38
+ TORCH_PRESERVE_FORMAT = 2
39
+
40
+
41
+ @dataclass
42
+ class TensorProperties:
43
+ """Properties used to create :class:`Tensor`"""
44
+
45
+ # Regular tensor fields
46
+ dtype: torch.dtype = field(default_factory=torch.get_default_dtype)
47
+ # This field is deprecated.
48
+ layout: torch.layout = field(default=torch.strided)
49
+ # This field is deprecated.
50
+ requires_grad: bool = False
51
+ # This field is deprecated.
52
+ memory_format: torch.memory_format = field(default=torch.contiguous_format)
53
+ # This field is deprecated.
54
+ pin_memory: bool = False
55
+
56
+ def __getstate__(self):
57
+ # Since torch.memory_format cannot be pickled!
58
+ memory_format = self.memory_format
59
+ if memory_format == torch.contiguous_format:
60
+ mem_format_encoding = _MEM_FORMAT_ENCODING.TORCH_CONTIGUOUS_FORMAT
61
+ elif memory_format == torch.channels_last:
62
+ mem_format_encoding = _MEM_FORMAT_ENCODING.TORCH_CHANNELS_LAST
63
+ elif memory_format == torch.preserve_format:
64
+ mem_format_encoding = _MEM_FORMAT_ENCODING.TORCH_PRESERVE_FORMAT
65
+ else:
66
+ raise RuntimeError(f"Invalid torch.memory_format: {memory_format}")
67
+
68
+ return (
69
+ self.dtype,
70
+ self.layout,
71
+ self.requires_grad,
72
+ mem_format_encoding,
73
+ self.pin_memory,
74
+ )
75
+
76
+ def __setstate__(
77
+ self,
78
+ state,
79
+ ):
80
+ (
81
+ self.dtype,
82
+ self.layout,
83
+ self.requires_grad,
84
+ mem_format_encoding,
85
+ self.pin_memory,
86
+ ) = state
87
+
88
+ if mem_format_encoding == _MEM_FORMAT_ENCODING.TORCH_CONTIGUOUS_FORMAT:
89
+ memory_format = torch.contiguous_format
90
+ elif mem_format_encoding == _MEM_FORMAT_ENCODING.TORCH_CHANNELS_LAST:
91
+ memory_format = torch.channels_last
92
+ elif mem_format_encoding == _MEM_FORMAT_ENCODING.TORCH_PRESERVE_FORMAT:
93
+ memory_format = torch.preserve_format
94
+ else:
95
+ raise RuntimeError(
96
+ f"Invalid torch.memory_format encoding: {mem_format_encoding}"
97
+ )
98
+
99
+ self.memory_format = memory_format
100
+
101
+ @staticmethod
102
+ def create_from_tensor(tensor: torch.Tensor) -> "TensorProperties":
103
+ return TensorProperties(
104
+ dtype=tensor.dtype,
105
+ layout=tensor.layout,
106
+ requires_grad=tensor.requires_grad,
107
+ memory_format=torch.contiguous_format,
108
+ pin_memory=tensor.is_pinned(),
109
+ )
110
+
111
+
112
+ @dataclass
113
+ class TensorStorageMetadata:
114
+ properties: TensorProperties
115
+ size: torch.Size
116
+ chunks: List[ChunkStorageMetadata]
117
+
118
+
119
+ @dataclass
120
+ class BytesStorageMetadata:
121
+ pass
122
+
123
+
124
+ STORAGE_TYPES = Union[TensorStorageMetadata, BytesStorageMetadata]
125
+ STATE_DICT_TYPE = Dict[str, Union[StatefulT, Any]]
126
+
127
+
128
+ @dataclass
129
+ class StorageMeta:
130
+ checkpoint_id: Union[str, os.PathLike, None] = None
131
+ save_id: Optional[str] = None
132
+ load_id: Optional[str] = None
133
+
134
+
135
+ @dataclass
136
+ class Metadata:
137
+ """This class represents the metadata of the checkpoint."""
138
+
139
+ # Keys are the same from the `state_dict` used.
140
+ state_dict_metadata: Dict[str, STORAGE_TYPES]
141
+ # It is the responsibility of the planner and storage plugins to ensure
142
+ # backward compatibility of the planner_data and storage_data. DCP will
143
+ # also ensure the backward compatibility of the metadata in this file and
144
+ # the metadata of the built-in planner and storage plugins.
145
+ planner_data: Any = None
146
+ storage_data: Any = None
147
+ storage_meta: Optional[StorageMeta] = None
148
+
149
+
150
+ @dataclass(frozen=True)
151
+ class MetadataIndex:
152
+ """This class represents a lookup key for items in a state dict or Metadata."""
153
+
154
+ fqn: str
155
+ """Fully Qualified Name of the object"""
156
+
157
+ offset: Optional[torch.Size] = None
158
+ """If the object is a tensor, offset into the tensor we're looking for"""
159
+
160
+ index: Optional[int] = field(hash=False, compare=False, default=None)
161
+ """
162
+ Index hint when searching for tensor chunk to speedup lookups (optional)
163
+
164
+ A common representation of a sharded tensor is as a list of chunks so to
165
+ find the index in such a list you need to linear search it.
166
+
167
+ When constructing an instance of MetadataIndex that points to that list,
168
+ one can provide the index as a hint and it will be probed first before
169
+ the linear search and thus making it significantly faster.
170
+ """
171
+
172
+ def __init__(
173
+ self,
174
+ fqn: str,
175
+ offset: Optional[Sequence[int]] = None,
176
+ index: Optional[int] = None,
177
+ ):
178
+ # We must use object.__setattr__ due to frozen=True
179
+ object.__setattr__(self, "fqn", fqn)
180
+ object.__setattr__(self, "index", index)
181
+ if offset is not None:
182
+ object.__setattr__(self, "offset", torch.Size(offset))
vllm/lib/python3.10/site-packages/torch/distributed/checkpoint/planner.py ADDED
@@ -0,0 +1,417 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+ import io
3
+ import operator
4
+ from dataclasses import dataclass
5
+ from enum import auto, Enum
6
+ from functools import reduce
7
+ from typing import Any, List, Optional, Tuple, Union
8
+
9
+ import torch
10
+ from torch.distributed.checkpoint.metadata import (
11
+ ChunkStorageMetadata,
12
+ Metadata,
13
+ MetadataIndex,
14
+ STATE_DICT_TYPE,
15
+ StorageMeta,
16
+ TensorProperties,
17
+ )
18
+
19
+
20
+ __all__ = [
21
+ "WriteItemType",
22
+ "LoadItemType",
23
+ "TensorWriteData",
24
+ "WriteItem",
25
+ "ReadItem",
26
+ "SavePlan",
27
+ "LoadPlan",
28
+ "SavePlanner",
29
+ "LoadPlanner",
30
+ ]
31
+
32
+
33
+ class WriteItemType(Enum):
34
+ TENSOR = auto()
35
+ SHARD = auto()
36
+ BYTE_IO = auto()
37
+
38
+
39
+ class LoadItemType(Enum):
40
+ TENSOR = auto()
41
+ BYTE_IO = auto()
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class TensorWriteData:
46
+ chunk: ChunkStorageMetadata
47
+ properties: TensorProperties
48
+ size: torch.Size
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class WriteItem:
53
+ """Dataclass which holds information about what needs to be written to storage."""
54
+
55
+ index: MetadataIndex
56
+ type: WriteItemType
57
+
58
+ # Value present if it's a tensor write
59
+ tensor_data: Optional[TensorWriteData] = None
60
+
61
+ def tensor_storage_size(self) -> Optional[int]:
62
+ """
63
+ Calculates the storage size of the underlying tensor, or None if this is not a tensor write.
64
+
65
+ Returns:
66
+ Optional[int] storage size, in bytes of underlying tensor if any.
67
+ """
68
+ if self.tensor_data is None:
69
+ return None
70
+
71
+ numels = reduce(operator.mul, self.tensor_data.size, 1)
72
+ dtype_size = torch._utils._element_size(self.tensor_data.properties.dtype)
73
+ return numels * dtype_size
74
+
75
+
76
+ @dataclass(frozen=True)
77
+ class ReadItem:
78
+ # Read Item
79
+ type: LoadItemType
80
+
81
+ # Index into the state_dict
82
+ dest_index: MetadataIndex
83
+ # Offsets into destination tensor
84
+ dest_offsets: torch.Size
85
+
86
+ # Index into the checkpoint
87
+ storage_index: MetadataIndex
88
+ # Offset into the checkpoint data
89
+ storage_offsets: torch.Size
90
+
91
+ # Size of the hypercube to copy
92
+ lengths: torch.Size
93
+
94
+
95
+ @dataclass(frozen=True)
96
+ class SavePlan:
97
+ items: List[WriteItem]
98
+ storage_data: Any = None
99
+ planner_data: Any = None
100
+
101
+
102
+ @dataclass
103
+ class LoadPlan:
104
+ items: List[ReadItem]
105
+ storage_data: Any = None
106
+ planner_data: Any = None
107
+
108
+
109
+ class SavePlanner(abc.ABC):
110
+ """
111
+ Abstract class defining the protocol used by save_state_dict to plan the save process.
112
+
113
+ SavePlanners are stateful objects that can be used to customize the whole save process.
114
+
115
+ SavePlanner acts as an access proxy to the state_dict, so any transformation done to it
116
+ will be visible to the whole process.
117
+
118
+ A planner subclass can expect the following sequence of calls during save_state_dict:
119
+
120
+ 1) set_up_planner - called on all ranks.
121
+ Signals the start of a checkpoint save.
122
+
123
+ 2) create_local_plan - called on all ranks.
124
+ Process the state_dict and produces a `SavePlan` that will be sent for global planning.
125
+
126
+ 3) create_global_plan - called on the coordinator rank only.
127
+ Takes the SavePlan from all ranks and make any global decision.
128
+
129
+ 4) finish_plan - called on all ranks.
130
+ This gives each rank a chance to adjust to global planning decisions.
131
+
132
+ 5) resolve_data - called multiple times on each rank
133
+ Lookups a value on the `state_dict` for the storage layer to write.
134
+
135
+ Users are recommended to extend DefaultSavePlanner instead of this interface directly as
136
+ most changes can be expressed by changes in a single method.
137
+
138
+ There are 3 usual patterns of extension:
139
+
140
+ Rewriting state_dict. This is the simplest way to extend the save process as it
141
+ doesn't requite understanding the intrincacies of how SavePlan works:
142
+
143
+ >>> # xdoctest: +SKIP("undefined vars")
144
+ >>> class RenamePlanner(DefaultSavePlanner):
145
+ >>> def set_up_planner(
146
+ >>> self,
147
+ >>> state_dict: STATE_DICT_TYPE,
148
+ >>> storage_meta: Optional[StorageMeta],
149
+ >>> is_coordinator: bool,
150
+ >>> ) -> None:
151
+ >>> # prefix all keys with `foo_``
152
+ >>> super().set_up_planner({"foo_" + k: v for k, v in state_dict.items()}, storage_meta, is_coordinator)
153
+
154
+ Modifying local plan and lookup in tandem. This is useful when fine control of how data is persisted
155
+
156
+ >>> # xdoctest: +SKIP("undefined vars")
157
+ >>> class FP16Planner(DefaultSavePlanner):
158
+ >>> def create_local_plan(self):
159
+ >>> plan = super().create_local_plan()
160
+ >>> for p in plan:
161
+ >>> if p.tensor_data is not None:
162
+ >>> p.tensor_data.properties.dtype = torch.float16
163
+ >>> return plan
164
+ >>>
165
+ >>> def resolve_data(self, write_item):
166
+ >>> item = super().resolve_data(write_item)
167
+ >>> return item if write_item.type == WriteItemType.BYTE_IO else item.to(torch.float16)
168
+
169
+ Using the global planning step to make central decisions that can't be made individually by each rank
170
+
171
+ >>> # xdoctest: +SKIP("undefined vars")
172
+ >>> from itertools import zip_longest
173
+ >>> from dataclasses import replace
174
+ >>> class DDPLoadBalancingPlanner(DefaultSavePlanner):
175
+ >>> # This uses the default local plan behavior of having all non-sharded writes in rank 0
176
+ >>> # This sample doesn't handle ShardedTensors
177
+ >>> def create_global_plan(self, all_plans):
178
+ >>> iters = [iter(all_plans[0].items)] * len(all_plans)
179
+ >>> items_per_rank = [
180
+ >>> [item for item in items if item is not None]
181
+ >>> for items in zip(*zip_longest(*iters), strict=True)
182
+ >>> ]
183
+ >>> all_plans = [
184
+ >>> replace(plan, items=items)
185
+ >>> for plan, items in zip(all_plans, items_per_rank, strict=True)
186
+ >>> ]
187
+ >>> return super().create_global_plan(all_plans)
188
+
189
+ Finally, some planners need to save additional metadata in the checkpoint, this is
190
+ accomplished by having each rank contribute their data items in the local plan and
191
+ the global planner aggregate them:
192
+
193
+ >>> # xdoctest: +SKIP("undefined vars")
194
+ >>> class SaveExtraDataPlanner(DefaultSavePlanner):
195
+ >>> def create_local_plan(self) -> SavePlan:
196
+ >>> plan = super().create_local_plan()
197
+ >>> return replace(plan, planner_data="per-rank-data")
198
+ >>>
199
+ >>> def create_global_plan(self, all_plans: List[SavePlan]) -> Tuple[List[SavePlan], Metadata]:
200
+ >>> global_plan, metadata = super().create_global_plan(all_plans)
201
+ >>> merged_data = [p.planner_data for p in global_plan]
202
+ >>> metadata = replace(metadata, planner_data=merged_data)
203
+ >>> return global_plan, metadata
204
+ """
205
+
206
+ @abc.abstractmethod
207
+ def set_up_planner(
208
+ self,
209
+ state_dict: STATE_DICT_TYPE,
210
+ storage_meta: Optional[StorageMeta] = None,
211
+ is_coordinator: bool = False,
212
+ ) -> None:
213
+ """
214
+ Initialize this planner to save ``state_dict``.
215
+
216
+ Implementations should save those values as they won't be provided lated in the save process.
217
+
218
+ This is called on all ranks.
219
+ """
220
+
221
+ @abc.abstractmethod
222
+ def create_local_plan(self) -> SavePlan:
223
+ """
224
+ Compute the save plan for the current rank.
225
+
226
+ This will be aggregated and passed to create_global_plan.
227
+ Planner specific data can be passed through SavePlan::planner_data.
228
+
229
+ This is called on all ranks.
230
+ """
231
+
232
+ @abc.abstractmethod
233
+ def create_global_plan(
234
+ self, all_plans: List[SavePlan]
235
+ ) -> Tuple[List[SavePlan], Metadata]:
236
+ """
237
+ Compute the global checkpoint plan and return the local plan of each rank.
238
+
239
+ This is called on the coordinator rank only.
240
+ """
241
+
242
+ @abc.abstractmethod
243
+ def finish_plan(self, new_plan: SavePlan) -> SavePlan:
244
+ """
245
+ Merge the plan created by `create_local_plan` and the result of `create_global_plan`.
246
+
247
+ This is called on all ranks.
248
+ """
249
+
250
+ @abc.abstractmethod
251
+ def resolve_data(self, write_item: WriteItem) -> Union[torch.Tensor, io.BytesIO]:
252
+ """
253
+ Transform and prepare ``write_item`` from ``state_dict`` for storage, ensuring idempotency and thread-safety.
254
+
255
+ Lookup the object associated with ``write_item`` in ``state_dict`` and apply any
256
+ transformation (such as serialization) prior to the storage layer consuming it.
257
+
258
+ Called on each rank multiple times, at least once per WriteItem in the final SavePlan.
259
+
260
+ This method should be idempotent and thread-save. StorageWriter implementations
261
+ are free to call it as frequently as they need.
262
+
263
+ Any transformation that allocates memory should be lazily done when his method
264
+ is called in order to reduce peak memory required by checkpointing.
265
+
266
+ When returning tensors, they can be on any device or format, they can be views too.
267
+ It's the storage layer responsibility to figure out how to save them.
268
+ """
269
+
270
+
271
+ class LoadPlanner:
272
+ """
273
+ Abstract class defining the protocol used by load_state_dict to plan the load process.
274
+
275
+ LoadPlanner are stateful objects that can be used to customize the whole load process.
276
+
277
+ LoadPlanner acts as an access proxy to the state_dict, so any transformation done to it
278
+ will be visible to the whole process.
279
+
280
+ A planner subclass can expect the following sequence of calls during load_state_dict:
281
+
282
+ 1) set_up_planner - called on all ranks.
283
+ Signals the start of loading a checkpoint.
284
+
285
+ 2) create_local_plan - called on all ranks.
286
+ Process the state_dict and produces a `LoadPlan` that will be sent for global planning.
287
+
288
+ 3) create_global_plan - called on the coordinator rank only.
289
+ Takes the LoadPlan from all ranks and make any global decision.
290
+
291
+ 4) load_bytes - called multiple times on each rank
292
+ This is called once per non-tensor value in state_dict.
293
+
294
+ 5) resolve_tensor and commit_tensor - called multiple times on each rank
295
+ They are called in pair for each Tensor value in state_dict.
296
+
297
+ Users are recommended to extend DefaultLoadPlanner instead of this interface directly as
298
+ most changes can be expressed by changes in a single method.
299
+
300
+ There are two usual patterns of extension:
301
+
302
+ Rewriting state_dict. This is the simplest way to extend the load process as it
303
+ doesn't requite understanding the intrincacies of how LoadPlan works. We need
304
+ to keep a reference to the original state_dict as load happens in place so
305
+ we need to be able to perform it in place
306
+
307
+ >>> # xdoctest: +SKIP("undefined vars")
308
+ >>> class RenamePlanner(DefaultLoadPlanner):
309
+ >>> def set_up_planner(
310
+ >>> self,
311
+ >>> state_dict: STATE_DICT_TYPE,
312
+ >>> metadata: Metadata,
313
+ >>> is_coordinator: bool,
314
+ >>> ) -> None:
315
+ >>> self.original_state_dict = state_dict
316
+ >>> state_dict = {"foo_" + k: v for k, v in state_dict.items()}
317
+ >>>
318
+ >>> if self.flatten_sharded_tensors:
319
+ >>> state_dict = _flatten_sharded_tensors(state_dict)
320
+ >>>
321
+ >>> if self.flatten_state_dict:
322
+ >>> state_dict, self.mappings = flatten_state_dict(state_dict)
323
+ >>>
324
+ >>> self.state_dict = state_dict
325
+ >>> self.metadata = metadata
326
+ >>> self.is_coordinator = is_coordinator
327
+ >>>
328
+ >>> def load_bytes(self, read_item, value):
329
+ >>> # Remove the "foo_" prefix
330
+ >>> self.original_state_dict[read_item.dest_index.fqn[4:]] = torch.load(value, weights_only=False)
331
+
332
+
333
+ Modifying resolve_tensor and commit_tensor to handle load time transformation.
334
+
335
+ >>> # xdoctest: +SKIP("undefined vars")
336
+ >>> class MetaModelMaterialize(DefaultSavePlanner):
337
+ >>> def resolve_tensor(self, read_item):
338
+ >>> tensor = super().resolve_tensor(read_item)
339
+ >>> return torch.empty_like(tensor, device="cpu")
340
+ >>>
341
+ >>> def commit_tensor(self, read_item, tensor):
342
+ >>> self.state_dict[read_item.dest_index.fqn] = tensor
343
+ """
344
+
345
+ @abc.abstractmethod
346
+ def set_up_planner(
347
+ self,
348
+ state_dict: STATE_DICT_TYPE,
349
+ metadata: Optional[Metadata] = None,
350
+ is_coordinator: bool = False,
351
+ ) -> None:
352
+ """
353
+ Initialize this instance to load data into ``state_dict``.
354
+
355
+ . N.B. This is called on every rank.
356
+ """
357
+
358
+ @abc.abstractmethod
359
+ def create_local_plan(self) -> LoadPlan:
360
+ """
361
+ Create a LoadPlan based on state_dict and metadata provided by set_up_planner.
362
+
363
+ . N.B. This is called on every rank.
364
+ """
365
+
366
+ @abc.abstractmethod
367
+ def create_global_plan(self, global_plan: List[LoadPlan]) -> List[LoadPlan]:
368
+ """
369
+ Compute the global load plan and return plans for each rank.
370
+
371
+ . N.B. This is called on the coordinator rank only
372
+ """
373
+
374
+ @abc.abstractmethod
375
+ def finish_plan(self, central_plan: LoadPlan) -> LoadPlan:
376
+ """Accept the plan from coordinator and return final LoadPlan."""
377
+
378
+ @abc.abstractmethod
379
+ def load_bytes(self, read_item: ReadItem, value: io.BytesIO) -> None:
380
+ """
381
+ Load the item described by ``read_item``and ``value``.
382
+
383
+ This method is expected to modify in-place the underlying state_dict.
384
+
385
+ The contents of ``value`` are defined by the SavePlanner used to produce
386
+ the checkpoint being loaded.
387
+ """
388
+
389
+ def resolve_bytes(self, read_item: ReadItem) -> io.BytesIO:
390
+ """
391
+ Return the BytesIO to be used by the StorageReader to load `read_item`.
392
+
393
+ The BytesIO should alias with one on the underlying state_dict as StorageReader will replace its contents.
394
+ """
395
+ raise NotImplementedError("LoadPlanner.resolve_bytes is not implemented")
396
+
397
+ @abc.abstractmethod
398
+ def resolve_tensor(self, read_item: ReadItem) -> torch.Tensor:
399
+ """
400
+ Return the tensor described by ``read_item`` to be used by the StorageReader to load `read_item`.
401
+
402
+ The tensor should alias with one on the underlying state_dict as StorageReader will replace its contents.
403
+ If, for any reason, that's not possible, the planner can use the ``commit_tensor`` method to copy the data
404
+ back to the one in state_dict.
405
+ """
406
+
407
+ @abc.abstractmethod
408
+ def commit_tensor(self, read_item: ReadItem, tensor: torch.Tensor) -> None:
409
+ """
410
+ Call once the StorageReader finished loading data into ``tensor``.
411
+
412
+ The provided tensor is the same one returned by the call to ``resolve_tensor``.
413
+ This method is only needed if this LoadPlanner needs to post process ``tensor`` prior to
414
+ copying it back to the one in the state_dict.
415
+
416
+ The contents of tensor will follow its device synchronization model.
417
+ """
vllm/lib/python3.10/site-packages/torch/distributed/checkpoint/state_dict.py ADDED
@@ -0,0 +1,1422 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import contextlib
3
+ import functools
4
+ import gc
5
+ import warnings
6
+ from dataclasses import asdict, dataclass, field
7
+ from itertools import chain
8
+ from typing import (
9
+ Any,
10
+ Callable,
11
+ cast,
12
+ Dict,
13
+ Generator,
14
+ Iterable,
15
+ List,
16
+ no_type_check,
17
+ Optional,
18
+ Set,
19
+ Tuple,
20
+ Union,
21
+ )
22
+
23
+ import torch
24
+ import torch.distributed as dist
25
+ import torch.nn as nn
26
+ from torch.distributed._shard.sharded_tensor import ShardedTensor
27
+ from torch.distributed._state_dict_utils import (
28
+ _broadcast_state_dict,
29
+ _distribute_state_dict,
30
+ _flatten_state_dict,
31
+ _gather_state_dict,
32
+ _offload_state_dict_to_cpu,
33
+ _unflatten_state_dict,
34
+ )
35
+ from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import (
36
+ _CHECKPOINT_PREFIX,
37
+ )
38
+ from torch.distributed.fsdp import (
39
+ FullOptimStateDictConfig,
40
+ FullStateDictConfig,
41
+ FullyShardedDataParallel as FSDP,
42
+ OptimStateDictConfig,
43
+ ShardedOptimStateDictConfig,
44
+ ShardedStateDictConfig,
45
+ StateDictConfig,
46
+ StateDictType,
47
+ )
48
+ from torch.distributed.fsdp._common_utils import (
49
+ _get_module_fsdp_state_if_fully_sharded_module,
50
+ FSDP_WRAPPED_MODULE,
51
+ )
52
+ from torch.distributed.tensor import DTensor
53
+ from torch.nn.modules.module import _IncompatibleKeys
54
+ from torch.nn.parallel import DistributedDataParallel as DDP
55
+ from torch.utils._pytree import tree_map_only
56
+
57
+
58
+ __all__ = [
59
+ "FQNS_T",
60
+ "PrimitiveType",
61
+ "ValueType",
62
+ "DictValueType",
63
+ "ListDictValueType",
64
+ "OptimizerStateType",
65
+ "StateDictOptions",
66
+ "get_model_state_dict",
67
+ "get_optimizer_state_dict",
68
+ "get_state_dict",
69
+ "set_model_state_dict",
70
+ "set_optimizer_state_dict",
71
+ "set_state_dict",
72
+ ]
73
+
74
+
75
+ _FLAT_PARAM = "_flat_param"
76
+ _PG = "param_groups"
77
+ _PARAMS = "params"
78
+ _STATE = "state"
79
+
80
+ FQNS_T = Set[str]
81
+ PrimitiveType = Union[DTensor, ShardedTensor, torch.Tensor, int, float, str]
82
+ ValueType = Union[
83
+ PrimitiveType, List[PrimitiveType], Tuple[PrimitiveType], Dict[str, "ValueType"]
84
+ ]
85
+ DictValueType = Dict[str, ValueType]
86
+ ListDictValueType = List[DictValueType]
87
+ OptimizerStateType = Dict[str, Union[DictValueType, ListDictValueType]]
88
+
89
+
90
+ _patched_state_dict: Set[Callable] = set()
91
+
92
+
93
+ @contextlib.contextmanager
94
+ def _gc_context():
95
+ is_enabled = gc.isenabled()
96
+ gc.disable()
97
+ try:
98
+ yield
99
+ finally:
100
+ if is_enabled:
101
+ gc.enable()
102
+
103
+
104
+ @dataclass
105
+ class StateDictOptions:
106
+ """
107
+ This dataclass specifies how get_state_dict/set_state_dict will work.
108
+
109
+ - ``full_state_dict``: if this is set to True, all the tensors in the
110
+ returned state_dict will be gathered. No ShardedTensor and DTensor
111
+ will be in the returned state_dict.
112
+
113
+ - ``cpu_offload``: offload all the tensors to cpu. To prevent CPU OOM, if
114
+ ``full_state_dict`` is also true, then only the rank0 will get the
115
+ state_dict and all other ranks will get empty state_dict.
116
+
117
+ - ``ignore_frozen_params``: if the value is True, the returned state_dict
118
+ won't contain any frozen parameters -- the ``requires_grad`` is False.
119
+ The default value is False.
120
+
121
+ - ``keep_submodule_prefixes`` (deprecated): when ``submodules`` is not None, this option
122
+ indicates whether to keep the submodule prefixes from the state_dict keys.
123
+ or example, if the submodule is ``module.pretrain`` and the full FQN of
124
+ the parameter is ``pretrain.layer1.weight`` of the param. When this option
125
+ is True, the parameter's key in the returned state_dict will be
126
+ ``pretrain.layer1.weight``. If the options is False, the key will be
127
+ ``layer1.weight``.
128
+ Note that if ``keep_submodule_prefixes`` is False, there may be conflicted
129
+ FQNs, hence there should be only one submodule in ``submodules``.
130
+
131
+ - ``strict``: the ``strict`` option when ``set_state_dict`` calls
132
+ model.load_state_dict().
133
+
134
+ - ``broadcast_from_rank0``: when the option is True, rank0 should receive a
135
+ full state_dict and will broadcast the tensors in the state_dict/
136
+ optim_state_dict one by one to other ranks. Other ranks will receive
137
+ the tensors and shard according to the local shards in the model and
138
+ optimizer. ``full_state_dict`` must be set to True when using this option.
139
+ This option currently only supports DTensor, not the legacy ShardedTensor.
140
+ """
141
+
142
+ full_state_dict: bool = False
143
+ cpu_offload: bool = False
144
+ ignore_frozen_params: bool = False
145
+ keep_submodule_prefixes: bool = True
146
+ strict: bool = True
147
+ broadcast_from_rank0: bool = False
148
+ flatten_optimizer_state_dict: bool = False
149
+
150
+
151
+ @dataclass
152
+ class _StateDictInfo(StateDictOptions):
153
+ fqn_param_mapping: Dict[
154
+ Union[str, torch.Tensor], Union[FQNS_T, torch.Tensor]
155
+ ] = field(default_factory=dict)
156
+ shared_params_mapping: Dict[
157
+ Union[str, torch.Tensor], Union[FQNS_T, torch.Tensor]
158
+ ] = field(default_factory=dict)
159
+ submodule_prefixes: Set[str] = field(default_factory=set)
160
+ handle_model: bool = True
161
+ handle_optim: bool = True
162
+ fsdp_context: Callable = contextlib.nullcontext
163
+ fsdp_modules: List[nn.Module] = field(default_factory=list)
164
+
165
+
166
+ @functools.lru_cache(maxsize=None)
167
+ def _get_fqns(
168
+ model: nn.Module,
169
+ name: str,
170
+ skip_ddp_prefix: bool = True,
171
+ skip_compiler_prefix: bool = True,
172
+ ) -> FQNS_T:
173
+ """
174
+ This API is used to convert the name of a parameter to the FQNs. For FSDP
175
+ without `use_orig_params`, the name of FlatParameter can be mapped to
176
+ multiple original parameters. As a result, the return type of this function
177
+ is `Set[str]`.
178
+
179
+ Args:
180
+ module (nn.Module): the root model.
181
+ name (str): the name
182
+ skip_ddp_prefix (bool): whether to skip DDP's `module` prefix
183
+
184
+ Returns:
185
+ The canonical FQNs based on the model traversal.
186
+ """
187
+
188
+ # Remove the checkpoint prefix, if it exists.
189
+ name = name.replace(_CHECKPOINT_PREFIX, "")
190
+ if "." not in name:
191
+ return {name}
192
+
193
+ obj_names = name.split(".")
194
+ fqn_obj_names = []
195
+ curr_obj = model
196
+ for i, curr_obj_name in enumerate(obj_names):
197
+ if isinstance(curr_obj, DDP):
198
+ assert curr_obj_name == "module"
199
+ curr_obj = curr_obj.module
200
+ if not skip_ddp_prefix:
201
+ fqn_obj_names.append(curr_obj_name)
202
+ elif isinstance(curr_obj, FSDP):
203
+ if i < len(obj_names) - 1 and obj_names[i + 1] == _FLAT_PARAM:
204
+ prefix = ".".join(fqn_obj_names)
205
+ flat_param = getattr(curr_obj, _FLAT_PARAM)
206
+ if prefix:
207
+ prefix = f"{prefix}."
208
+ return {f"{prefix}{fqn}" for fqn in flat_param._fqns}
209
+ curr_obj = getattr(curr_obj, FSDP_WRAPPED_MODULE)
210
+ if curr_obj_name != FSDP_WRAPPED_MODULE:
211
+ fqn_obj_names.append(curr_obj_name)
212
+ curr_obj = getattr(curr_obj, curr_obj_name)
213
+ elif isinstance(curr_obj, torch._dynamo.eval_frame.OptimizedModule):
214
+ assert curr_obj_name == "_orig_mod"
215
+ curr_obj = curr_obj._orig_mod
216
+ if not skip_compiler_prefix:
217
+ fqn_obj_names.append(curr_obj_name)
218
+ else:
219
+ fqn_obj_names.append(curr_obj_name)
220
+ if curr_obj_name == nn.modules.module._EXTRA_STATE_KEY_SUFFIX:
221
+ if i != len(obj_names) - 1:
222
+ raise RuntimeError("Expect `_extra_state` to be the last obj name")
223
+ else:
224
+ curr_obj = getattr(curr_obj, curr_obj_name)
225
+
226
+ return {".".join(fqn_obj_names).replace(_CHECKPOINT_PREFIX, "")}
227
+
228
+
229
+ class _EXTRA_STATE:
230
+ pass
231
+
232
+
233
+ def _iterate_valid_model_state(model):
234
+ visited_modules: Set[nn.Module] = set()
235
+
236
+ def recurse(module: nn.Module, curr_fqn: str) -> Generator:
237
+ visited_modules.add(module)
238
+
239
+ curr_fqn = f"{curr_fqn}." if curr_fqn else ""
240
+ for name, submodule in module.named_children():
241
+ if submodule in visited_modules:
242
+ continue
243
+ new_fqn = f"{curr_fqn}{name}"
244
+ yield from recurse(submodule, new_fqn)
245
+
246
+ for name, obj in chain(
247
+ module.named_buffers(recurse=False), module.named_parameters(recurse=False)
248
+ ):
249
+ if name in module._non_persistent_buffers_set:
250
+ continue
251
+ new_fqn = f"{curr_fqn}{name}"
252
+ yield new_fqn, obj
253
+
254
+ if (
255
+ getattr(module.__class__, "get_extra_state", nn.Module.get_extra_state)
256
+ != nn.Module.get_extra_state
257
+ ):
258
+ new_fqn = f"{curr_fqn}{nn.modules.module._EXTRA_STATE_KEY_SUFFIX}"
259
+ yield new_fqn, _EXTRA_STATE()
260
+
261
+ yield from recurse(model, "")
262
+
263
+
264
+ def _verify_options(
265
+ model: nn.Module,
266
+ optims: Tuple[torch.optim.Optimizer, ...],
267
+ optim_only: bool,
268
+ *,
269
+ submodules: Optional[Set[nn.Module]] = None,
270
+ options: Optional[StateDictOptions] = None,
271
+ ) -> _StateDictInfo:
272
+ """
273
+ Verify the model and options passed by the user and generates _StateDictInfo.
274
+ """
275
+ if submodules:
276
+ warnings.warn(
277
+ "Getting submodules only model/optim state_dict is deprecated and "
278
+ "will be removed in 2.5. This feature can be achieved by manually "
279
+ "filtering out the state_dict returned from get_state_dict.",
280
+ FutureWarning,
281
+ )
282
+ if optim_only and not optims:
283
+ raise RuntimeError(
284
+ "Optimizers are not passed in but optim_only is set to True."
285
+ )
286
+
287
+ options = options or StateDictOptions()
288
+
289
+ fqn_param_mapping: Dict[
290
+ Union[str, torch.Tensor], Union[Set[str], torch.Tensor]
291
+ ] = {}
292
+ shared_params_mapping: Dict[
293
+ Union[str, torch.Tensor], Union[Set[str], torch.Tensor]
294
+ ] = {}
295
+ for name, param in _iterate_valid_model_state(model):
296
+ if isinstance(param, _EXTRA_STATE):
297
+ continue
298
+
299
+ fqns = _get_fqns(model, name)
300
+ fqn = fqn_param_mapping.get(param, None)
301
+ if fqn is not None:
302
+ cast(Set[str], fqn_param_mapping[param]).update(fqns)
303
+ shared_params_mapping[param] = fqn_param_mapping[param]
304
+ else:
305
+ # We need to do copy as _get_fqns is lru_cached
306
+ fqn_param_mapping[param] = fqns.copy()
307
+ for fqn in fqns:
308
+ if not isinstance(param, _EXTRA_STATE):
309
+ fqn_param_mapping[fqn] = param
310
+
311
+ for param_, fqns_ in list(shared_params_mapping.items()):
312
+ for fqn in fqns_:
313
+ shared_params_mapping[fqn] = cast(torch.Tensor, param_)
314
+
315
+ submodule_prefixes: Set[str] = set()
316
+ if submodules:
317
+ submodules = set(submodules)
318
+ for name, module in model.named_modules():
319
+ if module not in submodules:
320
+ continue
321
+ fqns = _get_fqns(model, name)
322
+ assert len(fqns) == 1, "Submodule FQN should only have 1 instance"
323
+ submodule_prefixes.update(f"{fqn}." for fqn in fqns)
324
+
325
+ if options.broadcast_from_rank0 and not options.full_state_dict:
326
+ raise ValueError(
327
+ "full_state_dict must be True when broadcast_from_rank0 is True."
328
+ )
329
+ fsdp_modules = FSDP.fsdp_modules(model)
330
+ state_dict_config: StateDictConfig
331
+ optim_state_dict_config: OptimStateDictConfig
332
+ fsdp_context: Callable
333
+ if fsdp_modules:
334
+ # FSDP API only work if at least one FSDP instance exists.
335
+ if options.full_state_dict:
336
+ state_dict_config = FullStateDictConfig(
337
+ offload_to_cpu=options.cpu_offload, rank0_only=options.cpu_offload
338
+ )
339
+ optim_state_dict_config = FullOptimStateDictConfig(
340
+ offload_to_cpu=options.cpu_offload,
341
+ rank0_only=(options.cpu_offload or options.broadcast_from_rank0),
342
+ )
343
+ state_dict_type = StateDictType.FULL_STATE_DICT
344
+ else:
345
+ state_dict_config = ShardedStateDictConfig(
346
+ offload_to_cpu=options.cpu_offload,
347
+ )
348
+ optim_state_dict_config = ShardedOptimStateDictConfig(
349
+ offload_to_cpu=options.cpu_offload,
350
+ )
351
+ state_dict_type = StateDictType.SHARDED_STATE_DICT
352
+
353
+ @contextlib.contextmanager
354
+ def fsdp_state_dict_type_without_warning(
355
+ module,
356
+ state_dict_type,
357
+ state_dict_config,
358
+ optim_state_dict_config,
359
+ ):
360
+ with warnings.catch_warnings():
361
+ warnings.filterwarnings(
362
+ "ignore", message="FSDP.state_dict_type", category=FutureWarning
363
+ )
364
+ with FSDP.state_dict_type(
365
+ module=module,
366
+ state_dict_type=state_dict_type,
367
+ state_dict_config=state_dict_config,
368
+ optim_state_dict_config=optim_state_dict_config,
369
+ ):
370
+ yield
371
+
372
+ fsdp_context = functools.partial(
373
+ fsdp_state_dict_type_without_warning,
374
+ module=model,
375
+ state_dict_type=state_dict_type,
376
+ state_dict_config=state_dict_config,
377
+ optim_state_dict_config=optim_state_dict_config,
378
+ )
379
+ else:
380
+ fsdp_context = contextlib.nullcontext
381
+
382
+ return _StateDictInfo(
383
+ **asdict(options),
384
+ fqn_param_mapping=fqn_param_mapping,
385
+ shared_params_mapping=shared_params_mapping,
386
+ submodule_prefixes=submodule_prefixes,
387
+ fsdp_context=fsdp_context,
388
+ fsdp_modules=cast(List[nn.Module], fsdp_modules),
389
+ handle_model=not optim_only,
390
+ handle_optim=(len(optims) > 0),
391
+ )
392
+
393
+
394
+ def _verify_state_dict(
395
+ model_state_dict: Dict[str, ValueType],
396
+ optim_state_dict: OptimizerStateType,
397
+ info: _StateDictInfo,
398
+ ) -> None:
399
+ for module in info.fsdp_modules:
400
+ fsdp_state = _get_module_fsdp_state_if_fully_sharded_module(module)
401
+ assert fsdp_state is not None, "Expected a fsdp_state with a fsdp module."
402
+
403
+ # Verify if the model_state_dict and optim_state_dict are valid. This API
404
+ # should give the users an explicit error message to debug or report.
405
+ if (
406
+ info.handle_model
407
+ and not model_state_dict
408
+ and not info.submodule_prefixes
409
+ and not info.ignore_frozen_params
410
+ and not (info.cpu_offload and info.full_state_dict)
411
+ and info.strict
412
+ and not info.broadcast_from_rank0
413
+ ):
414
+ raise RuntimeError(
415
+ "The option indicates that model state_dict is required to save "
416
+ "or load, but model state_dict is empty."
417
+ f"rank = {dist.get_rank()=}."
418
+ )
419
+
420
+ if info.handle_optim:
421
+ if (
422
+ not optim_state_dict
423
+ and not (info.cpu_offload and info.full_state_dict)
424
+ and (not info.broadcast_from_rank0)
425
+ ):
426
+ raise RuntimeError(
427
+ "The option indicates that model state_dict is required to save, "
428
+ f"or load but optim state_dict is empty. {optim_state_dict}"
429
+ )
430
+
431
+ for key in model_state_dict.keys():
432
+ if _FLAT_PARAM in key:
433
+ raise RuntimeError(
434
+ f"{key} contains {_FLAT_PARAM}. This can happen if the model "
435
+ "is not the root module."
436
+ )
437
+
438
+
439
+ def _state_dict_fn(obj: Union[nn.Module, torch.optim.Optimizer], api: str) -> Callable:
440
+ call = getattr(obj, api)
441
+ if call in _patched_state_dict:
442
+ call = functools.partial(getattr(obj.__class__, api), self=obj)
443
+ return call
444
+
445
+
446
+ def _maybe_full_or_cpu_state_dict(
447
+ state_dict: Dict[str, Any], info: _StateDictInfo
448
+ ) -> Dict[str, Any]:
449
+ if info.full_state_dict:
450
+ ranks_only = (
451
+ ()
452
+ if (not info.cpu_offload or not torch.distributed.is_initialized())
453
+ else (0,)
454
+ )
455
+ return _gather_state_dict(
456
+ state_dict, cpu_offload=info.cpu_offload, ranks_only=ranks_only
457
+ )
458
+ elif info.cpu_offload:
459
+ return _offload_state_dict_to_cpu(state_dict)
460
+ else:
461
+ return state_dict
462
+
463
+
464
+ @torch.no_grad()
465
+ def _get_model_state_dict(
466
+ model: nn.Module, info: _StateDictInfo
467
+ ) -> Dict[str, ValueType]:
468
+ if not info.handle_model:
469
+ return {}
470
+
471
+ with info.fsdp_context():
472
+ state_dict = _state_dict_fn(model, "state_dict")()
473
+
474
+ for key in list(state_dict.keys()):
475
+ fqns = _get_fqns(model, key)
476
+ assert len(fqns) == 1, (key, fqns)
477
+ fqn = next(iter(fqns))
478
+ if fqn != key:
479
+ # As we only support FSDP, DDP, and TP, the only cases are
480
+ # wrapper-based DDP and compiler. Verify if the assumption
481
+ # is correct.
482
+ def verify(key, fqn) -> bool:
483
+ if len(fqn) >= len(key):
484
+ return False
485
+ fqn_split = fqn.split(".")
486
+ key_split = key.split(".")
487
+ fqn_idx = 0
488
+ for key_idx, key_name in enumerate(key_split):
489
+ if key_name == fqn_split[fqn_idx]:
490
+ fqn_idx += 1
491
+ if fqn_idx == len(fqn_split):
492
+ return key_idx == len(key_split) - 1
493
+ elif key_name in ("module", "_orig_mod"):
494
+ continue
495
+ else:
496
+ return False
497
+ return True
498
+
499
+ if not verify(key, fqn):
500
+ raise RuntimeError(f"An unexpected key, {key}, exists. FQN is {fqn}")
501
+ state_dict[fqn] = state_dict.pop(key)
502
+
503
+ if info.submodule_prefixes:
504
+ new_state_dict: Dict[str, ValueType] = {}
505
+ # TODO: make this faster.
506
+ for fqn in state_dict.keys():
507
+ for prefix in info.submodule_prefixes:
508
+ if not fqn.startswith(prefix):
509
+ continue
510
+ if info.keep_submodule_prefixes:
511
+ new_state_dict[fqn] = state_dict[fqn]
512
+ else:
513
+ new_fqn = fqn[len(prefix) :]
514
+ new_state_dict[new_fqn] = state_dict[fqn]
515
+ state_dict = new_state_dict
516
+
517
+ if info.ignore_frozen_params:
518
+ for key, param in model.named_parameters():
519
+ if param.requires_grad:
520
+ continue
521
+ fqns = _get_fqns(model, key)
522
+ for fqn in fqns:
523
+ state_dict.pop(fqn)
524
+
525
+ for key, p in list(state_dict.items()):
526
+ if torch.is_tensor(p) and p.is_meta:
527
+ state_dict.pop(key)
528
+
529
+ return _maybe_full_or_cpu_state_dict(state_dict, info)
530
+
531
+
532
+ @torch.no_grad()
533
+ def _load_model_state_dict(
534
+ model: nn.Module,
535
+ state_dict: Dict[str, ValueType],
536
+ info: _StateDictInfo,
537
+ ) -> _IncompatibleKeys:
538
+ if not info.handle_model or (not state_dict and not info.broadcast_from_rank0):
539
+ return _IncompatibleKeys({}, {})
540
+
541
+ local_state_dict = {}
542
+ for key, value in _iterate_valid_model_state(model):
543
+ fqns = _get_fqns(model, key)
544
+ fqns_with_prefix = _get_fqns(
545
+ model, key, skip_ddp_prefix=False, skip_compiler_prefix=False
546
+ )
547
+
548
+ for fqn, fqn_with_prefix in zip(fqns, fqns_with_prefix):
549
+ if (
550
+ not info.broadcast_from_rank0 or dist.get_rank() == 0
551
+ ) and fqn != fqn_with_prefix:
552
+ state_dict[fqn_with_prefix] = state_dict.pop(fqn)
553
+ local_state_dict[fqn_with_prefix] = value
554
+
555
+ assign = False
556
+ if info.broadcast_from_rank0 or info.full_state_dict:
557
+ device = None
558
+ for key, value in local_state_dict.items():
559
+ if torch.is_tensor(value) and value.dim() > 0:
560
+ if device is None:
561
+ device = value.device
562
+ else:
563
+ assert device == value.device
564
+ assert device is not None
565
+ if device == torch.device("meta"):
566
+ device = dist.distributed_c10d._get_pg_default_device()
567
+ assign = True
568
+ if info.broadcast_from_rank0:
569
+ _broadcast_state_dict(
570
+ state_dict, local_state_dict, device=device, strict=info.strict
571
+ )
572
+ elif info.full_state_dict:
573
+ _distribute_state_dict(state_dict, local_state_dict, device=device)
574
+ for fqn, local_state in local_state_dict.items():
575
+ state_dict[fqn] = local_state
576
+
577
+ with info.fsdp_context():
578
+ return cast(
579
+ _IncompatibleKeys,
580
+ _state_dict_fn(model, "load_state_dict")(
581
+ state_dict=state_dict, strict=info.strict, assign=assign
582
+ ),
583
+ )
584
+
585
+
586
+ def _init_optim_state(optim: torch.optim.Optimizer) -> None:
587
+ """
588
+ Initialize optim states by calling the step() with zero grads.
589
+ """
590
+ if optim.state:
591
+ # The optimizer state is initialized.
592
+ return
593
+
594
+ # There are some stateless optimizers like SGD. These optimizer will
595
+ # not return in the above condition. So if gradients exist, we should also
596
+ # return. If gradients do not exist, the following initialization should
597
+ # not disturb SGD because the gradients and lr are both zero.
598
+ for param_group in optim.param_groups:
599
+ for param in param_group[_PARAMS]:
600
+ if param.grad is not None:
601
+ return
602
+
603
+ for param_group in optim.param_groups:
604
+ for param in param_group[_PARAMS]:
605
+ if param.requires_grad:
606
+ param.grad = torch.zeros_like(param)
607
+
608
+ # Some optimizers will update parameters regardless of grads due to lr, so
609
+ # make lr to zero when calling `step()`.
610
+ lrs = []
611
+ for param_group in optim.param_groups:
612
+ if "lr" in param_group:
613
+ lrs.append(param_group["lr"])
614
+ param_group["lr"] = 0.0
615
+ optim.step(closure=None)
616
+ # Whether to recover the "lr" should not matter too much as we will
617
+ # restore checkpointing later.
618
+ for param_group in optim.param_groups:
619
+ if "lr" in param_group:
620
+ param_group["lr"] = lrs.pop(0)
621
+ optim.zero_grad(set_to_none=True)
622
+
623
+
624
+ def _flatten_optim_state_dict(state_dict: OptimizerStateType) -> Dict[str, ValueType]:
625
+ """
626
+ This API flattens the optimizer state_dict to support optimizer resharding for
627
+ MPMD, e.g., pipeline parallelism.
628
+
629
+ Without the API, the original optimizer state_dict looks like:
630
+ {
631
+ "state": {
632
+ "layer1.weight": {
633
+ "step": 10, "exp_avg": SomeTensor, "exp_avg_sq": SomeTensor
634
+ },
635
+ "layer2.weight": {
636
+ "step": 10, "exp_avg": SomeTensor, "exp_avg_sq": SomeTensor
637
+ },
638
+ },
639
+ "param_group": [
640
+ {
641
+ "lr": 0.0,
642
+ "betas": (0.9, 0.95), ...,
643
+ "params": ["layer1.weight", "layer2.weight"]
644
+ }
645
+ ]
646
+ }
647
+
648
+ With this API, the optimizer state_dict looks like:
649
+ {
650
+ "state.layer1.weight.step": 10,
651
+ "state.layer2.weight.step": 10,
652
+ "state.layer1.weight.exp_avg": SomeTensor,
653
+ "state.layer2.weight.exp_avg": SomeTensor,
654
+ "state.layer1.weight.exp_avg_sq": SomeTensor,
655
+ "state.layer2.weight.exp_avg_sq": SomeTensor,
656
+ "param_group.layer1.weight.lr" : 0.1,
657
+ "param_group.layer2.weight.lr" : 0.1,
658
+ "param_group.layer1.weight.betas" : (0.9, 0.95),
659
+ "param_group.layer2.weight.betas" : (0.9, 0.95),
660
+ }
661
+
662
+ Note that if any of the value is a container, like the betas in the example,
663
+ this API won't flattent it.
664
+ """
665
+
666
+ def _raise_if_type_not_supported(v):
667
+ if not isinstance(v, (torch.Tensor, int, float)):
668
+ raise NotImplementedError(
669
+ "Flattening optimizer state_dict only supports "
670
+ "tensor, int, float states now. "
671
+ f"Type is {type(v)}."
672
+ )
673
+
674
+ ret: Dict[str, ValueType] = {}
675
+ for fqn, state in cast(DictValueType, state_dict[_STATE]).items():
676
+ for k, v in cast(DictValueType, state).items():
677
+ _raise_if_type_not_supported(v)
678
+ ret[f"{_STATE}.{fqn}.{k}"] = v
679
+
680
+ for param_group in cast(ListDictValueType, state_dict[_PG]):
681
+ fqns = param_group.pop(_PARAMS)
682
+ for fqn in cast(List[str], fqns):
683
+ for k, v in param_group.items():
684
+ ret[f"{_PG}.{fqn}.{k}"] = v
685
+ return ret
686
+
687
+
688
+ def _unflatten_optim_state_dict(
689
+ optim: torch.optim.Optimizer,
690
+ state_dict: Dict[str, ValueType],
691
+ info: _StateDictInfo,
692
+ ) -> OptimizerStateType:
693
+ """
694
+ This API unflattens the state_dict generated by _flatten_optim_state_dict().
695
+ See the docstring of _flatten_optim_state_dict() for more detail.
696
+ """
697
+ state: DictValueType = {}
698
+ pg_state: ListDictValueType = []
699
+ return_osd: OptimizerStateType = {_STATE: state, _PG: pg_state}
700
+
701
+ for param_group in optim.param_groups:
702
+ pg_state.append({_PARAMS: []})
703
+ for param in param_group[_PARAMS]:
704
+ for fqn in info.fqn_param_mapping[param]:
705
+ params = pg_state[-1][_PARAMS]
706
+ assert isinstance(params, list) # typing
707
+ params.append(fqn)
708
+ if not param.requires_grad:
709
+ continue
710
+ state[fqn] = {}
711
+ for state_name in optim.state[param].keys():
712
+ cast(DictValueType, state[fqn])[state_name] = state_dict[
713
+ f"{_STATE}.{fqn}.{state_name}"
714
+ ]
715
+
716
+ first_param_fqn = cast(List[str], pg_state[-1][_PARAMS])[0]
717
+ for k in param_group.keys():
718
+ if k == _PARAMS:
719
+ continue
720
+ value = state_dict[f"{_PG}.{first_param_fqn}.{k}"]
721
+ if k not in pg_state[-1]:
722
+ pg_state[-1][k] = value
723
+ elif pg_state[-1][k] != value:
724
+ raise RuntimeError(
725
+ "All the parameters in the same parameter group should have "
726
+ f"the same saved param_group value. But {first_param_fqn}.{k} "
727
+ f"is {value} while other(s) is {pg_state[-1][k]}."
728
+ )
729
+
730
+ return return_osd
731
+
732
+
733
+ @torch.no_grad()
734
+ def _get_optim_state_dict(
735
+ model: nn.Module,
736
+ optimizers: Tuple[torch.optim.Optimizer, ...],
737
+ info: _StateDictInfo,
738
+ ) -> OptimizerStateType:
739
+ if not info.handle_optim:
740
+ return {}
741
+
742
+ optim_state_dict: OptimizerStateType = {_STATE: {}, _PG: []}
743
+ for optim in optimizers:
744
+ _init_optim_state(optim)
745
+ osd = _state_dict_fn(optim, "state_dict")()
746
+ if info.fsdp_modules:
747
+ with info.fsdp_context():
748
+ osd = FSDP.optim_state_dict(model, optim, osd)
749
+
750
+ # We need to specially handle FlatParameter FSDP as
751
+ # FlatParameter FSDP converts the FQNs.
752
+ # There are no easy ways to do this conversion systematically.
753
+ # We can only use a string replacment without correctness check.
754
+ if not osd:
755
+ continue
756
+ for k in list(osd[_STATE].keys()):
757
+ if "_orig_mod" in k:
758
+ osd[_STATE][k.replace("_orig_mod.", "")] = osd[_STATE].pop(k)
759
+ for g in osd[_PG]:
760
+ params = [k.replace("_orig_mod.", "") for k in g[_PARAMS]]
761
+ g[_PARAMS] = params
762
+ else:
763
+ params = list(chain.from_iterable(g[_PARAMS] for g in optim.param_groups))
764
+ param_pid_mapping = dict(zip(params, range(len(params))))
765
+ fqn_pid_mapping = {}
766
+ for key, param in model.named_parameters():
767
+ fqns = _get_fqns(model, key)
768
+ assert len(fqns) == 1
769
+ fqn = next(iter(fqns))
770
+ if param not in param_pid_mapping:
771
+ continue
772
+ pid = param_pid_mapping[param]
773
+ fqn_pid_mapping[fqn] = pid
774
+ fqn_pid_mapping[pid] = fqn
775
+
776
+ for key in list(osd[_STATE].keys()):
777
+ fqn = fqn_pid_mapping[key]
778
+ osd[_STATE][fqn] = osd[_STATE].pop(key)
779
+
780
+ for group in osd[_PG]:
781
+ group[_PARAMS] = [fqn_pid_mapping[pid] for pid in group[_PARAMS]]
782
+
783
+ if not osd:
784
+ continue
785
+
786
+ cast(DictValueType, optim_state_dict[_STATE]).update(osd[_STATE])
787
+ cast(ListDictValueType, optim_state_dict[_PG]).extend(osd[_PG])
788
+
789
+ if info.flatten_optimizer_state_dict:
790
+ optim_state_dict = cast(
791
+ OptimizerStateType, _flatten_optim_state_dict(optim_state_dict)
792
+ )
793
+
794
+ return _maybe_full_or_cpu_state_dict(optim_state_dict, info)
795
+
796
+
797
+ def _split_optim_state_dict(
798
+ model: nn.Module,
799
+ optim: torch.optim.Optimizer,
800
+ optim_state_dict: OptimizerStateType,
801
+ info: _StateDictInfo,
802
+ ) -> OptimizerStateType:
803
+ """
804
+ Extract the corresponding optim state_dict from ``optim_state_dict`` for
805
+ ``optim`` and return the result optim state_dict.
806
+
807
+ Args:
808
+ model (nn.Module): the root model.
809
+ optim (torch.optim.Optimizer): the optimizer.
810
+ optim_state_dict (Dict[str, ValueType]): the superset optim state_dict that
811
+ contains the optim state_dict of ``optim``.
812
+ info (_StateDictInfo): state dict information.
813
+
814
+ Returns:
815
+ The optim state_dict of ``optim``.
816
+ """
817
+
818
+ state: DictValueType = {}
819
+ pg_state: ListDictValueType = []
820
+ return_osd: OptimizerStateType = {_STATE: state, _PG: pg_state}
821
+ pg_mapping: Dict[int, int] = {}
822
+
823
+ if all(
824
+ isinstance(k, int) for k in cast(DictValueType, optim_state_dict[_STATE]).keys()
825
+ ):
826
+ return optim_state_dict
827
+
828
+ for param_group in optim.param_groups:
829
+ pg_state.append({_PARAMS: []})
830
+ for param in param_group[_PARAMS]:
831
+ for fqn in info.fqn_param_mapping[param]:
832
+ if fqn in info.shared_params_mapping:
833
+ in_params = False
834
+ for loaded_param_group in cast(
835
+ ListDictValueType, optim_state_dict[_PG]
836
+ ):
837
+ if fqn in cast(List[str], loaded_param_group[_PARAMS]):
838
+ in_params = True
839
+ break
840
+ else:
841
+ in_params = True
842
+ if not in_params:
843
+ continue
844
+
845
+ params = pg_state[-1][_PARAMS]
846
+ assert isinstance(params, list)
847
+ params.append(fqn)
848
+ if param.requires_grad:
849
+ state[fqn] = cast(DictValueType, optim_state_dict[_STATE])[fqn]
850
+ for loaded_param_group in cast(
851
+ ListDictValueType, optim_state_dict[_PG]
852
+ ):
853
+ if fqn in cast(List[str], loaded_param_group[_PARAMS]):
854
+ pg_mapping[id(loaded_param_group)] = len(return_osd[_PG]) - 1
855
+
856
+ for param_group in cast(ListDictValueType, optim_state_dict[_PG]):
857
+ idx = pg_mapping.get(id(param_group), -1)
858
+ if idx == -1:
859
+ continue
860
+ for key, value in param_group.items():
861
+ if key == _PARAMS:
862
+ continue
863
+ # TODO: check if value is the same if exists.
864
+ pg_state[idx][key] = value
865
+
866
+ return return_osd
867
+
868
+
869
+ @torch.no_grad()
870
+ def _load_optim_state_dict(
871
+ model: nn.Module,
872
+ optimizers: Tuple[torch.optim.Optimizer, ...],
873
+ state_dict: OptimizerStateType,
874
+ info: _StateDictInfo,
875
+ ) -> None:
876
+ if not info.handle_optim:
877
+ return
878
+
879
+ for optim in optimizers:
880
+ _init_optim_state(optim)
881
+ if state_dict:
882
+ if _STATE in state_dict:
883
+ optim_state_dict = _split_optim_state_dict(
884
+ model, optim, state_dict, info
885
+ )
886
+ else:
887
+ optim_state_dict = _unflatten_optim_state_dict(
888
+ optim, cast(Dict[str, ValueType], state_dict), info
889
+ )
890
+ else:
891
+ optim_state_dict = {}
892
+ if info.fsdp_modules:
893
+ # We need to specially handle FlatParameter FSDP as
894
+ # FlatParameter FSDP converts the FQNs.
895
+ for original_fqn, _ in model.named_parameters():
896
+ fqns = _get_fqns(model, original_fqn)
897
+ fqns_with_compiler = _get_fqns(
898
+ model, original_fqn, skip_compiler_prefix=False
899
+ )
900
+ if fqns == fqns_with_compiler:
901
+ continue
902
+
903
+ assert len(fqns) == 1
904
+ fqn = fqns.pop()
905
+ fqn_with_compiler = fqns_with_compiler.pop()
906
+ for g in optim_state_dict[_PG]:
907
+ val = cast(Dict[str, Any], g)
908
+ params = [
909
+ key.replace(fqn, fqn_with_compiler) for key in val[_PARAMS]
910
+ ]
911
+ val[_PARAMS] = params
912
+ osd_state = cast(DictValueType, optim_state_dict[_STATE])
913
+ for k in list(osd_state.keys()):
914
+ if fqn in k:
915
+ osd_state[k.replace(fqn, fqn_with_compiler)] = osd_state.pop(k)
916
+
917
+ with info.fsdp_context():
918
+ optim_state_dict = FSDP.optim_state_dict_to_load(
919
+ model, optim, optim_state_dict
920
+ )
921
+ elif info.full_state_dict:
922
+ info.full_state_dict = False
923
+ local_state_dict = _get_optim_state_dict(model, (optim,), info)
924
+ info.full_state_dict = True
925
+ device = None
926
+
927
+ def _device(t):
928
+ if t.dim() > 0:
929
+ nonlocal device
930
+ if device is None:
931
+ device = t.device
932
+ elif device != t.device:
933
+ raise ValueError("Device mismatch")
934
+ return t
935
+
936
+ _ = tree_map_only(torch.Tensor, _device, local_state_dict)
937
+ assert device is not None
938
+ flatten_osd, osd_mapping = _flatten_state_dict(optim_state_dict)
939
+ flatten_local_osd, local_osd_mapping = _flatten_state_dict(local_state_dict)
940
+ if info.broadcast_from_rank0:
941
+ _broadcast_state_dict(flatten_osd, flatten_local_osd, device=device)
942
+ else:
943
+ _distribute_state_dict(flatten_osd, flatten_local_osd, device=device)
944
+ # The modifications listed seek to address the problem where optim might possess
945
+ # dissimilar parameters in comparison to optim_state_dict. This is achieved by
946
+ # incorporating differential parameters within local, which may result in optim
947
+ # having additional parameters ultimately.
948
+ for optim_key in flatten_osd.keys():
949
+ if optim_key not in flatten_local_osd:
950
+ assert optim_key in osd_mapping
951
+ flatten_local_osd[optim_key] = flatten_osd[optim_key]
952
+ local_osd_mapping[optim_key] = osd_mapping[optim_key]
953
+ optim_state_dict = _unflatten_state_dict(
954
+ flatten_local_osd, local_osd_mapping
955
+ )
956
+
957
+ # Note that we do not have to convert the FQN back to param id here if
958
+ # order in optim.param_groups[idx][_PARAMS] is the same as the one in
959
+ # optim_state_dict[_PG][idx][_PARAMS].
960
+ _state_dict_fn(optim, "load_state_dict")(state_dict=optim_state_dict)
961
+
962
+
963
+ def get_model_state_dict(
964
+ model: nn.Module,
965
+ *,
966
+ submodules: Optional[Set[nn.Module]] = None,
967
+ options: Optional[StateDictOptions] = None,
968
+ ) -> Dict[str, ValueType]:
969
+ """
970
+ Return the model state_dict of ``model``.
971
+
972
+ See ``get_state_dict`` for the detail usage.
973
+
974
+ Args:
975
+ model (nn.Module): the nn.Module to the model.
976
+ submodules (deprecated): Optional[Set[nn.Module]]: only return the model parameters
977
+ that belong to the submodules.
978
+ options (StateDictOptions): the options to control how
979
+ model state_dict and optimizer state_dict should be returned. See
980
+ `StateDictOptions` for the details.
981
+
982
+ Returns:
983
+ The state_dict for ``model``.
984
+
985
+ :rtype: typing.Dict[str, ValueType]
986
+ """
987
+ with _gc_context():
988
+ info = _verify_options(
989
+ model,
990
+ (),
991
+ optim_only=False,
992
+ submodules=submodules,
993
+ options=options,
994
+ )
995
+ model_state_dict = _get_model_state_dict(model, info)
996
+ _verify_state_dict(model_state_dict, {}, info)
997
+ return model_state_dict
998
+
999
+
1000
+ def get_optimizer_state_dict(
1001
+ model: nn.Module,
1002
+ optimizers: Union[torch.optim.Optimizer, Iterable[torch.optim.Optimizer]],
1003
+ *,
1004
+ submodules: Optional[Set[nn.Module]] = None,
1005
+ options: Optional[StateDictOptions] = None,
1006
+ ) -> OptimizerStateType:
1007
+ """
1008
+ Return the combined state_dict for optimizers.
1009
+
1010
+ See ``get_state_dict`` for the detail usage.
1011
+
1012
+ Args:
1013
+ model (nn.Module): the nn.Module to the model.
1014
+ optimizers (Union[None, Optimizer, Iterable[Optimizer]]):
1015
+ The optimizers that are used to optimize ``model``.
1016
+ submodules (deprecated): Optional[Set[nn.Module]]: only return the model parameters
1017
+ that belong to the submodules.
1018
+ options (StateDictOptions): the options to control how
1019
+ model state_dict and optimizer state_dict should be returned. See
1020
+ `StateDictOptions` for the details.
1021
+
1022
+ Returns:
1023
+ The state_dict for ``optimizers``.
1024
+
1025
+ :rtype: OptimizerStateType
1026
+ """
1027
+ with _gc_context():
1028
+ optimizers = (
1029
+ (optimizers,)
1030
+ if isinstance(optimizers, torch.optim.Optimizer)
1031
+ else tuple(optimizers)
1032
+ )
1033
+ info = _verify_options(
1034
+ model,
1035
+ optimizers,
1036
+ optim_only=True,
1037
+ submodules=submodules,
1038
+ options=options,
1039
+ )
1040
+ optim_state_dict = _get_optim_state_dict(model, optimizers, info)
1041
+ _verify_state_dict({}, optim_state_dict, info)
1042
+ return optim_state_dict
1043
+
1044
+
1045
+ def get_state_dict(
1046
+ model: nn.Module,
1047
+ optimizers: Union[torch.optim.Optimizer, Iterable[torch.optim.Optimizer]],
1048
+ *,
1049
+ submodules: Optional[Set[nn.Module]] = None,
1050
+ options: Optional[StateDictOptions] = None,
1051
+ ) -> Tuple[Dict[str, ValueType], OptimizerStateType]:
1052
+ """
1053
+ Return the model state_dict and optimizers state_dict.
1054
+
1055
+ ``get_state_dict`` can process any module that is parallelized by PyTorch
1056
+ FSDP/fully_shard, DDP/replicate, tensor_parallel/parallelize_module, and any
1057
+ combination of these parallelisms. The main functions of ``get_state_dict``
1058
+ are: 1.) returning a model and optimizer state_dict that can be resharded
1059
+ with a different number of trainers and/or different parallelisms.
1060
+ 2.) hiding the parallelism-specific state_dict APIs. Users don't have to call
1061
+ these APIs.
1062
+ 3.) sanity checking the result state_dict.
1063
+
1064
+ The keys of the result state dictionary are the canonical FQNs (Fully
1065
+ Qualified Names). A canonical FQN refers to the FQN based on a parameter's
1066
+ position in an nn.Module hierarchy. More specifically, a canonical FQN to a
1067
+ parameter is the FQN returned by ``module.named_parameters()`` or
1068
+ ``module.named_buffers()`` when the module is not distributed by any
1069
+ parallelisms. Since the optimizer internally uses parameter IDs to represent
1070
+ a parameter, there will be a conversion from the parameter IDs to the
1071
+ canonical FQNs when calling this API.
1072
+
1073
+ ``get_state_dict`` can also process a module that is not parallelized. In
1074
+ such a case, ``get_state_dict`` only performs one function -- converting the
1075
+ optimizer parameter IDs to the canonical FQNs.
1076
+
1077
+ Example:
1078
+ >>> # xdoctest: +SKIP
1079
+ >>> import torch
1080
+ >>> from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
1081
+ >>> from torch.nn.parallel import DistributedDataParallel as DDP
1082
+ >>> from torch.distributed.checkpoint.state_dict import get_state_dict
1083
+
1084
+ >>> fsdp_model = FSDP(copy.deepcopy(model))
1085
+ >>> fsdp_optim = torch.optim.Adam(model.parameters(), lr=1e-3)
1086
+ >>> ddp_model = DDP(copy.deepcopy(model))
1087
+ >>> ddp_optim = torch.optim.Adam(model.parameters(), lr=1e-3)
1088
+
1089
+
1090
+ >>> ddp_state_dict, ddp_optim_state_dict = get_state_dict(ddp_model, ddp_optim)
1091
+ >>> fsdp_state_dict, fsdp_optim_state_dict = get_state_dict(fsdp_model, fsdp_optim)
1092
+
1093
+ >>> # if we simply call ddp_model.state_dict() and fsdp_model.state_dict(),
1094
+ >>> # the asserts will fail.
1095
+ >>> assert ddp_state_dict == fsdp_state_dict
1096
+ >>> assert ddp_optim_state == fsdp_optim_state_dict
1097
+
1098
+
1099
+ Args:
1100
+ model (nn.Module): the nn.Module to the model.
1101
+ optimizers (Union[None, Optimizer, Iterable[Optimizer]]):
1102
+ The optimizers that are used to optimize ``model``.
1103
+ submodules (deprecated): Optional[Set[nn.Module]]: only return the model parameters
1104
+ that belong to the submodules.
1105
+ options (StateDictOptions): the options to control how
1106
+ model state_dict and optimizer state_dict should be returned. See
1107
+ `StateDictOptions` for the details.
1108
+
1109
+ Returns:
1110
+ ``Tuple`` that contain model state_dict and optimizer state_dict.
1111
+
1112
+ :rtype: typing.Tuple[typing.Dict[str, ValueType], OptimizerStateType]
1113
+ """
1114
+
1115
+ with _gc_context():
1116
+ optimizers = (
1117
+ (optimizers,)
1118
+ if isinstance(optimizers, torch.optim.Optimizer)
1119
+ else tuple(optimizers)
1120
+ )
1121
+ info = _verify_options(
1122
+ model,
1123
+ optimizers,
1124
+ optim_only=False,
1125
+ submodules=submodules,
1126
+ options=options,
1127
+ )
1128
+ model_state_dict = _get_model_state_dict(model, info)
1129
+ optim_state_dict = _get_optim_state_dict(model, optimizers, info)
1130
+ _verify_state_dict(model_state_dict, optim_state_dict, info)
1131
+ return model_state_dict, optim_state_dict
1132
+
1133
+
1134
+ def _unflatten_model_state_dict(
1135
+ model: nn.Module,
1136
+ state_dict: Union[Dict[nn.Module, Dict[str, ValueType]], Dict[str, ValueType]],
1137
+ ) -> Dict[str, ValueType]:
1138
+ if not state_dict:
1139
+ return {}
1140
+
1141
+ if isinstance(next(iter(state_dict.keys())), nn.Module):
1142
+ warnings.warn(
1143
+ "Passing model_state_dict as a ``Dict[nn.Module, Dict[str, Any]]``"
1144
+ "is deprecated and will be removed in 2.5. If you need this "
1145
+ "feature, please preprocessing the model_state_dict to achieve the "
1146
+ "same functionality.",
1147
+ FutureWarning,
1148
+ )
1149
+ cast_state_dict = cast(Dict[nn.Module, Dict[str, ValueType]], state_dict)
1150
+ new_state_dict: Dict[str, ValueType] = {}
1151
+ for submodule, sub_state_dict in cast_state_dict.items():
1152
+ for name, m in model.named_modules():
1153
+ if m != submodule:
1154
+ continue
1155
+
1156
+ fqns = _get_fqns(model, name)
1157
+ assert len(fqns) == 1, "FQNs for a submodule should only have 1 element"
1158
+ prefix = f"{next(iter(fqns))}."
1159
+ new_state_dict.update(
1160
+ {prefix + subfqn: value for subfqn, value in sub_state_dict.items()}
1161
+ )
1162
+ return new_state_dict
1163
+ else:
1164
+ return cast(Dict[str, ValueType], state_dict)
1165
+
1166
+
1167
+ def set_model_state_dict(
1168
+ model: nn.Module,
1169
+ model_state_dict: Dict[str, ValueType],
1170
+ *,
1171
+ options: Optional[StateDictOptions] = None,
1172
+ ) -> _IncompatibleKeys:
1173
+ """Load the model state_dict.
1174
+
1175
+ The counterpart of ``get_model_state_dict`` to set the state_dict to the
1176
+ model. See ``set_state_dict`` for the detail usage.
1177
+
1178
+ Args:
1179
+ model (nn.Module): the nn.Module to the model.
1180
+ model_state_dict: (Dict[str, ValueType]):
1181
+ the model state_dict to load. If the key of the ``model_state_dict``
1182
+ is nn.Module, the key is a submodule of ``model`` and the value should
1183
+ be the state_dict of the submodule. When loading the state_dict,
1184
+ the prefix of the submodule will be append to the state_dict.
1185
+ options (StateDictOptions): the options to control how
1186
+ model state_dict and optimizer state_dict should be loaded. See
1187
+ `StateDictOptions` for the details.
1188
+
1189
+ Returns:
1190
+ ``NamedTuple`` with ``missing_keys`` and ``unexpected_keys`` fields:
1191
+ * **missing_keys** is a list of str containing the missing keys
1192
+ * **unexpected_keys** is a list of str containing the unexpected keys
1193
+
1194
+ :type model_state_dict: typing.Dict[str, ValueType]
1195
+ """
1196
+ model_state_dict: Dict[str, ValueType] = _unflatten_model_state_dict(
1197
+ model, model_state_dict
1198
+ )
1199
+ with _gc_context():
1200
+ info = _verify_options(model, (), optim_only=False, options=options)
1201
+
1202
+ _verify_state_dict(model_state_dict, {}, info)
1203
+ return _load_model_state_dict(model, model_state_dict, info)
1204
+
1205
+
1206
+ def set_optimizer_state_dict(
1207
+ model: nn.Module,
1208
+ optimizers: Union[torch.optim.Optimizer, Iterable[torch.optim.Optimizer]],
1209
+ optim_state_dict: OptimizerStateType,
1210
+ *,
1211
+ options: Optional[StateDictOptions] = None,
1212
+ ) -> None:
1213
+ """Load the optimizers state_dict.
1214
+
1215
+ The counterpart of ``get_optimizer_state_dict`` to set the state_dict to the
1216
+ optimizers. See ``set_state_dict`` for the detail usage.
1217
+
1218
+ Args:
1219
+ model (nn.Module): the nn.Module to the model.
1220
+ optimizers (Union[Optimizer, Iterable[Optimizer]]):
1221
+ The optimizers that are used to optimize ``model``.
1222
+ optim_state_dict: OptimizerStateType:
1223
+ the optimizer state_dict to load.
1224
+ options (StateDictOptions): the options to control how
1225
+ model state_dict and optimizer state_dict should be loaded. See
1226
+ `StateDictOptions` for the details.
1227
+
1228
+ Returns:
1229
+ None
1230
+
1231
+ :type optim_state_dict: typing.OptimizerStateType
1232
+ """
1233
+ with _gc_context():
1234
+ optimizers = (
1235
+ (optimizers,)
1236
+ if isinstance(optimizers, torch.optim.Optimizer)
1237
+ else tuple(optimizers)
1238
+ )
1239
+ info = _verify_options(model, optimizers, optim_only=True, options=options)
1240
+
1241
+ _verify_state_dict({}, optim_state_dict, info)
1242
+ _load_optim_state_dict(model, optimizers, optim_state_dict, info)
1243
+
1244
+
1245
+ def set_state_dict(
1246
+ model: nn.Module,
1247
+ optimizers: Union[torch.optim.Optimizer, Iterable[torch.optim.Optimizer]],
1248
+ *,
1249
+ model_state_dict: Dict[str, ValueType],
1250
+ optim_state_dict: OptimizerStateType,
1251
+ options: Optional[StateDictOptions] = None,
1252
+ ) -> _IncompatibleKeys:
1253
+ """Load the model state_dict and optimizers state_dict.
1254
+
1255
+ The counterpart of ``get_state_dict`` to set the state_dict to the model and
1256
+ optimizers. The given ``model_state_dict`` and ``optim_state_dict`` do not
1257
+ have to be returned by ``get_state_dict`` but must meet the following
1258
+ requirements: 1) all FQNs are canonical FQNs as defined in ``get_state_dict``,
1259
+ 2) if a tensor is sharded, it must be either a ShardedTensor or DTensor,
1260
+ 3) optimizer state_dict cannot contain the parameter IDs; the keys should be
1261
+ the canonical FQNs.
1262
+
1263
+ Args:
1264
+ model (nn.Module): the nn.Module to the model.
1265
+ optimizers (Union[Optimizer, Iterable[Optimizer]]):
1266
+ The optimizers that are used to optimize ``model``.
1267
+ model_state_dict: (Union[Dict[nn.Module, Dict[str, ValueType]], Dict[str, ValueType]]):
1268
+ the model state_dict to load. If the key of the ``model_state_dict``
1269
+ is nn.Module, the key is a submodule of ``model`` and the value should
1270
+ be the state_dict of the submodule. When loading the state_dict,
1271
+ the prefix of the submodule will be append to the state_dict.
1272
+ optim_state_dict: OptimizerStateType:
1273
+ the optimizer state_dict to load.
1274
+ options (StateDictOptions): the options to control how
1275
+ model state_dict and optimizer state_dict should be loaded. See
1276
+ `StateDictOptions` for the details.
1277
+
1278
+ Returns:
1279
+ ``NamedTuple`` with ``missing_keys`` and ``unexpected_keys`` fields:
1280
+ * **missing_keys** is a list of str containing the missing keys of the model state_dict.
1281
+ * **unexpected_keys** is a list of str containing the unexpected keys of the model state_dict.
1282
+
1283
+ :type model_state_dict: typing.Dict[str, ValueType]
1284
+ :type optim_state_dict: typing.OptimizerStateType
1285
+ """
1286
+
1287
+ model_state_dict: Dict[str, ValueType] = _unflatten_model_state_dict(
1288
+ model, model_state_dict
1289
+ )
1290
+ with _gc_context():
1291
+ optimizers = (
1292
+ (optimizers,)
1293
+ if isinstance(optimizers, torch.optim.Optimizer)
1294
+ else tuple(optimizers)
1295
+ )
1296
+ info = _verify_options(
1297
+ model, optimizers, optim_only=not model_state_dict, options=options
1298
+ )
1299
+
1300
+ _verify_state_dict(model_state_dict, optim_state_dict, info)
1301
+ _load_optim_state_dict(model, optimizers, optim_state_dict, info)
1302
+ return _load_model_state_dict(model, model_state_dict, info)
1303
+
1304
+
1305
+ # TODO: correct the state_dict function signature.
1306
+ # TODO: this API is not yet fully tested. Make it private
1307
+ @no_type_check
1308
+ def _patch_model_state_dict(
1309
+ model: nn.Module,
1310
+ *,
1311
+ options: Optional[StateDictOptions] = None,
1312
+ ) -> None:
1313
+ """Patch the ``state_dict`` and ``load_state_dict`` attributes of ``model``.
1314
+
1315
+ Patch the ``state_dict`` and ``load_state_dict`` attributes of ``model`` to
1316
+ be a partial function to call ``get_state_dict`` and ``set_state_dict``.
1317
+
1318
+ Example:
1319
+ from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
1320
+ from torch.distributed.checkpoint.state_dict import patch_model_state_dict
1321
+
1322
+ model = fsdp(model)
1323
+ patch_model_state_dict(model)
1324
+
1325
+ Args:
1326
+ model (nn.Module): the nn.Module to the model.
1327
+ options (StateDictOptions): the options to control how
1328
+ model state_dict and optimizer state_dict should be loaded. See
1329
+ `StateDictOptions` for the details.
1330
+ Returns:
1331
+ None
1332
+ """
1333
+
1334
+ _state_dict_call = functools.partial(
1335
+ get_model_state_dict,
1336
+ model=model,
1337
+ options=options,
1338
+ )
1339
+
1340
+ def state_dict_call():
1341
+ return _state_dict_call()
1342
+
1343
+ model.state_dict = state_dict_call
1344
+
1345
+ _load_state_dict_call = functools.partial(
1346
+ set_model_state_dict,
1347
+ model=model,
1348
+ options=options,
1349
+ )
1350
+
1351
+ def load_state_dict_call(state_dict: Dict[str, Any]):
1352
+ _load_state_dict_call(model_state_dict=state_dict)
1353
+
1354
+ model.load_state_dict = load_state_dict_call
1355
+
1356
+ _patched_state_dict.add(state_dict_call)
1357
+ _patched_state_dict.add(load_state_dict_call)
1358
+
1359
+
1360
+ # TODO: correct the load_state_dict function signature.
1361
+ # TODO: this API is not yet fully tested. Make it private
1362
+ @no_type_check
1363
+ def _patch_optimizer_state_dict(
1364
+ model: nn.Module,
1365
+ *,
1366
+ optimizers: Tuple[torch.optim.Optimizer, ...],
1367
+ options: Optional[StateDictOptions] = None,
1368
+ ) -> None:
1369
+ """Patch the ``state_dict`` and ``load_state_dict`` attributes of ``optimizers``.
1370
+
1371
+ Patch the ``state_dict`` and ``load_state_dict`` attributes of ``optimizers`` to
1372
+ be a partial function to call ``get_state_dict`` and ``set_state_dict``.
1373
+
1374
+ Note that if there are multiple optimizers, all of the optimizers will be patched.
1375
+ So users only need to call one of the state_dict() to get the full result.
1376
+
1377
+ Example:
1378
+ from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
1379
+ from torch.distributed.checkpoint.state_dict import patch_model_state_dict
1380
+
1381
+ model = fsdp(model)
1382
+ patch_model_state_dict(model)
1383
+
1384
+ Args:
1385
+ model (nn.Module): the nn.Module to the model.
1386
+ options (StateDictOptions): the options to control how
1387
+ model state_dict and optimizer state_dict should be loaded. See
1388
+ `StateDictOptions` for the details.
1389
+ Returns:
1390
+ None
1391
+ """
1392
+
1393
+ _state_dict_call = functools.partial(
1394
+ get_optimizer_state_dict,
1395
+ model=model,
1396
+ optimizers=optimizers,
1397
+ options=options,
1398
+ )
1399
+
1400
+ def state_dict_call():
1401
+ return _state_dict_call()
1402
+
1403
+ _load_state_dict_call = functools.partial(
1404
+ set_optimizer_state_dict,
1405
+ model=model,
1406
+ optimizers=optimizers,
1407
+ options=options,
1408
+ )
1409
+
1410
+ def load_state_dict_call(state_dict: Dict[str, Any]):
1411
+ _load_state_dict_call(optim_state_dict=state_dict)
1412
+
1413
+ _patched_state_dict.add(state_dict_call)
1414
+ _patched_state_dict.add(load_state_dict_call)
1415
+ optimizers = (
1416
+ (optimizers,)
1417
+ if isinstance(optimizers, torch.optim.Optimizer)
1418
+ else tuple(optimizers)
1419
+ )
1420
+ for optim in optimizers:
1421
+ optim.state_dict = state_dict_call
1422
+ optim.load_state_dict = load_state_dict_call
vllm/lib/python3.10/site-packages/torch/distributed/fsdp/__init__.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ._flat_param import FlatParameter as FlatParameter
2
+ from .fully_sharded_data_parallel import (
3
+ BackwardPrefetch,
4
+ CPUOffload,
5
+ FullOptimStateDictConfig,
6
+ FullStateDictConfig,
7
+ FullyShardedDataParallel,
8
+ LocalOptimStateDictConfig,
9
+ LocalStateDictConfig,
10
+ MixedPrecision,
11
+ OptimStateDictConfig,
12
+ OptimStateKeyType,
13
+ ShardedOptimStateDictConfig,
14
+ ShardedStateDictConfig,
15
+ ShardingStrategy,
16
+ StateDictConfig,
17
+ StateDictSettings,
18
+ StateDictType,
19
+ )
20
+
21
+
22
+ __all__ = [
23
+ "BackwardPrefetch",
24
+ "CPUOffload",
25
+ "FullOptimStateDictConfig",
26
+ "FullStateDictConfig",
27
+ "FullyShardedDataParallel",
28
+ "LocalOptimStateDictConfig",
29
+ "LocalStateDictConfig",
30
+ "MixedPrecision",
31
+ "OptimStateDictConfig",
32
+ "OptimStateKeyType",
33
+ "ShardedOptimStateDictConfig",
34
+ "ShardedStateDictConfig",
35
+ "ShardingStrategy",
36
+ "StateDictConfig",
37
+ "StateDictSettings",
38
+ "StateDictType",
39
+ ]
vllm/lib/python3.10/site-packages/torch/distributed/fsdp/__pycache__/_trace_utils.cpython-310.pyc ADDED
Binary file (9.52 kB). View file
 
vllm/lib/python3.10/site-packages/torch/distributed/fsdp/__pycache__/_unshard_param_utils.cpython-310.pyc ADDED
Binary file (8.11 kB). View file
 
vllm/lib/python3.10/site-packages/torch/distributed/fsdp/_common_utils.py ADDED
@@ -0,0 +1,558 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ """
3
+ This file includes private common utilities for FSDP.
4
+ """
5
+ import logging
6
+ import traceback
7
+ import warnings
8
+ import weakref
9
+ from enum import auto, Enum
10
+ from functools import partial
11
+ from typing import (
12
+ Any,
13
+ Callable,
14
+ cast,
15
+ Dict,
16
+ Generator,
17
+ Iterable,
18
+ List,
19
+ no_type_check,
20
+ Optional,
21
+ Set,
22
+ Tuple,
23
+ Type,
24
+ TYPE_CHECKING,
25
+ )
26
+
27
+ import torch
28
+ import torch.distributed as dist
29
+ import torch.distributed.fsdp._flat_param as flat_param_file
30
+ import torch.nn as nn
31
+ from torch.distributed._composable_state import _get_module_state, _State
32
+ from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import (
33
+ _CHECKPOINT_PREFIX,
34
+ )
35
+ from torch.distributed.utils import _apply_to_tensors
36
+ from torch.utils._mode_utils import no_dispatch
37
+
38
+ from .api import (
39
+ FullOptimStateDictConfig,
40
+ FullStateDictConfig,
41
+ OptimStateDictConfig,
42
+ ShardingStrategy,
43
+ StateDictConfig,
44
+ StateDictType,
45
+ )
46
+
47
+
48
+ if TYPE_CHECKING:
49
+ from torch.distributed.device_mesh import DeviceMesh
50
+ from torch.distributed.fsdp._fsdp_extensions import FSDPExtensions
51
+
52
+ from ._flat_param import FlatParamHandle
53
+
54
+ FSDP_WRAPPED_MODULE = "_fsdp_wrapped_module"
55
+ FSDP_PREFIX = FSDP_WRAPPED_MODULE + "."
56
+ FSDP_FLATTENED = "_fsdp_flattened"
57
+
58
+ # Save a global mapping from module to its input tensor dtype to be populated
59
+ # during the forward pre-hook and consumed in the forward post-hook when
60
+ # overriding a module's mixed precision
61
+ # NOTE: We currently take the last input tensor's dtype in the case of multiple
62
+ # floating-point input tensors, which may be incorrect. However, since there is
63
+ # not a 1:1 correspondence between input and output tensors, we must use *some*
64
+ # heuristic like this to predict the desired output dtype.
65
+ _MODULE_TO_INP_DTYPE: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary()
66
+
67
+
68
+ class _FSDPDeviceHandle:
69
+ """
70
+ This is a simple abstraction for FSDP computing devices,
71
+ which enables custom backends that implement CUDA-like
72
+ semantics to be integrated with FSDP.
73
+ """
74
+
75
+ def __init__(self, device: torch.device, backend: Any = None):
76
+ if backend is None:
77
+ try:
78
+ self.__backend = getattr(torch, device.type)
79
+ self.__device = device
80
+ except AttributeError as exc:
81
+ raise AttributeError(
82
+ f"Device '{device}' does not have a corresponding backend registered as 'torch.{device.type}'."
83
+ ) from exc
84
+ else:
85
+ self.__backend = backend
86
+
87
+ @classmethod
88
+ def from_device(cls, device: torch.device) -> "_FSDPDeviceHandle":
89
+ """
90
+ Return a device handle corresponding to the device, and through this handle,
91
+ operations with the same semantics as CUDA can be performed on the device.
92
+ Just return torch.cuda if the device is cuda to make attribute-access faster.
93
+ Custom backend must first register a module with the same name with {device.type} on torch.
94
+ """
95
+ if device.type == "cuda":
96
+ return cast(_FSDPDeviceHandle, torch.cuda)
97
+ elif device.type == "mtia":
98
+ return cast(_FSDPDeviceHandle, torch.mtia)
99
+ return cls(device)
100
+
101
+ def __getattr__(self, __name: str) -> Any:
102
+ try:
103
+ return getattr(self.__backend, __name)
104
+ except AttributeError as exc:
105
+ raise AttributeError(
106
+ f"Custom backend '{self.__device.type}' not implement 'torch.{self.__device.type}.{__name}'"
107
+ ) from exc
108
+
109
+
110
+ class _UninitializedDeviceHandle(_FSDPDeviceHandle):
111
+ def __init__(self) -> None:
112
+ pass
113
+
114
+ def __getattribute__(self, __name: str) -> Any:
115
+ raise RuntimeError("Trying to use an uninitialized device handle.")
116
+
117
+
118
+ class _FSDPState(_State):
119
+ def __init__(self) -> None:
120
+ # TODO: Move all the attributes to this class to enable typing for
121
+ # FSDP/fully_shard.
122
+ self._ignored_modules: Set[nn.Module] = set()
123
+ self._ignored_params: Set[nn.Parameter] = set()
124
+ # Buffer names are cleaned (without wrapper prefixes)
125
+ self._ignored_buffer_names: Set[str] = set()
126
+ self.process_group: Optional[dist.ProcessGroup] = None
127
+ self.rank: int = -1
128
+ self.world_size: int = -1
129
+ self._device_mesh: Optional[DeviceMesh] = None
130
+ self.sharding_strategy = ShardingStrategy.FULL_SHARD
131
+ self._use_orig_params: bool = False
132
+ self.training_state = TrainingState.IDLE
133
+ self._unshard_params_ctx: Dict[nn.Module, Generator] = {}
134
+ self._state_dict_type: StateDictType = StateDictType.FULL_STATE_DICT
135
+ self._state_dict_config: StateDictConfig = FullStateDictConfig()
136
+ self._optim_state_dict_config: OptimStateDictConfig = FullOptimStateDictConfig()
137
+ self._is_root: Optional[bool] = None
138
+ self._handle: Optional[flat_param_file.FlatParamHandle] = None
139
+ self._fully_sharded_module_to_handle: Dict[
140
+ nn.Module, Optional[flat_param_file.FlatParamHandle]
141
+ ] = {}
142
+ self.compute_device: Optional[torch.device] = None
143
+ self._gradient_predivide_factor: int = 0
144
+ self._gradient_postdivide_factor: int = 0
145
+ self._comm_hook: Optional[Callable] = None
146
+ self._comm_hook_state: Optional[Any] = None
147
+ self._unshard_event: Optional[torch.Event] = None
148
+ # Abstract device handle for fsdp compute device. For now,
149
+ # the compute device must implement cuda semantics used by fsdp
150
+ self._device_handle: _FSDPDeviceHandle = _UninitializedDeviceHandle()
151
+ # All following attributes should only be used for root states:
152
+ # Save these static lists to avoid the repeated tree traversals
153
+ self._all_fsdp_states: List[_FSDPState] = []
154
+ self._all_handles: List[flat_param_file.FlatParamHandle] = []
155
+ self._fsdp_extension: Optional[FSDPExtensions] = None
156
+
157
+
158
+ def _get_module_fsdp_state(module: nn.Module) -> Optional[_FSDPState]:
159
+ state = _get_module_state(module)
160
+ if state is None or not isinstance(state, _FSDPState):
161
+ return None
162
+ return state
163
+
164
+
165
+ def _get_module_fsdp_state_if_fully_sharded_module(
166
+ module: nn.Module,
167
+ ) -> Optional[_FSDPState]:
168
+ state = _get_module_fsdp_state(module)
169
+ if state is None:
170
+ return None
171
+ if state == module: # FullyShardedDataParallel module case.
172
+ return state
173
+ if module in state._fully_sharded_module_to_handle: # fully_shard case.
174
+ return state
175
+ return None
176
+
177
+
178
+ class TrainingState(Enum):
179
+ """
180
+ An enum that indicates the state of a ``FullyShardedDataParallel` instance.
181
+ """
182
+
183
+ IDLE = auto()
184
+ FORWARD_BACKWARD = auto()
185
+ SUMMON_FULL_PARAMS = auto()
186
+
187
+
188
+ class HandleTrainingState(Enum):
189
+ """
190
+ An enum that indicates the state of a ``FlatParamHandle`.
191
+ """
192
+
193
+ IDLE = auto()
194
+ FORWARD = auto()
195
+ BACKWARD_PRE = auto()
196
+ BACKWARD_POST = auto()
197
+ SUMMON_FULL_PARAMS = auto()
198
+
199
+
200
+ def _is_composable(state: _FSDPState):
201
+ # TODO: This is a temporary hack for differentiate between code paths.
202
+ return not isinstance(state, nn.Module)
203
+
204
+
205
+ @no_type_check
206
+ def _module_handle(state: _FSDPState, module: nn.Module) -> Optional["FlatParamHandle"]:
207
+ """
208
+ Returns the ``FlatParamHandle`` s corresponding to ``module``. This is
209
+ the handle that contains some parameter in ``module``.
210
+ """
211
+ if _is_composable(state):
212
+ # A valid FSDP state may have no managed parameters and hence no
213
+ # handles, meaning no entry in `_fully_sharded_module_to_handles`
214
+ if state._handle is None:
215
+ return None
216
+ assert (
217
+ module in state._fully_sharded_module_to_handle
218
+ ), f"Expects a fully sharded module but got {module} on rank {state.rank}"
219
+ return state._fully_sharded_module_to_handle[module]
220
+ else:
221
+ # NOTE: This assumes `module` is a `FullyShardedDataParallel` instance.
222
+ return module._handle
223
+
224
+
225
+ @no_type_check
226
+ def _has_fsdp_params(state: _FSDPState, module: nn.Module) -> bool:
227
+ """Returns if ``module`` has parameters managed by FSDP."""
228
+ return _module_handle(state, module) is not None
229
+
230
+
231
+ def _get_sharding_strategy(handle):
232
+ """
233
+ Returns the sharding strategy of the handle.
234
+ """
235
+ return handle._sharding_strategy if handle else None
236
+
237
+
238
+ def clean_tensor_name(tensor_name: str) -> str:
239
+ """
240
+ Cleans the parameter or buffer name by removing any module wrapper
241
+ prefixes.
242
+ """
243
+ tensor_name = tensor_name.replace(FSDP_PREFIX, "")
244
+ # TODO: Explicitly replacing the checkpoint wrapper prefix is not ideal as
245
+ # it couples `CheckpointWrapper` and FSDP and also does not scale for more
246
+ # module wrappers.
247
+ tensor_name = tensor_name.replace(_CHECKPOINT_PREFIX, "")
248
+ return tensor_name
249
+
250
+
251
+ def _set_fsdp_flattened(tensor: torch.Tensor) -> None:
252
+ """
253
+ Sets an attribute on ``tensor`` to mark it as flattened by FSDP. This is to
254
+ avoid re-flattening it during nested construction.
255
+ """
256
+ setattr(tensor, FSDP_FLATTENED, True)
257
+
258
+
259
+ def _is_fsdp_flattened(tensor: torch.Tensor) -> bool:
260
+ """Returns if ``tensor`` has been marked as flattened by FSDP."""
261
+ return getattr(tensor, FSDP_FLATTENED, False)
262
+
263
+
264
+ def _named_parameters_with_duplicates(
265
+ module: nn.Module, **kwargs: Any
266
+ ) -> List[Tuple[str, nn.Parameter]]:
267
+ """
268
+ This API is required as some modules overwrite `named_parameters()` but do not support
269
+ `remove_duplicate`.
270
+ """
271
+ assert (
272
+ "remove_duplicate" not in kwargs
273
+ ), "_named_parameters_with_duplicates cannot be used with `remove_duplicate` argument."
274
+ kwargs["remove_duplicate"] = False
275
+ try:
276
+ ret = list(module.named_parameters(**kwargs))
277
+ except AssertionError as e:
278
+ kwargs.pop("remove_duplicate")
279
+ ret = list(module.named_parameters(**kwargs))
280
+ return ret
281
+
282
+
283
+ def _get_param_to_fqns(
284
+ model: torch.nn.Module,
285
+ dedup_shared_params: bool = True,
286
+ ) -> Dict[nn.Parameter, List[str]]:
287
+ """
288
+ Constructs a mapping from parameter to a list of its \"canonical\" FQNs. Here,
289
+ we use canonical to mean the fully-qualified name assigned to the parameter
290
+ based on its position in the original nn.Module hierarchy before any wrapper
291
+ or parallelism has been applied to it. This is in contrast to FQNs that may be
292
+ generated after parallelisms or wrappers have been applied to the model.
293
+
294
+ Each normal parameter maps to a singleton list containing its FQN, while each
295
+ ``FlatParameter`` maps to a list of its original parameter FQNs, which may
296
+ have length greater than one. All FQNs are prefixed starting from ``model``.
297
+
298
+ In the case where FSDP was applied with ``use_orig_params=True``, there should be no
299
+ ``FlatParameter`` s registered to the model's modules and this mapping will only
300
+ contain mappings from ``nn.Parameter`` s to singleton FQN lists.
301
+
302
+ It is only in the case where FSDP was applied with ``use_orig_params=False`` where
303
+ a ``FlatParameter`` will be registered in place of the original parameters and there
304
+ will be mappings from each ``FlatParameter`` to lists of FQNs corresponding to the
305
+ original parameters.
306
+
307
+ Args:
308
+ model (torch.nn.Module): Root module (which may or may not be a
309
+ :class:`FullyShardedDataParallel` instance).
310
+ dedup_shared_params (bool): For shared parameters, if ``True``, only
311
+ includes the FQNs corresponding to the first encounter of the
312
+ shared parameter in the module traversal; if ``False``, then
313
+ includes the FQNs across all encounters. (Default: ``True``)
314
+ """
315
+
316
+ def module_fn(module, prefix, tree_level, param_to_fqns):
317
+ for param_name, param in _named_parameters_with_duplicates(
318
+ module, recurse=False
319
+ ):
320
+ local_fqns = (
321
+ param._fqns
322
+ if isinstance(param, flat_param_file.FlatParameter)
323
+ else [param_name]
324
+ ) # prefixed from `module`
325
+ global_fqns = [
326
+ clean_tensor_name(prefix + name) for name in local_fqns
327
+ ] # prefixed from the top level `model` (i.e. including `prefix`)
328
+ is_shared_param = param in param_to_fqns
329
+ if not is_shared_param:
330
+ param_to_fqns[param] = global_fqns
331
+ else:
332
+ if isinstance(param, flat_param_file.FlatParameter):
333
+ # DMP overwrites `named_parameters` and skip (advance to
334
+ # the next child module) the wrapped_module (e.g.,
335
+ # _dmp_wrapped_module and _fsdp_wrapped_module). When a user
336
+ # calls `named_child` to traverse the module recursively and
337
+ # calls `named_parameters` with `recurse=False`, parameters
338
+ # will be traversed more than once.
339
+ # This hack is specified designed for DMP + FSDP. We
340
+ # overwrite the flat_parameters traversal result to only obtain
341
+ # the last one, which happens to be the correct one.
342
+ #
343
+ # TODO: Remove this hack once DMP + FSDP is not supported.
344
+ warnings.warn(
345
+ "FlatParameter is being traversed more than once. "
346
+ "This case should only happen when using "
347
+ "DistributedModelParallel with FullyShardedDataParallel."
348
+ )
349
+ param_to_fqns[param] = global_fqns
350
+ elif not dedup_shared_params:
351
+ param_to_fqns[param].extend(global_fqns)
352
+
353
+ def return_fn(param_to_fqns):
354
+ return param_to_fqns
355
+
356
+ param_to_unflat_param_names: Dict[torch.nn.Parameter, List[str]] = {}
357
+ return _apply_to_modules(
358
+ model,
359
+ module_fn,
360
+ return_fn,
361
+ [key for key, _ in _named_parameters_with_duplicates(model)],
362
+ param_to_unflat_param_names,
363
+ )
364
+
365
+
366
+ @no_type_check
367
+ def _log_post_backward_hook(
368
+ state: _FSDPState, handle: "FlatParamHandle", logger: logging.Logger
369
+ ) -> None:
370
+ # Under TORCH_DISTRIBUTED_DEBUG=INFO, log the module names this hook fires for.
371
+ # Below logging of module names this post-bwd hook fires for can help debug certain
372
+ # cases where hooks don't fire, such as under certain activation checkpoint configs.
373
+ if state._use_orig_params and handle._debug_level == dist.DebugLevel.INFO:
374
+ param_fqns = _get_handle_fqns_from_root(state, handle)
375
+ logger.warning("FSDP firing post-backward hooks for parameters %s", param_fqns)
376
+
377
+
378
+ @no_type_check
379
+ def _get_handle_fqns_from_root(
380
+ state: _FSDPState, handle: "FlatParamHandle"
381
+ ) -> Optional[List[str]]:
382
+ if handle is None:
383
+ return None
384
+ param_to_fqn = state._exec_order_data.param_to_fqn
385
+ handle_params = handle.flat_param._params # only populated for use_orig_params
386
+ param_fqns = [
387
+ fqn for fqn_list in [param_to_fqn[p] for p in handle_params] for fqn in fqn_list
388
+ ]
389
+ return param_fqns
390
+
391
+
392
+ def _apply_to_modules(
393
+ root_module: torch.nn.Module,
394
+ module_fn: Callable,
395
+ return_fn: Callable,
396
+ filter_fqns: Optional[List[str]] = None,
397
+ *args,
398
+ **kwargs,
399
+ ):
400
+ """
401
+ Performs a pre-order traversal of the modules in the hierarchy rooted at
402
+ ``root_module``, applying ``module_fn`` at each module and finally
403
+ returning a value using ``return_fn``. The traversal constructs the full
404
+ module prefix name (e.g. "module.submodule." just like in model state dict)
405
+ and makes that available to ``module_fn``.
406
+
407
+ ``filter_fqns`` is used because some module may have its own prefix similar
408
+ to ``FullyShardedDataParallel`` and the ``named_parameters()`` is overwritten
409
+ to remove the prefix.
410
+ """
411
+
412
+ def f(module: torch.nn.Module, prefix: str, tree_level: int, *args, **kwargs):
413
+ # Call the module function before recursing over children (pre-order)
414
+ module_fn(module, prefix, tree_level, *args, **kwargs)
415
+ for submodule_name, submodule in module.named_children():
416
+ if submodule is None:
417
+ continue
418
+ new_prefix = prefix + submodule_name + "."
419
+ new_tree_level = tree_level + 1
420
+ if filter_fqns is not None:
421
+ for fqn in filter_fqns:
422
+ if fqn.startswith(new_prefix):
423
+ break
424
+ else:
425
+ # DMP's named_parameter() will mess up the traversal with
426
+ # ``named_children`` + `named_parameter(recurse=False)``.
427
+ # This hack is a must to make the traversal work.
428
+ # TODO: Remove this hack once DMP + FSDP is not supported.
429
+ # It turns out that recursive wrapping may trigger this as
430
+ # well.
431
+ if (
432
+ submodule_name == "_fsdp_wrapped_module"
433
+ or submodule_name == "_dmp_wrapped_module"
434
+ ):
435
+ new_prefix = prefix
436
+ elif submodule_name == "module":
437
+ new_prefix = prefix
438
+ f(submodule, new_prefix, new_tree_level, *args, **kwargs)
439
+
440
+ f(root_module, "", 0, *args, **kwargs)
441
+ return return_fn(*args, **kwargs)
442
+
443
+
444
+ @no_type_check
445
+ def _assert_in_training_states(
446
+ state: _FSDPState,
447
+ training_states: List[TrainingState],
448
+ ) -> None:
449
+ """Asserts that FSDP is in the states ``_training_states``."""
450
+ # Raise a `ValueError` instead of using `assert` to ensure that these
451
+ # logical assertions run even if `assert`s are disabled
452
+ if state.training_state not in training_states:
453
+ msg = (
454
+ f"expected to be in states {training_states} but current state is "
455
+ f"{state.training_state}"
456
+ )
457
+ # Print the error on rank 0 in case this is called in the backward pass
458
+ if state.rank == 0:
459
+ if isinstance(state, nn.Module):
460
+ print(f"Asserting FSDP instance is: {state}")
461
+ print(f"ERROR: {msg}")
462
+ traceback.print_stack()
463
+ raise ValueError(msg)
464
+
465
+
466
+ def _get_root_modules(modules: Set[nn.Module]) -> Set[nn.Module]:
467
+ """
468
+ Returns:
469
+ Set[nn.Module]: The subset of ``modules`` that are root modules (i.e.
470
+ parent-less) with respect to the modules in the set itself. In other
471
+ words, these are the modules in ``modules`` that are not the child of
472
+ any other module in ``modules``.
473
+ """
474
+ root_modules: Set[nn.Module] = set()
475
+ module_to_submodules = {module: set(module.modules()) for module in modules}
476
+ for candidate_module in modules:
477
+ is_root_module = True
478
+ for module, submodules in module_to_submodules.items():
479
+ is_child_module = (
480
+ candidate_module is not module and candidate_module in submodules
481
+ )
482
+ if is_child_module:
483
+ is_root_module = False
484
+ break
485
+ if is_root_module:
486
+ root_modules.add(candidate_module)
487
+ return root_modules
488
+
489
+
490
+ def _override_module_mixed_precision(
491
+ root: torch.nn.Module,
492
+ module_classes_to_override: Iterable[Type[nn.Module]],
493
+ wrap_override_dict: Dict[str, Any] = {"mixed_precision": None}, # noqa: B006
494
+ ) -> Set[Type[nn.Module]]:
495
+ module_classes_to_override = tuple(set(module_classes_to_override))
496
+ # Return a set of the actually overridden module classes
497
+ overridden_module_classes: Set[Type[nn.Module]] = set()
498
+ for mod in root.modules():
499
+ if isinstance(mod, module_classes_to_override):
500
+ overridden_module_classes.add(type(mod))
501
+ mod._wrap_overrides = wrap_override_dict # type: ignore[assignment]
502
+ # TODO: We need to run this mixed precision ignored module in fp32,
503
+ # but ensure subsequent modules, that may possibly be running with
504
+ # mixed precision, still receive the appropriate precision inputs
505
+ # without user having to adjust mixed precision config too much.
506
+ # As a result, we attach pre and post forward hooks to up / down
507
+ # cast. We should revisit this design.
508
+
509
+ def cast_fn(
510
+ dtype: torch.dtype, module: nn.Module, x: torch.Tensor
511
+ ) -> torch.Tensor:
512
+ if not torch.is_floating_point(x) or x.dtype == dtype:
513
+ return x
514
+ _MODULE_TO_INP_DTYPE[module] = x.dtype
515
+ return x.to(dtype)
516
+
517
+ def forward_pre_hook(module, args):
518
+ return _apply_to_tensors(partial(cast_fn, torch.float32, module), args)
519
+
520
+ def forward_post_hook(module, args, output):
521
+ # NOTE: If the forward did not have any floating-point tensors,
522
+ # then the dtype will not be set for this module, and we do not
523
+ # upcast the dtype.
524
+ if module in _MODULE_TO_INP_DTYPE:
525
+ old_dtype = _MODULE_TO_INP_DTYPE[module]
526
+ return _apply_to_tensors(
527
+ partial(cast_fn, old_dtype, module), output
528
+ )
529
+
530
+ # We intentionally append both of these hooks so that they run after
531
+ # all other hooks.
532
+ mod.register_forward_pre_hook(forward_pre_hook, prepend=False)
533
+ mod.register_forward_hook(forward_post_hook, prepend=False)
534
+ return overridden_module_classes
535
+
536
+
537
+ def _no_dispatch_record_stream(tensor: torch.Tensor, stream: torch.Stream) -> None:
538
+ # FIXME record_stream doesn't work with non-cuda/mtia tensors
539
+ if tensor.device.type not in [
540
+ "cuda",
541
+ "mtia",
542
+ torch._C._get_privateuse1_backend_name(),
543
+ ]:
544
+ return
545
+
546
+ if torch.distributed._functional_collectives.is_torchdynamo_compiling():
547
+ return
548
+ # from @ezyang:
549
+ # The no_dispatch was added in https://github.com/pytorch/pytorch/pull/88014 cc @fegin
550
+ # Looking over the PR, it looks like this is because we don't actually support Stream arguments
551
+ # in torch dispatch, so it just chokes.
552
+ # If Dynamo is able to answer "are there any torch dispatch modes" active (it should answer False),
553
+ # a better version of this would just be to check if there are any modes before disabling dispatch.
554
+ # TODO(voz): Extend a dynamo util to answer the above, unify the codepaths here.
555
+ tensor.record_stream(stream)
556
+ else:
557
+ with no_dispatch():
558
+ tensor.record_stream(stream)
vllm/lib/python3.10/site-packages/torch/distributed/fsdp/_debug_utils.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import logging
3
+ import time
4
+ from collections import defaultdict
5
+ from contextlib import contextmanager
6
+ from enum import Enum
7
+ from typing import Dict, Iterator, List, Set, Tuple
8
+
9
+ import torch
10
+ import torch.distributed as dist
11
+ import torch.distributed.fsdp._flat_param as flat_param_file
12
+ from torch.distributed.fsdp._common_utils import (
13
+ _apply_to_modules,
14
+ _get_module_fsdp_state,
15
+ clean_tensor_name,
16
+ )
17
+
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ class SimpleProfiler:
23
+ class Type(str, Enum):
24
+ ALL = "all"
25
+ ALLGATHER = "all_gather"
26
+ ALLGATHER_OBJ = "all_gather_object"
27
+ RESHARDING = "resharding"
28
+ H2D = "H2D"
29
+ D2H = "D2H"
30
+
31
+ results: Dict[str, float] = defaultdict(float)
32
+ profiling: Set[str] = set()
33
+
34
+ @classmethod
35
+ def reset(cls) -> None:
36
+ cls.results.clear()
37
+ cls.profiling.clear()
38
+
39
+ @classmethod
40
+ @contextmanager
41
+ def profile(cls, profile_type: str) -> Iterator[None]:
42
+ assert profile_type not in cls.profiling, (
43
+ f"{profile_type} is already being profiled. "
44
+ "SimpleProfiler does not support profiling multiple instances at "
45
+ "the same time. "
46
+ )
47
+
48
+ cls.profiling.add(profile_type)
49
+ begin = time.monotonic()
50
+ try:
51
+ yield
52
+ finally:
53
+ end = time.monotonic()
54
+ cls.results[profile_type] += end - begin
55
+ cls.profiling.remove(profile_type)
56
+
57
+ @classmethod
58
+ def dump_and_reset(cls, msg: str) -> None:
59
+ # This cannot be combined with DETAIL distributed log
60
+ # as the profiling will be very incorrect.
61
+ if dist.get_rank() == 0 and dist.get_debug_level() == dist.DebugLevel.INFO:
62
+ logger.info("%s %s", msg, cls.results)
63
+ cls.reset()
64
+
65
+
66
+ def _get_sharded_module_tree_with_module_name_to_fqns(
67
+ model: torch.nn.Module,
68
+ ) -> Tuple[str, Dict[str, List[str]]]:
69
+ """
70
+ It is used for composable fully_shard() code path, it returns
71
+ 1. sharded module tree info: each line reprents a submodule name that contats the
72
+ submodule's FQN and its submodule class name, if the submodule is sharded by `fully_shard`,
73
+ the submodule name will add a postfix with ' FULLY SHARDED'. Each increased tree
74
+ level adds 4 spaces before the printed name. A printed sharded module tree info for a toy model
75
+ is like this:
76
+ [CompositeModel] FULLY SHARDED
77
+ l1[Linear]
78
+ u1[UnitModule] FULLY SHARDED
79
+ u1.l1[Linear]
80
+ u1.seq[Sequential]
81
+ u1.seq.0[ReLU]
82
+ u1.seq.1[Linear]
83
+ u1.seq.2[ReLU]
84
+ u1.l2[Linear]
85
+ u2[UnitModule] FULLY SHARDED
86
+ u2.l1[Linear]
87
+ u2.seq[Sequential]
88
+ u2.seq.0[ReLU]
89
+ u2.seq.1[Linear]
90
+ u2.seq.2[ReLU]
91
+ u2.l2[Linear]
92
+ l2[Linear]
93
+ 2. a dict mapping from the concated module FQN and class name to a list of its managed
94
+ original parameters' FQNs. An example of the dict for the above toy sharded model is like this:
95
+ {'[CompositeModel]': ['l1.weight', 'l1.bias', 'l2.weight', 'l2.bias'],
96
+ 'u1[UnitModule]': ['u1.l1.weight', 'u1.l1.bias', 'u1.seq.1.weight', 'u1.seq.1.bias', 'u1.l2.weight', 'u1.l2.bias'],
97
+ 'u2[UnitModule]': ['u2.l1.weight', 'u2.l1.bias', 'u2.seq.1.weight', 'u2.seq.1.bias', 'u2.l2.weight', 'u2.l2.bias']
98
+ }
99
+ All FQNs are prefixed starting from ``model``.
100
+
101
+ Args:
102
+ model (torch.nn.Module): Root module (which may or may not be passed to
103
+ composable `fully_shard()`).
104
+ """
105
+
106
+ def module_fn(
107
+ module, prefix, tree_level, sharded_tree_info, sharded_module_name_to_fqns
108
+ ):
109
+ num_spaces = tree_level * 4
110
+ trimed_prefix = (
111
+ prefix[:-1] if (len(prefix) > 0 and prefix[-1] == ".") else prefix
112
+ )
113
+ prefixed_module_name = trimed_prefix + "[" + module.__class__.__name__ + "]"
114
+ printed_prefixed_module_name = " " * num_spaces + prefixed_module_name
115
+
116
+ state = _get_module_fsdp_state(module)
117
+ if state is None:
118
+ sharded_tree_info[0] += printed_prefixed_module_name + "\n"
119
+ return
120
+
121
+ handle = state._fully_sharded_module_to_handle.get(module, None)
122
+
123
+ if handle:
124
+ sharded_tree_info[0] += (
125
+ printed_prefixed_module_name + " FULLY SHARDED" + "\n"
126
+ )
127
+ else:
128
+ sharded_tree_info[0] += printed_prefixed_module_name + "\n"
129
+
130
+ if handle:
131
+ param = handle.flat_param
132
+ assert isinstance(param, flat_param_file.FlatParameter)
133
+ global_fqns = [
134
+ clean_tensor_name(prefix + name) for name in param._fqns
135
+ ] # prefixed from the top level `model` (i.e. including `prefix`)
136
+
137
+ if prefixed_module_name in sharded_module_name_to_fqns:
138
+ sharded_module_name_to_fqns[prefixed_module_name].extend(global_fqns)
139
+ else:
140
+ sharded_module_name_to_fqns[prefixed_module_name] = global_fqns
141
+
142
+ def return_fn(sharded_tree_info, sharded_module_name_to_fqns):
143
+ return sharded_tree_info[0], sharded_module_name_to_fqns
144
+
145
+ # Use List to mutate its value in place while running the recursive functions
146
+ sharded_tree_info: List[str] = [
147
+ "",
148
+ ]
149
+ sharded_module_name_to_fqns: Dict[str, List[str]] = {}
150
+ return _apply_to_modules(
151
+ model,
152
+ module_fn,
153
+ return_fn,
154
+ [key for key, _ in model.named_parameters()],
155
+ sharded_tree_info,
156
+ sharded_module_name_to_fqns,
157
+ )
vllm/lib/python3.10/site-packages/torch/distributed/fsdp/_exec_order_utils.py ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import itertools
3
+ import warnings
4
+ from enum import auto, Enum
5
+ from typing import Dict, List, Optional, Tuple, Union
6
+
7
+ import torch
8
+ import torch.distributed as dist
9
+ import torch.distributed.fsdp._traversal_utils as traversal_utils
10
+ import torch.nn as nn
11
+ from torch.distributed.fsdp._common_utils import _FSDPState, _get_param_to_fqns
12
+ from torch.distributed.fsdp._flat_param import FlatParamHandle
13
+
14
+
15
+ class _ExecOrderWarnStatus(Enum):
16
+ """Used internally for execution order validation."""
17
+
18
+ NONE = auto() # no deviation yet
19
+ WARNING = auto() # deviated this iteration; currently issuing warnings
20
+ WARNED = auto() # deviated in a previous iteration
21
+
22
+
23
+ class _ExecOrderData:
24
+ """
25
+ This contains the data structures to track the execution order. We track
26
+ the pre-forward order on the *first* iteration for forward prefetching
27
+ (which thus assumes static graph) and the post-forward order on *every*
28
+ iteration for backward prefetching (which thus does not assume static
29
+ graph but may be provide an incorrect order).
30
+ """
31
+
32
+ def __init__(
33
+ self,
34
+ debug_level: dist.DebugLevel,
35
+ backward_prefetch_limit: int,
36
+ forward_prefetch_limit: int,
37
+ ) -> None:
38
+ # Tracks the (static) pre-forward order for execution order validation
39
+ # and forward prefetching
40
+ self.handles_pre_forward_order: List[FlatParamHandle] = []
41
+ # Tracks the post-forward order for pre-backward prefetching
42
+ self.handles_post_forward_order: List[Optional[FlatParamHandle]] = []
43
+ self._iter = 0
44
+
45
+ # Gives the max number of backward/forward prefetched all-gathers by a
46
+ # single module
47
+ self._backward_prefetch_limit = backward_prefetch_limit
48
+ self._forward_prefetch_limit = forward_prefetch_limit
49
+
50
+ # Data structures for execution order validation
51
+ self._checking_order: bool = debug_level == dist.DebugLevel.DETAIL
52
+ self.process_group: Optional[dist.ProcessGroup] = None
53
+ self.world_size: Optional[int] = None
54
+ self.all_handles: List[FlatParamHandle] = []
55
+ # Names are prefixed from the root module
56
+ self.param_to_fqn: Dict[nn.Parameter, List[str]] = {}
57
+ # Current index in the pre-forward execution order
58
+ self.current_order_index = 0
59
+ self.warn_status = _ExecOrderWarnStatus.NONE
60
+
61
+ def init(
62
+ self,
63
+ state: _FSDPState,
64
+ root_module: nn.Module,
65
+ process_group: dist.ProcessGroup,
66
+ ) -> None:
67
+ """
68
+ Initializes the data structures needed for checking the forward order.
69
+ This should be called after a root FSDP instance has been set during
70
+ lazy initialization.
71
+ """
72
+ self.process_group = process_group
73
+ self.rank = process_group.rank()
74
+ self.world_size = process_group.size()
75
+ # Fix an order over the handles, which should be the same across ranks
76
+ for handle in traversal_utils._get_fsdp_handles(root_module):
77
+ index = len(self.all_handles)
78
+ self.all_handles.append(handle)
79
+ handle._handle_index = index
80
+ self.param_to_fqn = _get_param_to_fqns(root_module)
81
+ # TODO (awgu): We can broadcast the metadata of rank 0's `all_handles`
82
+ # to check that all ranks have the same handles in the same order.
83
+ # https://github.com/pytorch/pytorch/issues/79620
84
+
85
+ @property
86
+ def is_first_iter(self) -> bool:
87
+ return self._iter == 0
88
+
89
+ def get_handle_to_backward_prefetch(
90
+ self,
91
+ current_handle: FlatParamHandle,
92
+ ) -> Optional[FlatParamHandle]:
93
+ """
94
+ Returns a :class:`list` of the handles keys of the handles to backward
95
+ prefetch given the current handles key. If there are no valid handles
96
+ keys to prefetch, then this returns an empty :class:`list`.
97
+ """
98
+ current_index = current_handle._post_forward_index
99
+ if current_index is None:
100
+ return None
101
+ target_index = current_index - 1
102
+ target_handle: Optional[FlatParamHandle] = None
103
+ for _ in range(self._backward_prefetch_limit):
104
+ if target_index < 0:
105
+ break
106
+ target_handle = self.handles_post_forward_order[target_index]
107
+ target_index -= 1
108
+ return target_handle
109
+
110
+ def get_handle_to_forward_prefetch(
111
+ self,
112
+ current_handle: FlatParamHandle,
113
+ ) -> Optional[FlatParamHandle]:
114
+ """
115
+ Returns a :class:`list` of the handles keys of the handles to forward
116
+ prefetch given the current handles key. If there are no valid handles
117
+ keys to prefetch, then this returns an empty :class:`list`.
118
+ """
119
+ current_index = current_handle._pre_forward_order_index
120
+ if current_index is None:
121
+ return None
122
+ target_index = current_index + 1
123
+ target_handle: Optional[FlatParamHandle] = None
124
+ for _ in range(self._forward_prefetch_limit):
125
+ if target_index >= len(self.handles_pre_forward_order):
126
+ break
127
+ target_handle = self.handles_pre_forward_order[target_index]
128
+ target_index += 1
129
+ return target_handle
130
+
131
+ def record_post_forward(self, handle: Optional[FlatParamHandle]) -> None:
132
+ """
133
+ Records ``handles`` in the post-forward order, where ``handles`` should
134
+ be a group of handles used in the same module's forward. If ``handles``
135
+ is empty, then it is omitted.
136
+
137
+ Unlike :meth:`record_pre_forward`, this records the order *every*
138
+ iteration with the expectation that the recorded order is reset in
139
+ :meth:`next_iter`.
140
+ """
141
+ if not handle:
142
+ return
143
+ # Only record the first usage of a handles key
144
+ if handle._post_forward_index:
145
+ self.handles_post_forward_order.append(handle)
146
+ return
147
+ index = len(self.handles_post_forward_order)
148
+ handle._post_forward_index = index
149
+ self.handles_post_forward_order.append(handle)
150
+
151
+ def record_pre_forward(
152
+ self, handle: Optional[FlatParamHandle], is_training: bool
153
+ ) -> None:
154
+ """
155
+ Records ``handles`` in the pre-forward order, where ``handles`` should
156
+ be a group of handles used in the same module's forward. If ``handles``
157
+ is empty, then it is omitted.
158
+
159
+ On the first iteration, this checks the execution order across ranks.
160
+ See :meth:`_check_order` for details.
161
+ """
162
+ if not handle:
163
+ return
164
+ self._check_order(handle, is_training)
165
+ # Fix the order after the first iteration and only record the first
166
+ # usage of a handles key
167
+ if not self.is_first_iter or handle._pre_forward_order_index is not None:
168
+ return
169
+ index = len(self.handles_pre_forward_order)
170
+ handle._pre_forward_order_index = index
171
+ self.handles_pre_forward_order.append(handle)
172
+
173
+ def _check_order(self, handle: FlatParamHandle, is_training: bool) -> None:
174
+ """
175
+ Checks the forward execution order as long as ``is_training`` is
176
+ ``True`` since checking in eval mode is not supported. This only checks
177
+ if the distributed debug level is DETAIL.
178
+
179
+ - On the first iteration, this uses all-gathers to check that all ranks
180
+ are all-gathering the same handles and hence ``FlatParameter`` s,
181
+ raising an error if not.
182
+ - On subsequent iterations, this checks that each rank is locally
183
+ consistent with its own forward order from the first iteration, issuing
184
+ a warning if not. This issues a warning on the first deviating
185
+ iteration and stops warning thereafter.
186
+ """
187
+ # Do not check order in eval mode since the post-backward callback does
188
+ # not run so it cannot be used to mark the end of an iteration
189
+ if not is_training or not self._checking_order:
190
+ return
191
+ if self.is_first_iter:
192
+ msg_prefix = "Forward order differs across ranks:"
193
+ optional_local_indices: Tuple[
194
+ Optional[int], ...
195
+ ] = self._get_handle_indices(handle)
196
+ device = handle.device # guaranteed to be non-CPU
197
+ num_valid_indices = sum(
198
+ (index is not None) for index in optional_local_indices
199
+ )
200
+ tensor_kwargs: Dict[str, Union[torch.dtype, torch.device]] = {
201
+ "dtype": torch.int32,
202
+ "device": device,
203
+ }
204
+ world_num_valid_indices = torch.zeros(self.world_size, **tensor_kwargs) # type: ignore[arg-type, call-overload]
205
+ local_num_valid_indices = torch.tensor([num_valid_indices], **tensor_kwargs) # type: ignore[arg-type, call-overload]
206
+ dist.all_gather_into_tensor(
207
+ world_num_valid_indices,
208
+ local_num_valid_indices,
209
+ group=self.process_group,
210
+ )
211
+ # Copy entire tensor from D2H once to avoid per element D2H copies
212
+ world_num_valid_indices = world_num_valid_indices.cpu()
213
+ # Check that all ranks plan to all-gather the same number of
214
+ # parameters
215
+ # TODO (awgu): Since every module has at most one handle in the
216
+ # current implementation, this should never raise the error.
217
+ assert self.world_size is not None # mypy
218
+ if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
219
+ # TODO(voz): Don't graph break on this - dynamo hates the n1 != n2
220
+ # tensor comparison control flow.
221
+ # https://github.com/pytorch/pytorch/issues/107055
222
+ for (r1, n1), (r2, n2) in itertools.combinations(
223
+ (
224
+ (rank, world_num_valid_indices[rank])
225
+ for rank in range(self.world_size)
226
+ ),
227
+ 2,
228
+ ):
229
+ if n1 != n2:
230
+ raise RuntimeError(
231
+ f"{msg_prefix} rank {r1} is all-gathering {n1} parameters "
232
+ f"while rank {r2} is all-gathering {n2} parameters"
233
+ )
234
+ world_indices = torch.zeros( # type: ignore[call-overload]
235
+ self.world_size * num_valid_indices, **tensor_kwargs
236
+ )
237
+ local_indices = torch.tensor(optional_local_indices, **tensor_kwargs) # type: ignore[arg-type]
238
+ dist.all_gather_into_tensor(
239
+ world_indices, local_indices, group=self.process_group
240
+ )
241
+ # Copy entire tensor from D2H once to avoid per element D2H copies
242
+ world_indices = world_indices.cpu()
243
+ # Check that all ranks plan to all-gather the same index parameters
244
+ if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
245
+ # TODO(voz): Don't graph break on this - dynamo hates the i1 != i2
246
+ # tensor comparison control flow.
247
+ # https://github.com/pytorch/pytorch/issues/107055
248
+ for (r1, i1), (r2, i2) in itertools.combinations(
249
+ (
250
+ (
251
+ rank,
252
+ world_indices[
253
+ rank
254
+ * num_valid_indices : (rank + 1)
255
+ * num_valid_indices
256
+ ],
257
+ )
258
+ for rank in range(self.world_size)
259
+ ),
260
+ 2,
261
+ ):
262
+ if i1 != i2:
263
+ r1_param_names = self._get_names_from_handle_indices(i1)
264
+ r2_param_names = self._get_names_from_handle_indices(i2)
265
+ raise RuntimeError(
266
+ f"{msg_prefix} rank {r1} is all-gathering parameters "
267
+ f"for {r1_param_names} while rank {r2} is all-gathering "
268
+ f"parameters for {r2_param_names}"
269
+ )
270
+ else:
271
+ # Only issue warnings on the first deviating iteration and stop
272
+ # checking thereafter to avoid flooding the console
273
+ if self.warn_status == _ExecOrderWarnStatus.WARNED:
274
+ return
275
+ msg_prefix = None # non-`None` means we should warn
276
+ if self.current_order_index >= len(self.handles_pre_forward_order):
277
+ # This iteration sees extra all-gather(s) compared to the first
278
+ msg_prefix = (
279
+ "Expected to not all-gather any more parameters in the "
280
+ "forward but trying to all-gather parameters for "
281
+ )
282
+ else:
283
+ expected_handle = self.handles_pre_forward_order[
284
+ self.current_order_index
285
+ ]
286
+ if expected_handle != handle:
287
+ expected_param_names = self._get_names_from_handles(expected_handle)
288
+ msg_prefix = (
289
+ f"Expected to all-gather for {expected_param_names} "
290
+ "but trying to all-gather parameters for "
291
+ )
292
+ if msg_prefix is not None:
293
+ param_names = self._get_names_from_handles(handle)
294
+ msg_suffix = (
295
+ f"{param_names}"
296
+ if param_names
297
+ else "a newly-added parameter since construction time"
298
+ )
299
+ warnings.warn(
300
+ "Forward order differs from that of the first iteration "
301
+ f"on rank {self.rank}. Collectives are unchecked and may "
302
+ f"give incorrect results or hang.\n{msg_prefix}{msg_suffix}"
303
+ )
304
+ self.warn_status = _ExecOrderWarnStatus.WARNING
305
+ self.current_order_index += 1
306
+
307
+ def _get_handle_indices(
308
+ self,
309
+ handle: FlatParamHandle,
310
+ ) -> Tuple[Optional[int], ...]:
311
+ """
312
+ Returns the handle indices (i.e. indices into ``self.all_handles``)
313
+ corresponding to the handles in ``handle``. An entry in the
314
+ returned tuple is ``None`` if the handle is invalid.
315
+ """
316
+ indices: List[Optional[int]] = []
317
+ if handle:
318
+ indices.append(handle._handle_index)
319
+ return tuple(indices)
320
+
321
+ def _get_names_from_handle_indices(
322
+ self,
323
+ handle_indices: Tuple[int, ...],
324
+ ) -> List[List[str]]:
325
+ """
326
+ Returns a list of FQNs for each handle in ``handle_indices``. If a
327
+ handle index is invalid, then its FQNs are omitted from the returned
328
+ list.
329
+ """
330
+ fqns: List[List[str]] = []
331
+ for index in handle_indices:
332
+ if index is None or index < 0 or index >= len(self.all_handles):
333
+ continue
334
+ handle = self.all_handles[index]
335
+ flat_param = handle.flat_param
336
+ fqns.append(self.param_to_fqn[flat_param])
337
+ return fqns
338
+
339
+ def _get_names_from_handles(
340
+ self,
341
+ handle: FlatParamHandle,
342
+ ) -> List[List[str]]:
343
+ """
344
+ Returns a list of FQNs for each handle in ``handles_key``. If a handle
345
+ is invalid, then its FQNs are omitted from the returned list.
346
+ """
347
+ fqns: List[List[str]] = []
348
+ if handle:
349
+ flat_param = handle.flat_param
350
+ if flat_param in self.param_to_fqn:
351
+ fqns.append(self.param_to_fqn[flat_param])
352
+ return fqns
353
+
354
+ def next_iter(self):
355
+ """
356
+ Advances the internal data structures per iteration. This should be
357
+ called in the post-backward callback since that marks the true end of
358
+ an iteration.
359
+ """
360
+ self._iter += 1
361
+ self.handles_post_forward_order.clear()
362
+ if self._checking_order:
363
+ self.current_order_index = 0
364
+ if self.warn_status == _ExecOrderWarnStatus.WARNING:
365
+ self.warn_status = _ExecOrderWarnStatus.WARNED
vllm/lib/python3.10/site-packages/torch/distributed/fsdp/_flat_param.py ADDED
The diff for this file is too large to render. See raw diff
 
vllm/lib/python3.10/site-packages/torch/distributed/fsdp/_fsdp_extensions.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC, abstractmethod
2
+ from typing import Any, List, Optional, Tuple
3
+
4
+ import torch
5
+ import torch.distributed as dist
6
+ from torch.distributed._shard.sharded_tensor.api import ShardedTensor
7
+ from torch.distributed._shard.sharded_tensor.shard import Shard
8
+ from torch.distributed.fsdp._shard_utils import (
9
+ _all_gather_dtensor,
10
+ _create_chunk_dtensor,
11
+ _create_chunk_sharded_tensor,
12
+ )
13
+ from torch.distributed.tensor import DeviceMesh, DTensor
14
+
15
+
16
+ class FSDPExtensions(ABC):
17
+ """
18
+ This enables some customizable hooks to enable composability with tensor
19
+ parallelism. To activate these hooks, use :func:`_set_fsdp_extensions` to
20
+ set a custom :class:`FSDPExtensions` that implements the hooks.
21
+ """
22
+
23
+ @abstractmethod
24
+ def pre_flatten_transform(
25
+ self,
26
+ tensor: torch.Tensor,
27
+ ) -> Tuple[torch.Tensor, Optional[Any]]:
28
+ """E.g. converting ``DistributedTensor`` to local tensor."""
29
+ ...
30
+
31
+ @abstractmethod
32
+ def post_unflatten_transform(
33
+ self,
34
+ tensor: torch.Tensor,
35
+ param_extension: Any,
36
+ ) -> torch.Tensor:
37
+ """E.g. converting local tensor to ``DistributedTensor``."""
38
+ ...
39
+
40
+ @abstractmethod
41
+ def chunk_tensor(
42
+ self,
43
+ tensor: torch.Tensor,
44
+ rank: int,
45
+ world_size: int,
46
+ num_devices_per_node: int,
47
+ pg: dist.ProcessGroup,
48
+ device: Optional[torch.device] = None,
49
+ ) -> torch.Tensor:
50
+ """Shards a tensor to chunks and returns the local chunk."""
51
+ ...
52
+
53
+ @abstractmethod
54
+ def chunk_dtensor(
55
+ self,
56
+ tensor: torch.Tensor,
57
+ rank: int,
58
+ device_mesh: DeviceMesh,
59
+ ) -> torch.Tensor:
60
+ """Shards a tensor/DTensor to DTensor and returns the local DTensor."""
61
+ ...
62
+
63
+ @abstractmethod
64
+ def pre_load_state_dict_transform(
65
+ self,
66
+ tensor: torch.Tensor,
67
+ ) -> Tuple[torch.Tensor, List[Shard]]:
68
+ """
69
+ This is to be called before loading a *sharded* model state dict and
70
+ should return the tensor and list of shards from which to load data.
71
+ """
72
+ ...
73
+
74
+ @abstractmethod
75
+ def all_gather_dtensor(
76
+ self,
77
+ tensor: DTensor,
78
+ parent_mesh: Optional[DeviceMesh],
79
+ ) -> torch.Tensor:
80
+ """
81
+ This is to be called before loading a *sharded* DTensor state dict.
82
+ This gathers tensor in FSDP dimension and returns local tensor of
83
+ TP DTensor.
84
+ """
85
+ ...
86
+
87
+
88
+ _extensions: Optional[FSDPExtensions] = None
89
+
90
+
91
+ def _set_fsdp_extensions(flattener: FSDPExtensions) -> None:
92
+ global _extensions
93
+ _extensions = flattener
94
+
95
+
96
+ def _ext_pre_flatten_transform(
97
+ tensor: torch.Tensor,
98
+ fsdp_extension: Optional[FSDPExtensions] = None,
99
+ ) -> Tuple[torch.Tensor, Optional[Any]]:
100
+ if fsdp_extension is not None:
101
+ new_tensor, param_extension = fsdp_extension.pre_flatten_transform(tensor)
102
+ if param_extension is not None:
103
+ return new_tensor, param_extension
104
+ return tensor, None
105
+
106
+
107
+ def _ext_post_unflatten_transform(
108
+ tensor: torch.Tensor,
109
+ param_extension: Any,
110
+ fsdp_extension: Optional[FSDPExtensions] = None,
111
+ ) -> torch.Tensor:
112
+ if fsdp_extension is not None and param_extension is not None:
113
+ return fsdp_extension.post_unflatten_transform(tensor, param_extension)
114
+ return tensor
115
+
116
+
117
+ def _ext_chunk_tensor(
118
+ tensor: torch.Tensor,
119
+ rank: int,
120
+ world_size: int,
121
+ num_devices_per_node: int,
122
+ pg: dist.ProcessGroup,
123
+ fsdp_extension: Optional[FSDPExtensions] = None,
124
+ ) -> torch.Tensor:
125
+ chunk_tensor_fn = (
126
+ fsdp_extension.chunk_tensor
127
+ if fsdp_extension is not None
128
+ else _create_chunk_sharded_tensor
129
+ )
130
+ return chunk_tensor_fn(
131
+ tensor,
132
+ rank,
133
+ world_size,
134
+ num_devices_per_node,
135
+ pg,
136
+ )
137
+
138
+
139
+ def _ext_chunk_dtensor(
140
+ tensor: torch.Tensor,
141
+ rank: int,
142
+ device_mesh: DeviceMesh,
143
+ fsdp_extension: Optional[FSDPExtensions] = None,
144
+ ) -> torch.Tensor:
145
+ chunk_dtensor_fn = (
146
+ fsdp_extension.chunk_dtensor
147
+ if fsdp_extension is not None
148
+ else _create_chunk_dtensor
149
+ )
150
+ return chunk_dtensor_fn(
151
+ tensor,
152
+ rank,
153
+ device_mesh,
154
+ )
155
+
156
+
157
+ def _ext_pre_load_state_dict_transform(
158
+ tensor: torch.Tensor,
159
+ fsdp_extension: Optional[FSDPExtensions] = None,
160
+ ) -> Tuple[torch.Tensor, List[Shard]]:
161
+ if fsdp_extension is not None:
162
+ return fsdp_extension.pre_load_state_dict_transform(tensor)
163
+
164
+ assert type(tensor) is ShardedTensor
165
+ shards = tensor.local_shards()
166
+ return (tensor, shards)
167
+
168
+
169
+ def _ext_all_gather_dtensor(
170
+ tensor: DTensor,
171
+ parent_mesh: Optional[DeviceMesh],
172
+ fsdp_extension: Optional[FSDPExtensions] = None,
173
+ ) -> torch.Tensor:
174
+ all_gather_dtensor_fn = (
175
+ fsdp_extension.all_gather_dtensor
176
+ if fsdp_extension is not None
177
+ else _all_gather_dtensor
178
+ )
179
+ return all_gather_dtensor_fn(tensor, parent_mesh)
vllm/lib/python3.10/site-packages/torch/distributed/fsdp/_init_utils.py ADDED
@@ -0,0 +1,1200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import collections
3
+ import itertools
4
+ import os
5
+ import warnings
6
+ from typing import (
7
+ Any,
8
+ Callable,
9
+ Deque,
10
+ Dict,
11
+ Generator,
12
+ Iterable,
13
+ Iterator,
14
+ List,
15
+ no_type_check,
16
+ Optional,
17
+ Set,
18
+ Tuple,
19
+ TYPE_CHECKING,
20
+ Union,
21
+ )
22
+
23
+ import torch
24
+ import torch.distributed as dist
25
+ import torch.distributed.fsdp._exec_order_utils as exec_order_utils
26
+ import torch.distributed.fsdp._traversal_utils as traversal_utils
27
+ import torch.distributed.fsdp.fully_sharded_data_parallel as fsdp_file
28
+ import torch.nn as nn
29
+ from torch.distributed.algorithms._comm_hooks import default_hooks
30
+ from torch.distributed.device_mesh import _mesh_resources, DeviceMesh
31
+ from torch.distributed.distributed_c10d import _get_default_group
32
+ from torch.distributed.fsdp._common_utils import (
33
+ _FSDPDeviceHandle,
34
+ _FSDPState,
35
+ _get_module_fsdp_state,
36
+ _is_fsdp_flattened,
37
+ _named_parameters_with_duplicates,
38
+ clean_tensor_name,
39
+ TrainingState,
40
+ )
41
+ from torch.distributed.fsdp._flat_param import (
42
+ _FSDP_USE_FULL_PREC_IN_EVAL,
43
+ FlatParameter,
44
+ FlatParamHandle,
45
+ HandleShardingStrategy,
46
+ )
47
+ from torch.distributed.fsdp._limiter_utils import _FreeEventQueue
48
+ from torch.distributed.fsdp.api import (
49
+ BackwardPrefetch,
50
+ CPUOffload,
51
+ FullOptimStateDictConfig,
52
+ FullStateDictConfig,
53
+ MixedPrecision,
54
+ ShardingStrategy,
55
+ StateDictConfig,
56
+ StateDictType,
57
+ )
58
+ from torch.distributed.fsdp.wrap import _Policy
59
+ from torch.distributed.tensor.parallel.fsdp import DTensorExtensions
60
+ from torch.distributed.utils import _sync_params_and_buffers
61
+ from torch.utils._python_dispatch import is_traceable_wrapper_subclass
62
+
63
+
64
+ if TYPE_CHECKING:
65
+ from torch.utils.hooks import RemovableHandle
66
+
67
+ _TORCHDISTX_AVAIL = True
68
+ try:
69
+ from torchdistx import deferred_init, fake # type: ignore[import]
70
+ except ImportError:
71
+ _TORCHDISTX_AVAIL = False
72
+
73
+ PARAM_BROADCAST_BUCKET_SIZE = int(250 * 1024 * 1024)
74
+ FSDP_SYNCED = "_fsdp_synced"
75
+ # Specification of process groups for hybrid sharding strategies.
76
+ HybridShardProcessGroupType = Tuple[dist.ProcessGroup, dist.ProcessGroup]
77
+ # Overall specification of process group.
78
+ ProcessGroupType = Optional[Union[dist.ProcessGroup, HybridShardProcessGroupType]]
79
+
80
+
81
+ # TODO (awgu): Refactor this later
82
+ SHARDING_STRATEGY_MAP = {
83
+ ShardingStrategy.NO_SHARD: HandleShardingStrategy.NO_SHARD,
84
+ ShardingStrategy.FULL_SHARD: HandleShardingStrategy.FULL_SHARD,
85
+ ShardingStrategy.SHARD_GRAD_OP: HandleShardingStrategy.SHARD_GRAD_OP,
86
+ ShardingStrategy.HYBRID_SHARD: HandleShardingStrategy.HYBRID_SHARD,
87
+ ShardingStrategy._HYBRID_SHARD_ZERO2: HandleShardingStrategy._HYBRID_SHARD_ZERO2,
88
+ }
89
+ HYBRID_SHARDING_STRATEGIES = [
90
+ ShardingStrategy.HYBRID_SHARD,
91
+ ShardingStrategy._HYBRID_SHARD_ZERO2,
92
+ ]
93
+ NO_RESHARD_AFTER_FORWARD_STRATEGIES = (
94
+ ShardingStrategy.SHARD_GRAD_OP,
95
+ ShardingStrategy._HYBRID_SHARD_ZERO2,
96
+ )
97
+
98
+
99
+ # NOTE: Since non-self attributes cannot be type annotated, several attributes
100
+ # on `state` are defined first as local variables before being assigned.
101
+
102
+
103
+ @no_type_check
104
+ def _init_process_group_state(
105
+ state: _FSDPState,
106
+ process_group: ProcessGroupType,
107
+ sharding_strategy: ShardingStrategy,
108
+ policy: Optional[_Policy],
109
+ device_mesh: Optional[DeviceMesh] = None,
110
+ ) -> _FSDPState:
111
+ if process_group is not None and device_mesh is not None:
112
+ raise ValueError(
113
+ "Cannot pass both process_group and device_mesh at the "
114
+ "same time. Please just pass only one of them."
115
+ )
116
+ is_hybrid_strategy = sharding_strategy in HYBRID_SHARDING_STRATEGIES
117
+ if is_hybrid_strategy:
118
+ if process_group is None and policy is None and device_mesh is None:
119
+ # Raise an error here, since this is manual wrapping with no process group
120
+ # passed in, there is no way to ensure all wrapped FSDP instances use the same
121
+ # process groups.
122
+ raise ValueError(
123
+ f"Manual wrapping with {sharding_strategy} "
124
+ "requires explicit specification of process group or device_mesh."
125
+ )
126
+ else:
127
+ state = _init_process_group_state_for_hybrid_shard(
128
+ state, process_group, device_mesh
129
+ )
130
+ else:
131
+ if device_mesh:
132
+ state._device_mesh = device_mesh
133
+ state.process_group = device_mesh.get_group(mesh_dim=0)
134
+ else:
135
+ state.process_group = (
136
+ process_group if process_group is not None else _get_default_group()
137
+ )
138
+
139
+ state.rank = state.process_group.rank()
140
+ state.world_size = state.process_group.size()
141
+ data_parallel_world_size = state.world_size
142
+ if is_hybrid_strategy:
143
+ data_parallel_world_size *= state._inter_node_pg.size()
144
+ state._gradient_predivide_factor = (
145
+ default_hooks.DefaultState._get_gradient_predivide_factor(
146
+ data_parallel_world_size
147
+ )
148
+ )
149
+ state._gradient_postdivide_factor = (
150
+ data_parallel_world_size / state._gradient_predivide_factor
151
+ )
152
+ return state
153
+
154
+
155
+ @no_type_check
156
+ def _init_process_group_state_for_hybrid_shard(
157
+ state: _FSDPState,
158
+ process_group: ProcessGroupType,
159
+ device_mesh: DeviceMesh,
160
+ ) -> _FSDPState:
161
+ if device_mesh:
162
+ if _is_valid_hybrid_shard_device_mesh(device_mesh):
163
+ state._device_mesh = device_mesh
164
+ # We currently only allow _inter_node_pg to be the outermost dimension, and the
165
+ # process_group(intra_node) to be the innermost dimension.
166
+ state._inter_node_pg = device_mesh.get_group(mesh_dim=0)
167
+ state.process_group = device_mesh.get_group(mesh_dim=1)
168
+ else:
169
+ raise ValueError(
170
+ f"Expected device_mesh to have ndim=2 but got {device_mesh.ndim}"
171
+ )
172
+ elif process_group is None:
173
+ default_group = _get_default_group()
174
+ intra_node_group, inter_node_group = _init_intra_and_inter_node_groups(
175
+ default_group, state._device_handle.device_count()
176
+ )
177
+ # we shard across intra-node
178
+ state.process_group = intra_node_group
179
+ # save _inter_node_pg to allreduce across.
180
+ state._inter_node_pg = inter_node_group
181
+ else:
182
+ # Check type and assign state.process_group and state._inter_node_pg.
183
+ if _is_valid_hybrid_shard_pg_type(process_group):
184
+ # Assuming that user passed in as intra node group and inter node group
185
+ # as documented.
186
+ state.process_group, state._inter_node_pg = process_group
187
+ else:
188
+ raise ValueError(
189
+ "Expected process_group to be passed in as either None or "
190
+ f"Tuple[dist.ProcessGroup, dist.ProcessGroup] but got {type(process_group)}"
191
+ )
192
+ # Create state for allreduce
193
+ state._inter_node_state = _get_default_comm_hook_state(
194
+ process_group=state._inter_node_pg,
195
+ )
196
+ return state
197
+
198
+
199
+ @no_type_check
200
+ def _is_valid_hybrid_shard_pg_type(process_group: Any) -> bool:
201
+ return (
202
+ isinstance(process_group, tuple)
203
+ and len(process_group) == 2
204
+ and all(isinstance(pg, dist.ProcessGroup) for pg in process_group)
205
+ )
206
+
207
+
208
+ @no_type_check
209
+ def _is_valid_hybrid_shard_device_mesh(device_mesh: DeviceMesh) -> bool:
210
+ return isinstance(device_mesh, DeviceMesh) and device_mesh.ndim == 2
211
+
212
+
213
+ @no_type_check
214
+ def _init_intra_node_process_group(num_devices_per_node: int) -> dist.ProcessGroup:
215
+ """
216
+ Return a process group across the current node.
217
+
218
+ For example, given each row is a distinct node:
219
+ 0 1 2 3 4 5 6 7
220
+ 8 9 10 11 12 13 14 15
221
+ This API would return an intra-node subgroup across
222
+ [0, 1, ..., 7] or [8, 9, ..., 15] depending on the process's rank.
223
+ For example, rank 3 would get [0, 1, ..., 7].
224
+ """
225
+ intra_node_subgroup, _ = dist.new_subgroups(num_devices_per_node)
226
+ return intra_node_subgroup
227
+
228
+
229
+ @no_type_check
230
+ def _init_inter_node_process_group(
231
+ global_process_group: dist.ProcessGroup,
232
+ num_devices_per_node: int,
233
+ ) -> dist.ProcessGroup:
234
+ """
235
+ Return an inter-node process group where each contained rank has the same local rank.
236
+
237
+ For example, given each row is a distinct node:
238
+ 0 1 2 3 4 5 6 7
239
+ 8 9 10 11 12 13 14 15
240
+ This API would return inter-node process group [0, 8], [1, 9], [2, 10], and so forth
241
+ depending on the process's rank. For example, rank 1 would get [1, 9], rank 5
242
+ would get [5, 13].
243
+ """
244
+ # the inter-node pg that is returned
245
+ inter_node_pg = None
246
+ sharding_backend = dist.get_backend(global_process_group)
247
+ world_size = dist.get_world_size(global_process_group)
248
+ # Assuming fully homogeneous setup
249
+ num_nodes = world_size // num_devices_per_node
250
+ my_local_rank = dist.get_rank(global_process_group) % num_devices_per_node
251
+ for local_rank in range(num_devices_per_node):
252
+ ranks_for_inter_group = [
253
+ local_rank + (i * num_devices_per_node) for i in range(num_nodes)
254
+ ]
255
+ # every rank always needs to call dist.new_group
256
+ grp = dist.new_group(ranks=ranks_for_inter_group, backend=sharding_backend)
257
+ if local_rank == my_local_rank:
258
+ inter_node_pg = grp
259
+
260
+ assert (
261
+ inter_node_pg is not None
262
+ ), f"{my_local_rank} expected to assign inter-node pg, but did not"
263
+ return inter_node_pg
264
+
265
+
266
+ def _init_intra_and_inter_node_groups(
267
+ global_process_group: dist.ProcessGroup,
268
+ num_devices_per_node: int,
269
+ ) -> Tuple[dist.ProcessGroup, dist.ProcessGroup]:
270
+ """
271
+ Initialize intra and inter-node process groups and return the ones corresponding to this process's rank.
272
+
273
+ This function can be used to initialize process groups for ``HYBRID_SHARD`` or
274
+ ``_HYBRID_SHARD_ZERO2`` in FSDP.
275
+ This function assumes each node has an equal number of CUDA-enabled devices.
276
+ Returns:
277
+ Tuple[dist.ProcessGroup, dist.ProcessGroup]: Intra and inter-node process group.
278
+ """
279
+ return (
280
+ _init_intra_node_process_group(num_devices_per_node),
281
+ _init_inter_node_process_group(global_process_group, num_devices_per_node),
282
+ )
283
+
284
+
285
+ @no_type_check
286
+ def _init_ignored_module_states(
287
+ state: _FSDPState,
288
+ module: nn.Module,
289
+ ignored_modules: Optional[Iterable[torch.nn.Module]],
290
+ ignored_states: Union[
291
+ Optional[Iterable[torch.nn.Parameter]], Optional[Iterable[torch.nn.Module]]
292
+ ] = None,
293
+ ) -> _FSDPState:
294
+ if ignored_modules is not None and ignored_states is not None:
295
+ raise ValueError(
296
+ "Cannot pass both ignored_modules and ignored_states at the "
297
+ "same time. Please just pass ignored_states."
298
+ )
299
+ ignored_parameters = None
300
+ passed_as_ignored_states = ignored_states is not None
301
+ if passed_as_ignored_states:
302
+ ignored_states_list = list(ignored_states)
303
+ _check_ignored_states(ignored_states_list, True)
304
+ else:
305
+ ignored_states_list = []
306
+ _check_ignored_states(
307
+ list(ignored_modules) if ignored_modules is not None else [], False
308
+ )
309
+ if len(ignored_states_list) > 0:
310
+ if isinstance(ignored_states_list[0], nn.Parameter):
311
+ ignored_parameters = ignored_states_list
312
+ else:
313
+ ignored_modules = ignored_states_list
314
+ state._ignored_modules = _get_ignored_modules(module, ignored_modules)
315
+ state._ignored_params = _get_ignored_params(
316
+ module,
317
+ state._ignored_modules,
318
+ ignored_parameters,
319
+ )
320
+ state._ignored_buffer_names = _get_ignored_buffer_names(
321
+ module,
322
+ state._ignored_modules,
323
+ )
324
+ # TODO: FSDP's contract for buffers is not well-defined. They are
325
+ # implicitly ignored for most functionality since they are not sharded;
326
+ # however, FSDP still imposes some semantics on buffers (e.g. buffer mixed
327
+ # precision). We should formalize this contract and decide if we need to
328
+ # compute and store `_ignored_buffers`.
329
+ return state
330
+
331
+
332
+ def _check_ignored_states(
333
+ ignored_states: List[Any], passed_as_ignored_states: bool
334
+ ) -> None:
335
+ """
336
+ Check that the ignored states are uniformly parameters or uniformly modules.
337
+
338
+ We may remove this check in the future if we permit mixing.
339
+ """
340
+ if len(ignored_states) == 0:
341
+ return
342
+ if passed_as_ignored_states:
343
+ all_params = all(isinstance(state, nn.Parameter) for state in ignored_states)
344
+ all_modules = all(isinstance(state, nn.Module) for state in ignored_states)
345
+ if not all_params and not all_modules:
346
+ # Sort for consistent ordering for unit test regex matching
347
+ sorted_types = sorted({type(state) for state in ignored_states}, key=repr)
348
+ raise ValueError(
349
+ "ignored_states expects all nn.Parameter or all nn.Module list "
350
+ f"elements but got types {sorted_types}"
351
+ )
352
+ else:
353
+ if not all(isinstance(state, nn.Module) for state in ignored_states):
354
+ sorted_types = sorted({type(state) for state in ignored_states}, key=repr)
355
+ raise ValueError(
356
+ "ignored_modules expects nn.Module list elements but got "
357
+ f"types {sorted_types}"
358
+ )
359
+
360
+
361
+ @no_type_check
362
+ def _init_device_handle(
363
+ state: _FSDPState,
364
+ module: nn.Module,
365
+ ignored_params: Set[nn.Parameter],
366
+ device_id: Optional[Union[int, torch.device]],
367
+ ) -> _FSDPState:
368
+ """
369
+ Determine device handle used for initializing FSDP.
370
+
371
+ If a device is specified by ``device_id``,
372
+ then returns device handle corresponds to that device type. Otherwise, If the
373
+ module is already on a non-CPU device, then the device type is that non-CPU device type.
374
+ If the module is on CPU or meta, then the device type is the current accelerator device.
375
+ See the :ref:`Accelerators<accelerators>` for details.
376
+
377
+
378
+ This method will be called once ignored paramters was determined, as the device handle maybe needed
379
+ for other initialization.
380
+ """
381
+ determined_device = None
382
+ if device_id is not None:
383
+ determined_device = (
384
+ device_id
385
+ if isinstance(device_id, torch.device)
386
+ else torch.device(device_id)
387
+ )
388
+ if determined_device is None:
389
+ for param in _get_orig_params(module, ignored_params):
390
+ if param.device.type in {"cpu", "meta"}:
391
+ continue
392
+ if determined_device is None:
393
+ determined_device = param.device
394
+ else:
395
+ if param.device.type != determined_device.type:
396
+ raise RuntimeError(
397
+ f"FSDP does not support modules with different device types "
398
+ f"but got params on {determined_device.type} and {param.device.type}"
399
+ )
400
+ determined_device = determined_device or torch._C._get_accelerator()
401
+ if determined_device.type == "cpu":
402
+ raise RuntimeError(
403
+ "FSDP needs a non-CPU accelerator device, but no accelerator device is detected."
404
+ )
405
+
406
+ state._device_handle = _FSDPDeviceHandle.from_device(determined_device)
407
+ return state
408
+
409
+
410
+ @no_type_check
411
+ def _init_buffer_state(
412
+ state: _FSDPState,
413
+ module: nn.Module,
414
+ ) -> _FSDPState:
415
+ state._buffer_names = _get_buffer_names(module)
416
+ # Save a mapping from clean fully-qualified buffer name (starting from
417
+ # `module`) to its original dtype for restoring that dtype during model
418
+ # checkpointing when buffer mixed precision is enabled. The names should
419
+ # be clean since the casting happens in a `summon_full_params()` context.
420
+ _buffer_name_to_orig_dtype: Dict[str, torch.dtype] = {}
421
+ for buffer_name, buffer in module.named_buffers():
422
+ buffer_name = clean_tensor_name(buffer_name)
423
+ _buffer_name_to_orig_dtype[buffer_name] = buffer.dtype
424
+ state._buffer_name_to_orig_dtype = _buffer_name_to_orig_dtype
425
+ return state
426
+
427
+
428
+ @no_type_check
429
+ def _init_core_state(
430
+ state: _FSDPState,
431
+ sharding_strategy: Optional[ShardingStrategy],
432
+ mixed_precision: Optional[MixedPrecision],
433
+ cpu_offload: Optional[CPUOffload],
434
+ limit_all_gathers: bool,
435
+ use_orig_params: bool,
436
+ backward_prefetch_limit: int,
437
+ forward_prefetch_limit: int,
438
+ ) -> _FSDPState:
439
+ # We clamp the strategy to `NO_SHARD` for world size of 1 since they are
440
+ # currently functionally equivalent. This may change if/when we integrate
441
+ # FSDP with MoE.
442
+ if state.world_size == 1:
443
+ if sharding_strategy != ShardingStrategy.NO_SHARD:
444
+ warnings.warn(
445
+ "FSDP is switching to use `NO_SHARD` instead of "
446
+ f"{sharding_strategy or ShardingStrategy.FULL_SHARD} since "
447
+ "the world size is 1."
448
+ )
449
+ sharding_strategy = ShardingStrategy.NO_SHARD
450
+ elif sharding_strategy == ShardingStrategy.NO_SHARD:
451
+ warnings.warn(
452
+ "The `NO_SHARD` sharding strategy is deprecated. If having issues, "
453
+ "please use `DistributedDataParallel` instead.",
454
+ FutureWarning,
455
+ # Level 1 is here, level 2 is from `FullyShardedDataParallel`, and
456
+ # level 3 is from the true caller
457
+ stacklevel=3,
458
+ )
459
+ state.sharding_strategy = sharding_strategy or ShardingStrategy.FULL_SHARD
460
+ state.mixed_precision = mixed_precision or MixedPrecision()
461
+ if mixed_precision is not None:
462
+ torch._C._log_api_usage_once(
463
+ f"torch.distributed.fsdp.mixed_precision.{str(state.mixed_precision)}"
464
+ )
465
+ state._use_full_prec_in_eval = (
466
+ os.environ.get(_FSDP_USE_FULL_PREC_IN_EVAL, "") == "1"
467
+ )
468
+ state.cpu_offload = cpu_offload or CPUOffload()
469
+ state.limit_all_gathers = limit_all_gathers
470
+ state._use_orig_params = use_orig_params
471
+ state.training_state = TrainingState.IDLE
472
+ state._is_root = None
473
+ state._free_event_queue = _FreeEventQueue()
474
+ state._debug_level = dist.get_debug_level()
475
+ state._exec_order_data = exec_order_utils._ExecOrderData(
476
+ state._debug_level,
477
+ backward_prefetch_limit,
478
+ forward_prefetch_limit,
479
+ )
480
+ state._unshard_event = None
481
+ # Mapping from fully sharded module to the handles it is responsible to
482
+ # unshard and reshard (see [Note: Fully Sharded Module])
483
+ _fully_sharded_module_to_handle: Dict[nn.Module, FlatParamHandle] = {}
484
+ state._fully_sharded_module_to_handle = _fully_sharded_module_to_handle
485
+ # Invariant: `state.params` contains exactly the `FlatParameter`s of the
486
+ # handles in `state._handle`
487
+ _handle: Optional[FlatParamHandle] = None
488
+ state._handle = _handle
489
+ params: List[FlatParameter] = []
490
+ state.params = params
491
+ return state
492
+
493
+
494
+ @no_type_check
495
+ def _init_runtime_state(
496
+ state: _FSDPState,
497
+ ) -> _FSDPState:
498
+ _root_pre_forward_handles: List[RemovableHandle] = []
499
+ state._root_pre_forward_handles = _root_pre_forward_handles
500
+ _pre_forward_handles: List[RemovableHandle] = []
501
+ state._pre_forward_handles = _pre_forward_handles
502
+ _post_forward_handles: List[RemovableHandle] = []
503
+ state._post_forward_handles = _post_forward_handles
504
+ state._sync_gradients = True
505
+ state._comm_hook = None
506
+ state._comm_hook_state = None
507
+ # Used to prevent running the pre-backward hook multiple times
508
+ return state
509
+
510
+
511
+ @no_type_check
512
+ def _init_prefetching_state(
513
+ state: _FSDPState,
514
+ backward_prefetch: BackwardPrefetch,
515
+ forward_prefetch: bool,
516
+ ) -> _FSDPState:
517
+ state.backward_prefetch = backward_prefetch
518
+ state.forward_prefetch = forward_prefetch
519
+ # The data structures use tuples of handles to generalize over the case
520
+ # where a module's forward involves multiple handles.
521
+ return state
522
+
523
+
524
+ @no_type_check
525
+ def _init_extension(state: _FSDPState, device_mesh: DeviceMesh = None) -> _FSDPState:
526
+ # TODO: we need to add additional check once we support FSDP + PiPPy.
527
+ # This check is currently sufficient, since we only support FSDP + TP.
528
+ root_mesh = _mesh_resources.get_root_mesh(device_mesh)
529
+ # if a root mesh is not the same as device_mesh,
530
+ # meaning the device_mesh is sliced out from the root mesh.
531
+ if device_mesh and root_mesh != state._device_mesh:
532
+ state._fsdp_extension = DTensorExtensions(state._device_handle)
533
+ else:
534
+ # We need to explicilty set _fsdp_extension to None.
535
+ # Otherwise, we will run into an infinite recursion when getting the attribute.
536
+ state._fsdp_extension = None
537
+ return state
538
+
539
+
540
+ @no_type_check
541
+ def _init_state_dict_state(state: _FSDPState) -> _FSDPState:
542
+ state._state_dict_type = StateDictType.FULL_STATE_DICT
543
+ state_dict_config: StateDictConfig = FullStateDictConfig()
544
+ state._optim_state_dict_config = FullOptimStateDictConfig()
545
+ state._state_dict_config = state_dict_config
546
+ unshard_params_ctx: Dict[nn.Module, Generator] = {}
547
+ state._unshard_params_ctx = unshard_params_ctx
548
+
549
+ return state
550
+
551
+
552
+ def _verify_managed_params(module: nn.Module, params: List[nn.Parameter]) -> None:
553
+ """
554
+ Verify if the parameters are accepted by FSDP. The only restriction now
555
+ is that the parameter cannot be a scalar tensor (param.shape == []).
556
+ """
557
+ for param in params:
558
+ if len(param.shape) == 0:
559
+ param_name = ""
560
+ for name, param_ in module.named_parameters():
561
+ if param is param_:
562
+ param_name = name
563
+ break
564
+ assert param_name
565
+ raise ValueError(
566
+ "FSDP doesn't support salar parameters. "
567
+ f"Change {param_name} to a 1D tensor with numel equal to 1."
568
+ )
569
+
570
+
571
+ @no_type_check
572
+ def _init_param_handle_from_module(
573
+ state: _FSDPState,
574
+ fully_sharded_module: nn.Module,
575
+ device_id: Optional[Union[int, torch.device]],
576
+ param_init_fn: Optional[Callable[[nn.Module], None]],
577
+ sync_module_states: bool,
578
+ ) -> _FSDPState:
579
+ """Initialize a ``FlatParamHandle`` from a module ``fully_sharded_module``."""
580
+ _check_single_device_module(fully_sharded_module, state._ignored_params, device_id)
581
+ device_from_device_id = _get_device_from_device_id(
582
+ device_id, state.rank, state._device_handle
583
+ )
584
+ is_meta_module, is_torchdistX_deferred_init = _need_to_materialize_module(
585
+ fully_sharded_module, state._ignored_params, state._ignored_modules
586
+ )
587
+ # Materialize the module if needed
588
+ if (is_meta_module or is_torchdistX_deferred_init) and param_init_fn is not None:
589
+ _materialize_with_param_init_fn(
590
+ fully_sharded_module, param_init_fn, state._ignored_modules
591
+ )
592
+ elif is_meta_module:
593
+ _materialize_meta_module(
594
+ fully_sharded_module,
595
+ device_id,
596
+ state._ignored_modules,
597
+ state._device_handle,
598
+ )
599
+ elif is_torchdistX_deferred_init:
600
+ deferred_init.materialize_module(
601
+ fully_sharded_module,
602
+ check_fn=lambda submodule: _get_module_fsdp_state(submodule) is None
603
+ and submodule not in state._ignored_modules,
604
+ )
605
+
606
+ ignored_buffers = {
607
+ buffer
608
+ for ignored_module in state._ignored_modules
609
+ for buffer in ignored_module.buffers()
610
+ }
611
+
612
+ _move_module_to_device(
613
+ fully_sharded_module,
614
+ state._ignored_params,
615
+ ignored_buffers,
616
+ device_from_device_id,
617
+ )
618
+ state.compute_device = _get_compute_device(
619
+ fully_sharded_module,
620
+ state._ignored_params,
621
+ device_from_device_id,
622
+ state.rank,
623
+ state._device_handle,
624
+ )
625
+
626
+ managed_params = list(_get_orig_params(fully_sharded_module, state._ignored_params))
627
+ _verify_managed_params(fully_sharded_module, managed_params)
628
+ if sync_module_states:
629
+ _sync_module_params_and_buffers(
630
+ fully_sharded_module, managed_params, state.process_group
631
+ )
632
+ if state.sharding_strategy in HYBRID_SHARDING_STRATEGIES:
633
+ _sync_module_params_and_buffers(
634
+ fully_sharded_module, managed_params, state._inter_node_pg
635
+ )
636
+ _init_param_handle_from_params(state, managed_params, fully_sharded_module)
637
+ return state
638
+
639
+
640
+ @no_type_check
641
+ def _init_param_handle_from_params(
642
+ state: _FSDPState,
643
+ params: List[nn.Parameter],
644
+ fully_sharded_module: nn.Module,
645
+ ):
646
+ if len(params) == 0:
647
+ return
648
+ handle = FlatParamHandle(
649
+ params,
650
+ fully_sharded_module,
651
+ state.compute_device,
652
+ SHARDING_STRATEGY_MAP[state.sharding_strategy],
653
+ state.cpu_offload.offload_params,
654
+ state.mixed_precision.param_dtype,
655
+ state.mixed_precision.reduce_dtype,
656
+ state.mixed_precision.keep_low_precision_grads,
657
+ state.process_group,
658
+ state._use_orig_params,
659
+ fsdp_extension=state._fsdp_extension,
660
+ )
661
+ handle.shard()
662
+ assert not state._handle
663
+ state.params.append(handle.flat_param)
664
+ state._handle = handle
665
+ state._fully_sharded_module_to_handle[handle._fully_sharded_module] = handle
666
+ cpu_device = torch.device("cpu")
667
+ if state.cpu_offload.offload_params and handle.flat_param.device != cpu_device:
668
+ handle.flat_param_to(cpu_device)
669
+
670
+
671
+ def _get_ignored_modules(
672
+ root_module: nn.Module,
673
+ _ignored_modules: Optional[Iterable[torch.nn.Module]],
674
+ ) -> Set[nn.Module]:
675
+ """
676
+ Check that ``_ignored_modules`` is an iterable of ``nn.Module`` s without any FSDP instances.
677
+
678
+ Return the modules contained in their module
679
+ subtrees as a :class:`set`. Nested FSDP instances are excluded, but their
680
+ already-computed ignored modules are included.
681
+
682
+ ``_ignored_modules`` represents the argument passed by the user to FSDP.
683
+ """
684
+ msg_prefix = "`ignored_modules` should be an iterable of `torch.nn.Module`s "
685
+ try:
686
+ ignored_root_modules = (
687
+ set(_ignored_modules) if _ignored_modules is not None else set()
688
+ )
689
+ except TypeError as e:
690
+ raise TypeError(msg_prefix + f"but got {type(_ignored_modules)}") from e
691
+ for module in ignored_root_modules:
692
+ if not isinstance(module, torch.nn.Module):
693
+ raise TypeError(msg_prefix + f"but got an iterable with {type(module)}")
694
+ if _get_module_fsdp_state(module):
695
+ # TODO: We may relax this by taking the FSDP instance's wrapped
696
+ # module to provide more flexibility to the user.
697
+ raise ValueError("`ignored_modules` should not include FSDP modules")
698
+ # Treat modules that cannot compose with `fully_shard` as ignored modules,
699
+ # meaning that their subtrees are ignored
700
+ for module in root_module.modules():
701
+ if not traversal_utils._composable(module):
702
+ ignored_root_modules.add(module)
703
+ # NOTE: Even if `ignored_root_modules` is empty, do not return early so
704
+ # that this FSDP instance can get any ignored modules from its children.
705
+
706
+ # Include child modules and exclude nested FSDP modules themselves
707
+ ignored_modules = {
708
+ child
709
+ for module in ignored_root_modules
710
+ for child in module.modules()
711
+ if not isinstance(child, fsdp_file.FullyShardedDataParallel)
712
+ }
713
+ if root_module in ignored_modules:
714
+ warnings.warn(
715
+ "Trying to ignore the top-level module passed into the FSDP "
716
+ "constructor itself will result in all parameters being "
717
+ f"ignored and is not well-supported: {module}"
718
+ )
719
+ # Include nested FSDP modules' ignored modules
720
+ for submodule in root_module.modules():
721
+ optional_fsdp_state = _get_module_fsdp_state(submodule)
722
+ if optional_fsdp_state is not None:
723
+ assert hasattr(optional_fsdp_state, "_ignored_modules")
724
+ ignored_modules.update(optional_fsdp_state._ignored_modules)
725
+ return ignored_modules
726
+
727
+
728
+ def _get_ignored_params(
729
+ root_module: torch.nn.Module,
730
+ ignored_modules: Set[torch.nn.Module],
731
+ ignored_parameters: Optional[Iterable[torch.nn.Parameter]] = None,
732
+ ) -> Set[torch.nn.Parameter]:
733
+ """
734
+ Return the parameters of the modules in ``ignored_modules`` and the parameters in ``ignored_parameters``.
735
+
736
+ :class:`FlatParameter` s are excluded from the result.
737
+ """
738
+ all_ignored_params: Set[torch.nn.Parameter] = set()
739
+
740
+ params_in_ignored_modules = {
741
+ p for m in ignored_modules for p in m.parameters() if not _is_fsdp_flattened(p)
742
+ }
743
+
744
+ all_ignored_params.update(params_in_ignored_modules)
745
+
746
+ if ignored_parameters is not None:
747
+ params_in_ignored_parameters = {
748
+ p for p in ignored_parameters if not _is_fsdp_flattened(p)
749
+ }
750
+ all_ignored_params.update(params_in_ignored_parameters)
751
+
752
+ # Always include nested FSDP modules' ignored parameters
753
+ for submodule in root_module.modules():
754
+ optional_fsdp_state = _get_module_fsdp_state(submodule)
755
+ if optional_fsdp_state is not None:
756
+ assert hasattr(optional_fsdp_state, "_ignored_params")
757
+ all_ignored_params.update(optional_fsdp_state._ignored_params)
758
+
759
+ return all_ignored_params
760
+
761
+
762
+ def _get_ignored_buffer_names(
763
+ root_module: torch.nn.Module,
764
+ ignored_modules: Set[torch.nn.Module],
765
+ ) -> Set[str]:
766
+ """Return the cleaned buffer FQNs in ``ignored_modules``."""
767
+ all_ignored_buffer_names: Set[str] = set()
768
+
769
+ buffers_in_ignored_modules = {
770
+ buffer for m in ignored_modules for buffer in m.buffers()
771
+ }
772
+
773
+ all_ignored_buffer_names.update(
774
+ {
775
+ clean_tensor_name(buffer_name)
776
+ for buffer_name, buffer in root_module.named_buffers()
777
+ if buffer in buffers_in_ignored_modules
778
+ }
779
+ )
780
+
781
+ # Always include nested FSDP modules' ignored buffer names
782
+ for submodule in root_module.modules():
783
+ optional_fsdp_state = _get_module_fsdp_state(submodule)
784
+ if optional_fsdp_state is not None:
785
+ assert hasattr(optional_fsdp_state, "_ignored_buffer_names")
786
+ all_ignored_buffer_names.update(optional_fsdp_state._ignored_buffer_names)
787
+
788
+ return all_ignored_buffer_names
789
+
790
+
791
+ def _get_buffer_names(root_module: nn.Module) -> Set[str]:
792
+ """Return the fully prefixed names of all buffers in the module hierarchy rooted at ``root_module`` as a class:`set`."""
793
+ return {
794
+ clean_tensor_name(buffer_name) for buffer_name, _ in root_module.named_buffers()
795
+ }
796
+
797
+
798
+ def _check_single_device_module(
799
+ module: nn.Module,
800
+ ignored_params: Set[nn.Parameter],
801
+ device_id: Optional[Union[int, torch.device]],
802
+ ) -> None:
803
+ """
804
+ Raise an error if ``module`` has original parameters on multiple devices, ignoring the parameters in ``ignored_params``.
805
+
806
+ Thus, after this method, the
807
+ module must be either fully on the CPU or fully on a non-CPU device.
808
+ """
809
+ devices = {param.device for param in _get_orig_params(module, ignored_params)}
810
+ # We allow module to be partially on CPU and partially on GPU if device_id is not
811
+ # None, since the device_id arg will result in the CPU portion being moved to
812
+ # GPU. This is useful in cases where part of the module may be parallelized
813
+ # by another algorithm and may already be on GPU. We'd like to enforce device_id
814
+ # to not be None, otherwise we'd flatten parameters in a mixed module which is
815
+ # not supported.
816
+ if len(devices) == 2 and torch.device("cpu") in devices:
817
+ if device_id is None:
818
+ raise RuntimeError(
819
+ "To support a module with both CPU and GPU params, "
820
+ "please pass in device_id argument."
821
+ )
822
+ elif len(devices) > 1:
823
+ raise RuntimeError(
824
+ f"FSDP only supports single device modules but got params on {devices}"
825
+ )
826
+
827
+
828
+ def _get_device_from_device_id(
829
+ device_id: Optional[Union[int, torch.device]],
830
+ rank: int,
831
+ device_handle: _FSDPDeviceHandle,
832
+ ) -> Optional[torch.device]:
833
+ """
834
+ Return a ``torch.device`` for the specified ``device_id``.
835
+
836
+ Processes ``device_id`` and returns either the corresponding device or
837
+ ``None`` if ``device_id`` is ``None``.
838
+ """
839
+ if device_id is None:
840
+ return None
841
+ device = (
842
+ device_id if isinstance(device_id, torch.device) else torch.device(device_id)
843
+ )
844
+ if device.type != "cpu" and device.index is None:
845
+ warnings.warn(
846
+ f"FSDP got the argument `device_id` {device_id} on rank "
847
+ f"{rank}, which does not have an explicit index. "
848
+ f"FSDP will use the current device {device_handle.current_device()}. "
849
+ f"If this is incorrect, please explicitly call `torch.{device.type}.set_device()` "
850
+ "before FSDP initialization or pass in the explicit device "
851
+ "index as the `device_id` argument."
852
+ )
853
+ device = torch.device(device_handle.current_device())
854
+ return device
855
+
856
+
857
+ def _need_to_materialize_module(
858
+ module: nn.Module,
859
+ ignored_params: Set[nn.Parameter],
860
+ ignored_modules: Set[nn.Module],
861
+ ) -> Tuple[bool, bool]:
862
+ """
863
+ Return if ``module`` has parameters on meta device and if ``module`` is using torchdistX deferred initialization.
864
+
865
+ At most of the returned bools can
866
+ be ``True``. If either is ``True``, then ``module`` needs to be
867
+ materialized.
868
+ """
869
+ managed_params = list(_get_orig_params(module, ignored_params))
870
+ is_meta_module = any(param.is_meta for param in managed_params)
871
+ # TODO: We need to establish a contract for FSDP and buffers. For now, we
872
+ # skip checking for meta buffers from ignored modules. We should consider
873
+ # refactoring the initialization holistically to avoid so many traversals.
874
+ for submodule in module.modules():
875
+ if submodule in ignored_modules:
876
+ continue
877
+ for buf in submodule.buffers(recurse=False):
878
+ is_meta_module |= buf.is_meta
879
+ is_torchdistX_deferred_init = (
880
+ not is_meta_module
881
+ and _TORCHDISTX_AVAIL
882
+ and any(fake.is_fake(param) for param in managed_params)
883
+ )
884
+ return is_meta_module, is_torchdistX_deferred_init
885
+
886
+
887
+ def _materialize_with_param_init_fn(
888
+ root_module: nn.Module,
889
+ param_init_fn: Callable[[nn.Module], None],
890
+ ignored_modules: Set[nn.Module],
891
+ ) -> None:
892
+ if not callable(param_init_fn):
893
+ raise ValueError(
894
+ f"Expected {param_init_fn} to be callable but got {type(param_init_fn)}"
895
+ )
896
+ modules_to_materialize = _get_modules_to_materialize(root_module, ignored_modules)
897
+ for module in modules_to_materialize:
898
+ param_init_fn(module)
899
+
900
+
901
+ def _materialize_meta_module(
902
+ root_module: nn.Module,
903
+ device_from_device_id: Optional[torch.device],
904
+ ignored_modules: Set[nn.Module],
905
+ device_handle: _FSDPDeviceHandle,
906
+ ):
907
+ # Run default meta device initialization
908
+ materialization_device = device_from_device_id or torch.device(
909
+ device_handle.current_device()
910
+ )
911
+ modules_to_materialize = _get_modules_to_materialize(root_module, ignored_modules)
912
+ module = None
913
+ try:
914
+ # Assume that each module's `reset_parameters()` only initializes its
915
+ # own parameters and not those of its children
916
+ with torch.no_grad():
917
+ for module in modules_to_materialize:
918
+ # As a contract to the user, only call `reset_parameters()` if
919
+ # the module has directly managed parameters/buffers
920
+ module_state_iter = itertools.chain(
921
+ module.parameters(recurse=False), module.buffers(recurse=False)
922
+ )
923
+ has_module_states = len(list(module_state_iter)) > 0
924
+ if has_module_states:
925
+ module.to_empty(device=materialization_device, recurse=False)
926
+ module.reset_parameters() # type: ignore[operator]
927
+ except BaseException as e:
928
+ warnings.warn(
929
+ "Unable to call `reset_parameters()` for module on meta "
930
+ f"device with error {str(e)}. Please ensure that your module of"
931
+ f"type {type(module)} implements a `reset_parameters()` method." # type: ignore[possibly-undefined]
932
+ )
933
+ raise e
934
+
935
+
936
+ def _get_modules_to_materialize(
937
+ root_module: nn.Module, ignored_modules: Set[nn.Module]
938
+ ) -> List[nn.Module]:
939
+ # Run BFS to collect the modules to materialize via `reset_parameters()`,
940
+ # stopping at any module with FSDP already applied or at ignored modules.
941
+ modules_to_materialize: List[nn.Module] = []
942
+ queue = collections.deque([root_module])
943
+ visited_modules: Set[nn.Module] = {root_module}
944
+ while queue:
945
+ module = queue.popleft()
946
+ modules_to_materialize.append(module)
947
+ for child_module in module.children():
948
+ if (
949
+ child_module not in visited_modules
950
+ and _get_module_fsdp_state(child_module) is None
951
+ and child_module not in ignored_modules
952
+ ):
953
+ visited_modules.add(child_module)
954
+ queue.append(child_module)
955
+ return modules_to_materialize
956
+
957
+
958
+ def _move_module_to_device(
959
+ module: nn.Module,
960
+ ignored_params: Set[nn.Parameter],
961
+ ignored_buffers: Set[torch.Tensor],
962
+ device_from_device_id: Optional[torch.device],
963
+ ) -> None:
964
+ """
965
+ Move ``module`` depending on ``device_from_device_id`` and its current device.
966
+
967
+ This includes moving ignored modules' parameters.
968
+
969
+ - If ``device_from_device_id`` is not ``None``, then this moves
970
+ ``module`` to the device.
971
+ - If ``device_from_device_id`` is ``None``, then this does not move
972
+ ``module`` but warns the user if it is on CPU.
973
+
974
+ Precondition: ``_check_single_device_module()``.
975
+ """
976
+ cpu_device = torch.device("cpu")
977
+ if device_from_device_id is not None:
978
+ # BFS from `module` without traversing any nested FSDP instances to
979
+ # collect the parameters/buffers that have not yet been managed
980
+ queue: Deque[nn.Module] = collections.deque()
981
+ queue.append(module)
982
+ params: List[nn.Parameter] = []
983
+ buffers: List[torch.Tensor] = []
984
+ while queue:
985
+ curr_module = queue.popleft()
986
+ # NOTE: We include a check to only move parameters/buffers that are
987
+ # on CPU device. If they are on a CUDA device different from the
988
+ # one specified by `device_id`, then this does NOT move them. This
989
+ # is so that we can raise an error in `_get_compute_device()`.
990
+ params.extend(
991
+ param
992
+ for param in curr_module.parameters(recurse=False)
993
+ if param.device == cpu_device
994
+ )
995
+ buffers.extend(
996
+ buffer
997
+ for buffer in curr_module.buffers(recurse=False)
998
+ if buffer.device == cpu_device
999
+ )
1000
+ for submodule in curr_module.children():
1001
+ if not isinstance(submodule, fsdp_file.FullyShardedDataParallel):
1002
+ queue.append(submodule)
1003
+ params_to_move = [p for p in params if p not in ignored_params]
1004
+ bufs_to_move = [p for p in buffers if p not in ignored_buffers]
1005
+ _move_states_to_device(params_to_move, bufs_to_move, device_from_device_id)
1006
+ return
1007
+ param = next(_get_orig_params(module, ignored_params), None)
1008
+ if param is not None and param.device == cpu_device:
1009
+ _warn_cpu_init()
1010
+
1011
+
1012
+ def _move_states_to_device(
1013
+ params: List[nn.Parameter],
1014
+ buffers: List[torch.Tensor],
1015
+ device_from_device_id: Optional[torch.device],
1016
+ ) -> None:
1017
+ """
1018
+ Move states to the specified device.
1019
+
1020
+ Precondition: ``_check_single_device_module()`` and module's parameters and
1021
+ buffers have been materialized if needed.
1022
+ """
1023
+ if len(params) == 0 and len(buffers) == 0:
1024
+ return
1025
+ if len(params) > 0:
1026
+ current_device = params[0].device
1027
+ elif len(buffers) > 0:
1028
+ current_device = buffers[0].device
1029
+ cpu_device = torch.device("cpu")
1030
+ if device_from_device_id is not None:
1031
+ # Move the parameters and buffers like the `.data` code path in
1032
+ # `nn.Module._apply()`, which underlies `nn.Module.to()`
1033
+ for param in params:
1034
+ with torch.no_grad():
1035
+ param.data = param.to(device_from_device_id)
1036
+ if param.grad is not None:
1037
+ param.grad.data = param.grad.to(device_from_device_id)
1038
+ for buffer in buffers:
1039
+ buffer.data = buffer.to(device_from_device_id)
1040
+ elif current_device == cpu_device: # type: ignore[possibly-undefined]
1041
+ _warn_cpu_init()
1042
+
1043
+
1044
+ def _warn_cpu_init():
1045
+ warnings.warn(
1046
+ "The passed-in `module` is on CPU and will thus have FSDP's sharding "
1047
+ "initialization run on CPU, which may be slower than on GPU. We "
1048
+ "recommend passing in the `device_id` argument for FSDP to move "
1049
+ "`module` to GPU for the sharding initialization. `module` must also "
1050
+ "be on GPU device to work with the `sync_module_states=True` flag "
1051
+ "since that requires GPU communication."
1052
+ )
1053
+
1054
+
1055
+ def _get_compute_device(
1056
+ module: nn.Module,
1057
+ ignored_params: Set[nn.Parameter],
1058
+ device_from_device_id: Optional[torch.device],
1059
+ rank: int,
1060
+ device_handle: _FSDPDeviceHandle,
1061
+ ) -> torch.device:
1062
+ """
1063
+ Determine and return this FSDP instance's compute device.
1064
+
1065
+ If the module is already on a non-CPU device, then the compute device is that non-CPU
1066
+ device. If the module is on CPU, then the compute device is the current
1067
+ device.
1068
+
1069
+ Since this method should be called after materializing the module, any
1070
+ non-CPU device should not be meta device. For now, the compute device is
1071
+ always a CUDA or CUDA-like device with its explicit index.
1072
+
1073
+ Precondition: ``_check_single_device_module()`` and
1074
+ ``_move_module_to_device()``.
1075
+ """
1076
+ param = next(_get_orig_params(module, ignored_params), None)
1077
+ if param is not None and param.device.type != "cpu":
1078
+ compute_device = param.device # Determined by model param placement
1079
+ else:
1080
+ compute_device = torch.device(device_handle.current_device())
1081
+ if device_from_device_id is not None and compute_device != device_from_device_id:
1082
+ raise ValueError(
1083
+ f"Inconsistent compute device and `device_id` on rank {rank}: "
1084
+ f"{compute_device} vs {device_from_device_id}"
1085
+ )
1086
+ return compute_device
1087
+
1088
+
1089
+ # TODO: See how to deprecate!
1090
+ def _sync_module_params_and_buffers(
1091
+ module: nn.Module,
1092
+ params: List[nn.Parameter],
1093
+ process_group: dist.ProcessGroup,
1094
+ ) -> None:
1095
+ """
1096
+ Synchronize module states (i.e. parameters ``params`` and all not-yet-synced buffers) by broadcasting from rank 0 to all ranks.
1097
+
1098
+ Precondition: ``sync_module_states == True`` and ``self.process_group`` has
1099
+ been set.
1100
+ """
1101
+ module_states: List[torch.Tensor] = []
1102
+ for buffer in module.buffers():
1103
+ # Avoid re-synchronizing buffers in case of nested wrapping
1104
+ if not getattr(buffer, FSDP_SYNCED, False):
1105
+ setattr(buffer, FSDP_SYNCED, True)
1106
+ detached_buffer = buffer.detach()
1107
+ if is_traceable_wrapper_subclass(detached_buffer):
1108
+ # NOTE: Here we assume no nested subclasses, at most one level of subclass
1109
+ # in both model's buffers and params
1110
+ attrs, _ = detached_buffer.__tensor_flatten__() # type: ignore[attr-defined]
1111
+ inner_buffers = [getattr(detached_buffer, attr) for attr in attrs]
1112
+ module_states.extend(inner_buffers)
1113
+ else:
1114
+ module_states.append(detached_buffer)
1115
+
1116
+ for param in params:
1117
+ detached_param = param.detach()
1118
+ if is_traceable_wrapper_subclass(detached_param):
1119
+ attrs, _ = detached_param.__tensor_flatten__() # type: ignore[attr-defined]
1120
+ inner_params = [getattr(detached_param, attr) for attr in attrs]
1121
+ module_states.extend(inner_params)
1122
+ else:
1123
+ module_states.append(detached_param)
1124
+
1125
+ _check_module_states_for_sync_module_states(module_states)
1126
+ _sync_params_and_buffers(
1127
+ process_group,
1128
+ module_states,
1129
+ PARAM_BROADCAST_BUCKET_SIZE,
1130
+ src=0,
1131
+ )
1132
+
1133
+
1134
+ def _check_module_states_for_sync_module_states(
1135
+ module_states: List[torch.Tensor],
1136
+ ) -> None:
1137
+ if module_states and any(
1138
+ tensor.device == torch.device("cpu") for tensor in module_states
1139
+ ):
1140
+ raise ValueError(
1141
+ "The module has CPU parameters or buffers when `sync_module_states=True`, "
1142
+ "which requires them to be on GPU. Please specify the `device_id` argument "
1143
+ "or move the module to GPU before passing it to FSDP."
1144
+ )
1145
+
1146
+
1147
+ def _get_orig_params(
1148
+ module: nn.Module,
1149
+ ignored_params: Set[nn.Parameter],
1150
+ ) -> Iterator[nn.Parameter]:
1151
+ """
1152
+ Return an iterator over the original parameters in ``module``.
1153
+
1154
+ The iterator does not return
1155
+ the parameters in ``ignored_params``, any ``FlatParameter`` s (which may be
1156
+ present due to nested FSDP wrapping), or any original parameters already
1157
+ flattened (only relevant when ``use_orig_params=True``).
1158
+ """
1159
+ param_gen = module.parameters()
1160
+ try:
1161
+ while True:
1162
+ param = next(param_gen)
1163
+ if param not in ignored_params and not _is_fsdp_flattened(param):
1164
+ yield param
1165
+ except StopIteration:
1166
+ pass
1167
+
1168
+
1169
+ def _check_orig_params_flattened(
1170
+ fsdp_module,
1171
+ ignored_params: Set[nn.Parameter],
1172
+ ) -> None:
1173
+ """
1174
+ Check that original parameters in ``fsdp_module`` have been flattened.
1175
+
1176
+ The flattened parameters are made
1177
+ invisible to ``named_parameters()`` for the module hierarchy rooted at
1178
+ ``fsdp_module``. This should be called as a sanity check after flattening
1179
+ the wrapped module's parameters.
1180
+ """
1181
+ for param_name, param in _named_parameters_with_duplicates(fsdp_module):
1182
+ if param not in ignored_params and not _is_fsdp_flattened(param):
1183
+ raise RuntimeError(
1184
+ f"Found an unflattened parameter: {param_name}; "
1185
+ f"{param.size()} {param.__class__}"
1186
+ )
1187
+
1188
+
1189
+ def _get_default_comm_hook(sharding_strategy: ShardingStrategy):
1190
+ return (
1191
+ default_hooks.allreduce_hook
1192
+ if sharding_strategy == ShardingStrategy.NO_SHARD
1193
+ else default_hooks.reduce_scatter_hook
1194
+ )
1195
+
1196
+
1197
+ def _get_default_comm_hook_state(
1198
+ process_group: dist.ProcessGroup,
1199
+ ) -> default_hooks.DefaultState:
1200
+ return default_hooks.DefaultState(process_group=process_group)
vllm/lib/python3.10/site-packages/torch/distributed/fsdp/_limiter_utils.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ from typing import Deque, Optional
3
+
4
+ import torch
5
+
6
+
7
+ class _FreeEventQueue:
8
+ """
9
+ This tracks all pending frees corresponding to inflight all-gathers. The
10
+ queueing pattern is iterative enqueues with a single dequeue per iteration
11
+ once the limit ``_max_num_inflight_all_gathers`` is reached.
12
+ """
13
+
14
+ def __init__(self) -> None:
15
+ self._queue: Deque[torch.Event] = collections.deque()
16
+ self._max_num_inflight_all_gathers = 2 # empirically chosen
17
+
18
+ def enqueue(self, free_event: torch.Event) -> None:
19
+ """Enqueues a free event."""
20
+ self._queue.append(free_event)
21
+
22
+ def dequeue_if_needed(self) -> Optional[torch.Event]:
23
+ """Dequeues a single event if the limit is reached."""
24
+ if len(self._queue) >= self._max_num_inflight_all_gathers:
25
+ return self._dequeue()
26
+ return None
27
+
28
+ def _dequeue(self) -> Optional[torch.Event]:
29
+ """Dequeues a free event if possible."""
30
+ if self._queue:
31
+ event = self._queue.popleft()
32
+ return event
33
+ return None
vllm/lib/python3.10/site-packages/torch/distributed/fsdp/_optim_utils.py ADDED
@@ -0,0 +1,2091 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import copy
3
+ import functools
4
+ import logging
5
+ import warnings
6
+ from contextlib import ExitStack
7
+ from dataclasses import dataclass, field
8
+ from typing import (
9
+ Any,
10
+ cast,
11
+ Dict,
12
+ Iterable,
13
+ Iterator,
14
+ List,
15
+ NamedTuple,
16
+ no_type_check,
17
+ Optional,
18
+ Sequence,
19
+ Set,
20
+ Tuple,
21
+ TYPE_CHECKING,
22
+ Union,
23
+ )
24
+
25
+ import torch
26
+ import torch.distributed as dist
27
+ import torch.distributed.fsdp._traversal_utils as traversal_utils
28
+ import torch.nn as nn
29
+ from torch.distributed._state_dict_utils import _gather_state_dict
30
+ from torch.distributed.distributed_c10d import _get_pg_default_device
31
+ from torch.distributed.fsdp._common_utils import (
32
+ _apply_to_modules,
33
+ _FSDPState,
34
+ _get_module_fsdp_state_if_fully_sharded_module,
35
+ _get_param_to_fqns,
36
+ _module_handle,
37
+ _named_parameters_with_duplicates,
38
+ clean_tensor_name,
39
+ )
40
+ from torch.distributed.fsdp._debug_utils import SimpleProfiler
41
+ from torch.distributed.fsdp._flat_param import FlatParameter, FlatParamHandle
42
+ from torch.distributed.fsdp._fsdp_extensions import (
43
+ _ext_chunk_dtensor,
44
+ _ext_chunk_tensor,
45
+ )
46
+ from torch.distributed.fsdp._runtime_utils import (
47
+ _lazy_init,
48
+ _reset_flat_param_grad_info_if_needed,
49
+ )
50
+ from torch.distributed.fsdp.api import (
51
+ ShardingStrategy,
52
+ StateDictSettings,
53
+ StateDictType,
54
+ )
55
+ from torch.distributed.tensor import DTensor, Replicate
56
+ from torch.utils._pytree import tree_map_only
57
+
58
+
59
+ if TYPE_CHECKING:
60
+ from torch.distributed._shard.sharded_tensor import ShardedTensor
61
+
62
+
63
+ logger = logging.getLogger(__name__)
64
+
65
+
66
+ @dataclass
67
+ class FSDPParamInfo:
68
+ state: _FSDPState
69
+ handle: FlatParamHandle
70
+ param_indices: Dict[str, int]
71
+ param_requires_grad: List[bool]
72
+
73
+
74
+ def sorted_items(dictionary: Dict[str, Any]) -> Iterator[Tuple[str, Any]]:
75
+ keys = sorted(dictionary.keys())
76
+ for k in keys:
77
+ yield k, dictionary[k]
78
+
79
+
80
+ @dataclass
81
+ class _ConsolidatedOptimState:
82
+ """
83
+ This holds the consolidated optimizer state on the target rank. Positive-
84
+ dimension tensor state is communicated across ranks, while zero-dimension
85
+ tensor state and non-tensor state is taken directly from the target rank.
86
+
87
+ PyTorch version 1.12 moved to using zero-dimension tensors for scalar
88
+ values, but user implemented optimizers may still use float (i.e. a
89
+ non-tensor). Thus, we support both and handle them identically.
90
+
91
+ Attributes:
92
+ tensor_state (Dict[str, torch.Tensor]): Mapping from positive-dimension
93
+ tensor state name to the unsharded flat tensor representing the
94
+ state.
95
+ zero_dim_tensor_state (Dict[str, torch.Tensor]): Mapping from zero-
96
+ dimension tensor state name to its value.
97
+ non_tensor_state (Dict[str, Any]): Mapping from non-tensor state
98
+ name to its value.
99
+ """
100
+
101
+ tensor_state: Dict[str, torch.Tensor] = field(default_factory=dict)
102
+ zero_dim_tensor_state: Dict[str, torch.Tensor] = field(default_factory=dict)
103
+ non_tensor_state: Dict[str, Any] = field(default_factory=dict)
104
+
105
+
106
+ class _PosDimTensorInfo(NamedTuple):
107
+ """
108
+ Meatadata for positive-dimension tensors used internally for
109
+ :meth:`scatter_full_optim_state_dict`.
110
+
111
+ Attributes:
112
+ shape (torch.Size): Sharded tensor shape (which is equal to the
113
+ unsharded tensor shape if the tensor is optimizer state for a
114
+ non-FSDP parameter and is hence not sharded).
115
+ dtype (torch.dtype): Data type of the tensor.
116
+ """
117
+
118
+ shape: torch.Size
119
+ dtype: torch.dtype
120
+
121
+
122
+ class _OptimStateKey(NamedTuple):
123
+ """
124
+ This represents an optimizer state key that may be used commonly across
125
+ ranks. It is based on the unflattened parameter names rather than parameter
126
+ IDs to make it independent of each rank's own optimizer construction.
127
+ """
128
+
129
+ unflat_param_names: Tuple[str, ...]
130
+ is_fsdp_managed: bool
131
+
132
+
133
+ def _unflatten_optim_state(
134
+ fsdp_param_info: FSDPParamInfo,
135
+ flat_param_state: Dict[str, Any],
136
+ to_save: bool,
137
+ shard_state: bool,
138
+ cpu_offload: bool,
139
+ ) -> List[Dict[str, Any]]:
140
+ """
141
+ Unflattens the optimizer state, consisting of the "state" part and the
142
+ "param_groups" part. Unflattening the "state" part involves consolidating
143
+ the state on the target rank and remapping from flattened to unflattened
144
+ parameter IDs, and the "param_groups" part only involves remapping from
145
+ flattened to unflattened parameter IDs.
146
+
147
+ Args:
148
+ fsdp_param_info (FSDPParamInfo): The FSDP state, the handle, and a
149
+ mapping from FQN to original parameter index.
150
+ flat_param_state (Dict[str, Any]): Entry for the flat parameter in the
151
+ "state" part of the optimizer state dict.
152
+ to_save (bool): Whether to save the state on this rank.
153
+
154
+ Returns:
155
+ List[Dict[str, Any]]: A :class:`list` holding the entries in the
156
+ "state" part of the optimizer state dict corresponding to the
157
+ unflattened parameters comprising the flat parameter if on the target
158
+ rank or an empty :class:`list` otherwise. The final optimizer state
159
+ dict will need to map these entries using the proper unflattened
160
+ parameter IDs.
161
+ """
162
+ assert (
163
+ not shard_state or to_save
164
+ ), "If ``shard_state`` is True, ``to_save`` has to be True."
165
+ consolidated_state = _communicate_optim_state(
166
+ fsdp_param_info,
167
+ flat_param_state,
168
+ )
169
+ if to_save:
170
+ unflat_param_state = _unflatten_communicated_optim_state(
171
+ fsdp_param_info,
172
+ consolidated_state,
173
+ shard_state,
174
+ )
175
+ for optim_state in unflat_param_state:
176
+ # We can't use .items() below cuz we'd run into a concurrent modification error
177
+ if cpu_offload:
178
+ for key in list(optim_state.keys()):
179
+ state = optim_state[key]
180
+ if not isinstance(state, torch.Tensor):
181
+ continue
182
+ optim_state[key] = state.cpu()
183
+ return unflat_param_state
184
+ else:
185
+ return []
186
+
187
+
188
+ def _is_zero_dim_tensor(x: Any) -> bool:
189
+ return torch.is_tensor(x) and x.dim() == 0
190
+
191
+
192
+ def _communicate_optim_state(
193
+ fsdp_param_info: FSDPParamInfo,
194
+ flat_param_state: Dict[str, Any],
195
+ ) -> _ConsolidatedOptimState:
196
+ """
197
+ Communicates the optimizer state for a flat parameter across ranks. All
198
+ ranks will hold the entire non-sharded optimizer state on GPU.
199
+
200
+ If ``N`` is the number of tensor optimizer states in the optimizer state
201
+ dict, then the communication complexity is 0 if ``N = 0`` and ``N + 1``
202
+ otherwise (where the plus 1 comes from all-gathering the padding per rank).
203
+
204
+ Args:
205
+ fsdp_param_info (FSDPParamInfo): The FSDP state, the handle, and a
206
+ mapping from FQN to original parameter index.
207
+ flat_param_state (Dict[str, Any]): The entry in the "state" part of the
208
+ optimizer state dict corresponding to the flat parameter.
209
+
210
+ Returns:
211
+ ConsolidatedOptimState: Consolidated optimizer state for the target
212
+ flat parameter.
213
+ """
214
+ fsdp_state = fsdp_param_info.state
215
+ flat_param = fsdp_param_info.handle.flat_param
216
+ state = _ConsolidatedOptimState()
217
+ tensor_state, zero_dim_tensor_state, non_tensor_state = (
218
+ state.tensor_state,
219
+ state.zero_dim_tensor_state,
220
+ state.non_tensor_state,
221
+ )
222
+
223
+ for state_name, value in sorted_items(flat_param_state):
224
+ # Positive-dimension tensor state: communicate across ranks
225
+ if torch.is_tensor(value) and value.dim() > 0:
226
+ # If the parameter is not sharded, then neither is the
227
+ # positive-dimension tensor state, so no need to communicate it --
228
+ # we take the target rank's value
229
+ if (
230
+ fsdp_state.world_size == 1
231
+ or fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD
232
+ ):
233
+ tensor_state[state_name] = value
234
+ continue
235
+ assert (
236
+ fsdp_state.compute_device is not None
237
+ ), "compute_device has not been initialized"
238
+ if value.device.type != fsdp_state.compute_device.type:
239
+ value = value.to(fsdp_state.compute_device)
240
+ # Assume that positive-dimension tensor optimizer state
241
+ # has the same shape as the sharded flat parameter
242
+ buffer_size = flat_param._full_param_padded.size() # type: ignore[attr-defined]
243
+ tensor_buffer = value.new_zeros(*buffer_size)
244
+ dist.all_gather_into_tensor(
245
+ tensor_buffer, value, group=fsdp_state.process_group
246
+ )
247
+ fsdp_state._device_handle.synchronize()
248
+ unpadded_numel = cast(
249
+ nn.Parameter, flat_param._unpadded_unsharded_size
250
+ ).numel()
251
+ tensor_state[state_name] = tensor_buffer[:unpadded_numel]
252
+ # Zero-dimension tensor state and non-tensor state: take this rank's
253
+ # value directly
254
+ else:
255
+ if _is_zero_dim_tensor(value):
256
+ zero_dim_tensor_state[state_name] = value.detach().clone()
257
+ else:
258
+ non_tensor_state[state_name] = value
259
+ return state
260
+
261
+
262
+ def _unflatten_communicated_optim_state(
263
+ fsdp_param_info: FSDPParamInfo,
264
+ state: _ConsolidatedOptimState,
265
+ shard_state: bool,
266
+ ) -> List[Dict[str, Any]]:
267
+ """
268
+ Unflattens the communicated optimizer state (given by ``tensor_state``,
269
+ ``non_tensor_state``, and ``zero_dim_tensor_state``) for a single flat
270
+ parameter. This should only be called on the target rank.
271
+
272
+ Args:
273
+ fsdp_param_info (FSDPParamInfo): The FSDP state, the handle, and a
274
+ mapping from FQN to original parameter index.
275
+ state (_ConsolidatedOptimState): Consolidated optimizer state.
276
+
277
+ Returns:
278
+ List[Dict[str, Any]]: A :class:`list` holding the entries in the
279
+ "state" part of the optimizer state dict corresponding to the
280
+ unflattened parameters comprising the flat parameter. The final
281
+ optimizer state dict will need to map these entries using the proper
282
+ unflattened parameter IDs.
283
+ """
284
+ fsdp_state = fsdp_param_info.state
285
+ handle = fsdp_param_info.handle
286
+ flat_param = handle.flat_param
287
+ unflat_param_state: List[Dict[str, Any]] = []
288
+ flat_param_views: Dict[str, Iterator] = {}
289
+ num_unflat_params = flat_param._num_params
290
+ tensor_state, zero_dim_tensor_state, non_tensor_state = (
291
+ state.tensor_state,
292
+ state.zero_dim_tensor_state,
293
+ state.non_tensor_state,
294
+ )
295
+
296
+ for _ in range(num_unflat_params):
297
+ unflat_state_param = {}
298
+ # Add positive-dimension tensor state: unflatten with views
299
+ for state_name, flat_tensor in sorted_items(tensor_state):
300
+ views_generated = state_name in flat_param_views
301
+ if not views_generated:
302
+ views = handle._get_unflat_views(flat_tensor)
303
+ flat_param_views[state_name] = views
304
+ else:
305
+ views = flat_param_views[state_name]
306
+ optim_state: Union[torch.Tensor, ShardedTensor, DTensor] = next(views)
307
+ if shard_state:
308
+ osd_config = fsdp_state._optim_state_dict_config
309
+ if getattr(osd_config, "_use_dtensor", False):
310
+ assert fsdp_state._device_mesh is not None
311
+ optim_state = _ext_chunk_dtensor(
312
+ optim_state,
313
+ fsdp_state.rank,
314
+ fsdp_state._device_mesh,
315
+ fsdp_state._fsdp_extension,
316
+ )
317
+ else:
318
+ assert fsdp_state.process_group is not None
319
+ optim_state = _ext_chunk_tensor(
320
+ optim_state,
321
+ fsdp_state.rank,
322
+ fsdp_state.world_size,
323
+ fsdp_state._device_handle.device_count(),
324
+ fsdp_state.process_group,
325
+ fsdp_state._fsdp_extension,
326
+ )
327
+ unflat_state_param[state_name] = optim_state
328
+
329
+ # Add zero-dimension tensor state: take the target rank's value
330
+ for state_name, zero_dim_tensor in sorted_items(zero_dim_tensor_state):
331
+ unflat_state_param[state_name] = zero_dim_tensor
332
+ # Add non-tensor state: take the target rank's value
333
+ for state_name, non_tensor in sorted_items(non_tensor_state):
334
+ unflat_state_param[state_name] = non_tensor
335
+ unflat_param_state.append(unflat_state_param)
336
+ return unflat_param_state
337
+
338
+
339
+ def _broadcast_processed_state(
340
+ fsdp_state: _FSDPState,
341
+ optim_state: Dict[str, Any],
342
+ group: Optional[dist.ProcessGroup],
343
+ ) -> Dict[str, Any]:
344
+ objects: List[Any] = [None]
345
+ if dist.get_rank(group) == 0:
346
+ objects[0] = tree_map_only(
347
+ torch.Tensor,
348
+ lambda v: v.cpu() if v.dim() == 0 else _PosDimTensorInfo(v.shape, v.dtype), # type: ignore[union-attr]
349
+ optim_state,
350
+ )
351
+ dist.broadcast_object_list(objects, src=0, group=group)
352
+ if dist.get_rank(group) == 0:
353
+ return optim_state
354
+ else:
355
+ return objects[0]
356
+
357
+
358
+ def _broadcast_state(
359
+ fsdp_state: _FSDPState, state: Any, group: Optional[dist.ProcessGroup]
360
+ ) -> Any:
361
+ if dist.get_rank(group) == 0:
362
+ if not isinstance(state, torch.Tensor) or state.dim() == 0:
363
+ return state
364
+ tensor = state.to(fsdp_state.compute_device)
365
+ else:
366
+ if isinstance(state, torch.Tensor):
367
+ assert state.dim() == 0, (
368
+ "For non-zero ranks, a tensor state should have zero dimension, "
369
+ "but got the state with shape {state.shape()}."
370
+ )
371
+ return state
372
+ elif not isinstance(state, _PosDimTensorInfo):
373
+ return state
374
+ tensor = torch.zeros(
375
+ state.shape, dtype=state.dtype, device=fsdp_state.compute_device
376
+ )
377
+ dist.broadcast(tensor, src=0, group=group)
378
+ return tensor
379
+
380
+
381
+ def _shard_orig_param_state(
382
+ fsdp_param_info: FSDPParamInfo,
383
+ fqn: str,
384
+ optim_state: Dict[str, Any],
385
+ ) -> Dict[str, Any]:
386
+ """
387
+ Shard the optimizer state for the original parameter with the name ``fqn``.
388
+ This API should only be used when ``use_orig_params`` is True.
389
+ """
390
+ if not optim_state:
391
+ return {}
392
+ fsdp_state = fsdp_param_info.state
393
+ flat_param = fsdp_param_info.handle.flat_param
394
+ param_idx = fsdp_param_info.param_indices[fqn]
395
+ shard_param_info = flat_param._shard_param_infos[param_idx] # type: ignore[attr-defined]
396
+ optim_state = _gather_state_dict(
397
+ optim_state, pg=fsdp_state.process_group, device=fsdp_state.compute_device
398
+ )
399
+ if not shard_param_info.in_shard:
400
+ return {}
401
+ # Flatten and shard the state.
402
+ new_optim_state: Dict[str, Any] = {}
403
+ intra_param_start_idx = shard_param_info.intra_param_start_idx
404
+ intra_param_end_idx = shard_param_info.intra_param_end_idx
405
+ for state_name, value in optim_state.items():
406
+ if (
407
+ torch.is_tensor(value)
408
+ and value.dim() > 0
409
+ and fsdp_state.sharding_strategy != ShardingStrategy.NO_SHARD
410
+ ):
411
+ value = value.flatten()[intra_param_start_idx : intra_param_end_idx + 1].clone() # type: ignore[operator]
412
+ new_optim_state[state_name] = value
413
+ return new_optim_state
414
+
415
+
416
+ def _flatten_optim_state_dict(
417
+ optim_state_dict: Dict[str, Any],
418
+ model: nn.Module,
419
+ use_orig_params: bool = False,
420
+ optim: Optional[torch.optim.Optimizer] = None,
421
+ rank0_only: bool = False,
422
+ group: Optional[dist.ProcessGroup] = None,
423
+ ) -> Dict[str, Any]:
424
+ """
425
+ Flattens the full optimizer state dict, still keying by unflattened parameter
426
+ names.
427
+
428
+ If ``use_orig_params`` is True, each rank will have all FSDP-managed
429
+ parameters but some of these parameters may be empty due to the sharding.
430
+ For a regular optim.Optimizer, states for those empty parameters will
431
+ not be initialized. So, when aggregating the FQNs across ranks, no assert
432
+ will be raised on a rank even if it does not have all the states -- it is
433
+ valid and FSDP know how to aggregate them. However, FSDP has to ignore
434
+ handling those parameters that are not managed by FSDP and do not exist on
435
+ the local rank -- it is managed by other parallelism and FSDP does not
436
+ know ho to handle/aggregate them.
437
+
438
+ Note that ``_flatten_tensor_optim_state`` does not need ``optim`` to
439
+ flatten/shard the state. However, NamedOptimizer and KeyedOptimizer require
440
+ all the states even if the corresponding parameters are empty. To this end,
441
+ ``optim`` will be used to to get the initial state of the empty parameters.
442
+ ``optim`` should only be non-None if the ``optim` is KeyedOptimizer or
443
+ NamedOptimizer.
444
+
445
+ Returns:
446
+ Dict[str, Any]: The flattened optimizer state dict.
447
+ """
448
+ SimpleProfiler.reset()
449
+
450
+ unflat_osd = optim_state_dict
451
+ if "state" not in unflat_osd and not rank0_only:
452
+ raise ValueError(
453
+ '`optim_state_dict` must have the keys "state"'
454
+ "to be a valid optimizer state dict"
455
+ )
456
+ param_to_fqns = _get_param_to_fqns(model)
457
+ fqn_to_fsdp_param_info = _get_fqn_to_fsdp_param_info(model)
458
+ fsdp_state = next(iter(fqn_to_fsdp_param_info.values())).state
459
+
460
+ # Broadcast unflat_osd without non-scalar tensor if rank0_only is True.
461
+ if rank0_only:
462
+ unflat_osd = _broadcast_processed_state(fsdp_state, unflat_osd, group=group)
463
+
464
+ # Construct the "state" part
465
+ flat_osd_state: Dict[Union[_OptimStateKey, str], Any] = {}
466
+ unflat_osd_state = unflat_osd["state"]
467
+ all_state_keys = set(unflat_osd_state.keys())
468
+
469
+ for param, fqns in param_to_fqns.items():
470
+ fqn = fqns[0]
471
+ if fqn not in unflat_osd_state:
472
+ continue
473
+ all_state_keys.difference_update(fqns)
474
+
475
+ if rank0_only:
476
+ for fqn in fqns:
477
+ if not unflat_osd_state[fqn]:
478
+ continue
479
+ for state_name in unflat_osd_state[fqn].keys():
480
+ unflat_osd_state[fqn][state_name] = _broadcast_state(
481
+ fsdp_state, unflat_osd_state[fqn][state_name], group=group
482
+ )
483
+ fqn = fqns[0]
484
+ if fqn in fqn_to_fsdp_param_info:
485
+ fsdp_param_info = fqn_to_fsdp_param_info[fqn]
486
+ if use_orig_params:
487
+ with SimpleProfiler.profile(SimpleProfiler.Type.RESHARDING):
488
+ flat_state = _shard_orig_param_state(
489
+ fsdp_param_info,
490
+ fqn,
491
+ unflat_osd_state[fqn],
492
+ )
493
+ else:
494
+ flat_state = _flatten_optim_state(
495
+ fsdp_param_info,
496
+ unflat_osd_state,
497
+ fqns,
498
+ )
499
+ key = _OptimStateKey(tuple(fqns), True)
500
+ # Only include non-empty states since as expected by
501
+ # `torch.optim.Optimizer` s unless the optimizer is KeyedOptimizer
502
+ # or NamedOptimizer.
503
+ if flat_state:
504
+ flat_osd_state[key] = flat_state
505
+ elif use_orig_params:
506
+ assert (
507
+ len(fqns) == 1
508
+ ), f"use_orig_params is True but there are multiple FQNs, {fqns}."
509
+ if optim is not None: # NamedOptimizer or KeyedOptimizer case.
510
+ state = optim.state.get(param, None) # type: ignore[call-overload]
511
+ if state is not None:
512
+ flat_osd_state[key] = copy.deepcopy(state)
513
+ else:
514
+ warnings.warn(
515
+ f"optim_state[{key}] is not on rank{fsdp_state.rank}."
516
+ )
517
+
518
+ else:
519
+ raise RuntimeError(
520
+ f"The state of {key} is empty. This should happen when "
521
+ "use_orig_params=True."
522
+ )
523
+ else: # do not flatten non-FSDP parameters' states
524
+ assert len(fqns) == 1
525
+ key = _OptimStateKey(tuple(fqns), False)
526
+ flat_osd_state[key] = copy.copy(unflat_osd_state[fqn])
527
+
528
+ if rank0_only:
529
+ for fqn in fqns:
530
+ if not unflat_osd_state[fqn]:
531
+ continue
532
+ for state_name, param_state in list(unflat_osd_state[fqn].items()):
533
+ if fsdp_state.rank > 0:
534
+ # Deference the tensor so that PyTorch can collect the memory.
535
+ del unflat_osd_state[fqn][state_name]
536
+ else:
537
+ # Move the tensor in the original osd back to CPU to make the
538
+ # original osd unaffected.
539
+ unflat_osd_state[fqn][state_name] = unflat_osd_state[fqn][
540
+ state_name
541
+ ].cpu()
542
+
543
+ # Handle user-defined state, states that are not associated with parameters.
544
+ for key in all_state_keys:
545
+ user_state = unflat_osd_state[key]
546
+ if isinstance(user_state, torch.Tensor) and rank0_only and use_orig_params:
547
+ user_state = _broadcast_state(fsdp_state, user_state, group=group)
548
+ flat_osd_state[key] = copy.copy(user_state)
549
+
550
+ SimpleProfiler.dump_and_reset("FSDP _flatten_optim_state_dict() profiling: ")
551
+ # Construct the "param_groups" part -- copy as is since it will be
552
+ # rekeyed later according to the target rank's optimizer
553
+ # Only copy param_groups if it exists in unflat_osd
554
+ if "param_groups" in unflat_osd:
555
+ flat_osd_param_groups = copy.deepcopy(unflat_osd["param_groups"])
556
+ return {"state": flat_osd_state, "param_groups": flat_osd_param_groups}
557
+ else:
558
+ return {"state": flat_osd_state}
559
+
560
+
561
+ def _flatten_optim_state(
562
+ fsdp_param_info: FSDPParamInfo,
563
+ unflat_osd_state: Dict[str, Dict[str, Any]],
564
+ unflat_param_names: List[str],
565
+ ) -> Dict[str, Any]:
566
+ """
567
+ Flattens the optimizer state in ``full_optim_state_dict`` for a single
568
+ flat parameter in ``fsdp_param_info`` corresponding to the unflattened
569
+ parameter names in ``unflat_param_names``.
570
+
571
+ Args:
572
+ fsdp_param_info (FSDPParamInfo): The FSDP state, the handle, and a
573
+ mapping from FQN to original parameter index.
574
+ unflat_osd_state (Dict[str, Dict[str, Any]]): The "state" part of the
575
+ optimizer state dict corresponding to the unflattened parameters.
576
+ unflat_param_names (List[str]): A :class:`list` of unflattened
577
+ parameter names corresponding to the flat parameter ``flat_param``.
578
+
579
+ Returns:
580
+ Dict[str, Any]: A :class:`dict` mapping state names to their values for
581
+ a particular flat parameter. The sharded optimizer state dict's "state"
582
+ part will map a key to this returned value.
583
+ """
584
+ fsdp_state = fsdp_param_info.state
585
+ handle = fsdp_param_info.handle
586
+ flat_param = handle.flat_param
587
+ num_unflat_params = len(unflat_param_names)
588
+ assert num_unflat_params > 0, (
589
+ "Expects at least one unflattened parameter corresponding to the "
590
+ "flat parameter"
591
+ )
592
+ unflat_param_shapes = flat_param._shapes
593
+ num_unflat_param_shapes = len(unflat_param_shapes)
594
+ assert (
595
+ num_unflat_params == num_unflat_param_shapes
596
+ ), f"Expects {num_unflat_params} shapes but got {num_unflat_param_shapes}"
597
+
598
+ # Check if these unflattened parameters have any optimizer state
599
+ has_state = [
600
+ bool(unflat_param_name in unflat_osd_state)
601
+ for unflat_param_name in unflat_param_names
602
+ ]
603
+ # If none of the unflattened parameters comprising this flat parameter have
604
+ # any state, then we do not want an entry in the optimizer state dict
605
+ if not any(has_state):
606
+ return {} # no need to flatten any state
607
+ # There may still be some unflattened parameters with state and some
608
+ # without
609
+ unflat_param_states = [
610
+ _gather_state_dict(
611
+ unflat_osd_state[unflat_param_name],
612
+ pg=fsdp_state.process_group,
613
+ device=fsdp_state.compute_device,
614
+ )
615
+ if unflat_param_name in unflat_osd_state
616
+ else None
617
+ for unflat_param_name in unflat_param_names
618
+ ]
619
+ # Check that the unflattened parameters have the same state names
620
+ state_names = None
621
+ for unflat_param_state in unflat_param_states:
622
+ if unflat_param_state is None:
623
+ continue
624
+ if state_names is None:
625
+ state_names = set(unflat_param_state.keys())
626
+ else:
627
+ if state_names != set(unflat_param_state.keys()):
628
+ raise ValueError(
629
+ "Differing optimizer state names for the unflattened "
630
+ f"parameters: {unflat_param_names}"
631
+ )
632
+ assert state_names is not None
633
+
634
+ # Flatten the state
635
+ flat_state: Dict[str, Any] = {}
636
+ for state_name in state_names:
637
+ state_values = [
638
+ unflat_param_state[state_name] if unflat_param_state is not None else None
639
+ for unflat_param_state in unflat_param_states
640
+ ]
641
+ non_none_state_values = [v for v in state_values if v is not None]
642
+ # If all ranks have None, this is a None value
643
+ if not non_none_state_values:
644
+ flat_state[state_name] = None
645
+ continue
646
+ are_pos_dim_tensors = are_zero_dim_tensors = are_non_tensors = True
647
+ for v in non_none_state_values:
648
+ are_pos_dim_tensors &= torch.is_tensor(v) and v.dim() > 0
649
+ are_zero_dim_tensors &= _is_zero_dim_tensor(v)
650
+ are_non_tensors &= not torch.is_tensor(v)
651
+ types = {type(v) for v in non_none_state_values}
652
+ if len(types) != 1 or not (
653
+ are_pos_dim_tensors or are_zero_dim_tensors or are_non_tensors
654
+ ):
655
+ raise ValueError(
656
+ f"Differing optimizer state types for state {state_name}, "
657
+ f"values {non_none_state_values}, and unflattened parameter "
658
+ f"names {unflat_param_names}"
659
+ )
660
+ if are_pos_dim_tensors:
661
+ flat_tensor = _flatten_tensor_optim_state(
662
+ state_name,
663
+ state_values,
664
+ unflat_param_names,
665
+ unflat_param_shapes,
666
+ handle,
667
+ )
668
+ # Shard the flattened tensor immediately to minimize max memory
669
+ # usage
670
+ if (
671
+ fsdp_state.world_size != 1
672
+ and fsdp_state.sharding_strategy != ShardingStrategy.NO_SHARD
673
+ ):
674
+ sharded_flat_tensor, _ = FlatParamHandle._get_shard(
675
+ flat_tensor,
676
+ fsdp_state.rank,
677
+ fsdp_state.world_size,
678
+ )
679
+ else:
680
+ sharded_flat_tensor = flat_tensor
681
+ flat_state[state_name] = sharded_flat_tensor
682
+ elif are_zero_dim_tensors:
683
+ flat_state[state_name] = _flatten_zero_dim_tensor_optim_state(
684
+ state_name,
685
+ state_values,
686
+ unflat_param_names,
687
+ )
688
+ else:
689
+ assert are_non_tensors
690
+ flat_state[state_name] = _flatten_non_tensor_optim_state(
691
+ state_name,
692
+ state_values,
693
+ unflat_param_names,
694
+ )
695
+
696
+ return flat_state
697
+
698
+
699
+ def _flatten_tensor_optim_state(
700
+ state_name: str,
701
+ pos_dim_tensors: List[torch.Tensor],
702
+ unflat_param_names: List[str],
703
+ unflat_param_shapes: Sequence[torch.Size],
704
+ handle: FlatParamHandle,
705
+ ) -> torch.Tensor:
706
+ """
707
+ Flattens the positive-dimension tensor optimizer state given by the values
708
+ ``tensors`` for the state ``state_name`` for a single flat parameter
709
+ from ``handle`` corresponding to the unflattened parameter names
710
+ ``unflat_param_names`` and unflatted parameter shapes
711
+ ``unflat_param_shapes``. This flattens each unflattened parameter's tensor
712
+ state into one tensor.
713
+
714
+ NOTE: We use zero tensors for any unflattened parameters without state
715
+ since some value is required to fill those entries. This assumes that the
716
+ zero tensor is mathematically equivalent to having no state, which is true
717
+ for Adam's "exp_avg" and "exp_avg_sq" but may not be true for all
718
+ optimizers.
719
+
720
+ Args:
721
+ state_name (str): Optimizer state name.
722
+ pos_dim_tensors (List[torch.Tensor]): Positive-dimension tensor
723
+ optimizer state values for the unflattened parameters corresponding
724
+ to the single flat parameter.
725
+ unflat_param_names (List[str]): A :class:`list` of unflattened
726
+ parameter names corresponding to the single flat parameter.
727
+ unflat_param_shapes (List[torch.Size]): Unflattened parameter shapes
728
+ corresponding to the single flat parameter.
729
+ handle (FlatParamHandle): The flat parameter's handle.
730
+
731
+ Returns:
732
+ torch.Tensor: A flat tensor containing the optimizer state
733
+ corresponding to ``state_name`` constructed by concatenating the
734
+ unflattened parameter tensor states in ``pos_dim_tensors`` (using zero
735
+ tensors for any unflattened parameters without the state).
736
+ """
737
+ flat_param = handle.flat_param
738
+ non_none_tensors = [t for t in pos_dim_tensors if t is not None]
739
+ # Check that all are tensors with the same dtype
740
+ dtypes = {t.dtype for t in non_none_tensors}
741
+ if len(dtypes) != 1:
742
+ raise ValueError(
743
+ "All unflattened parameters comprising a single flat "
744
+ "parameter must have positive-dimension tensor state with the "
745
+ f"same dtype but got dtypes {dtypes} for state {state_name} and "
746
+ f"unflattened parameter names {unflat_param_names}"
747
+ )
748
+ dtype = next(iter(dtypes))
749
+ # Check that each tensor state matches its parameter's shape
750
+ for tensor, shape in zip(pos_dim_tensors, unflat_param_shapes):
751
+ if tensor is None and len(shape) == 0:
752
+ raise ValueError("Flattening a zero-dimension parameter is not supported")
753
+ elif tensor is not None and tensor.shape != shape:
754
+ raise ValueError(
755
+ "Tensor optimizer state does not have same shape as its "
756
+ f"parameter: {tensor.shape} {shape}"
757
+ )
758
+ # Flatten the tensor states: we do not need to add any right-hand-side
759
+ # padding since the flat optimizer state tensor is sharded via
760
+ # `_get_shard()`, which pads the shard as needed (just like for the flat
761
+ # parameter)
762
+ cpu_device = torch.device("cpu")
763
+ tensors_to_flatten = [
764
+ torch.flatten(state_value.to(cpu_device))
765
+ if state_value is not None
766
+ else torch.flatten(
767
+ torch.zeros(
768
+ size=shape,
769
+ dtype=dtype,
770
+ device=cpu_device,
771
+ )
772
+ )
773
+ for state_value, shape in zip(pos_dim_tensors, unflat_param_shapes)
774
+ ]
775
+ flat_tensor = handle.flatten_tensors(tensors_to_flatten, handle._aligned_numel)
776
+ flat_param_shape = flat_param._unpadded_unsharded_size # type: ignore[attr-defined]
777
+ assert flat_tensor.shape == flat_param_shape, (
778
+ f"tensor optim state: {flat_tensor.shape} "
779
+ f"flat parameter: {flat_param_shape}"
780
+ )
781
+ return flat_tensor
782
+
783
+
784
+ def _flatten_zero_dim_tensor_optim_state(
785
+ state_name: str,
786
+ zero_dim_tensors: List[torch.Tensor],
787
+ unflat_param_names: List[str],
788
+ ) -> torch.Tensor:
789
+ """
790
+ Flattens the zero-dimension tensor optimizer state given by the values
791
+ ``zero_dim_tensors`` for the state ``state_name`` for a single flat
792
+ parameter corresponding to the unflattened parameter names
793
+ ``unflat_param_names`` by enforcing that all tensors are the same and using
794
+ that common value.
795
+
796
+ NOTE: The requirement that the tensors are the same across all unflattened
797
+ parameters comprising the flat parameter is needed to maintain the
798
+ invariant that FSDP performs the same computation as its non-sharded
799
+ equivalent. This means that none of the unflattened parameters can be
800
+ missing this state since imposing a value may differ from having no value.
801
+ For example, for Adam's "step", no value means maximum bias correction,
802
+ while having some positive value means less bias correction.
803
+
804
+ Args:
805
+ state_name (str): Optimizer state name.
806
+ zero_dim_tensors (List[torch.Tensor]): Zero-dimension optimizer state
807
+ for the unflattened parameters corresponding to the single
808
+ flat parameter.
809
+ unflat_param_names (List[str]): A :class:`list` of unflattened
810
+ parameter names corresponding to the single flat parameter.
811
+
812
+ Returns:
813
+ torch.Tensor: A zero-dimensional tensor giving the value of the state
814
+ ``state_name`` for all unflattened parameters corresponding to the
815
+ names ``unflat_param_names``.
816
+ """
817
+ non_none_tensors = [t for t in zero_dim_tensors if t is not None]
818
+ # Enforce that all have the same value and dtype
819
+ values_set = {t.item() if t is not None else None for t in zero_dim_tensors}
820
+ dtypes = {t.dtype if t is not None else None for t in zero_dim_tensors}
821
+ if (
822
+ len(non_none_tensors) != len(zero_dim_tensors)
823
+ or len(values_set) != 1
824
+ or len(dtypes) != 1
825
+ ):
826
+ raise ValueError(
827
+ "All unflattened parameters comprising a single flat "
828
+ "parameter must have scalar state with the same value and dtype "
829
+ f"but got values {values_set} and dtypes {dtypes} for state "
830
+ f"{state_name} and unflattened parameter names "
831
+ f"{unflat_param_names}"
832
+ )
833
+ value = next(iter(values_set))
834
+ dtype = next(iter(dtypes))
835
+ return torch.tensor(value, dtype=dtype, device=torch.device("cpu"))
836
+
837
+
838
+ def _flatten_non_tensor_optim_state(
839
+ state_name: str,
840
+ non_tensors: List[Any],
841
+ unflat_param_names: List[str],
842
+ ) -> Any:
843
+ """
844
+ Flattens the non-tensor optimizer state given by the values ``non_tensors``
845
+ for the state ``state_name`` for a single flat parameter corresponding
846
+ to the unflattened parameter names ``unflat_param_names`` by enforcing that
847
+ all values are the same and using that common value.
848
+
849
+ See the note in :func:`_flatten_zero_dim_tensor_optim_state`.
850
+
851
+ Args:
852
+ state_name (str): Optimizer state name.
853
+ non_tensors (List[Any]): Non-tensor optimizer state for the unflattened
854
+ parameters corresponding to the single flat parameter.
855
+ unflat_param_names (List[str]): A :class:`list` of unflattened
856
+ parameter names corresponding to the single flat parameter.
857
+
858
+ Returns:
859
+ Any: A non-tensor giving the value of the state ``state_name`` for all
860
+ unflattened parameters corresponding to the names
861
+ ``unflat_param_names``.
862
+ """
863
+ non_none_non_tensors = [nt for nt in non_tensors if nt is not None]
864
+ # Enforce that all have the same value (same type already checked)
865
+ non_tensor_set = set(non_tensors)
866
+ if len(non_none_non_tensors) != len(non_tensors) or len(non_tensor_set) != 1:
867
+ raise ValueError(
868
+ "All unflattened parameters comprising a single flat "
869
+ "parameter must have scalar state with the same value and dtype "
870
+ f"but got values {non_tensor_set} for state {state_name} and "
871
+ f"unflattened parameter names {unflat_param_names}"
872
+ )
873
+ non_tensor = next(iter(non_tensor_set))
874
+ return non_tensor
875
+
876
+
877
+ def _rekey_sharded_optim_state_dict(
878
+ sharded_osd: Dict[str, Any],
879
+ model: nn.Module,
880
+ optim: torch.optim.Optimizer,
881
+ optim_input: Optional[
882
+ Union[
883
+ List[Dict[str, Any]],
884
+ Iterable[nn.Parameter],
885
+ ]
886
+ ],
887
+ using_optim_input: bool,
888
+ is_named_optimizer: bool = False,
889
+ ) -> Dict[str, Any]:
890
+ """
891
+ Rekeys the optimizer state dict from unflattened parameter names to flat
892
+ parameter IDs according to the calling rank's ``optim``, which may be
893
+ different across ranks. In particular, the unflattened parameter names are
894
+ represented as :class:`_OptimStateKey` s.
895
+ """
896
+ param_to_fqns = _get_param_to_fqns(model)
897
+ flat_param_to_fqn = _get_flat_param_to_fqn(model)
898
+ param_to_param_key: Dict[nn.Parameter, Union[int, str]] = cast(
899
+ Dict[nn.Parameter, Union[int, str]],
900
+ (
901
+ _get_param_to_param_id_from_optim_input(model, optim_input)
902
+ if using_optim_input
903
+ else _get_param_to_param_key(
904
+ optim, model, is_named_optimizer, param_to_fqns, flat_param_to_fqn
905
+ )
906
+ ),
907
+ )
908
+ # All parameter keys in `param_to_param_key` should be in
909
+ # `param_to_fqns` -- strict inequality follows when not all parameters are
910
+ # passed to the optimizer
911
+ assert len(param_to_param_key) <= len(param_to_fqns)
912
+
913
+ unflat_param_names_to_flat_param_key: Dict[
914
+ Tuple[str, ...], Union[int, str]
915
+ ] = {} # for "state"
916
+ unflat_param_name_to_flat_param_key: Dict[
917
+ str, Union[int, str]
918
+ ] = {} # for "param_groups"
919
+ for param, unflat_param_names in param_to_fqns.items():
920
+ if param not in param_to_param_key:
921
+ # This parameter was not passed to the optimizer
922
+ continue
923
+ flat_param_key = param_to_param_key[param]
924
+ unflat_param_names_to_flat_param_key[tuple(unflat_param_names)] = flat_param_key
925
+ for unflat_param_name in unflat_param_names:
926
+ unflat_param_name_to_flat_param_key[unflat_param_name] = flat_param_key
927
+
928
+ sharded_osd_state = sharded_osd["state"]
929
+ rekeyed_osd_state: Dict[Union[str, int], Any] = {}
930
+ for key, param_state in sharded_osd_state.items():
931
+ if isinstance(key, str):
932
+ rekeyed_osd_state[key] = param_state
933
+ continue
934
+ flat_param_key = unflat_param_names_to_flat_param_key.get(
935
+ key.unflat_param_names, key.unflat_param_names
936
+ )
937
+ rekeyed_osd_state[flat_param_key] = param_state
938
+
939
+ # Only process param_groups if it exists in sharded_osd
940
+ if "param_groups" in sharded_osd:
941
+ rekeyed_osd_param_groups: List[Dict[str, Any]] = []
942
+ for unflat_param_group in sharded_osd["param_groups"]:
943
+ flat_param_group = copy.deepcopy(unflat_param_group)
944
+ flat_param_keys = sorted(
945
+ {
946
+ unflat_param_name_to_flat_param_key[unflat_param_name]
947
+ for unflat_param_name in unflat_param_group["params"]
948
+ }
949
+ )
950
+ flat_param_group["params"] = flat_param_keys
951
+ rekeyed_osd_param_groups.append(flat_param_group)
952
+ return {"state": rekeyed_osd_state, "param_groups": rekeyed_osd_param_groups}
953
+ else:
954
+ return {"state": rekeyed_osd_state}
955
+
956
+
957
+ def _get_param_id_to_param_from_optim_input(
958
+ model: nn.Module,
959
+ optim_input: Optional[
960
+ Union[
961
+ List[Dict[str, Any]],
962
+ Iterable[nn.Parameter],
963
+ ]
964
+ ] = None,
965
+ ) -> Dict[int, nn.Parameter]:
966
+ """
967
+ Constructs a mapping from parameter IDs to parameters. This may be used
968
+ both for models with ``FlatParameter`` s and without.
969
+
970
+ NOTE: This method is only preserved for backward compatibility. The method
971
+ :meth:`_get_param_key_to_param` is the preferred code path that does not
972
+ rely on ``optim_input``.
973
+
974
+ NOTE: We critically assume that, whether the optimizer input is a list of
975
+ parameters or a list of parameter groups, :class:`torch.optim.Optimizer`
976
+ enumerates the parameter IDs in order. In other words, for a parameter list
977
+ input, the parameter IDs should be in that list order, and for a parameter
978
+ groups input, the parameter IDs should be in order within each parameter
979
+ group and in order across parameter groups.
980
+
981
+ Args:
982
+ model (nn.Module): Model whose parameters are passed into the
983
+ optimizer.
984
+ optim_input (Optional[Union[List[Dict[str, Any]],
985
+ Iterable[nn.Parameter]]]): Input passed into the optimizer
986
+ representing either a :class:`list` of parameter groups or an
987
+ iterable of parameters; if ``None``, then this method assumes the
988
+ input was ``model.parameters()``. (Default: ``None``)
989
+
990
+ Returns:
991
+ List[nn.Parameter]: Mapping from parameter IDs to parameters,
992
+ where the parameter ID is implicitly the index in the :class:`list`.
993
+ """
994
+ # Assume the standard case of passing `model.parameters()` to the optimizer
995
+ # if `optim_input` is not specified
996
+ if optim_input is None:
997
+ return dict(enumerate(model.parameters()))
998
+ try:
999
+ params = cast(List[nn.Parameter], list(optim_input))
1000
+ except TypeError as e:
1001
+ raise TypeError(
1002
+ "Optimizer input should be an iterable of Tensors or dicts, "
1003
+ f"but got {optim_input}"
1004
+ ) from e
1005
+ if len(params) == 0:
1006
+ raise ValueError("Optimizer input should not be empty")
1007
+
1008
+ # Check if the optimizer input represents tensors or parameter groups
1009
+ all_tensors = True
1010
+ all_dicts = True
1011
+ for param in params:
1012
+ all_tensors &= isinstance(param, torch.Tensor)
1013
+ all_dicts &= isinstance(param, dict)
1014
+ if not all_tensors and not all_dicts:
1015
+ raise TypeError("Optimizer input should be an iterable of Tensors or dicts")
1016
+ if all_tensors:
1017
+ return dict(enumerate(params))
1018
+ assert all_dicts
1019
+ param_id_to_param: List[nn.Parameter] = []
1020
+ for param_group in params:
1021
+ has_params_key = "params" in param_group # type: ignore[operator]
1022
+ assert has_params_key, (
1023
+ 'A parameter group should map "params" to a list of the '
1024
+ "parameters in the group"
1025
+ )
1026
+ # Implicitly map `flat_param_id` (current length of the list) to
1027
+ # `param`
1028
+ param_id_to_param.extend(param_group["params"]) # type: ignore[index]
1029
+ return dict(enumerate(param_id_to_param))
1030
+
1031
+
1032
+ def _get_flat_param_to_fqn(model: torch.nn.Module) -> Dict[FlatParameter, str]:
1033
+ """
1034
+ Constructs a mapping from ``FlatParameter`` to a cleaned (devoid of prefixes
1035
+ from wrappers) fully qualified name (FQN). Note that this FQN is "non-canonical"
1036
+ because ``FlatParameter`` s do not come from the original module but are
1037
+ registered only after FSDP has been applied. This function returns the FSDP-given
1038
+ name for the ``FlatParameter`` (usually module._flat_param) as opposed to the
1039
+ canonical FQNs returned for ``FlatParameter`` s in ``_common_utils._get_param_to_fqns(...)``).
1040
+
1041
+ Consequently, this function will only return a non-empty mapping if FSDP was
1042
+ applied with ``use_orig_params=False`` as, otherwise, the original parameters
1043
+ are used within the module and there would be no ``FlatParameter`` s in the module.
1044
+
1045
+ """
1046
+
1047
+ def module_fn(module, prefix, tree_level, flat_param_to_fqn):
1048
+ for param_name, param in _named_parameters_with_duplicates(
1049
+ module, recurse=False
1050
+ ):
1051
+ if not isinstance(param, FlatParameter):
1052
+ continue
1053
+ fqn = clean_tensor_name(prefix + param_name)
1054
+ flat_param_to_fqn[param] = fqn
1055
+
1056
+ def return_fn(flat_param_to_fqn):
1057
+ return flat_param_to_fqn
1058
+
1059
+ flat_param_to_fqn_ret: Dict[FlatParameter, str] = {}
1060
+ return _apply_to_modules(
1061
+ model,
1062
+ module_fn,
1063
+ return_fn,
1064
+ [fqn for fqn, _ in _named_parameters_with_duplicates(model)],
1065
+ flat_param_to_fqn_ret,
1066
+ )
1067
+
1068
+
1069
+ def _get_param_key_to_param(
1070
+ optim: torch.optim.Optimizer,
1071
+ model: Optional[nn.Module] = None,
1072
+ is_named_optimizer: bool = False,
1073
+ param_to_fqns: Optional[Dict[nn.Parameter, List[str]]] = None,
1074
+ flat_param_to_fqn: Optional[Dict[FlatParameter, str]] = None,
1075
+ ) -> Dict[Union[int, str], nn.Parameter]:
1076
+ """
1077
+ Constructs a mapping from parameter keys to parameters. For the regular
1078
+ optimizers, the keys are parameter IDs. For NamedOptimizer, the keys
1079
+ are FQNs. This API may be used both for models with ``FlatParameter`` s and
1080
+ without.
1081
+ """
1082
+ clean_fqn_to_curr_fqn: Dict[str, str] = {}
1083
+ if is_named_optimizer:
1084
+ assert (
1085
+ param_to_fqns is not None and flat_param_to_fqn is not None
1086
+ ), "The optimizer is a NamedOptimizer, `param_to_fqns` must not be None."
1087
+ assert model is not None
1088
+ for key, _ in _named_parameters_with_duplicates(model):
1089
+ clean_fqn_to_curr_fqn[clean_tensor_name(key)] = key
1090
+
1091
+ param_key_to_param: Dict[Union[str, int], nn.Parameter] = {}
1092
+ pid = 0
1093
+ for param_group in optim.param_groups:
1094
+ if is_named_optimizer:
1095
+ for param in param_group["params"]:
1096
+ assert flat_param_to_fqn is not None
1097
+ if param in flat_param_to_fqn:
1098
+ # FlatParameter case
1099
+ key = flat_param_to_fqn[param]
1100
+ else:
1101
+ assert param_to_fqns is not None
1102
+ # use_orig_params case
1103
+ assert len(param_to_fqns[param]) == 1
1104
+ key = param_to_fqns[param][0]
1105
+ try:
1106
+ key = clean_fqn_to_curr_fqn[key]
1107
+ except KeyError as e:
1108
+ raise KeyError(
1109
+ f"Can't find {key} from {list(clean_fqn_to_curr_fqn.keys())}."
1110
+ ) from e
1111
+ param_key_to_param[key] = param
1112
+ else:
1113
+ for param in param_group["params"]:
1114
+ param_key_to_param[pid] = param
1115
+ pid += 1
1116
+
1117
+ return param_key_to_param
1118
+
1119
+
1120
+ def _get_param_to_param_key(
1121
+ optim: torch.optim.Optimizer,
1122
+ model: Optional[nn.Module] = None,
1123
+ is_named_optimizer: bool = False,
1124
+ param_to_fqns: Optional[Dict[nn.Parameter, List[str]]] = None,
1125
+ flat_param_to_fqn: Optional[Dict[FlatParameter, str]] = None,
1126
+ ) -> Dict[nn.Parameter, Union[int, str]]:
1127
+ """
1128
+ Constructs the inverse mapping of :func:`_get_param_key_to_param`. This API
1129
+ only supports the case where `optim` is a regular optimizer, not NamedOptimizer.
1130
+ So the parameter keys will be parameter ids.
1131
+ """
1132
+ param_id_to_param = _get_param_key_to_param(
1133
+ optim, model, is_named_optimizer, param_to_fqns, flat_param_to_fqn
1134
+ )
1135
+ return {param: param_id for param_id, param in param_id_to_param.items()}
1136
+
1137
+
1138
+ def _get_param_to_param_id_from_optim_input(
1139
+ model: nn.Module,
1140
+ optim_input: Optional[
1141
+ Union[
1142
+ List[Dict[str, Any]],
1143
+ Iterable[nn.Parameter],
1144
+ ]
1145
+ ] = None,
1146
+ ) -> Dict[nn.Parameter, int]:
1147
+ """Constructs the inverse mapping of :func:`_get_param_id_to_param_from_optim_input`."""
1148
+ param_id_to_param = _get_param_id_to_param_from_optim_input(model, optim_input)
1149
+ return {param: param_id for param_id, param in param_id_to_param.items()}
1150
+
1151
+
1152
+ def _check_missing_keys_on_rank(
1153
+ r0_optim_state_keys: List[_OptimStateKey],
1154
+ optim_state_key_to_param_key: Dict[_OptimStateKey, Union[str, int]],
1155
+ param_key_to_param: Dict[Union[str, int], nn.Parameter],
1156
+ group: Optional[dist.ProcessGroup],
1157
+ ) -> None:
1158
+ # Ensure that all ranks have at least the optimizer states needed by
1159
+ # rank 0's optimizer
1160
+ missing_keys: List[_OptimStateKey] = []
1161
+ for r0_optim_state_key in r0_optim_state_keys:
1162
+ if r0_optim_state_key not in optim_state_key_to_param_key:
1163
+ # A parameter from rank 0's optimizer does not exist for this
1164
+ # rank's optimizer
1165
+ missing_keys.append(r0_optim_state_key)
1166
+ continue
1167
+ param_key = optim_state_key_to_param_key[r0_optim_state_key]
1168
+ if isinstance(param_key, int):
1169
+ assert param_key >= 0 and param_key < len(
1170
+ param_key_to_param
1171
+ ), "Check the `param_key_to_param` construction"
1172
+ # We cannot use FSDPState.compute_device as this API is a global view.
1173
+ device = _get_pg_default_device(group)
1174
+ num_missing = torch.tensor([len(missing_keys)], dtype=torch.int32, device=device)
1175
+ dist.all_reduce(num_missing, group=group)
1176
+ if num_missing.item() > 0:
1177
+ obj_list = [None for _ in range(dist.get_world_size(group))]
1178
+ dist.all_gather_object(obj_list, missing_keys, group=group)
1179
+ error_msg = (
1180
+ "FSDP currently requires each rank to have at least the "
1181
+ "optimizer states needed by rank 0's optimizer but some ranks "
1182
+ "are missing some of those states"
1183
+ )
1184
+ for rank, keys in enumerate(obj_list):
1185
+ keys = cast(List[_OptimStateKey], keys)
1186
+ if len(keys) > 0:
1187
+ error_msg += (
1188
+ f"\nRank {rank} is missing states for the parameters: "
1189
+ f"{[key.unflat_param_names for key in keys]}"
1190
+ )
1191
+ raise RuntimeError(error_msg)
1192
+
1193
+
1194
+ def _map_param_key_to_optim_keys(
1195
+ optim_state_dict: Dict[str, Any],
1196
+ group: Optional[dist.ProcessGroup],
1197
+ param_key_to_param: Dict[Union[int, str], nn.Parameter],
1198
+ param_to_fqns: Dict[nn.Parameter, List[str]],
1199
+ fqn_to_fsdp_param_info: Dict[str, FSDPParamInfo],
1200
+ merge_keys: bool = False,
1201
+ ) -> Tuple[List[_OptimStateKey], Dict[_OptimStateKey, Union[int, str]]]:
1202
+ """
1203
+ Construct the local mapping between the ``_OptimStateKey`` and parameter keys
1204
+ and all the ``_OptimStateKey`` across ranks. If ``merge_keys`` is False, rank0
1205
+ must contain all the ``_OptimStateKey``, an exception will be raised otherwise.
1206
+ Note that ``merge_keys`` should equal to ``use_orig_params``.
1207
+ """
1208
+ rank = dist.get_rank(group)
1209
+ optim_state_key_to_param_key: Dict[_OptimStateKey, Union[int, str]] = {} # local
1210
+ all_optim_state_keys: List[_OptimStateKey] = []
1211
+
1212
+ for param_key, param in param_key_to_param.items():
1213
+ # Do not include parameters without state to avoid empty mappings
1214
+ # just like in normal `torch.optim.Optimizer.state_dict()`
1215
+ if param_key not in optim_state_dict["state"]:
1216
+ continue
1217
+ fqns = param_to_fqns[param]
1218
+ is_fsdp_managed = isinstance(param, FlatParameter)
1219
+ if is_fsdp_managed:
1220
+ assert fqns[0] in fqn_to_fsdp_param_info, (
1221
+ fqns[0],
1222
+ list(fqn_to_fsdp_param_info.keys()),
1223
+ )
1224
+ is_fsdp_managed = fqns[0] in fqn_to_fsdp_param_info
1225
+ optim_state_key = _OptimStateKey(
1226
+ unflat_param_names=tuple(fqns),
1227
+ is_fsdp_managed=is_fsdp_managed,
1228
+ )
1229
+ if rank == 0 or merge_keys:
1230
+ all_optim_state_keys.append(optim_state_key)
1231
+ optim_state_key_to_param_key[optim_state_key] = param_key
1232
+
1233
+ if merge_keys:
1234
+ all_keys: List[List[_OptimStateKey]] = [
1235
+ [] for _ in range(dist.get_world_size(group))
1236
+ ]
1237
+ dist.all_gather_object(all_keys, all_optim_state_keys, group=group)
1238
+ merge_all_optim_state_keys = [
1239
+ key for local_keys in all_keys for key in local_keys
1240
+ ]
1241
+ all_optim_state_keys = sorted(set(merge_all_optim_state_keys))
1242
+ else:
1243
+ key_obj_list: List[Optional[List[_OptimStateKey]]] = (
1244
+ [all_optim_state_keys] if rank == 0 else [None]
1245
+ )
1246
+ dist.broadcast_object_list(key_obj_list, src=0, group=group)
1247
+ assert key_obj_list[0] is not None
1248
+ all_optim_state_keys = key_obj_list[0]
1249
+ _check_missing_keys_on_rank(
1250
+ all_optim_state_keys,
1251
+ optim_state_key_to_param_key,
1252
+ param_key_to_param,
1253
+ group,
1254
+ )
1255
+
1256
+ return all_optim_state_keys, optim_state_key_to_param_key
1257
+
1258
+
1259
+ def _unflatten_param_groups(
1260
+ state_dict: Dict[str, Any],
1261
+ param_key_to_param: Dict[Union[int, str], nn.Parameter],
1262
+ param_to_fqns: Dict[nn.Parameter, List[str]],
1263
+ ) -> List[Dict[str, Any]]:
1264
+ param_groups: List[Dict[str, Any]] = []
1265
+ for flat_param_group in state_dict["param_groups"]:
1266
+ unflat_param_group = copy.deepcopy(flat_param_group)
1267
+ param_group_params = [
1268
+ param_key_to_param[flat_param_key]
1269
+ for flat_param_key in flat_param_group["params"]
1270
+ ]
1271
+ nested_unflat_param_names = [
1272
+ param_to_fqns[param] for param in param_group_params
1273
+ ]
1274
+ unflat_param_group["params"] = [
1275
+ unflat_param_name
1276
+ for unflat_param_names in nested_unflat_param_names
1277
+ for unflat_param_name in unflat_param_names
1278
+ ] # flatten the list of lists
1279
+ param_groups.append(unflat_param_group)
1280
+ return param_groups
1281
+
1282
+
1283
+ def _is_named_optimizer(optim_state_dict: Dict[str, Any]) -> bool:
1284
+ """
1285
+ Returns whether the state_dict is from a NamedOptimizer.
1286
+ This function checks that the keys in the state_dict['state'] are strings
1287
+ (which usually are FQNs) versus integers (which usually refer to param_ids
1288
+ from a vanilla torch.optim.Optimizer).
1289
+ """
1290
+ state = optim_state_dict.get("state", None)
1291
+ if not state:
1292
+ # If we cannot find a state, assume it is not NamedOptimizer as
1293
+ # NamedOptimizer has eager initialization.
1294
+ return False
1295
+ try:
1296
+ key = next(iter(state.keys()))
1297
+ except Exception as e:
1298
+ raise Exception(optim_state_dict) from e # noqa: TRY002
1299
+ return isinstance(key, str)
1300
+
1301
+
1302
+ @dataclass
1303
+ class StateInfo:
1304
+ # The key of these dictionaries are the state name, e.g., `exp_avg`.
1305
+ tensors: Dict[str, _PosDimTensorInfo]
1306
+ scalar_tensors: Dict[str, torch.Tensor]
1307
+ non_tensors: Dict[str, Any]
1308
+
1309
+
1310
+ def _allgather_state_info(
1311
+ fsdp_state: _FSDPState,
1312
+ input_states: Dict[str, Any],
1313
+ ) -> List[Dict[str, StateInfo]]:
1314
+ """
1315
+ Given the ``input_states``, allgather StateInfo for each state. The function
1316
+ uses all_gather_object to gather StateInfo so no GPU tensors are sent.
1317
+ """
1318
+
1319
+ processed_state_dict: Dict[str, StateInfo] = {}
1320
+ gathered_state_info: List[Dict[str, StateInfo]] = [
1321
+ {} for _ in range(fsdp_state.world_size)
1322
+ ]
1323
+
1324
+ for fqn, optim_state in input_states.items():
1325
+ # Allgather the scalar tensor state, non-tensor states and tensors metadata.
1326
+ processed_state = StateInfo({}, {}, {})
1327
+ for state_name, value in sorted_items(optim_state):
1328
+ if torch.is_tensor(value):
1329
+ if value.dim() == 0:
1330
+ # Ensure that `step` is on CPU.
1331
+ processed_state.scalar_tensors[state_name] = value.cpu()
1332
+ else:
1333
+ processed_state.tensors[state_name] = _PosDimTensorInfo(
1334
+ value.shape, value.dtype
1335
+ )
1336
+ else:
1337
+ processed_state.non_tensors[state_name] = value
1338
+ processed_state_dict[fqn] = processed_state
1339
+ dist.all_gather_object(
1340
+ gathered_state_info,
1341
+ processed_state_dict,
1342
+ group=fsdp_state.process_group,
1343
+ )
1344
+ return gathered_state_info
1345
+
1346
+
1347
+ def _convert_all_state_info(
1348
+ fsdp_param_info: FSDPParamInfo,
1349
+ gathered_state_info: List[Dict[str, StateInfo]],
1350
+ input_states: Dict[str, Any],
1351
+ output_states: Dict[str, Dict[str, Any]],
1352
+ ) -> Tuple[Optional[torch.dtype], Dict[str, List[Optional[torch.Tensor]]]]:
1353
+ """
1354
+ Given the ``gathered_state_info`` and ``input_states``, the API converted
1355
+ the StateInfo into the original state if the state is not a non-scalar
1356
+ tensor. For a multi-dimensional tensor, the local state will be stored in
1357
+ ``state_buffer`` in a correct order for later allgather purpose.
1358
+ """
1359
+
1360
+ state_buffers: Dict[str, List[Optional[torch.Tensor]]] = {}
1361
+
1362
+ for fqn, gathered_state in output_states.items():
1363
+ state_info = [s[fqn] for s in gathered_state_info]
1364
+ all_tensor_states = sorted(
1365
+ {n for state in state_info for n in state.tensors.keys()}
1366
+ )
1367
+ empty_ranks: Set[int] = set()
1368
+ dtype: Optional[torch.dtype] = None
1369
+ # First check all the non-scalar states and get the information of
1370
+ # states on each rank.
1371
+ for state_name in all_tensor_states:
1372
+ numels = []
1373
+ _empty_ranks: Set[int] = set()
1374
+ for rank, object_state in enumerate(state_info):
1375
+ numels.append(0)
1376
+ info = object_state.tensors.get(state_name, None)
1377
+ if info is not None:
1378
+ numels[-1] = info.shape.numel()
1379
+ if not dtype:
1380
+ dtype = info.dtype
1381
+ else:
1382
+ assert dtype == info.dtype
1383
+ if numels[-1] == 0:
1384
+ _empty_ranks.add(rank)
1385
+
1386
+ assert not empty_ranks or empty_ranks == _empty_ranks
1387
+ empty_ranks = _empty_ranks
1388
+ if state_name not in state_buffers:
1389
+ state_buffers[state_name] = [
1390
+ None for _ in fsdp_param_info.param_indices
1391
+ ]
1392
+ local_state = input_states[fqn].get(state_name, None)
1393
+ # N.B. We need to move the state to compute_device. The reason is
1394
+ # not yet clear and we need to figure out why the state may be on a
1395
+ # different device.
1396
+ if local_state is not None:
1397
+ local_state = local_state.to(fsdp_param_info.state.compute_device)
1398
+ state_buffers[state_name][fsdp_param_info.param_indices[fqn]] = local_state
1399
+
1400
+ # Restoring the scalar and non-tensor states. If the corresponding
1401
+ # non-scalar states do not exist on the rank, we also skip the scalar
1402
+ # non-tensor states on that rank.
1403
+ for rank, object_state in enumerate(state_info):
1404
+ if rank in empty_ranks:
1405
+ continue
1406
+ for name, non_tensor_value in object_state.non_tensors.items():
1407
+ curr_non_tensor_value = gathered_state.get(name, None)
1408
+ assert (
1409
+ curr_non_tensor_value is None
1410
+ or curr_non_tensor_value == non_tensor_value
1411
+ ), (
1412
+ f"Rank {rank} has different values for {name}: {non_tensor_value}."
1413
+ + f" Other ranks: {curr_non_tensor_value}"
1414
+ )
1415
+ gathered_state[name] = non_tensor_value
1416
+
1417
+ for name, scalar_tensor_value in object_state.scalar_tensors.items():
1418
+ curr_scalar_tensor_value = gathered_state.get(name, None)
1419
+ assert curr_scalar_tensor_value is None or torch.equal(
1420
+ scalar_tensor_value, curr_scalar_tensor_value
1421
+ ), (
1422
+ f"Rank {rank} has different values for {name}: {scalar_tensor_value}."
1423
+ + f" Other ranks: {curr_scalar_tensor_value}"
1424
+ )
1425
+ gathered_state[name] = scalar_tensor_value
1426
+
1427
+ return dtype, state_buffers # type: ignore[possibly-undefined]
1428
+
1429
+
1430
+ def _unflatten_orig_param_states(
1431
+ fsdp_param_info: FSDPParamInfo,
1432
+ output_states: Dict[str, Dict[str, Any]],
1433
+ state_name: str,
1434
+ shard_state: bool,
1435
+ to_save: bool,
1436
+ cpu_offload: bool,
1437
+ ) -> None:
1438
+ """
1439
+ Given a output state dict, ``output_states``, which the keys are FQNs to the
1440
+ original parameters (not FlatParameters nor parmeter ID), and the values
1441
+ are gathered states, unflatten the states to the original dimensions.
1442
+
1443
+ This function performs the unflattening process in-place.
1444
+ """
1445
+ if not to_save:
1446
+ return
1447
+ flat_param = fsdp_param_info.handle.flat_param
1448
+ fsdp_state = fsdp_param_info.state
1449
+ for fqn, gathered_state in output_states.items():
1450
+ value = gathered_state[state_name]
1451
+ param_idx = fsdp_param_info.param_indices[fqn]
1452
+
1453
+ # TODO: This solution is not general and only apply to PTD TP solution.
1454
+ if isinstance(value, DTensor):
1455
+ placement = value.placements[0]
1456
+ # If gathered state is a DTensor and its TP placement is not Replicate(), we need to
1457
+ # gather the tensor on its TP dimension before chunking them into DTensor again.
1458
+ if placement != Replicate():
1459
+ placement_dim = placement.dim # type: ignore[attr-defined]
1460
+ value_local = value.redistribute(placements=(Replicate(),))
1461
+ reshape_size = list(flat_param._shapes[param_idx])
1462
+ reshape_size[placement_dim] *= value.device_mesh.size(0)
1463
+ reshape_size = torch.Size(reshape_size)
1464
+ value = value.reshape(reshape_size)
1465
+ # If gathered state is a replicate DTensor, we directly reshape it.
1466
+ else:
1467
+ value = value.reshape(flat_param._shapes[param_idx])
1468
+ else:
1469
+ # If gathered state is a tensor, we directly reshape it into unflatten state.
1470
+ value = value.reshape(flat_param._shapes[param_idx])
1471
+
1472
+ if shard_state:
1473
+ osd_config = fsdp_state._optim_state_dict_config
1474
+ if getattr(osd_config, "_use_dtensor", False):
1475
+ assert fsdp_state._device_mesh is not None
1476
+ value = _ext_chunk_dtensor(
1477
+ value,
1478
+ fsdp_state.rank,
1479
+ fsdp_state._device_mesh,
1480
+ fsdp_state._fsdp_extension,
1481
+ )
1482
+ else:
1483
+ assert fsdp_state.process_group is not None
1484
+ value = _ext_chunk_tensor(
1485
+ value,
1486
+ fsdp_state.rank,
1487
+ fsdp_state.world_size,
1488
+ fsdp_state._device_handle.device_count(),
1489
+ fsdp_state.process_group,
1490
+ fsdp_state._fsdp_extension,
1491
+ )
1492
+ elif not cpu_offload:
1493
+ with SimpleProfiler.profile("clone"):
1494
+ value = value.detach().clone()
1495
+
1496
+ if cpu_offload:
1497
+ with SimpleProfiler.profile(SimpleProfiler.Type.D2H):
1498
+ value = value.cpu()
1499
+ gathered_state[state_name] = value
1500
+
1501
+
1502
+ def _allgather_orig_param_states(
1503
+ fsdp_param_info: FSDPParamInfo,
1504
+ gathered_state_info: List[Dict[str, StateInfo]],
1505
+ input_states: Dict[str, Any],
1506
+ shard_state: bool,
1507
+ to_save: bool,
1508
+ cpu_offload: bool,
1509
+ ) -> Dict[str, Dict[str, Any]]:
1510
+ """
1511
+ Given the ``gathered_state_info`` and ``input_states``, the API allgathers
1512
+ all tensor states and restore non-tensor states from ``gathered_state_info``.
1513
+ """
1514
+ fsdp_state = fsdp_param_info.state
1515
+ if fsdp_state.rank == 0 and dist.get_debug_level() == dist.DebugLevel.DETAIL:
1516
+ logger.info(
1517
+ "Memory Summary before calling to _allgather_orig_param_states %s",
1518
+ fsdp_state._device_handle.memory_summary(),
1519
+ )
1520
+
1521
+ output_states: Dict[str, Dict[str, Any]] = {fqn: {} for fqn in input_states.keys()}
1522
+
1523
+ dtype, state_buffers = _convert_all_state_info(
1524
+ fsdp_param_info, gathered_state_info, input_states, output_states
1525
+ )
1526
+
1527
+ if len(state_buffers) == 0:
1528
+ return output_states
1529
+
1530
+ has_state_params: List[bool] = [
1531
+ True if fqn in output_states else False
1532
+ for fqn, idx in fsdp_param_info.param_indices.items()
1533
+ ]
1534
+
1535
+ # Loop through the ``state_buffers`` and construct the flattened, concatenated,
1536
+ # sharded states. The size of the constructed state will be the same size as
1537
+ # flat_param (also sharded).
1538
+ # Then we perform an allgather_into_tensor to get the full flat_param state.
1539
+ # The full flat_param state is the result of concatenation of multiple states
1540
+ # the order of of flat_param._fqns.
1541
+ # The final step is to split the flat_param state into original param states
1542
+ # and return the result.
1543
+ flat_param = fsdp_param_info.handle.flat_param
1544
+ empty_func = functools.partial(
1545
+ torch.empty, dtype=dtype, device=fsdp_state.compute_device
1546
+ )
1547
+ gathered_tensor = empty_func(flat_param._padded_unsharded_size)
1548
+ # Synchronize can be slow but this will be easier for us to debug.
1549
+ fsdp_state._device_handle.synchronize()
1550
+ for state_name, buffers in state_buffers.items():
1551
+ local_buffers: List[torch.Tensor] = []
1552
+ begin = fsdp_state.rank * flat_param._sharded_size.numel()
1553
+ # End is inclusive.
1554
+ end = begin + flat_param._sharded_size.numel() - 1
1555
+ # param_idx corresponds to the parameter index in the FlatParameter.
1556
+ mem_offset, param_idx = 0, 0
1557
+ for numel, is_padding in zip(
1558
+ flat_param._numels_with_padding, flat_param._is_padding_mask
1559
+ ):
1560
+ frozen_and_no_state = not is_padding and (
1561
+ not fsdp_param_info.param_requires_grad[param_idx]
1562
+ and not has_state_params[param_idx]
1563
+ )
1564
+
1565
+ if is_padding or frozen_and_no_state:
1566
+ # This memory range is a padding or the param is frozen and does
1567
+ # not require gradient. For the later case, we treat it as a
1568
+ # padding and add empty values to the local_buffers.
1569
+
1570
+ padding_begin, padding_end = mem_offset, mem_offset + numel - 1
1571
+ if padding_begin <= begin <= padding_end:
1572
+ # The range is an align padding before the first parameter in
1573
+ # the shard. The shard includes parts of this align padding.
1574
+ padding_len = (
1575
+ padding_end - begin + 1
1576
+ if end >= padding_end
1577
+ else end - begin + 1
1578
+ )
1579
+ elif padding_begin <= end <= padding_end:
1580
+ # The range is an align padding after the last parameter in
1581
+ # the shard. The shard includes parts of this align padding.
1582
+ padding_len = (
1583
+ end - padding_begin + 1
1584
+ if begin <= padding_begin
1585
+ else end - begin + 1
1586
+ )
1587
+ elif begin < padding_begin <= padding_end < end:
1588
+ # The range is an align padding that is completely in the
1589
+ # shard.
1590
+ padding_len = numel
1591
+ else:
1592
+ padding_len = 0
1593
+ if padding_len:
1594
+ local_buffers.append(empty_func(padding_len))
1595
+
1596
+ if not is_padding:
1597
+ # This memory range is a parameter in FlatParameter. So there
1598
+ # should be an corresponding state in the optimizer unless the
1599
+ # parameter is frozen, which we treat it as a padding above.
1600
+
1601
+ # We need to check if this rank owns the buffer. If this is None:
1602
+ # 1.) the rank does not own any part of the original parameter.
1603
+ # As a result, there is no corresponding optimizer state on
1604
+ # the rank as well.
1605
+ # 2.) the parameter is frozen AND no optimizer state for the
1606
+ # parameter. If a parameter is frozen, there can still be
1607
+ # optimizer state if the parameter is not frozen in the
1608
+ # previous steps.
1609
+ if buffers[param_idx] is not None:
1610
+ local_buffers.append(cast(torch.Tensor, buffers[param_idx]))
1611
+ param_idx += 1
1612
+
1613
+ mem_offset += numel
1614
+
1615
+ shard_numel_padded = flat_param._sharded_size.numel() - (
1616
+ sum(t.numel() for t in local_buffers)
1617
+ )
1618
+
1619
+ assert flat_param._shard_numel_padded == shard_numel_padded, (
1620
+ "Manually calculated _sharded_numel_padded is incorrect. "
1621
+ f"_shard_numel_padded={flat_param._shard_numel_padded}, "
1622
+ f"shard_numel_padded={shard_numel_padded}, "
1623
+ f"_sharded_size.numel={flat_param._sharded_size.numel()}, "
1624
+ f"_numels_with_padding={flat_param._numels_with_padding}, "
1625
+ f"begin={begin}, end={end},"
1626
+ )
1627
+ if shard_numel_padded > 0:
1628
+ # Add right-handed padding.
1629
+ local_buffers.append(empty_func(shard_numel_padded))
1630
+ local_shard = torch.cat(local_buffers)
1631
+ assert local_shard.numel() * fsdp_state.world_size == gathered_tensor.numel(), (
1632
+ "The size of local shard times the world size should equal to the "
1633
+ "gathered tensor size. The inconsistency may be from a bug of "
1634
+ "FlatParameter's metadata or the reconstruction logic in optimizer "
1635
+ "state dict."
1636
+ )
1637
+ fsdp_state._device_handle.synchronize()
1638
+ with SimpleProfiler.profile(SimpleProfiler.Type.ALLGATHER):
1639
+ dist.all_gather_into_tensor(
1640
+ gathered_tensor, local_shard, group=fsdp_state.process_group
1641
+ )
1642
+ # Synchronize can be slow but this will be easier for us to debug.
1643
+ fsdp_state._device_handle.synchronize()
1644
+
1645
+ unpadded_tensor = gathered_tensor[: flat_param._unpadded_unsharded_size.numel()]
1646
+ flat_param_handle = fsdp_param_info.handle
1647
+ orig_states = flat_param_handle._get_unflat_views_aligned(unpadded_tensor)
1648
+ assert len(orig_states) == len(fsdp_param_info.param_indices), (
1649
+ "The number of parameters from FlatParameter is not consistent to "
1650
+ "the number of states used by optimizer state dict reconstruction "
1651
+ "logic."
1652
+ )
1653
+ for fqn, idx in fsdp_param_info.param_indices.items():
1654
+ if fsdp_param_info.param_requires_grad[idx] or fqn in output_states:
1655
+ output_states[fqn][state_name] = orig_states[idx]
1656
+
1657
+ _unflatten_orig_param_states(
1658
+ fsdp_param_info,
1659
+ output_states,
1660
+ state_name,
1661
+ shard_state,
1662
+ to_save,
1663
+ cpu_offload,
1664
+ )
1665
+
1666
+ del gathered_tensor
1667
+ return output_states
1668
+
1669
+
1670
+ def _gather_all_orig_param_state(
1671
+ fsdp_param_info: FSDPParamInfo,
1672
+ input_states: Dict[str, Any],
1673
+ shard_state: bool,
1674
+ to_save: bool,
1675
+ cpu_offload: bool,
1676
+ ) -> Dict[str, Any]:
1677
+ """
1678
+ Given a optimizer state dict, ``input_states``, which the keys are FQNs to the
1679
+ original parameters (not FlatParameters nor parmeter ID), gather all the
1680
+ states and unflatten them to the original dimensions. Note that all the
1681
+ params referred by the ``input_states`` must be managed by FSDP.
1682
+ """
1683
+ fsdp_state = fsdp_param_info.state
1684
+ if (
1685
+ fsdp_state.world_size == 1
1686
+ or fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD
1687
+ ):
1688
+ return input_states if to_save else {}
1689
+
1690
+ with SimpleProfiler.profile(SimpleProfiler.Type.RESHARDING):
1691
+ with SimpleProfiler.profile(SimpleProfiler.Type.ALLGATHER_OBJ):
1692
+ gathered_state_info = _allgather_state_info(fsdp_state, input_states)
1693
+ output_states = _allgather_orig_param_states(
1694
+ fsdp_param_info,
1695
+ gathered_state_info,
1696
+ input_states,
1697
+ shard_state,
1698
+ to_save,
1699
+ cpu_offload,
1700
+ )
1701
+ if to_save:
1702
+ for key, idx in fsdp_param_info.param_indices.items():
1703
+ if key in output_states:
1704
+ continue
1705
+ if not fsdp_param_info.param_requires_grad[idx]:
1706
+ continue
1707
+
1708
+ raise RuntimeError(
1709
+ f"{key} is not in the output state. "
1710
+ "The FSDPParamInfo has the param keys "
1711
+ f"{sorted(fsdp_param_info.param_indices.keys())} while "
1712
+ "the output_states has the param keys "
1713
+ f"{sorted(output_states.keys())}."
1714
+ )
1715
+ return output_states
1716
+ else:
1717
+ return {}
1718
+
1719
+
1720
+ def _convert_state_with_orig_params(
1721
+ all_optim_state_keys: List[_OptimStateKey],
1722
+ optim_state_key_to_param_key: Dict[_OptimStateKey, Union[int, str]],
1723
+ fqn_to_fsdp_param_info: Dict[str, FSDPParamInfo],
1724
+ optim_state_dict: Dict[Union[str, int], Any],
1725
+ to_save: bool,
1726
+ shard_state: bool,
1727
+ cpu_offload: bool = True,
1728
+ ) -> Dict[str, Any]:
1729
+ fsdp_osd_state: Dict[str, Any] = {}
1730
+ # This variable is used to deduplicate the FSDPParamInfo as one FSDPParamInfo
1731
+ # usually corresponds to multiple parameters. We could not use FSDPParamInfo
1732
+ # as the key because FSDPParamInfo is not hashable. As a result, we fall back
1733
+ # to `id(FSDPParamInfo)`, which the type is an integer.
1734
+ all_states: Dict[int, Dict[str, Any]] = {}
1735
+ # Iterate in rank 0's flat parameter ID order to ensure aligned all-gathers
1736
+ # across ranks
1737
+ for optim_state_key in all_optim_state_keys:
1738
+ param_key: Union[str, int, None] = optim_state_key_to_param_key.get(
1739
+ optim_state_key, None
1740
+ )
1741
+
1742
+ if param_key is None and not optim_state_key.is_fsdp_managed:
1743
+ continue
1744
+
1745
+ if optim_state_key.is_fsdp_managed:
1746
+ fqn = optim_state_key.unflat_param_names[0]
1747
+ fsdp_param_info = fqn_to_fsdp_param_info.get(fqn, None)
1748
+ if fsdp_param_info is None:
1749
+ # This can happen if the not all FSDP instances have all the
1750
+ # parameters. This can happen with FSDP + some MPMD style
1751
+ # parallelism.
1752
+
1753
+ # TODO: it is unclear if we need to do the same check with
1754
+ # non-FSDP managed keys.
1755
+ continue
1756
+ state = {} if param_key is None else optim_state_dict[param_key]
1757
+ if id(fsdp_param_info) not in all_states:
1758
+ all_states[id(fsdp_param_info)] = {}
1759
+ all_states[id(fsdp_param_info)][fqn] = state
1760
+
1761
+ elif to_save:
1762
+ assert len(optim_state_key.unflat_param_names) == 1
1763
+ unflat_param_name = optim_state_key.unflat_param_names[0]
1764
+ with SimpleProfiler.profile("none_fsdp_managed_copy"):
1765
+ param_key = cast(Union[str, int], param_key)
1766
+ fsdp_osd_state[unflat_param_name] = copy.copy(
1767
+ optim_state_dict[param_key]
1768
+ )
1769
+ if cpu_offload:
1770
+ for state_name, value in sorted_items(
1771
+ fsdp_osd_state[unflat_param_name]
1772
+ ):
1773
+ if not torch.is_tensor(value):
1774
+ continue
1775
+ fsdp_osd_state[unflat_param_name][state_name] = value.cpu()
1776
+
1777
+ # Instead of gathering the state of each parameter individually, we perform
1778
+ # the gathering all at once to speed up the process.
1779
+ for _all_states in all_states.values():
1780
+ fqn = next(iter(_all_states.keys()))
1781
+ fsdp_param_info = fqn_to_fsdp_param_info[fqn]
1782
+ assert len(fsdp_param_info.param_requires_grad) > 0, (
1783
+ "With use_orig_params, FSDPParamInfo should have requires_grad "
1784
+ "information. However, the length is zero."
1785
+ )
1786
+ for key, idx in fsdp_param_info.param_indices.items():
1787
+ if key in _all_states:
1788
+ continue
1789
+ if not fsdp_param_info.param_requires_grad[idx]:
1790
+ continue
1791
+ raise RuntimeError(
1792
+ f"{key} is not in the optimizer state. "
1793
+ "The FSDPParamInfo has the param keys "
1794
+ f"{sorted(fsdp_param_info.param_indices.keys())} while "
1795
+ "the optimizer has the param keys "
1796
+ f"{sorted(_all_states.keys())}."
1797
+ )
1798
+ fsdp_osd_state.update(
1799
+ _gather_all_orig_param_state(
1800
+ fsdp_param_info,
1801
+ _all_states,
1802
+ shard_state,
1803
+ to_save,
1804
+ cpu_offload,
1805
+ )
1806
+ )
1807
+
1808
+ return fsdp_osd_state
1809
+
1810
+
1811
+ def _convert_state_with_flat_params(
1812
+ all_optim_state_keys: List[_OptimStateKey],
1813
+ optim_state_key_to_param_key: Dict[_OptimStateKey, Union[int, str]],
1814
+ fqn_to_fsdp_param_info: Dict[str, FSDPParamInfo],
1815
+ optim_state_dict: Dict[Union[str, int], Any],
1816
+ to_save: bool,
1817
+ shard_state: bool,
1818
+ cpu_offload: bool = True,
1819
+ ) -> Dict[str, Any]:
1820
+ fsdp_osd_state: Dict[str, Any] = {}
1821
+ # Iterate in rank 0's flat parameter ID order to ensure aligned all-gathers
1822
+ # across ranks
1823
+ for optim_state_key in all_optim_state_keys:
1824
+ param_key: Union[str, int, None] = optim_state_key_to_param_key.get(
1825
+ optim_state_key, None
1826
+ )
1827
+
1828
+ assert param_key is not None, (
1829
+ "If use_orig_params is False, we must be able to find the "
1830
+ f"corresponding param id. {optim_state_key} {param_key}"
1831
+ )
1832
+
1833
+ if optim_state_key.is_fsdp_managed:
1834
+ # If there are multiple unflat_param_names (not use_orig_params),
1835
+ # they share the same FSDPParamInfo. So the first unflat_param_name
1836
+ # is sufficient to fetch the FSDPParamInfo.
1837
+ fqn = optim_state_key.unflat_param_names[0]
1838
+ fsdp_param_info = fqn_to_fsdp_param_info[fqn]
1839
+ unflat_state = _unflatten_optim_state(
1840
+ fsdp_param_info,
1841
+ optim_state_dict[param_key],
1842
+ to_save,
1843
+ shard_state,
1844
+ cpu_offload,
1845
+ )
1846
+ if to_save:
1847
+ assert len(unflat_state) == len(optim_state_key.unflat_param_names)
1848
+ for unflat_param_name, unflat_param_state in zip(
1849
+ optim_state_key.unflat_param_names,
1850
+ unflat_state,
1851
+ ):
1852
+ fsdp_osd_state[unflat_param_name] = unflat_param_state
1853
+ elif to_save:
1854
+ assert len(optim_state_key.unflat_param_names) == 1
1855
+ unflat_param_name = optim_state_key.unflat_param_names[0]
1856
+ fsdp_osd_state[unflat_param_name] = copy.copy(optim_state_dict[param_key])
1857
+ if cpu_offload:
1858
+ for state_name, value in sorted_items(
1859
+ fsdp_osd_state[unflat_param_name]
1860
+ ):
1861
+ if not torch.is_tensor(value):
1862
+ continue
1863
+ fsdp_osd_state[unflat_param_name][state_name] = value.cpu()
1864
+
1865
+ return fsdp_osd_state
1866
+
1867
+
1868
+ @torch.no_grad()
1869
+ def _optim_state_dict(
1870
+ model: nn.Module,
1871
+ optim: torch.optim.Optimizer,
1872
+ optim_state_dict: Dict[str, Any],
1873
+ optim_input: Optional[
1874
+ Union[
1875
+ List[Dict[str, Any]],
1876
+ Iterable[nn.Parameter],
1877
+ ]
1878
+ ],
1879
+ rank0_only: bool,
1880
+ shard_state: bool,
1881
+ group: Optional[dist.ProcessGroup],
1882
+ using_optim_input: bool,
1883
+ use_orig_params: bool = False,
1884
+ cpu_offload: bool = True,
1885
+ ) -> Dict[str, Any]:
1886
+ """
1887
+ Consolidates the optimizer state and returns it as a :class:`dict`
1888
+ following the convention of :meth:`torch.optim.Optimizer.state_dict`,
1889
+ i.e. with keys ``"state"`` and ``"param_groups"``.
1890
+ The flat parameters in ``FSDP`` modules contained in ``model`` are mapped
1891
+ back to their unflattened parameters.
1892
+
1893
+ Parameter keys are not well-defined. For a regular optimizer, the optimizer
1894
+ state_dict contains a mapping from parameter IDs to parameter states.
1895
+ Parameter IDs are the order of parameters in ``optim.param_groups()`` across
1896
+ all the groups. This API also allows user to pass ``optim_input`` for the
1897
+ mapping between parameters and parameter IDs. Using ``optim_input`` is being
1898
+ deprecated.
1899
+
1900
+ If the optimizer is a ``NamedOptimizer``, the optimizer state_dict does not
1901
+ contain parameter IDs mapping but a mapping from parameter FQNs to parameter
1902
+ states. This API finds the mapping from FQNs to parameters if the optimizer
1903
+ is a ``NamedOptimizer``.
1904
+
1905
+ If ``use_orig_params`` is True, each rank will have all FSDP-managed
1906
+ parameters but some of these parameters may be empty due to the sharding.
1907
+ For a regular optim.Optimizer, states for those empty parameters will
1908
+ not be initialized. So, when aggregating the FQNs across ranks, no assert
1909
+ will be raised on a rank even if it does not have all the states -- it is
1910
+ valid and FSDP knows how to aggregate them. However, FSDP has to ignore
1911
+ handling those parameters that are not managed by FSDP and do not exist on
1912
+ the local rank -- those are managed by other parallelisms and FSDP does not
1913
+ know how to handle/aggregate them.
1914
+
1915
+ Args:
1916
+ model (nn.Module): Root module (which may or may not be a
1917
+ :class:`FullyShardedDataParallel` instance) whose parameters
1918
+ were passed into the optimizer ``optim``.
1919
+ optim (torch.optim.Optimizer): Optimizer for ``model`` 's
1920
+ parameters.
1921
+ rank0_only (bool): If ``True``, saves the populated :class:`dict`
1922
+ only on rank 0; if ``False``, saves it on all ranks. (Default:
1923
+ ``True``)
1924
+ shard_state (bool): If ``True``, shard and distribute all
1925
+ non-zero-dimension states.
1926
+
1927
+ Returns:
1928
+ Dict[str, Any]: A :class:`dict` containing the optimizer state for
1929
+ ``model`` 's original unflattened parameters and including keys
1930
+ "state" and "param_groups" following the convention of
1931
+ :meth:`torch.optim.Optimizer.state_dict`. If ``rank0_only=False``,
1932
+ then nonzero ranks return an empty :class:`dict`.
1933
+ """
1934
+ SimpleProfiler.reset()
1935
+ cm = ExitStack()
1936
+ cm.enter_context(SimpleProfiler.profile(SimpleProfiler.Type.ALL))
1937
+ _reset_flat_param_grad_info_if_needed(traversal_utils._get_fsdp_handles(model))
1938
+ to_save = not rank0_only or dist.get_rank(group) == 0 or shard_state
1939
+
1940
+ with SimpleProfiler.profile("preprocessing"):
1941
+ param_to_fqns = _get_param_to_fqns(model)
1942
+ flat_param_to_fqn = _get_flat_param_to_fqn(model)
1943
+ is_named_optimizer = _is_named_optimizer(optim_state_dict)
1944
+
1945
+ param_key_to_param = cast(
1946
+ Dict[Union[int, str], nn.Parameter],
1947
+ (
1948
+ _get_param_id_to_param_from_optim_input(model, optim_input)
1949
+ if using_optim_input
1950
+ else _get_param_key_to_param(
1951
+ optim, model, is_named_optimizer, param_to_fqns, flat_param_to_fqn
1952
+ )
1953
+ ),
1954
+ )
1955
+ fqn_to_fsdp_param_info = _get_fqn_to_fsdp_param_info(model)
1956
+
1957
+ with SimpleProfiler.profile("preprocessing_with_comm"):
1958
+ (
1959
+ all_optim_state_keys,
1960
+ optim_state_key_to_param_key,
1961
+ ) = _map_param_key_to_optim_keys(
1962
+ optim_state_dict,
1963
+ group,
1964
+ param_key_to_param,
1965
+ param_to_fqns,
1966
+ fqn_to_fsdp_param_info,
1967
+ merge_keys=use_orig_params,
1968
+ )
1969
+
1970
+ with SimpleProfiler.profile("state_converting"):
1971
+ convert_fn = (
1972
+ _convert_state_with_orig_params
1973
+ if use_orig_params
1974
+ else _convert_state_with_flat_params
1975
+ )
1976
+ fsdp_osd_state = convert_fn(
1977
+ all_optim_state_keys,
1978
+ optim_state_key_to_param_key,
1979
+ fqn_to_fsdp_param_info,
1980
+ optim_state_dict["state"],
1981
+ to_save,
1982
+ shard_state,
1983
+ cpu_offload,
1984
+ )
1985
+
1986
+ # At this point, communication is complete and ranks can return early if nothing
1987
+ # will be saved on that rank.
1988
+ if not to_save:
1989
+ return {}
1990
+
1991
+ fsdp_osd: Dict[str, Any] = {"state": fsdp_osd_state}
1992
+
1993
+ flat_param_fqns = set(flat_param_to_fqn.values())
1994
+ for key, value in optim_state_dict["state"].items():
1995
+ if key in fsdp_osd_state:
1996
+ continue
1997
+ if key in flat_param_fqns:
1998
+ continue
1999
+ if key in param_key_to_param:
2000
+ continue
2001
+ # This key is not recognized by FSDP. It may be a user-defined state
2002
+ # or some parameters state that FSDP is unable to map from
2003
+ # ``optim.param_groups``.
2004
+ warnings.warn(
2005
+ f"Found a optim state, {key}, that FSDP cannot process. FSDP "
2006
+ "will directly copy everything to the returned state_dict. In "
2007
+ "most cases, this is a user-defined state that is not "
2008
+ "associated with any particular parameter. Another possible "
2009
+ "case is this state is managed by TorchRec. Otherwise, there may "
2010
+ " be a mismatched assumption of optim_state_dict of this mode."
2011
+ )
2012
+ fsdp_osd_state[key] = value
2013
+
2014
+ if "param_groups" in optim_state_dict:
2015
+ fsdp_osd["param_groups"] = _unflatten_param_groups(
2016
+ optim_state_dict, param_key_to_param, param_to_fqns
2017
+ )
2018
+
2019
+ cm.close()
2020
+ SimpleProfiler.dump_and_reset("FSDP _optim_state_dict() profiling: ")
2021
+
2022
+ return fsdp_osd
2023
+
2024
+
2025
+ def _get_fqn_to_fsdp_param_info(model: nn.Module) -> Dict[str, FSDPParamInfo]:
2026
+ """
2027
+ Construct the mapping from a param's fqn to its corresponding ``FSDPParamInfo``
2028
+ if the param is managed by FSDP. Shared parameters, or original parameters that
2029
+ are shared across multiple nn.Modules, are required to belong to one and only
2030
+ one FSDP instance and thus correspond to one ``FlatParameter``. Within the one
2031
+ ``FlatParameter``, ``FlatParameter._fqns`` only stores the first FQN of a shared
2032
+ parameter. Thus, the keys in the mapping are guaranteed to map to unique parameters.
2033
+ """
2034
+
2035
+ def module_fn(module, prefix, tree_level, fqn_to_param_info):
2036
+ fsdp_state = _get_module_fsdp_state_if_fully_sharded_module(module)
2037
+ if fsdp_state is None:
2038
+ return
2039
+ _lazy_init(fsdp_state, module)
2040
+ handle = _module_handle(fsdp_state, module)
2041
+ if not handle:
2042
+ return
2043
+ flat_param = handle.flat_param
2044
+ fsdp_param_info = FSDPParamInfo(fsdp_state, handle, {}, [])
2045
+ # NOTE: `idx` indexes into the data structures *without* padding
2046
+ # elements
2047
+ for idx, local_fqn in enumerate(flat_param._fqns):
2048
+ fqn = clean_tensor_name(prefix + local_fqn)
2049
+ if fqn in fqn_to_param_info:
2050
+ assert fqn_to_param_info[fqn].handle.flat_param is flat_param, fqn
2051
+ fqn_to_param_info[fqn] = fsdp_param_info
2052
+ fsdp_param_info.param_indices[fqn] = idx
2053
+ if flat_param._params is not None:
2054
+ fsdp_param_info.param_requires_grad.append(
2055
+ flat_param._params[idx].requires_grad
2056
+ )
2057
+
2058
+ def return_fn(fqn_to_param_info):
2059
+ return fqn_to_param_info
2060
+
2061
+ fqn_to_param_info: Dict[str, FSDPParamInfo] = {}
2062
+ # FlatParameter._fqns stores the local fqn, starting from the root of the
2063
+ # FSDP. Using _apply_to_modules() with model (may not be the FSDP root
2064
+ # module) allows us to construct the global fqn.
2065
+ return _apply_to_modules(
2066
+ model,
2067
+ module_fn,
2068
+ return_fn,
2069
+ [fqn for fqn, _ in _named_parameters_with_duplicates(model)],
2070
+ fqn_to_param_info,
2071
+ )
2072
+
2073
+
2074
+ @no_type_check
2075
+ def _set_optim_use_dtensor(
2076
+ fsdp_state: _FSDPState,
2077
+ state_dict_settings: StateDictSettings,
2078
+ ) -> None:
2079
+ # If device_mesh is passed in when initalizing FSDP, we automatically turn the
2080
+ # _use_dtensor flag to be true for ShardedOptimStateDictConfig() if state_dict_type
2081
+ # has to be set to SHARDED_STATE_DICT.
2082
+ if getattr(fsdp_state, "_device_mesh", None):
2083
+ state_dict_type = state_dict_settings.state_dict_type
2084
+ if state_dict_type == StateDictType.LOCAL_STATE_DICT:
2085
+ raise RuntimeError(
2086
+ "Found state_dict_type LOCAL_STATE_DICT.",
2087
+ "DeviceMesh is not compatible with LOCAL_STATE_DICT.",
2088
+ "Please set state_dict_type to SHARDED_STATE_DICT to get DTensor state_dict.",
2089
+ )
2090
+ else:
2091
+ state_dict_settings.optim_state_dict_config._use_dtensor = True
vllm/lib/python3.10/site-packages/torch/distributed/fsdp/_runtime_utils.py ADDED
@@ -0,0 +1,1638 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import functools
3
+ import logging
4
+ from enum import auto, Enum
5
+ from typing import Any, Callable, Dict, List, no_type_check, Optional, Set, Tuple
6
+
7
+ import torch
8
+ import torch.distributed as dist
9
+ import torch.distributed.fsdp._traversal_utils as traversal_utils
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+ from torch.autograd import Variable
13
+ from torch.autograd.graph import register_multi_grad_hook
14
+ from torch.distributed.algorithms._comm_hooks import LOW_PRECISION_HOOKS
15
+ from torch.distributed.fsdp._common_utils import (
16
+ _assert_in_training_states,
17
+ _FSDPState,
18
+ _get_module_fsdp_state,
19
+ _is_composable,
20
+ _log_post_backward_hook,
21
+ _no_dispatch_record_stream,
22
+ clean_tensor_name,
23
+ TrainingState,
24
+ )
25
+ from torch.distributed.fsdp._flat_param import (
26
+ FlatParameter,
27
+ FlatParamHandle,
28
+ HandleShardingStrategy,
29
+ HandleTrainingState,
30
+ RESHARD_AFTER_FORWARD_HANDLE_STRATEGIES,
31
+ )
32
+ from torch.distributed.fsdp._init_utils import HYBRID_SHARDING_STRATEGIES
33
+ from torch.distributed.fsdp.api import BackwardPrefetch
34
+ from torch.distributed.utils import (
35
+ _apply_to_tensors,
36
+ _cast_forward_inputs,
37
+ _p_assert,
38
+ _to_kwargs,
39
+ )
40
+ from torch.utils import _pytree as pytree
41
+
42
+
43
+ logger = logging.getLogger(__name__)
44
+
45
+ # Do not include "process_group" to enable hybrid shard and MoE cases
46
+ HOMOGENEOUS_ATTR_NAMES = (
47
+ "_use_orig_params",
48
+ "limit_all_gathers",
49
+ "_use_full_prec_in_eval",
50
+ )
51
+
52
+
53
+ class _PrefetchMode(Enum):
54
+ BACKWARD = auto()
55
+ FORWARD = auto()
56
+
57
+
58
+ def _get_fsdp_root_states_with_modules(
59
+ module: nn.Module,
60
+ ) -> Tuple[List[_FSDPState], List[nn.Module]]:
61
+ """
62
+ Returns a tuple containing:
63
+ 1. A list of the root ``_FSDPState`` instances in the module tree rooted at
64
+ ``module`` without any duplicates and following the ``module.modules()``
65
+ traversal order (which is assumed to be depth-first).
66
+ 2. A corresponding list of the root modules owning the states in the first
67
+ list.
68
+
69
+ This is similar to :func:`_get_fsdp_states_with_modules` except that we
70
+ must call :func:`_is_fsdp_root` to force a lazy initialization to determine
71
+ the FSDP root in case lazy initialization has not yet happened.
72
+ """
73
+ fsdp_root_states: List[_FSDPState] = []
74
+ fsdp_root_modules: List[nn.Module] = []
75
+ visited_fsdp_states: Set[_FSDPState] = set()
76
+ # NOTE: This function assumes that `module.modules()` proceeds top-down.
77
+ for submodule in module.modules():
78
+ optional_state = _get_module_fsdp_state(submodule)
79
+ if (
80
+ optional_state is not None
81
+ and optional_state not in visited_fsdp_states
82
+ and _is_fsdp_root(optional_state, submodule)
83
+ ):
84
+ visited_fsdp_states.add(optional_state)
85
+ fsdp_root_states.append(optional_state)
86
+ fsdp_root_modules.append(submodule)
87
+ return fsdp_root_states, fsdp_root_modules
88
+
89
+
90
+ def _get_fsdp_root_states(module: nn.Module) -> List[_FSDPState]:
91
+ """See :func:`_get_fsdp_root_states_with_modules`."""
92
+ fsdp_root_states, _ = _get_fsdp_root_states_with_modules(module)
93
+ return fsdp_root_states
94
+
95
+
96
+ def _is_fsdp_root(state: _FSDPState, module: nn.Module) -> bool:
97
+ """
98
+ Returns if ``state`` corresponds to that of an FSDP root.
99
+
100
+ For the wrapper code path, ``state`` and ``module`` should be the same. For
101
+ the non-wrapper code path, ``state`` should be ``module`` 's state.
102
+ """
103
+ # Force a lazy initialization to determine the FSDP root
104
+ _lazy_init(state, module)
105
+ assert state._is_root is not None # mypy
106
+ return state._is_root
107
+
108
+
109
+ @no_type_check
110
+ def _lazy_init(
111
+ state: _FSDPState,
112
+ root_module: nn.Module,
113
+ ) -> _FSDPState:
114
+ """
115
+ Performs initialization lazily, typically right before the first forward
116
+ pass. The laziness is needed to ensure that the parameter device/dtype and
117
+ the FSDP hierarchy have finalized. This method's actual logic only runs on
118
+ the root FSDP instance, which performs initialization for all non-root FSDP
119
+ instances to avoid partial initialization.
120
+
121
+ For the non-composable code path, ``state`` and ``root_module`` should be
122
+ the same, namely the FSDP instance itself.
123
+ """
124
+ if state._is_root is not None:
125
+ return # no-op: already lazily initialized
126
+ if not state._device_handle.is_available():
127
+ # Allow the FSDP constructor to run even without CUDA but check this
128
+ # once we start real execution
129
+ raise RuntimeError("FSDP does not support CPU only execution")
130
+ # The following logic is only run on the root FSDP instance since it will
131
+ # set `_is_root=False` for the non-root instances
132
+ state._is_root = True
133
+ _assert_in_training_states(state, [TrainingState.IDLE])
134
+ _check_flat_params_on_expected_device(state, root_module)
135
+ state._all_fsdp_states = traversal_utils._get_fsdp_states(root_module)
136
+ _init_streams(state)
137
+ buffers, buffer_dtypes = _get_buffers_and_dtypes_for_computation(state, root_module)
138
+ _cast_buffers_to_dtype_and_device(buffers, buffer_dtypes, state.compute_device)
139
+ state._exec_order_data.init(state, root_module, state.process_group)
140
+ _share_state_and_init_handle_attrs(state, root_module)
141
+ return state
142
+
143
+
144
+ def _check_flat_params_on_expected_device(state: _FSDPState, module: nn.Module):
145
+ """
146
+ Checks that all ``FlatParameter``s in ``module`` 's tree managed by
147
+ ``state`` are on the expected device for *lazy initialization*.
148
+ """
149
+ cpu_device = torch.device("cpu")
150
+ for handle in traversal_utils._get_fsdp_handles(module):
151
+ if (
152
+ not handle._offload_params
153
+ and handle.flat_param.device != state.compute_device
154
+ ):
155
+ raise RuntimeError(
156
+ "An FSDP-managed module unexpectedly has parameters on "
157
+ f"{handle.flat_param.device}. Make sure to move the module to "
158
+ f"{state.compute_device} before training."
159
+ )
160
+ elif handle._offload_params and handle.flat_param.device != cpu_device:
161
+ raise RuntimeError(
162
+ "An FSDP-managed module with parameter CPU offloading enabled "
163
+ f"has parameters on {handle.flat_param.device}. Make sure to "
164
+ f"not move the module from CPU when offloading parameters."
165
+ )
166
+
167
+
168
+ @no_type_check
169
+ def _share_state_and_init_handle_attrs(
170
+ root_state: _FSDPState,
171
+ root_module: nn.Module,
172
+ ) -> None:
173
+ """
174
+ Shares data structure state from the ``root_state`` to all FSDP states in
175
+ ``root_module`` 's module tree, and initializes handle attributes. These
176
+ are done together to require a single loop over the states.
177
+ """
178
+ handle = root_state._handle
179
+ if handle:
180
+ handle.init_flat_param_attributes()
181
+ attr_name_to_values: Dict[str, Set[Any]] = {}
182
+ for attr_name in HOMOGENEOUS_ATTR_NAMES:
183
+ attr_name_to_values[attr_name] = set()
184
+ root_state._all_handles = root_state._exec_order_data.all_handles # share reference
185
+ # Update _has_optim_in_backward for each handle.
186
+ for handle in root_state._all_handles:
187
+ flat_param = handle.flat_param
188
+ if hasattr(flat_param, "_in_backward_optimizers"):
189
+ raise RuntimeError(
190
+ "FSDP optimizer in backward only supported with use_orig_params=True!"
191
+ )
192
+ handle._has_optim_in_backward = flat_param._params is not None and any(
193
+ hasattr(param, "_in_backward_optimizers") for param in flat_param._params
194
+ )
195
+ if handle._has_optim_in_backward:
196
+ torch._C._log_api_usage_once("fsdp.optimizer_in_backward")
197
+ for fsdp_state in root_state._all_fsdp_states:
198
+ for attr_name in HOMOGENEOUS_ATTR_NAMES:
199
+ _p_assert(
200
+ hasattr(fsdp_state, attr_name),
201
+ f"FSDP state missing attribute {attr_name}",
202
+ )
203
+ attr_name_to_values[attr_name].add(getattr(fsdp_state, attr_name))
204
+ if fsdp_state is root_state:
205
+ continue
206
+ # Relax the assert for non-root FSDP instances in case the nested
207
+ # initialized module is wrapped again in FSDP later (e.g. after
208
+ # training to run inference)
209
+ _p_assert(
210
+ fsdp_state._is_root is None or not fsdp_state._is_root,
211
+ "Non-root FSDP instance's `_is_root` should not have been "
212
+ "set yet or should have been set to `False`",
213
+ )
214
+ fsdp_state._is_root = False
215
+ fsdp_state._unshard_stream = root_state._unshard_stream
216
+ fsdp_state._post_backward_stream = root_state._post_backward_stream
217
+ fsdp_state._pre_unshard_stream = root_state._pre_unshard_stream
218
+ fsdp_state._all_reduce_stream = root_state._all_reduce_stream
219
+ fsdp_state._default_stream = root_state._default_stream
220
+ fsdp_state._exec_order_data = root_state._exec_order_data
221
+ fsdp_state._free_event_queue = root_state._free_event_queue
222
+ if fsdp_state._fsdp_extension is not None:
223
+ fsdp_state._fsdp_extension.compute_stream = root_state._default_stream
224
+ handle = fsdp_state._handle
225
+ if handle:
226
+ handle.init_flat_param_attributes()
227
+ for attr_name, attr_values in attr_name_to_values.items():
228
+ if len(attr_values) != 1:
229
+ raise ValueError(
230
+ f"Expects one homogeneous value for {attr_name} but got {attr_values}"
231
+ )
232
+
233
+
234
+ @no_type_check
235
+ def _init_streams(
236
+ state: _FSDPState,
237
+ ) -> None:
238
+ """
239
+ Initializes CUDA streams for overlapping communication, computation, and
240
+ data transfers. The streams should be shared across FSDP instances.
241
+ """
242
+ assert state._is_root
243
+ assert state._device_handle.is_available()
244
+ uses_hybrid_sharding = any(
245
+ fsdp_state.sharding_strategy in HYBRID_SHARDING_STRATEGIES
246
+ for fsdp_state in state._all_fsdp_states
247
+ )
248
+ # Prioritize all-gathers/reduce-scatters over async all-reduce for HSDP and
249
+ # preserve the default priority of 0 otherwise
250
+ high_priority = -1 if state.limit_all_gathers and uses_hybrid_sharding else 0
251
+ # Default stream for computation
252
+ state._default_stream = state._device_handle.current_stream()
253
+ if state._fsdp_extension is not None:
254
+ # set the compute stream to the FSDP extension
255
+ state._fsdp_extension.compute_stream = state._default_stream
256
+
257
+ # Stream for unshard logic, including allocating the all-gather destination
258
+ # tensors and the all-gathers themselves
259
+ state._unshard_stream = state._device_handle.Stream(priority=high_priority)
260
+ # Stream for overlapping gradient reduction with the backward pass gradient
261
+ # computation
262
+ state._post_backward_stream = state._device_handle.Stream(priority=high_priority)
263
+ # Stream for pre-unshard logic, namely allocations and writes for CPU
264
+ # offloading (H2D copy) and mixed precision (low precision cast)
265
+ state._pre_unshard_stream = state._device_handle.Stream(priority=high_priority)
266
+ # Stream to run HSDP's all-reduce as async (if using HSDP)
267
+ state._all_reduce_stream = (
268
+ state._device_handle.Stream() if uses_hybrid_sharding else state._default_stream
269
+ )
270
+
271
+
272
+ @no_type_check
273
+ def _unshard(
274
+ state: _FSDPState,
275
+ handle: FlatParamHandle,
276
+ unshard_stream: torch.Stream,
277
+ pre_unshard_stream: torch.Stream,
278
+ ) -> None:
279
+ """
280
+ Unshards the handles in ``handles``. If the handles are in
281
+ :meth:`summon_full_params` and are using mixed precision, then they are
282
+ forced to full precision.
283
+
284
+ Postcondition: handle's ``FlatParameter`` 's data is the padded
285
+ unsharded flat parameter on the compute device.
286
+ """
287
+ if not handle:
288
+ return
289
+ with state._device_handle.stream(pre_unshard_stream):
290
+ ran_pre_unshard = handle.pre_unshard()
291
+ if ran_pre_unshard:
292
+ unshard_stream.wait_stream(pre_unshard_stream)
293
+ if state.limit_all_gathers:
294
+ event = state._free_event_queue.dequeue_if_needed()
295
+ if event:
296
+ with torch.profiler.record_function(
297
+ "FullyShardedDataParallel.rate_limiter"
298
+ ):
299
+ event.synchronize()
300
+ with state._device_handle.stream(unshard_stream):
301
+ handle.unshard()
302
+ handle.post_unshard()
303
+
304
+
305
+ @no_type_check
306
+ def _reshard(
307
+ state: _FSDPState,
308
+ handle: FlatParamHandle,
309
+ free_unsharded_flat_param: bool,
310
+ ):
311
+ """
312
+ Reshards the handle. ``free_unsharded_flat_param`` indicates whether to
313
+ free the handle's padded unsharded flat parameter.
314
+ """
315
+ handle.reshard(free_unsharded_flat_param)
316
+ if state.limit_all_gathers and free_unsharded_flat_param:
317
+ if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
318
+ # We don't run a even queue for freeing under torch compile atm
319
+ # But maybe we need to? TODO(voz): Look into this
320
+ free_event = state._device_handle.Event()
321
+ free_event.record()
322
+ state._free_event_queue.enqueue(free_event)
323
+ handle.post_reshard()
324
+ # Flat parameter freed or not, we always have to "unshard" the parameter
325
+ # upon next access to get its shape correct.
326
+ handle._prefetched = False
327
+
328
+
329
+ def _unshard_grads(
330
+ handle: Optional[FlatParamHandle],
331
+ ) -> None:
332
+ if handle:
333
+ handle.unshard_grad()
334
+
335
+
336
+ def _reshard_grads(
337
+ handle: Optional[FlatParamHandle],
338
+ ) -> None:
339
+ if handle:
340
+ handle.reshard_grad()
341
+
342
+
343
+ @no_type_check
344
+ def _pre_forward(
345
+ state: _FSDPState,
346
+ handle: Optional[FlatParamHandle],
347
+ unshard_fn: Callable,
348
+ module: nn.Module,
349
+ args: Tuple[Any, ...],
350
+ kwargs: Dict[str, Any],
351
+ ) -> Tuple[Tuple[Any, ...], Dict[str, Any]]:
352
+ """
353
+ Runs the pre-forward logic. This includes an opportunity to unshard
354
+ currently sharded parameters such as those for the current forward and
355
+ registering post-backward hooks for these current parameters. This function
356
+ also converts forward ``args`` and ``kwargs`` to the given precision.
357
+
358
+ Args:
359
+ handles (List[FlatParamHandle]): Handles giving the parameters used in
360
+ the current forward.
361
+ unshard_fn (Optional[Callable]): A callable to unshard any currently
362
+ sharded parameters or ``None`` to not do any unsharding.
363
+ module (nn.Module): Module whose forward this method runs right before;
364
+ expected by the hook signature.
365
+ args (Tuple[Any, ...]): Module forward ``args``.
366
+ kwargs (Dict[str, Any]): Module forward ``kwargs``.
367
+ """
368
+ with torch.profiler.record_function("FullyShardedDataParallel._pre_forward"):
369
+ # For `fully_shard` + `checkpoint`, skip pre-forward logic in the
370
+ # recomputed forward
371
+ if handle and handle._training_state == HandleTrainingState.BACKWARD_PRE:
372
+ # For both checkpoint implementations, we do not need to re-cast
373
+ # inputs here since they will be checkpointed in the low precision
374
+ # either by AC or normally by autograd as long as the AC region is
375
+ # nested within FSDP
376
+ return args, kwargs
377
+ state.training_state = TrainingState.FORWARD_BACKWARD
378
+ state._exec_order_data.record_pre_forward(handle, module.training)
379
+ if handle:
380
+ handle._training_state = HandleTrainingState.FORWARD
381
+ if unshard_fn is not None:
382
+ unshard_fn(state, handle)
383
+ # Register post-backward hooks to reshard the parameters and reduce-scatter
384
+ # their gradients. They must be re-registered every forward pass in case
385
+ # the `grad_fn` is mutated.
386
+ _register_post_backward_hook(state, handle)
387
+ # We have to reallocate the _cpu_grad if optimizer overlap
388
+ # set the grad to None in the backward pass.
389
+ if handle and handle._offload_params and handle.flat_param._cpu_grad is None:
390
+ handle.flat_param._cpu_grad = torch.zeros_like(
391
+ handle.flat_param._local_shard, device=torch.device("cpu")
392
+ ).pin_memory(device=state.compute_device)
393
+
394
+ should_cast_forward_inputs = (
395
+ state._handle and not state._handle._force_full_precision
396
+ )
397
+
398
+ if should_cast_forward_inputs and state.mixed_precision.cast_forward_inputs:
399
+ # Recursively convert args and kwargs to specified precision.
400
+ input_dtype: Optional[torch.dtype] = state.mixed_precision.param_dtype
401
+ args, kwargs = _cast_forward_inputs(input_dtype, *args, **kwargs)
402
+ _register_post_backward_reshard_only_hook(state, handle, args, kwargs)
403
+ return args, kwargs
404
+
405
+
406
+ @no_type_check
407
+ def _pre_forward_unshard(
408
+ state: _FSDPState,
409
+ handle: Optional[FlatParamHandle],
410
+ ) -> None:
411
+ """Unshards parameters in the pre-forward."""
412
+ if not handle:
413
+ return
414
+ # If the handles have been prefetched, then there is no need to call
415
+ # `_unshard()` again
416
+ if not handle._prefetched:
417
+ _unshard(state, handle, state._unshard_stream, state._pre_unshard_stream)
418
+ handle._needs_pre_forward_unshard = False
419
+ # Don't wait during trace
420
+ if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
421
+ current_stream = state._device_handle.current_stream()
422
+ if state._unshard_event is not None:
423
+ current_stream.wait_event(state._unshard_event)
424
+ state._unshard_event = None
425
+ else:
426
+ current_stream.wait_stream(state._unshard_stream)
427
+ with torch.profiler.record_function(
428
+ "FullyShardedDataParallel._pre_forward_prefetch"
429
+ ):
430
+ _prefetch_handle(state, handle, _PrefetchMode.FORWARD)
431
+
432
+
433
+ @no_type_check
434
+ def _post_forward(
435
+ state: _FSDPState,
436
+ handle: Optional[FlatParamHandle],
437
+ reshard_fn: Callable,
438
+ module: nn.Module,
439
+ input: Any,
440
+ output: Any,
441
+ ) -> Any:
442
+ """
443
+ Runs the post-forward logic. This includes an opportunity to reshard
444
+ currently unsharded parameters such as those used in the current forward
445
+ and registering pre-backward hooks on the forward outputs.
446
+
447
+ Args:
448
+ handles (List[FlatParamHandle]): Handles giving the parameters used in
449
+ the current forward.
450
+ reshard_fn (Optional[Callable]): A callable to reshard any currently
451
+ unsharded parameters (e.g. from the current forward) or ``None`` to
452
+ not do any resharding.
453
+ module (nn.Module): Module whose forward just ran, which should be a
454
+ fully sharded module (see [Note: Fully Sharded Module]); expected
455
+ by the hook signature.
456
+ input (Any): Unused; expected by the hook signature.
457
+ output (Any): Forward pass output; pre-backward hooks are registered on
458
+ the tensors that require gradients in this output.
459
+
460
+ Postcondition: Each ``FlatParameter`` 's data points to the sharded flat
461
+ parameter.
462
+ """
463
+ with torch.profiler.record_function("FullyShardedDataParallel._post_forward"):
464
+ # For `fully_shard` + `checkpoint`, skip post-forward logic in the
465
+ # recomputed forward
466
+ if handle and handle._training_state == HandleTrainingState.BACKWARD_PRE:
467
+ return output
468
+
469
+ state._exec_order_data.record_post_forward(handle)
470
+ if reshard_fn is not None:
471
+ reshard_fn(state, handle)
472
+ # Register pre-backward hooks to unshard the flat parameters for the
473
+ # gradient computation (if needed)
474
+ output = _register_pre_backward_hooks(state, module, output, handle)
475
+ state.training_state = TrainingState.IDLE
476
+ if handle:
477
+ handle._training_state = HandleTrainingState.IDLE
478
+ return output
479
+
480
+
481
+ @no_type_check
482
+ def _post_forward_reshard(
483
+ state: _FSDPState,
484
+ handle: FlatParamHandle,
485
+ ) -> None:
486
+ """Reshards parameters in the post-forward."""
487
+ if not handle:
488
+ return
489
+ # Do not free the root's parameters in the post-forward for `FULL_SHARD`
490
+ # with the intention that they are immediately used for backward
491
+ # computation (though this may not be true)
492
+ free_unsharded_flat_param = (
493
+ not state._is_root
494
+ and handle._sharding_strategy in RESHARD_AFTER_FORWARD_HANDLE_STRATEGIES
495
+ )
496
+ _reshard(state, handle, free_unsharded_flat_param)
497
+
498
+
499
+ @no_type_check
500
+ def _root_pre_forward(
501
+ state: _FSDPState,
502
+ module: nn.Module,
503
+ args,
504
+ kwargs,
505
+ ) -> None:
506
+ """
507
+ Runs pre-forward logic specific to the root FSDP instance, which should run
508
+ before any individual module's pre-forward. This starts with an attempt at
509
+ lazy initialization (which only runs non-vacuously once). Otherwise, if
510
+ this is called on a non-root FSDP instance, then it returns directly.
511
+
512
+ Args:
513
+ module (nn.Module): Module for which this logic tries to run. It may or
514
+ may not be the root. If not, then this method does not do anything.
515
+ """
516
+ with torch.profiler.record_function("FullyShardedDataParallel._root_pre_forward"):
517
+ _lazy_init(state, module)
518
+ _p_assert(state._is_root is not None, "Expects a root FSDP to have been set")
519
+ if not state._is_root:
520
+ # Always cast forward inputs in the root of this local FSDP unit for mixed
521
+ # precision, as this is where mixed precision could be configed.
522
+ # This is more useful for auto wrapping that is recommended in composable path.
523
+ # For manual wrapping, cast forward inputs on each local FSDP unit root will
524
+ # increase some overhead, so not turned on for model wrapper path right now where
525
+ # manual wrapping is more broadly used.
526
+ if _is_composable(state):
527
+ return _root_cast_forward_input(state, module, args, kwargs)
528
+ return args, kwargs
529
+
530
+ # We cast buffers back to full precision if we're forcing full precision. Disjointly, we check if buffers
531
+ # are in full precision and if we should cast them back to lower precision, which happens when
532
+ # exiting eval() mode.
533
+ handle = state._handle
534
+ if handle:
535
+ should_cast_buffers_to_full_prec = handle._force_full_precision
536
+ else:
537
+ should_cast_buffers_to_full_prec = True
538
+
539
+ if should_cast_buffers_to_full_prec:
540
+ _cast_buffers_to_dtype_and_device(
541
+ buffers=dict(module.named_buffers()).values(),
542
+ buffer_dtypes=list(state._buffer_name_to_orig_dtype.values()),
543
+ device=state.compute_device,
544
+ )
545
+ # This flag is only set when we cast buffers to full precision, to avoid the
546
+ # CPU overhead that can stem from retrieving all buffers and their types in the
547
+ # following else branch.
548
+ state._needs_buffer_dtype_restore_check = True
549
+ elif getattr(state, "_needs_buffer_dtype_restore_check", False):
550
+ # Check if buffers are in full precision and we need to cast them
551
+ # back down.
552
+ (
553
+ buffers,
554
+ buffer_dtypes_for_computation,
555
+ ) = _get_buffers_and_dtypes_for_computation(state, module)
556
+ if len(buffers) > 0 and len(buffer_dtypes_for_computation) > 0:
557
+ if any(
558
+ buffer.dtype != buffer_dtype_for_computation
559
+ for buffer, buffer_dtype_for_computation in zip(
560
+ buffers, buffer_dtypes_for_computation
561
+ )
562
+ ):
563
+ # Assume we have to cast everything if there is one mismatch
564
+ _cast_buffers_to_dtype_and_device(
565
+ buffers, buffer_dtypes_for_computation, state.compute_device
566
+ )
567
+ # We don't have to check this again until we cast buffers to full precision again.
568
+ state._needs_buffer_dtype_restore_check = False
569
+
570
+ if state.forward_prefetch:
571
+ handles = []
572
+ for fsdp_state in state._all_fsdp_states:
573
+ if fsdp_state._handle:
574
+ handles.append(fsdp_state._handle)
575
+ for handle in handles:
576
+ handle._needs_pre_forward_unshard = True
577
+ handle._prefetched = False
578
+ _wait_for_computation_stream(
579
+ state._device_handle.current_stream(),
580
+ state._unshard_stream,
581
+ state._pre_unshard_stream,
582
+ )
583
+ _reset_flat_param_grad_info_if_needed(state._all_handles)
584
+
585
+ # Prepares the forward inputs by moving them to ``compute_device``
586
+ # TODO: Do not use the side stream for tensor copies for now; investigate
587
+ # the perf with/without it.
588
+ with torch.profiler.record_function("FullyShardedDataParallel._to_kwargs"):
589
+ args_tuple, kwargs_tuple = _to_kwargs(
590
+ args, kwargs, state.compute_device, False
591
+ )
592
+ args = args_tuple[0]
593
+ kwargs = kwargs_tuple[0]
594
+
595
+ return _root_cast_forward_input(state, module, args, kwargs)
596
+
597
+
598
+ @no_type_check
599
+ def _root_cast_forward_input(
600
+ state: _FSDPState, module: torch.nn.Module, args, kwargs
601
+ ) -> Tuple[Any, Any]:
602
+ if state._handle:
603
+ force_full_precision = not state._handle._force_full_precision
604
+ else:
605
+ force_full_precision = True
606
+
607
+ should_cast_forward_inputs = (
608
+ (module.training or not state._use_full_prec_in_eval) and force_full_precision
609
+ ) and state.mixed_precision.cast_root_forward_inputs
610
+
611
+ if should_cast_forward_inputs:
612
+ input_dtype: Optional[torch.dtype] = state.mixed_precision.param_dtype
613
+ args, kwargs = _cast_forward_inputs(input_dtype, *args, **kwargs)
614
+
615
+ return args, kwargs
616
+
617
+
618
+ @no_type_check
619
+ def _pre_backward_hook(
620
+ state: _FSDPState,
621
+ module: nn.Module,
622
+ handle: FlatParamHandle,
623
+ grad,
624
+ *unused: Any,
625
+ ) -> Any:
626
+ """
627
+ Prepares ``_handle`` 's ``FlatParameter`` s for gradient computation.
628
+
629
+ Args:
630
+ module (nn.Module): Fully sharded module (see [Note: Fully Sharded
631
+ Module]).
632
+ """
633
+ # Only run the pre-backward hook once per group of handles involved in the
634
+ # same module forward computation
635
+ if (
636
+ handle
637
+ and hasattr(handle, "_ran_pre_backward_hook")
638
+ and handle._ran_pre_backward_hook
639
+ ):
640
+ return grad
641
+
642
+ with torch.profiler.record_function("FullyShardedDataParallel._pre_backward_hook"):
643
+ # Queue the post-backward callback once for the root FSDP instance to
644
+ # attach it to the outermost backward graph task so that it is called
645
+ # after all backward calls complete
646
+ if state._is_root and not state._post_backward_callback_queued:
647
+ _register_post_backward_final_callback(state, module)
648
+ _reset_flat_param_grad_info_if_needed(state._all_handles)
649
+ elif handle:
650
+ allowed_states = [TrainingState.IDLE]
651
+ if _is_composable(state):
652
+ allowed_states.append(TrainingState.FORWARD_BACKWARD)
653
+ _assert_in_training_states(state, allowed_states)
654
+ state.training_state = TrainingState.FORWARD_BACKWARD
655
+ # Queueing the post-backward callback is the only logic that is not
656
+ # per-handle in the pre-backward hook, so we can return early here if
657
+ # there are no handles.
658
+ if not handle:
659
+ return grad
660
+ handle._training_state = HandleTrainingState.BACKWARD_PRE
661
+
662
+ if handle._needs_pre_backward_unshard:
663
+ # If the handles have been prefetched, then there is no need to
664
+ # call `_unshard()` again
665
+ if not handle._prefetched:
666
+ _unshard(
667
+ state,
668
+ handle,
669
+ state._unshard_stream,
670
+ state._pre_unshard_stream,
671
+ )
672
+ # Don't wait during trace
673
+ if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
674
+ state._device_handle.current_stream().wait_stream(state._unshard_stream)
675
+
676
+ # Set this to `False` to ensure that a mistargeted prefetch does not
677
+ # actually unshard these handles
678
+ handle._needs_pre_backward_unshard = False
679
+ with torch.profiler.record_function(
680
+ "FullyShardedDataParallel._pre_backward_prefetch"
681
+ ):
682
+ _prefetch_handle(state, handle, _PrefetchMode.BACKWARD)
683
+ handle.prepare_gradient_for_backward()
684
+ handle._ran_pre_backward_hook = True
685
+ return grad
686
+
687
+
688
+ @no_type_check
689
+ @torch.no_grad()
690
+ def _post_backward_hook(
691
+ state: _FSDPState,
692
+ handle: FlatParamHandle,
693
+ flat_param,
694
+ *unused: Any,
695
+ ):
696
+ """
697
+ Reduce-scatters the gradient of ``handle`` 's ``FlatParameter``.
698
+
699
+ Precondition: The ``FlatParameter`` 's ``.grad`` attribute contains the
700
+ unsharded gradient for the local batch.
701
+
702
+ Postcondition:
703
+ - If using ``NO_SHARD``, then the ``.grad`` attribute is the reduced
704
+ unsharded gradient.
705
+ - Otherwise, the ``_saved_grad_shard`` attribute is the reduced sharded
706
+ gradient (accumulating with any existing gradient).
707
+ """
708
+ _log_post_backward_hook(state, handle, logger)
709
+ flat_param = handle.flat_param
710
+ flat_param._post_backward_called = True
711
+ with torch.autograd.profiler.record_function(
712
+ "FullyShardedDataParallel._post_backward_hook"
713
+ ):
714
+ _assert_in_training_states(state, [TrainingState.FORWARD_BACKWARD])
715
+ # For multiple applications of reentrant AC across submodules sharing
716
+ # the same `FlatParameter`, the post-backward hook may run multiple
717
+ # times in one backward, in which case we permit the state to already
718
+ # be in `BACKWARD_POST`.
719
+ _p_assert(
720
+ handle._training_state
721
+ in (HandleTrainingState.BACKWARD_PRE, HandleTrainingState.BACKWARD_POST),
722
+ f"Expects `BACKWARD_PRE` or `BACKWARD_POST` state but got {handle._training_state}",
723
+ )
724
+ handle._training_state = HandleTrainingState.BACKWARD_POST
725
+
726
+ if flat_param.grad is None:
727
+ return
728
+ if flat_param.grad.requires_grad:
729
+ raise RuntimeError("FSDP does not support gradients of gradients")
730
+
731
+ _post_backward_reshard(state, handle)
732
+ if not state._sync_gradients:
733
+ if handle._use_orig_params:
734
+ handle._use_unsharded_grad_views()
735
+ return
736
+
737
+ # Wait for all ops in the current stream (e.g. gradient computation) to
738
+ # finish before reduce-scattering the gradient
739
+ if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
740
+ state._post_backward_stream.wait_stream(
741
+ state._device_handle.current_stream()
742
+ )
743
+
744
+ with state._device_handle.stream(state._post_backward_stream):
745
+ autograd_computed_grad = flat_param.grad.data
746
+ if (
747
+ not _low_precision_hook_enabled(state)
748
+ and flat_param.grad.dtype != handle._reduce_dtype
749
+ # If we are forcing full precision but communicating grads
750
+ # (i.e. model.eval() + full precision in eval was configured), don't downcast gradient.
751
+ and not handle._force_full_precision
752
+ ):
753
+ flat_param.grad.data = flat_param.grad.to(handle._reduce_dtype)
754
+ if handle.uses_sharded_strategy:
755
+ _reduce_grad(state, handle)
756
+ else:
757
+ _reduce_grad_no_shard(state, handle)
758
+ # Since the unsharded gradient is produced in the computation
759
+ # stream and consumed in the post-backward stream, inform the
760
+ # caching allocator (before it goes out of scope)
761
+ _no_dispatch_record_stream(
762
+ autograd_computed_grad, state._post_backward_stream
763
+ )
764
+
765
+
766
+ def _post_backward_reshard_only_hook(
767
+ state: _FSDPState,
768
+ handle: FlatParamHandle,
769
+ *unused: Any,
770
+ ) -> None:
771
+ with torch.profiler.record_function(
772
+ "FullyShardedDataParallel._post_backward_hook_reshard_only"
773
+ ):
774
+ # `_pre_backward_hook` may not get executed
775
+ # if forward output does not require grad
776
+ # overwrite IDLE state for post-backward prefetching
777
+ state.training_state = TrainingState.FORWARD_BACKWARD
778
+ handle._training_state = HandleTrainingState.BACKWARD_POST
779
+ _post_backward_reshard(state, handle)
780
+
781
+
782
+ def _post_backward_reshard(
783
+ state: _FSDPState,
784
+ handle: FlatParamHandle,
785
+ *unused: Any,
786
+ ) -> None:
787
+ free_unsharded_flat_param = _should_free_in_backward(state, handle)
788
+ _reshard(state, handle, free_unsharded_flat_param)
789
+
790
+ # TODO: Post-backward prefetching does not support the multiple handles
791
+ # per module case since the post-backward hook runs per handle, not per
792
+ # group of handles.
793
+ with torch.profiler.record_function(
794
+ "FullyShardedDataParallel._post_backward_prefetch"
795
+ ):
796
+ _prefetch_handle(state, handle, _PrefetchMode.BACKWARD)
797
+
798
+
799
+ @no_type_check
800
+ def _should_free_in_backward(
801
+ state: _FSDPState,
802
+ handle: FlatParamHandle,
803
+ ) -> bool:
804
+ """
805
+ Returns whether FSDP should free the unsharded flat parameter in the
806
+ post-backward or not.
807
+ """
808
+ if not handle.uses_sharded_strategy:
809
+ return False
810
+ # If not syncing gradients, then we do not free for strategies that do not
811
+ # reshard after forward as a *heuristic* to tradeoff higher memory for
812
+ # higher throughput.
813
+ return (
814
+ state._sync_gradients
815
+ or handle._sharding_strategy in RESHARD_AFTER_FORWARD_HANDLE_STRATEGIES
816
+ )
817
+
818
+
819
+ @no_type_check
820
+ def _reduce_grad(state: _FSDPState, handle: FlatParamHandle) -> None:
821
+ """
822
+ For sharded strategies, this runs gradient reduction, sharded gradient
823
+ accumulation if needed, and the post-reduction callback.
824
+ """
825
+ flat_param = handle.flat_param
826
+ uses_hybrid_sharded_strategy = handle._sharding_strategy in (
827
+ HandleShardingStrategy.HYBRID_SHARD,
828
+ HandleShardingStrategy._HYBRID_SHARD_ZERO2,
829
+ )
830
+ # We clear `.grad` to permit multiple backwards. This avoids a race where
831
+ # the second backward pass computation precedes ahead of the first backward
832
+ # pass reduction, which is possible since the reduction is issued in a
833
+ # separate stream and is async and would result in reducing the wrong
834
+ # gradient.
835
+ unsharded_grad = flat_param.grad.data
836
+ flat_param.grad = None
837
+ padded_unsharded_grad, new_sharded_grad = _get_reduce_scatter_tensors(
838
+ state, unsharded_grad
839
+ )
840
+ if state._comm_hook is None: # default path
841
+ _div_if_needed(padded_unsharded_grad, state._gradient_predivide_factor)
842
+ pg = (
843
+ handle._fake_process_group
844
+ if handle._use_fake_reduce
845
+ else state.process_group
846
+ )
847
+ dist.reduce_scatter_tensor(
848
+ new_sharded_grad,
849
+ padded_unsharded_grad,
850
+ group=pg,
851
+ )
852
+ if uses_hybrid_sharded_strategy:
853
+ # Don't wait during trace
854
+ if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
855
+ state._all_reduce_stream.wait_stream(state._post_backward_stream)
856
+ with state._device_handle.stream(state._all_reduce_stream):
857
+ # Since the new sharded gradient is produced in the post-
858
+ # backward stream and consumed in the all-reduce stream,
859
+ # inform the caching allocator
860
+ _no_dispatch_record_stream(new_sharded_grad, state._all_reduce_stream)
861
+ dist.all_reduce(new_sharded_grad, group=state._inter_node_pg)
862
+ _div_if_needed(new_sharded_grad, state._gradient_postdivide_factor)
863
+ grad_to_offload = _accumulate_sharded_grad(
864
+ state, handle, new_sharded_grad
865
+ )
866
+ _post_reduce_grad_callback(state, handle, grad_to_offload)
867
+ return
868
+ _div_if_needed(new_sharded_grad, state._gradient_postdivide_factor)
869
+ else:
870
+ state._comm_hook(
871
+ state._comm_hook_state, padded_unsharded_grad, new_sharded_grad
872
+ )
873
+ # NOTE: HSDP variants do not support communication hook.
874
+ grad_to_offload = _accumulate_sharded_grad(state, handle, new_sharded_grad)
875
+ _post_reduce_grad_callback(state, handle, grad_to_offload)
876
+
877
+
878
+ @no_type_check
879
+ def _get_reduce_scatter_tensors(
880
+ state: _FSDPState, unsharded_grad: torch.Tensor
881
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
882
+ """
883
+ Returns the input and output tensors to reduce-scatter, respectively.
884
+ """
885
+ chunks = list(unsharded_grad.chunk(state.world_size))
886
+ numel_to_pad = state.world_size * chunks[0].numel() - unsharded_grad.numel()
887
+ padded_unsharded_grad = (
888
+ F.pad(unsharded_grad, [0, numel_to_pad]) if numel_to_pad > 0 else unsharded_grad
889
+ )
890
+ new_sharded_grad = torch.empty_like(chunks[0]) # padded
891
+ return padded_unsharded_grad, new_sharded_grad
892
+
893
+
894
+ @no_type_check
895
+ def _accumulate_sharded_grad(
896
+ state: _FSDPState,
897
+ handle: FlatParamHandle,
898
+ sharded_grad: torch.Tensor,
899
+ ) -> torch.Tensor:
900
+ """
901
+ Accumulates the reduce-scattered sharded gradient with any existing sharded
902
+ gradient if needed, returning the gradient to offload (if CPU offloading is
903
+ enabled).
904
+ """
905
+ flat_param = handle.flat_param
906
+ _cast_grad_to_param_dtype(state, sharded_grad, flat_param)
907
+ # Save the sharded gradient in `_saved_grad_shard` to support gradient
908
+ # accumulation -- for multiple backwards, the gradient reductions may
909
+ # happen in arbitrary order
910
+ accumulate_grad = hasattr(flat_param, "_saved_grad_shard")
911
+ if accumulate_grad:
912
+ _check_grad_to_accumulate(sharded_grad, flat_param._saved_grad_shard)
913
+ flat_param._saved_grad_shard += sharded_grad
914
+ else:
915
+ flat_param._saved_grad_shard = sharded_grad
916
+ grad_to_offload = flat_param._saved_grad_shard
917
+ return grad_to_offload
918
+
919
+
920
+ @no_type_check
921
+ def _reduce_grad_no_shard(state: _FSDPState, handle: FlatParamHandle) -> None:
922
+ """
923
+ For no-shard, this runs gradient reduction (which directly covers any
924
+ gradient accumulation implicitly) and the post-reduction callback.
925
+ """
926
+ flat_param = handle.flat_param
927
+ if state._comm_hook is None: # default path
928
+ _div_if_needed(flat_param.grad, state._gradient_predivide_factor)
929
+ dist.all_reduce(flat_param.grad, group=state.process_group)
930
+ _div_if_needed(flat_param.grad, state._gradient_postdivide_factor)
931
+ else:
932
+ state._comm_hook(state._comm_hook_state, flat_param.grad)
933
+ # For `NO_SHARD`, we can keep the low precision gradients by simply
934
+ # omitting the cast altogether
935
+ if not handle._keep_low_precision_grads:
936
+ _cast_grad_to_param_dtype(state, flat_param.grad, flat_param)
937
+ grad_to_offload = flat_param.grad.data
938
+ _post_reduce_grad_callback(state, handle, grad_to_offload)
939
+
940
+
941
+ @no_type_check
942
+ def _post_reduce_grad_callback(
943
+ state: _FSDPState,
944
+ handle: FlatParamHandle,
945
+ # Additional arguments needed for the callback logic
946
+ grad_to_offload: torch.Tensor,
947
+ ):
948
+ """
949
+ This callback captures any logic to run after the gradient reduction
950
+ finishes. Currently, this offloads the gradient to CPU if CPU offloading is
951
+ enabled and uses sharded gradient views if ``use_orig_params=True``.
952
+ """
953
+ _offload_grad(state, handle, grad_to_offload)
954
+ _post_backward_use_sharded_grad_views(handle)
955
+
956
+
957
+ @no_type_check
958
+ def _offload_grad(
959
+ state: _FSDPState,
960
+ handle: FlatParamHandle,
961
+ grad_to_offload: torch.Tensor,
962
+ ):
963
+ if not handle._offload_params:
964
+ return
965
+ # Offload the gradient to CPU to ensure parameters and gradients are on the
966
+ # same device as required by the optimizer
967
+ # TODO: Investigate why `NO_SHARD` breaks correctness when using
968
+ # `non_blocking=True` here.
969
+ # TODO (rohan-varma): When CPU offload and optimizer overlap,
970
+ # non_blocking=True won't work since the copy may have not finished before
971
+ # the optimizer step executes on CPU. If we want to use non-blocking=True
972
+ # here, we'll have to synchronize before using result on CPU.
973
+ non_blocking = handle.uses_sharded_strategy and not handle._has_optim_in_backward
974
+ handle.flat_param._cpu_grad.copy_(
975
+ grad_to_offload.detach(), non_blocking=non_blocking
976
+ ) # synchronized in the post-backward callback
977
+ # Since the gradient being offloaded may have been produced in the
978
+ # computation stream and is being consumed here in the post-backward
979
+ # stream, inform the caching allocator
980
+ _no_dispatch_record_stream(grad_to_offload.data, state._post_backward_stream)
981
+
982
+
983
+ @no_type_check
984
+ def _post_backward_use_sharded_grad_views(handle: FlatParamHandle):
985
+ if not handle._use_orig_params:
986
+ return
987
+ # Since the handle's `FlatParameter` completed its gradient computation, we
988
+ # should reset the gradient noneness mask
989
+ handle._reset_is_grad_none()
990
+ # Delay using sharded gradient views until after the reduce-scatter instead
991
+ # of immediately after resharding
992
+ handle._use_sharded_grad_views()
993
+ if handle._has_optim_in_backward:
994
+ handle.prepare_gradient_for_optim()
995
+ for orig_param in handle.flat_param._params:
996
+ # Check for `None` gradient to filter parameters not in the rank
997
+ if orig_param.grad is not None and hasattr(
998
+ orig_param, "_in_backward_optimizers"
999
+ ):
1000
+ # TODO (rohan-varma): For CPU offload, this unfortunately
1001
+ # operates on CPU because the parameters and gradients have
1002
+ # already been offloaded. We should run this on GPU after
1003
+ # refactoring.
1004
+ for optim in orig_param._in_backward_optimizers:
1005
+ optim.step()
1006
+
1007
+ optim.zero_grad(set_to_none=True)
1008
+ handle._reset_flat_param_grad_info_if_needed()
1009
+ if handle._offload_params:
1010
+ handle.flat_param._cpu_grad = None
1011
+
1012
+
1013
+ def _div_if_needed(tensor: torch.Tensor, div_factor: float) -> None:
1014
+ if div_factor > 1:
1015
+ tensor.div_(div_factor)
1016
+
1017
+
1018
+ @no_type_check
1019
+ def _cast_grad_to_param_dtype(
1020
+ state: _FSDPState,
1021
+ sharded_grad: torch.Tensor,
1022
+ param: FlatParameter,
1023
+ ):
1024
+ """
1025
+ Casts ``sharded_grad`` back to the full parameter dtype so that the
1026
+ optimizer step runs with that dtype. This performs an actual cast if
1027
+ 1. parameters were in reduced precision during the forward since then
1028
+ gradients would be in that reduced precision, or
1029
+ 2. parameters were not in reduced precision but gradients were in
1030
+ reduced precision for communication.
1031
+ However, if a low precision communication hook is registered, then this
1032
+ dtype cast happens in the hook instead.
1033
+ """
1034
+ _assert_in_training_states(state, [TrainingState.FORWARD_BACKWARD])
1035
+ if not _low_precision_hook_enabled(state) and sharded_grad.dtype != param.dtype:
1036
+ low_prec_grad_data = sharded_grad.data
1037
+ sharded_grad.data = sharded_grad.data.to(dtype=param.dtype)
1038
+ # Since for `NO_SHARD`, the gradient is produced in the computation
1039
+ # stream and consumed here in the post-backward stream, inform the
1040
+ # caching allocator; for the sharded strategies, the gradient is
1041
+ # produced in the post-backward stream, so this `record_stream()`
1042
+ # should be a no-op
1043
+ _no_dispatch_record_stream(
1044
+ low_prec_grad_data, state._device_handle.current_stream()
1045
+ )
1046
+
1047
+
1048
+ def _check_grad_to_accumulate(
1049
+ new_sharded_grad: torch.Tensor,
1050
+ accumulated_grad: torch.Tensor,
1051
+ ) -> None:
1052
+ _p_assert(
1053
+ accumulated_grad.shape == new_sharded_grad.shape,
1054
+ "Shape mismatch when accumulating gradients: "
1055
+ f"existing gradient shape={accumulated_grad.shape} "
1056
+ f"new gradient shape={new_sharded_grad.shape}",
1057
+ )
1058
+ _p_assert(
1059
+ accumulated_grad.device == new_sharded_grad.device,
1060
+ "Device mismatch when accumulating gradients: "
1061
+ f"existing gradient device={accumulated_grad.device} "
1062
+ f"new gradient device={new_sharded_grad.device}",
1063
+ )
1064
+
1065
+
1066
+ @no_type_check
1067
+ def _low_precision_hook_enabled(state: _FSDPState) -> bool:
1068
+ return state._comm_hook in LOW_PRECISION_HOOKS
1069
+
1070
+
1071
+ @no_type_check
1072
+ @torch.no_grad()
1073
+ def _post_backward_final_callback(
1074
+ state: _FSDPState,
1075
+ module: nn.Module,
1076
+ ):
1077
+ """
1078
+ This waits for the post-backward to finish and performs some final cleanup.
1079
+ This runs at the end of the entire backward pass and should only be called
1080
+ on the root FSDP instance.
1081
+ """
1082
+ _p_assert(
1083
+ state._is_root,
1084
+ "The post-backward callback should only be called on the root FSDP instance",
1085
+ )
1086
+ root_state = state
1087
+
1088
+ if root_state._sync_gradients:
1089
+ current_stream = state._device_handle.current_stream()
1090
+ # TODO (rohan-varma): this also waits for the overlapped optimizer step to finish
1091
+ # since it currently runs in the post-backward stream. That can be
1092
+ # pushed to the next forward if run in a different stream
1093
+ current_stream.wait_stream(root_state._post_backward_stream)
1094
+ if root_state._all_reduce_stream is not current_stream: # uses HSDP
1095
+ current_stream.wait_stream(root_state._all_reduce_stream)
1096
+ if root_state.cpu_offload.offload_params:
1097
+ # Wait for non-blocking GPU -> CPU sharded gradient copies from the
1098
+ # post-backward hooks to finish explicitly since CPU gradients do
1099
+ # not automatically synchronize with the GPU
1100
+ state._device_handle.current_stream().synchronize()
1101
+ root_state._exec_order_data.next_iter()
1102
+
1103
+ for fsdp_state in state._all_fsdp_states:
1104
+ _catch_all_reshard(fsdp_state)
1105
+ _finalize_params(fsdp_state)
1106
+ fsdp_state.training_state = TrainingState.IDLE
1107
+ handle = fsdp_state._handle
1108
+ if handle:
1109
+ handle._ran_pre_backward_hook = False
1110
+ handle._needs_pre_backward_unshard = False
1111
+ handle._post_forward_index = None
1112
+ handle._training_state = HandleTrainingState.IDLE
1113
+ handle._prefetched = False
1114
+ # Reset for cases like one forward and multiple backwards
1115
+ root_state._post_backward_callback_queued = False
1116
+
1117
+
1118
+ @no_type_check
1119
+ def _catch_all_reshard(
1120
+ state: _FSDPState,
1121
+ ) -> None:
1122
+ """
1123
+ Reshards the parameters that may not have been resharded in the
1124
+ post-backward hook. This can happen when a module's output is used in the
1125
+ forward pass, meaning that its pre-backward hook runs (unsharding the
1126
+ parameter), but the post-backward hook does not run because the output was
1127
+ not jused in the loss computation corresponding to this backward pass.
1128
+ """
1129
+ # Wrap with a try-except to provide a more informative traceback if an
1130
+ # error is raised
1131
+ try:
1132
+ if state._handle:
1133
+ # TODO: This already-resharded check is brittle:
1134
+ # https://github.com/pytorch/pytorch/issues/83956
1135
+ already_resharded = (
1136
+ state._handle.flat_param.data_ptr()
1137
+ == state._handle.flat_param._local_shard.data_ptr()
1138
+ # If FSDP skipped using sharded views, then the flat parameter
1139
+ # still points to the sharded data, so we need to reshard to
1140
+ # use sharded views
1141
+ and not state._handle._skipped_use_sharded_views
1142
+ )
1143
+ if already_resharded:
1144
+ return
1145
+ free_unsharded_flat_param = _should_free_in_backward(state, state._handle)
1146
+ _reshard(state, state._handle, free_unsharded_flat_param)
1147
+ except Exception as e:
1148
+ _p_assert(
1149
+ False,
1150
+ f"Got exception in the catch-all reshard for {state}: {str(e)}",
1151
+ raise_assertion_error=False,
1152
+ )
1153
+ raise e
1154
+
1155
+
1156
+ @no_type_check
1157
+ def _finalize_params(
1158
+ state: _FSDPState,
1159
+ ) -> None:
1160
+ """Finalizes the parameters before the next iteration."""
1161
+ handle = state._handle
1162
+ if not handle:
1163
+ return
1164
+ flat_param = handle.flat_param
1165
+ if torch.distributed._functional_collectives.is_torchdynamo_compiling():
1166
+ if hasattr(flat_param, "_post_backward_hook_handle"):
1167
+ pbhs_handle = flat_param._post_backward_hook_handle
1168
+ pbhs_handle.remove()
1169
+ del flat_param._post_backward_hook_handle
1170
+ else:
1171
+ if hasattr(flat_param, "_post_backward_hook_state"):
1172
+ post_backward_hook_state_len = len(flat_param._post_backward_hook_state)
1173
+ expected_post_backward_hook_state_len = int(flat_param.requires_grad) + 1
1174
+ _p_assert(
1175
+ post_backward_hook_state_len == expected_post_backward_hook_state_len,
1176
+ f"Invalid: ``_post_backward_hook_state``: {flat_param._post_backward_hook_state}",
1177
+ )
1178
+ flat_param._post_backward_hook_state[-1].remove()
1179
+ delattr(flat_param, "_post_backward_hook_state")
1180
+ if flat_param.requires_grad:
1181
+ if not state._sync_gradients:
1182
+ # Preserve the gradient accumulation state if not synchronizing
1183
+ # gradients: `.grad` remains the unsharded gradient from prior
1184
+ # `no_sync()` iterations, and `_saved_grad_shard` remains the
1185
+ # sharded gradient from the last synchronized iteration
1186
+ return
1187
+ if not handle._has_optim_in_backward:
1188
+ handle.prepare_gradient_for_optim()
1189
+ _p_assert(
1190
+ hasattr(flat_param, "_post_backward_called"),
1191
+ "Expects `_post_backward_called` to be set on the `FlatParameter`",
1192
+ )
1193
+ flat_param._post_backward_called = False
1194
+
1195
+
1196
+ @no_type_check
1197
+ def _prefetch_handle(
1198
+ state: _FSDPState,
1199
+ current_handle: Optional[FlatParamHandle],
1200
+ prefetch_mode: _PrefetchMode,
1201
+ ) -> None:
1202
+ """
1203
+ Prefetches the next handles if needed (without synchronization). An empty
1204
+ handles key cannot prefetch.
1205
+ """
1206
+ if not current_handle:
1207
+ return
1208
+ handle = _get_handle_to_prefetch(state, current_handle)
1209
+ if not handle:
1210
+ return
1211
+ # Temporarily emulate the training state while calling `_unshard` to
1212
+ # ensure the correct `as_params` for `_use_unsharded_views()`
1213
+ prev_training_state = handle._training_state
1214
+ if prefetch_mode == _PrefetchMode.BACKWARD:
1215
+ handle._training_state = HandleTrainingState.BACKWARD_PRE
1216
+ elif prefetch_mode == _PrefetchMode.FORWARD:
1217
+ handle._training_state = HandleTrainingState.FORWARD
1218
+ else:
1219
+ raise ValueError(f"Invalid prefetch mode on rank {state.rank}: {prefetch_mode}")
1220
+ # Prefetch the next set of handles without synchronizing to allow
1221
+ # the sync to happen as late as possible to maximize overlap
1222
+ _unshard(state, handle, state._unshard_stream, state._pre_unshard_stream)
1223
+ handle._training_state = prev_training_state
1224
+ handle._prefetched = True
1225
+
1226
+
1227
+ @no_type_check
1228
+ def _get_handle_to_prefetch(
1229
+ state: _FSDPState,
1230
+ current_handle: FlatParamHandle,
1231
+ ) -> FlatParamHandle:
1232
+ """
1233
+ Returns a :class:`list` of the handles keys to prefetch for the next
1234
+ module(s), where ``current_handle`` represents the current module.
1235
+
1236
+ "Prefetching" refers to running the unshard logic early (without
1237
+ synchronization), and the "next" modules depend on the recorded execution
1238
+ order and the current training state.
1239
+ """
1240
+ training_state = _get_training_state(current_handle)
1241
+ valid_training_states = (
1242
+ HandleTrainingState.BACKWARD_PRE,
1243
+ HandleTrainingState.BACKWARD_POST,
1244
+ HandleTrainingState.FORWARD,
1245
+ )
1246
+ _p_assert(
1247
+ training_state in valid_training_states,
1248
+ f"Prefetching is only supported in {valid_training_states} but "
1249
+ f"currently in {training_state}",
1250
+ )
1251
+ eod = state._exec_order_data
1252
+ target_handle: Optional[FlatParamHandle] = None
1253
+ if (
1254
+ training_state == HandleTrainingState.BACKWARD_PRE
1255
+ and state.backward_prefetch == BackwardPrefetch.BACKWARD_PRE
1256
+ ) or (
1257
+ training_state == HandleTrainingState.BACKWARD_POST
1258
+ and state.backward_prefetch == BackwardPrefetch.BACKWARD_POST
1259
+ ):
1260
+ target_handle_candidate = eod.get_handle_to_backward_prefetch(current_handle)
1261
+ if (
1262
+ target_handle_candidate
1263
+ and target_handle_candidate._needs_pre_backward_unshard
1264
+ and not target_handle_candidate._prefetched
1265
+ ):
1266
+ target_handle = target_handle_candidate
1267
+ else:
1268
+ target_handle = None
1269
+ elif training_state == HandleTrainingState.FORWARD and state.forward_prefetch:
1270
+ target_handle_candidate = eod.get_handle_to_forward_prefetch(current_handle)
1271
+ if (
1272
+ target_handle_candidate
1273
+ and target_handle_candidate._needs_pre_forward_unshard
1274
+ and not target_handle_candidate._prefetched
1275
+ ):
1276
+ target_handle = target_handle_candidate
1277
+ else:
1278
+ target_handle = None
1279
+
1280
+ return target_handle
1281
+
1282
+
1283
+ def _get_training_state(
1284
+ handle: FlatParamHandle,
1285
+ ) -> HandleTrainingState:
1286
+ """Returns the training state of the handles in ``handle``."""
1287
+ _p_assert(handle, "Expects a non-empty handle")
1288
+ return handle._training_state
1289
+
1290
+
1291
+ @no_type_check
1292
+ def _register_pre_forward_hook(
1293
+ state: _FSDPState,
1294
+ module: nn.Module,
1295
+ ) -> None:
1296
+ """
1297
+ Registers a pre-forward hook on ``module``.
1298
+ """
1299
+ for forward_handle in state._pre_forward_handles:
1300
+ forward_handle.remove()
1301
+ state._pre_forward_handles.clear()
1302
+ module_param_handle = state._fully_sharded_module_to_handle.get(module, None)
1303
+ hook = functools.partial(
1304
+ _pre_forward, state, module_param_handle, _pre_forward_unshard
1305
+ )
1306
+ state._pre_forward_handles.append(
1307
+ module.register_forward_pre_hook(hook, prepend=True, with_kwargs=True)
1308
+ )
1309
+
1310
+
1311
+ @no_type_check
1312
+ def _register_post_forward_hook(
1313
+ state: _FSDPState,
1314
+ module: nn.Module,
1315
+ ) -> None:
1316
+ """
1317
+ Registers a post-forward hook on ``module``. Even if the module has no
1318
+ handles, we should register the hook since it will register the module's
1319
+ pre-backward hook.
1320
+ """
1321
+ for forward_handle in state._post_forward_handles:
1322
+ forward_handle.remove()
1323
+ state._post_forward_handles.clear()
1324
+ module_param_handle = state._fully_sharded_module_to_handle.get(module, None)
1325
+ hook = functools.partial(
1326
+ _post_forward,
1327
+ state,
1328
+ module_param_handle,
1329
+ _post_forward_reshard,
1330
+ )
1331
+ state._post_forward_handles.append(module.register_forward_hook(hook))
1332
+
1333
+
1334
+ @no_type_check
1335
+ def _register_root_pre_forward_hook(
1336
+ state: _FSDPState,
1337
+ module: nn.Module,
1338
+ ):
1339
+ """
1340
+ Registers root pre-forward hook on ``module``, which should be the local
1341
+ FSDP root.
1342
+
1343
+ NOTE: For the current composable FSDP design, we have each application of
1344
+ ``fully_shard()`` to a module to indicate that that module is the local
1345
+ FSDP root. We may remove this assumption in the future, in which case we
1346
+ will need to register this root pre-forward hook on any candidate module
1347
+ that may be the local FSDP root.
1348
+ """
1349
+ for forward_handle in state._root_pre_forward_handles:
1350
+ forward_handle.remove()
1351
+ state._root_pre_forward_handles.clear()
1352
+ hook = functools.partial(_root_pre_forward, state)
1353
+ state._root_pre_forward_handles.append(
1354
+ module.register_forward_pre_hook(hook, prepend=True, with_kwargs=True)
1355
+ )
1356
+
1357
+
1358
+ @no_type_check
1359
+ def _register_pre_backward_hooks(
1360
+ state: _FSDPState,
1361
+ module: nn.Module,
1362
+ outputs: Any,
1363
+ handle: FlatParamHandle,
1364
+ ) -> None:
1365
+ """
1366
+ Registers pre-backward hooks on the tensors that require gradients in the
1367
+ forward pass outputs ``outputs``, which were computed using the
1368
+ ``FlatParameter`` s of ``handles``.
1369
+
1370
+ Args:
1371
+ module (nn.Module): Fully sharded module (see [Note: Fully Sharded
1372
+ Module]).
1373
+
1374
+ Returns:
1375
+ Forward pass outputs with pre-backward hooks registered to tensors that
1376
+ require gradients.
1377
+ """
1378
+ # If there is no gradient computation, then there is no need for
1379
+ # pre-backward logic
1380
+ if not torch.is_grad_enabled():
1381
+ return outputs
1382
+ if state._is_root:
1383
+ state._post_backward_callback_queued = False # only defined on the root
1384
+
1385
+ if handle:
1386
+ handle._needs_pre_backward_unshard = False
1387
+ # Since these handles' `FlatParameter`s participated in a forward, we
1388
+ # conservatively assume that they will be used in the backward
1389
+ handle._ran_pre_backward_hook = False
1390
+
1391
+ def _register_hook(t: torch.Tensor) -> torch.Tensor:
1392
+ if t.requires_grad:
1393
+ t.register_hook(
1394
+ torch.utils.hooks.unserializable_hook(
1395
+ functools.partial(_pre_backward_hook, state, module, handle)
1396
+ )
1397
+ )
1398
+ if handle:
1399
+ handle._needs_pre_backward_unshard = True
1400
+ return t
1401
+
1402
+ return _apply_to_tensors(_register_hook, outputs)
1403
+
1404
+
1405
+ def _register_post_backward_hook(
1406
+ state: _FSDPState,
1407
+ handle: Optional[FlatParamHandle],
1408
+ ) -> None:
1409
+ """
1410
+ Registers post-backward hooks on the ``FlatParameter`` s'
1411
+ ``AccumulateGrad`` objects to reshard and to reduce-scatter gradients.
1412
+
1413
+ The ``AccumulateGrad`` object represents the last function that finalizes
1414
+ the ``FlatParameter`` 's gradient, so it only runs after its entire
1415
+ gradient computation has finished.
1416
+
1417
+ We register the post-backward hook only once in the *first* forward that a
1418
+ ``FlatParameter`` participates in. This relies on the ``AccumulateGrad``
1419
+ object being preserved through multiple forwards.
1420
+
1421
+ NOTE: We follow this heuristic to prefer the *first* forward to target the
1422
+ parameter mixed precision case, where there are *separate*
1423
+ ``AccumulateGrad`` objects across the different forwards. (Without
1424
+ parameter mixed precision, the ``AccumulateGrad`` objects are the same.) If
1425
+ we instead prefer the *last* forward, then the hook runs early.
1426
+ """
1427
+ # If there is no gradient computation, then there is no need for
1428
+ # post-backward logic
1429
+ if not torch.is_grad_enabled():
1430
+ return
1431
+ if not handle:
1432
+ return
1433
+ flat_param = handle.flat_param
1434
+
1435
+ if torch.distributed._functional_collectives.is_torchdynamo_compiling():
1436
+ already_registered = hasattr(flat_param, "_post_backward_hook_handle")
1437
+ if already_registered or not flat_param.requires_grad:
1438
+ return
1439
+ hook = functools.partial(_post_backward_hook, state, handle)
1440
+ hook_handle = flat_param.register_post_accumulate_grad_hook(hook)
1441
+ flat_param._post_backward_hook_handle = hook_handle # type: ignore[attr-defined]
1442
+ else:
1443
+ already_registered = hasattr(flat_param, "_post_backward_hook_state")
1444
+ if already_registered or not flat_param.requires_grad:
1445
+ return
1446
+ # Get the `AccumulateGrad` object
1447
+ temp_flat_param = flat_param.expand_as(flat_param)
1448
+ _p_assert(
1449
+ temp_flat_param.grad_fn is not None,
1450
+ "The `grad_fn` is needed to access the `AccumulateGrad` and "
1451
+ "register the post-backward hook",
1452
+ )
1453
+ acc_grad = temp_flat_param.grad_fn.next_functions[0][0] # type: ignore[union-attr]
1454
+ assert acc_grad is not None
1455
+ hook_handle = acc_grad.register_hook(
1456
+ functools.partial(_post_backward_hook, state, handle)
1457
+ )
1458
+ flat_param._post_backward_hook_state = (acc_grad, hook_handle) # type: ignore[attr-defined]
1459
+
1460
+
1461
+ def _register_post_backward_reshard_only_hook(
1462
+ state: _FSDPState,
1463
+ handle: Optional[FlatParamHandle],
1464
+ args: Tuple[Any, ...],
1465
+ kwargs: Dict[str, Any],
1466
+ ) -> None:
1467
+ """
1468
+ Registers post-backward hooks to reshard flat parameters that do not
1469
+ require gradient. We register these using multi-post-grad hooks on the
1470
+ input activations to ensure that all gradients that may depend on the
1471
+ parameters have been computed before resharding.
1472
+ """
1473
+ # If there is no gradient computation, then there is no need for
1474
+ # post-backward logic
1475
+ if not torch.is_grad_enabled():
1476
+ return
1477
+ # Construct `inp_tensors` lazily to avoid CPU overhead in typical case
1478
+ # where each flat parameter requires gradient
1479
+ inp_tensors: Optional[List[torch.Tensor]] = None
1480
+ if not handle:
1481
+ return
1482
+ flat_param = handle.flat_param
1483
+
1484
+ if torch.distributed._functional_collectives.is_torchdynamo_compiling():
1485
+ already_registered = hasattr(flat_param, "_post_backward_hook_handle")
1486
+ else:
1487
+ already_registered = hasattr(flat_param, "_post_backward_hook_state")
1488
+
1489
+ if already_registered or flat_param.requires_grad:
1490
+ return
1491
+ if inp_tensors is None:
1492
+ args_flat = pytree.arg_tree_leaves(*args, **kwargs)
1493
+ inp_tensors = [
1494
+ obj for obj in args_flat if torch.is_tensor(obj) and obj.requires_grad
1495
+ ]
1496
+ assert inp_tensors is not None # mypy
1497
+ hook_handle = register_multi_grad_hook(
1498
+ inp_tensors, functools.partial(_post_backward_reshard_only_hook, state, handle)
1499
+ )
1500
+ if torch.distributed._functional_collectives.is_torchdynamo_compiling():
1501
+ flat_param._post_backward_hook_handle = hook_handle # type: ignore[attr-defined, assignment]
1502
+ else:
1503
+ flat_param._post_backward_hook_state = (hook_handle,) # type: ignore[attr-defined, assignment]
1504
+
1505
+
1506
+ @no_type_check
1507
+ def _register_post_backward_final_callback(
1508
+ state: _FSDPState, module: nn.Module
1509
+ ) -> None:
1510
+ """
1511
+ Registers the post-backward final callback that runs at the end of the
1512
+ backward pass. This should be called from the root FSDP instance at the
1513
+ beginning of the pre-backward.
1514
+ """
1515
+ _p_assert(
1516
+ state._is_root,
1517
+ "Only the root FSDP instance should register the post-backward callback",
1518
+ )
1519
+ if state._post_backward_callback_queued:
1520
+ return
1521
+ _assert_in_training_states(state, [TrainingState.IDLE])
1522
+ # Trace does not need this callback
1523
+ if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
1524
+ state._post_backward_callback_queued = True
1525
+ Variable._execution_engine.queue_callback(
1526
+ functools.partial(_post_backward_final_callback, state, module)
1527
+ )
1528
+
1529
+
1530
+ def _wait_for_computation_stream(
1531
+ computation_stream: torch.Stream,
1532
+ unshard_stream: torch.Stream,
1533
+ pre_unshard_stream: torch.Stream,
1534
+ ):
1535
+ """
1536
+ Has the unshard and pre-unshard streams wait for the computation stream.
1537
+ For example, this should be called in the FSDP root's pre-forward to
1538
+ respect optimizer step computation.
1539
+ """
1540
+ # Tracing does not need to wait
1541
+ if torch.distributed._functional_collectives.is_torchdynamo_compiling():
1542
+ return
1543
+ unshard_stream.wait_stream(computation_stream) # type: ignore[attr-defined]
1544
+ # Having the pre-all-gather stream wait for the current stream even if we
1545
+ # do not leverage the pre-all-gather stream is tolerable since this only
1546
+ # runs once per iteration
1547
+ pre_unshard_stream.wait_stream(computation_stream) # type: ignore[attr-defined]
1548
+
1549
+
1550
+ def _reset_flat_param_grad_info_if_needed(
1551
+ handles: List[FlatParamHandle],
1552
+ ):
1553
+ """
1554
+ Clears the original parameters' gradients if needed. This method's CPU
1555
+ overhead is minimal, so we may call it throughout FSDP methods, which serve
1556
+ as callsites to free the gradient memory earlier.
1557
+ """
1558
+ if not isinstance(handles, list):
1559
+ handles = [handles]
1560
+ for handle in handles:
1561
+ if handle._use_orig_params:
1562
+ handle._reset_flat_param_grad_info_if_needed()
1563
+
1564
+
1565
+ @no_type_check
1566
+ def _get_buffers_and_dtypes_for_computation(
1567
+ state: _FSDPState,
1568
+ root_module: nn.Module,
1569
+ ) -> Tuple[List[torch.Tensor], List[Optional[torch.dtype]]]:
1570
+ """
1571
+ Returns all buffers in the module tree rooted at ``root_module`` and a
1572
+ corresponding list of the buffer dtypes for computation. Each buffer dtype
1573
+ is either ``None`` if buffer mixed precision is not enabled or the buffer
1574
+ low precision dtype otherwise.
1575
+ """
1576
+ _p_assert(state._is_root, "Expects the root to cast buffers")
1577
+ buffers: List[torch.Tensor] = []
1578
+ buffer_dtypes: List[Optional[torch.dtype]] = []
1579
+ visited_buffers: Set[torch.Tensor] = set()
1580
+ # Traverse the FSDP states bottom-up so that we prefer the owning FSDP
1581
+ # instance's mixed precision setting for each buffer
1582
+ fsdp_states, fsdp_modules = traversal_utils._get_fsdp_states_with_modules(
1583
+ root_module
1584
+ )
1585
+ for fsdp_state, fsdp_module in zip(reversed(fsdp_states), reversed(fsdp_modules)):
1586
+ for buffer_name, buffer in fsdp_module.named_buffers():
1587
+ if buffer in visited_buffers:
1588
+ continue
1589
+ visited_buffers.add(buffer)
1590
+ if clean_tensor_name(buffer_name) in fsdp_state._ignored_buffer_names:
1591
+ continue
1592
+ buffers.append(buffer)
1593
+ buffer_dtypes.append(fsdp_state.mixed_precision.buffer_dtype)
1594
+ assert len(buffers) == len(buffer_dtypes), f"{len(buffers)} {len(buffer_dtypes)}"
1595
+ return buffers, buffer_dtypes
1596
+
1597
+
1598
+ @no_type_check
1599
+ def _get_orig_buffer_dtypes(
1600
+ state: _FSDPState,
1601
+ buffer_names: List[str],
1602
+ ) -> List[torch.dtype]:
1603
+ """
1604
+ Returns the original buffer types of the given buffer names.
1605
+ """
1606
+ buffer_dtypes: List[torch.dtype] = []
1607
+ for buffer_name in buffer_names:
1608
+ _p_assert(
1609
+ buffer_name in state._buffer_name_to_orig_dtype,
1610
+ f"{buffer_name} is missing from pre-computed dict on rank "
1611
+ f"{state.rank}, which only has keys "
1612
+ f"{state._buffer_name_to_orig_dtype.keys()}",
1613
+ )
1614
+ buffer_dtypes.append(state._buffer_name_to_orig_dtype[buffer_name])
1615
+ return buffer_dtypes
1616
+
1617
+
1618
+ def _cast_buffers_to_dtype_and_device(
1619
+ buffers: List[torch.Tensor],
1620
+ buffer_dtypes: List[Optional[torch.dtype]],
1621
+ device: torch.device,
1622
+ ) -> None:
1623
+ """
1624
+ Casts ``buffers`` to the dtypes given by ``buffer_dtypes`` and moves them
1625
+ to ``device``. If an element in ``buffer_dtypes`` is ``None``, then the
1626
+ corresponding buffer is only moved to ``device``.
1627
+ """
1628
+ _p_assert(
1629
+ buffer_dtypes is None or len(buffers) == len(buffer_dtypes),
1630
+ f"Expects `buffers` and `buffer_dtypes` to have the same length if "
1631
+ f"`buffer_dtypes` is specified but got {len(buffers)} and "
1632
+ f"{len(buffer_dtypes)}",
1633
+ )
1634
+ for buffer, buffer_dtype in zip(buffers, buffer_dtypes):
1635
+ if not torch.is_floating_point(buffer) or buffer_dtype is None:
1636
+ buffer.data = buffer.to(device=device)
1637
+ else:
1638
+ buffer.data = buffer.to(device=device, dtype=buffer_dtype)
vllm/lib/python3.10/site-packages/torch/distributed/fsdp/_shard_utils.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import copy
3
+ import itertools
4
+ import math
5
+ from typing import Optional
6
+
7
+ import torch
8
+ import torch.distributed as dist
9
+ from torch._utils import _get_device_module
10
+ from torch.distributed import distributed_c10d
11
+ from torch.distributed._shard.sharded_tensor import (
12
+ Shard,
13
+ ShardedTensor,
14
+ ShardedTensorMetadata,
15
+ TensorProperties,
16
+ )
17
+ from torch.distributed._shard.sharding_spec import ShardMetadata
18
+ from torch.distributed.tensor import DeviceMesh, DTensor, Replicate, Shard as DShard
19
+
20
+
21
+ def _get_remote_device_str(rank, device_type, num_devices_per_node):
22
+ if device_type.lower() == "cpu":
23
+ return f"rank:{rank}/{device_type}"
24
+ elif device_type.lower() == "hpu":
25
+ return f"rank:{rank}/{device_type}:{_get_device_module(device_type).current_device()}"
26
+ else:
27
+ return f"rank:{rank}/{device_type}:{rank % num_devices_per_node}"
28
+
29
+
30
+ def _create_chunk_sharded_tensor(
31
+ tensor: torch.Tensor,
32
+ rank: int,
33
+ world_size: int,
34
+ num_devices_per_node: int,
35
+ pg: dist.ProcessGroup,
36
+ device: Optional[torch.device] = None,
37
+ ) -> ShardedTensor:
38
+ """
39
+ Shard a tensor to chunks along the first dimension. The local rank will gets its
40
+ corresponding chunk as the local shard to create a ShardedTensor.
41
+ """
42
+ chunks = tensor.chunk(world_size, dim=0)
43
+ if len(chunks) > rank:
44
+ local_shard = chunks[rank].clone()
45
+ offsets = [0 for _ in tensor.size()]
46
+ offsets[0] = math.ceil(tensor.size()[0] / world_size) * rank
47
+ local_shards = [Shard.from_tensor_and_offsets(local_shard, offsets, rank)]
48
+ else:
49
+ local_shards = []
50
+
51
+ # Create a ShardedTensor without invoking communication.
52
+ chunk_sizes = [list(chunk.size()) for chunk in chunks]
53
+ dim0_offsets = [0] + list(
54
+ itertools.accumulate([chunk_size[0] for chunk_size in chunk_sizes])
55
+ )[:-1]
56
+ offsets = [0] * (len(chunk_sizes[0]) - 1)
57
+ chunk_offsets = [[d0] + offsets for d0 in dim0_offsets]
58
+ device_type = (
59
+ distributed_c10d._get_pg_default_device(pg).type
60
+ if device is None
61
+ else device.type
62
+ )
63
+ placements = [
64
+ _get_remote_device_str(
65
+ dist.get_global_rank(pg, r),
66
+ device_type,
67
+ num_devices_per_node,
68
+ )
69
+ for r in range(len(chunk_sizes))
70
+ ]
71
+ assert len(chunk_sizes) == len(chunk_offsets) == len(placements)
72
+ shard_metadata = [
73
+ ShardMetadata(offset, size, placement)
74
+ for offset, size, placement in zip(chunk_offsets, chunk_sizes, placements)
75
+ ]
76
+ sharded_tensor_metadata = ShardedTensorMetadata(
77
+ shards_metadata=shard_metadata,
78
+ size=tensor.size(),
79
+ tensor_properties=TensorProperties(
80
+ dtype=tensor.dtype,
81
+ layout=tensor.layout,
82
+ requires_grad=False,
83
+ memory_format=torch.contiguous_format,
84
+ pin_memory=tensor.is_pinned(),
85
+ ),
86
+ )
87
+ return ShardedTensor._init_from_local_shards_and_global_metadata(
88
+ local_shards, sharded_tensor_metadata=sharded_tensor_metadata, process_group=pg
89
+ )
90
+
91
+
92
+ def _create_chunk_dtensor(
93
+ tensor: torch.Tensor,
94
+ rank: int,
95
+ device_mesh: DeviceMesh,
96
+ ) -> DTensor:
97
+ """
98
+ Shard a tensor to chunks along the first dimension. The local rank will gets its
99
+ corresponding chunk as the local tensor to create a DTensor.
100
+ """
101
+ # We need to explicitly call .detach() to return a new tensor detached from the current graph.
102
+ tensor = tensor.clone().detach()
103
+
104
+ # FSDP placements: [Shard(0)]
105
+ # HSDP placements: [Replicate(), Shard(0)]
106
+ replicate_placements = [Replicate() for _ in range(device_mesh.ndim)]
107
+ shard_placements = [Replicate() for _ in range(device_mesh.ndim)]
108
+ shard_placements[-1] = DShard(0) # type: ignore[call-overload]
109
+
110
+ return DTensor.from_local(
111
+ tensor, device_mesh, replicate_placements, run_check=False
112
+ ).redistribute(
113
+ placements=shard_placements,
114
+ )
115
+
116
+
117
+ def _all_gather_dtensor(
118
+ tensor: DTensor,
119
+ root_mesh: Optional[DeviceMesh],
120
+ ) -> torch.Tensor:
121
+ """
122
+ All gather a DTensor in its sharded dimension and return the local tensor.
123
+ """
124
+ assert (
125
+ root_mesh == tensor.device_mesh
126
+ ), "The device mesh of a tensor should be a root mesh."
127
+
128
+ placements = list(copy.deepcopy(tensor.placements))
129
+ # FSDP placements: [Shard(0)] -> [Replicate()]
130
+ # HSDP placements: [Replicate(), Shard(0)] -> [Replicate(), Replicate()]
131
+ placements[-1] = Replicate()
132
+ tensor = tensor.redistribute(
133
+ device_mesh=tensor.device_mesh,
134
+ placements=placements,
135
+ )
136
+
137
+ return tensor.to_local()
vllm/lib/python3.10/site-packages/torch/distributed/fsdp/_state_dict_utils.py ADDED
@@ -0,0 +1,924 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import contextlib
3
+ import logging
4
+ import math
5
+ import warnings
6
+ from typing import (
7
+ Any,
8
+ Callable,
9
+ cast,
10
+ Dict,
11
+ Generator,
12
+ Iterator,
13
+ List,
14
+ no_type_check,
15
+ Tuple,
16
+ )
17
+
18
+ import torch
19
+ import torch.distributed as dist
20
+ import torch.distributed.algorithms._checkpoint.checkpoint_wrapper as checkpoint_wrapper
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+ from torch.distributed._shard.sharded_tensor import (
24
+ init_from_local_shards,
25
+ Shard,
26
+ ShardedTensor,
27
+ )
28
+ from torch.distributed.device_mesh import _mesh_resources
29
+ from torch.distributed.fsdp._common_utils import (
30
+ _FSDPState,
31
+ _get_module_fsdp_state_if_fully_sharded_module,
32
+ _has_fsdp_params,
33
+ _is_composable,
34
+ _module_handle,
35
+ clean_tensor_name,
36
+ FSDP_PREFIX,
37
+ FSDP_WRAPPED_MODULE,
38
+ )
39
+ from torch.distributed.fsdp._debug_utils import SimpleProfiler
40
+ from torch.distributed.fsdp._runtime_utils import (
41
+ _cast_buffers_to_dtype_and_device,
42
+ _get_orig_buffer_dtypes,
43
+ _lazy_init,
44
+ _reset_flat_param_grad_info_if_needed,
45
+ )
46
+ from torch.distributed.fsdp.api import (
47
+ FullStateDictConfig,
48
+ ShardingStrategy,
49
+ StateDictType,
50
+ )
51
+ from torch.distributed.tensor import DTensor
52
+ from torch.distributed.utils import _replace_by_prefix
53
+
54
+ from ._fsdp_extensions import (
55
+ _ext_all_gather_dtensor,
56
+ _ext_chunk_dtensor,
57
+ _ext_chunk_tensor,
58
+ _ext_post_unflatten_transform,
59
+ _ext_pre_load_state_dict_transform,
60
+ )
61
+ from ._unshard_param_utils import _unshard_fsdp_state_params, FLAT_PARAM
62
+
63
+
64
+ logger = logging.getLogger(__name__)
65
+
66
+
67
+ def _should_unshard_params(fsdp_state: _FSDPState) -> bool:
68
+ return not (
69
+ fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD
70
+ and (_is_composable(fsdp_state) or fsdp_state._use_orig_params)
71
+ )
72
+
73
+
74
+ def _convert_to_wrapped_module_name(module_name: str) -> str:
75
+ module_name = module_name.replace(f"{FSDP_PREFIX}", "")
76
+ module_name = module_name.replace(f"{FSDP_WRAPPED_MODULE}", "")
77
+ if module_name:
78
+ module_name = f"{module_name}."
79
+ # `CheckpointWrapper` adds a prefix that has to be removed as well.
80
+ module_name = module_name.replace(checkpoint_wrapper._CHECKPOINT_PREFIX, "")
81
+ return module_name
82
+
83
+
84
+ def _param_name_infos(
85
+ module: nn.Module, fsdp_state: _FSDPState
86
+ ) -> Iterator[Tuple[str, str, str]]:
87
+ if not _has_fsdp_params(fsdp_state, module):
88
+ return
89
+ for param_name, module_name in _module_handle(
90
+ fsdp_state, module
91
+ ).param_module_names():
92
+ module_name = _convert_to_wrapped_module_name(module_name)
93
+ fqn = f"{module_name}{param_name}"
94
+ yield fqn, param_name, module_name
95
+
96
+
97
+ def _shared_param_name_infos(
98
+ module: nn.Module, fsdp_state
99
+ ) -> Iterator[Tuple[str, str, str]]:
100
+ for param_name, module_name in _module_handle(
101
+ fsdp_state, module
102
+ ).shared_param_module_names():
103
+ module_name = _convert_to_wrapped_module_name(module_name)
104
+ fqn = f"{module_name}{param_name}"
105
+ yield fqn, param_name, module_name
106
+
107
+
108
+ @no_type_check
109
+ def _enter_unshard_params_ctx(
110
+ module: nn.Module,
111
+ fsdp_state: _FSDPState,
112
+ writeback: bool = False,
113
+ rank0_only: bool = False,
114
+ offload_to_cpu: bool = False,
115
+ with_grads: bool = False,
116
+ ) -> None:
117
+ """
118
+ state_dict hooks cannot use the pure context call as the checkpoint flow
119
+ requires to enter the context in the pre-hook but leave the context in the
120
+ post-hook. This API enters the context of ``_unshard_fsdp_state_params``.
121
+ """
122
+ assert module not in fsdp_state._unshard_params_ctx, (
123
+ "Entering the ``_unshard_fsdp_state_params`` context but _unshard_params_ctx[module] "
124
+ "is not None."
125
+ )
126
+ fsdp_state._unshard_params_ctx[module] = _unshard_fsdp_state_params(
127
+ module,
128
+ fsdp_state,
129
+ writeback=writeback,
130
+ rank0_only=rank0_only,
131
+ offload_to_cpu=offload_to_cpu,
132
+ with_grads=with_grads,
133
+ )
134
+ fsdp_state._unshard_params_ctx[module].__enter__()
135
+
136
+
137
+ @no_type_check
138
+ def _exit_unshard_params_ctx(module: nn.Module, fsdp_state: _FSDPState) -> None:
139
+ """A helper function to exit ``_unshard_fsdp_state_params`` context."""
140
+ fsdp_state._unshard_params_ctx[module].__exit__(None, None, None)
141
+ fsdp_state._unshard_params_ctx.pop(module)
142
+
143
+
144
+ def _common_pre_state_dict_hook(
145
+ module: nn.Module,
146
+ fsdp_state: _FSDPState,
147
+ ) -> None:
148
+ """Performs the pre-state_dict tasks shared by all state_dict types."""
149
+ if fsdp_state._device_handle.is_available():
150
+ fsdp_state._device_handle.synchronize()
151
+ # TODO: need to check if this is always correct for composable FSDP.
152
+ _lazy_init(fsdp_state, module)
153
+ if fsdp_state._is_root:
154
+ _reset_flat_param_grad_info_if_needed(fsdp_state._all_handles)
155
+
156
+
157
+ def _common_unshard_pre_state_dict_hook(
158
+ module: nn.Module,
159
+ fsdp_state: _FSDPState,
160
+ offload_to_cpu: bool,
161
+ rank0_only: bool,
162
+ ) -> None:
163
+ """
164
+ Performs the pre-state_dict tasks shared by all state_dict types that require
165
+ ``_unshard_fsdp_state_params()``. FULL_STATE_DICT and SHARDED_STATE_DICT use this hook.
166
+ """
167
+ # For composable `fully_shard`, it does not need to unshard parameters for `NO_SHARD` cases.
168
+ if not _should_unshard_params(fsdp_state):
169
+ return
170
+ _enter_unshard_params_ctx(
171
+ module,
172
+ fsdp_state,
173
+ writeback=False,
174
+ offload_to_cpu=offload_to_cpu,
175
+ rank0_only=rank0_only,
176
+ )
177
+
178
+
179
+ @no_type_check
180
+ def _common_unshard_post_state_dict_hook(
181
+ module: nn.Module,
182
+ fsdp_state: _FSDPState,
183
+ state_dict: Dict[str, Any],
184
+ prefix: str,
185
+ param_hook: Callable,
186
+ ) -> Dict[str, Any]:
187
+ """
188
+ The post-state_dict flow that shared by all state_dict types that require
189
+ ``_unshard_fsdp_state_params()``. FULL_STATE_DICT and SHARDED_STATE_DICT use this
190
+ hook.
191
+ """
192
+ _replace_by_prefix(state_dict, prefix + f"{FSDP_PREFIX}", prefix)
193
+ # Return early for trivial cases
194
+ if not state_dict or not _has_fsdp_params(fsdp_state, module):
195
+ if _should_unshard_params(fsdp_state):
196
+ _exit_unshard_params_ctx(module, fsdp_state)
197
+ return state_dict
198
+
199
+ # If a rank does not have unsharded parameters(when `rank0_only=True`
200
+ # and `rank != 0`), then the rank only needed to participate in the
201
+ # all-gather and does not need to save the # state dict. We simply check
202
+ # rank0_only to ensure this issue.
203
+ rank0_only = (
204
+ fsdp_state._state_dict_type == StateDictType.FULL_STATE_DICT
205
+ and cast(FullStateDictConfig, fsdp_state._state_dict_config).rank0_only
206
+ )
207
+ # no_fsdp_return means the state_dict returned by this rank should contain
208
+ # only non-FSDP controlled parameters and buffers.
209
+ no_fsdp_return = rank0_only and fsdp_state.rank != 0
210
+ if no_fsdp_return and not fsdp_state._use_orig_params:
211
+ for clean_key in fsdp_state._buffer_names:
212
+ # This is a hack to support activation checkpoint.
213
+ clean_key = clean_key.replace(
214
+ f"{checkpoint_wrapper._CHECKPOINT_PREFIX}.", ""
215
+ )
216
+ state_dict.pop(f"{prefix}{clean_key}", None)
217
+ # Non-zero ranks have flat_param key when rank0_only=True, because rank0_only=True is
218
+ # passed in to unshard context, but nonzero ranks reshard early, causing this flat_param
219
+ # to appear in state_dict.
220
+ state_dict.pop(f"{prefix}{FLAT_PARAM}")
221
+ _exit_unshard_params_ctx(module, fsdp_state)
222
+ return state_dict
223
+
224
+ # Loop only the parameters saved in this instance's wrapped module to
225
+ # avoid processing buffers.
226
+ for fqn, param_name, module_name in _param_name_infos(module, fsdp_state):
227
+ fqn = f"{prefix}{fqn}"
228
+ if no_fsdp_return:
229
+ state_dict.pop(fqn)
230
+ continue
231
+ assert fqn in state_dict, (
232
+ f"FSDP assumes {fqn} is in the state_dict but the state_dict only "
233
+ f"has {state_dict.keys()}. "
234
+ f"prefix={prefix}, module_name={module_name}, "
235
+ f"param_name={param_name} rank={fsdp_state.rank}."
236
+ )
237
+
238
+ param_hook(state_dict, prefix, fqn)
239
+
240
+ if _should_unshard_params(fsdp_state):
241
+ _exit_unshard_params_ctx(module, fsdp_state)
242
+
243
+ cpu_device = torch.device("cpu")
244
+ buffer_clean_fqns = []
245
+ buffers = []
246
+ for clean_key in fsdp_state._buffer_names:
247
+ # This is a hack to support activation checkpoint.
248
+ clean_key = clean_tensor_name(clean_key)
249
+ fqn = f"{prefix}{clean_key}"
250
+ if fqn not in state_dict:
251
+ # A buffer can be registered as non-persistent.
252
+ continue
253
+ if no_fsdp_return:
254
+ state_dict.pop(fqn)
255
+ else:
256
+ buffer = state_dict[fqn]
257
+ if (
258
+ fsdp_state._state_dict_config.offload_to_cpu
259
+ and buffer.device != cpu_device
260
+ ):
261
+ state_dict[fqn] = buffer.to(cpu_device)
262
+ # skip upcasting for ignored buffers
263
+ if clean_key not in fsdp_state._ignored_buffer_names:
264
+ buffer_clean_fqns.append(clean_key)
265
+ buffers.append(state_dict[fqn])
266
+
267
+ if buffers:
268
+ mixed_precision_enabled_for_buffers = (
269
+ fsdp_state._mixed_precision_enabled_for_buffers()
270
+ if not _is_composable(fsdp_state)
271
+ else (fsdp_state.mixed_precision.buffer_dtype is not None)
272
+ )
273
+ if mixed_precision_enabled_for_buffers:
274
+ buffer_dtypes = _get_orig_buffer_dtypes(fsdp_state, buffer_clean_fqns)
275
+ _cast_buffers_to_dtype_and_device(
276
+ buffers, buffer_dtypes, fsdp_state.compute_device
277
+ )
278
+ for buffer, clean_fqn in zip(buffers, buffer_clean_fqns):
279
+ fqn = f"{prefix}{clean_fqn}"
280
+ logger.info("FSDP is casting the dtype of %s to %s", fqn, buffer.dtype)
281
+ state_dict[fqn] = buffer.clone()
282
+ return state_dict
283
+
284
+
285
+ @no_type_check
286
+ def _full_pre_state_dict_hook(
287
+ fsdp_state: _FSDPState,
288
+ module: nn.Module,
289
+ *args,
290
+ **kwargs,
291
+ ) -> None:
292
+ """
293
+ Hook that runs before model.state_dict() is called. pre-state_dict hook is
294
+ not actually supported by ``nn.Module``. As a result, this API is called
295
+ from ``_full_post_state_dict_hook()`` to simulate the case. Once pre-state_dict
296
+ is supported in ``nn.Module``, this hook will be registered as a hook in
297
+ ``nn.Module``.
298
+ """
299
+ if getattr(fsdp_state, "_device_mesh", False):
300
+ root_mesh = _mesh_resources.get_root_mesh(fsdp_state._device_mesh)
301
+
302
+ _common_pre_state_dict_hook(module, fsdp_state)
303
+ _common_unshard_pre_state_dict_hook(
304
+ module,
305
+ fsdp_state,
306
+ offload_to_cpu=fsdp_state._state_dict_config.offload_to_cpu,
307
+ rank0_only=cast(FullStateDictConfig, fsdp_state._state_dict_config).rank0_only,
308
+ )
309
+
310
+
311
+ @no_type_check
312
+ def _full_post_state_dict_hook(
313
+ module: nn.Module,
314
+ fsdp_state: _FSDPState,
315
+ state_dict: Dict[str, Any],
316
+ prefix: str,
317
+ ) -> Dict[str, Any]:
318
+ """
319
+ Hook that runs after model.state_dict() is called before returning result to
320
+ user. For FSDP, we may have to clone the tensors in state_dict as params go
321
+ back to sharded version after _unshard_fsdp_state_params ends, and also remove
322
+ the ``FSDP_WRAPPED_MODULE`` prefix.
323
+ """
324
+
325
+ def param_hook(
326
+ state_dict: Dict[str, Any],
327
+ prefix: str,
328
+ fqn: str,
329
+ ) -> None:
330
+ clean_key = fqn
331
+ clean_prefix = clean_tensor_name(prefix)
332
+ # Strip prefix out of key if needed as buffer names and param names
333
+ # do not have prefix considered as they are not computed in `state_dict`
334
+ # call.
335
+ if clean_key.startswith(clean_prefix):
336
+ clean_key = clean_key[len(clean_prefix) :]
337
+
338
+ # Clone parameters before exiting the `_unshard_fsdp_state_params()` context.
339
+ if not getattr(state_dict[fqn], "_has_been_cloned", False):
340
+ try:
341
+ state_dict[fqn] = state_dict[fqn].clone().detach()
342
+ state_dict[fqn]._has_been_cloned = True # type: ignore[attr-defined]
343
+ except BaseException as e:
344
+ warnings.warn(
345
+ f"Failed to clone() tensor with name {fqn} on rank {fsdp_state.rank}. "
346
+ "This may mean that this state_dict entry could point to invalid "
347
+ "memory regions after returning from state_dict() call if this "
348
+ "parameter is managed by FSDP. Please check clone "
349
+ f"implementation of {fqn}. Error: {str(e)}"
350
+ )
351
+
352
+ return _common_unshard_post_state_dict_hook(
353
+ module, fsdp_state, state_dict, prefix, param_hook
354
+ )
355
+
356
+
357
+ def _full_pre_load_state_dict_hook(
358
+ module: nn.Module,
359
+ fsdp_state: _FSDPState,
360
+ state_dict: Dict[str, Any],
361
+ prefix: str,
362
+ ) -> None:
363
+ _lazy_init(fsdp_state, module)
364
+ if _should_unshard_params(fsdp_state):
365
+ with SimpleProfiler.profile("_enter_unshard_params_ctx"):
366
+ _enter_unshard_params_ctx(module, fsdp_state, writeback=True)
367
+ # Add FSDP_PREFIX only for wrapper-based FSDP.
368
+ if not _is_composable(fsdp_state):
369
+ _replace_by_prefix(state_dict, prefix, prefix + f"{FSDP_PREFIX}")
370
+
371
+
372
+ def _full_post_load_state_dict_hook(
373
+ module: nn.Module, fsdp_state: _FSDPState, *args, **kwargs
374
+ ) -> None:
375
+ if _should_unshard_params(fsdp_state):
376
+ with SimpleProfiler.profile("_exit_unshard_params_ctx"):
377
+ _exit_unshard_params_ctx(module, fsdp_state)
378
+
379
+
380
+ def _local_pre_state_dict_hook(
381
+ fsdp_state: _FSDPState,
382
+ module: nn.Module,
383
+ *args,
384
+ **kwargs,
385
+ ) -> None:
386
+ """
387
+ Hook that runs before model.state_dict() is called. Right now, pre-state_dict
388
+ hook is not supported by the PyTorch core. So this API is called from
389
+ `_local_post_state_dict_hook()` to simulate the case.
390
+ """
391
+ if (
392
+ _has_fsdp_params(fsdp_state, module)
393
+ and not _module_handle(fsdp_state, module).uses_sharded_strategy
394
+ ):
395
+ raise RuntimeError(
396
+ "``local_state_dict`` can only be used when parameters are flatten "
397
+ "and sharded."
398
+ )
399
+ _common_pre_state_dict_hook(module, fsdp_state)
400
+
401
+
402
+ @no_type_check
403
+ def _local_post_state_dict_hook(
404
+ module: nn.Module,
405
+ fsdp_state: _FSDPState,
406
+ state_dict: Dict[str, Any],
407
+ prefix: str,
408
+ ) -> Dict[str, Any]:
409
+ """
410
+ This hook create a ShardedTensor from the local flat_param and replace
411
+ the state_dict[f"{prefix}{FLAT_PARAM}] with the ShardedTensor. No copy
412
+ will happen. The underlying storage is the same.
413
+ """
414
+
415
+ _replace_by_prefix(state_dict, f"{prefix}{FSDP_PREFIX}", prefix)
416
+ if not _has_fsdp_params(fsdp_state, module):
417
+ return state_dict
418
+
419
+ # state_dict[f"{prefix}{FLAT_PARAM}"] exists and has the same tensor
420
+ # value as the flat_param but it is a pure Tensor because
421
+ # nn.Module.state_dict() will detach the parameter. Therefore, we need
422
+ # to get flat_param to get the metadata.
423
+ assert _module_handle(fsdp_state, module), "Should have returned early"
424
+ flat_param = _module_handle(fsdp_state, module).flat_param
425
+ # Constructs a ShardedTensor from the flat_param "without" padding.
426
+ # Removing the padding allows users to change the number of ranks
427
+ # when loading the local_state_dict.
428
+ full_numel = flat_param._unpadded_unsharded_size.numel() # type: ignore[attr-defined]
429
+ shard_offset = flat_param.numel() * fsdp_state.rank
430
+ valid_data_size = flat_param.numel() - flat_param._shard_numel_padded
431
+ if valid_data_size > 0:
432
+ # If FlatParameter is returned, FlatParameter._local_shard cause a
433
+ # pickling issue (can be torch.save but not torch.load). Since there
434
+ # is no benefit for state_dict to return the actual FlatParameter class,
435
+ # a view (which is a tensor) of the FlatParameter will be returned.
436
+ flat_param = flat_param[:valid_data_size].view(valid_data_size)
437
+ local_shards = [
438
+ Shard.from_tensor_and_offsets(flat_param, [shard_offset], fsdp_state.rank)
439
+ ]
440
+ else:
441
+ local_shards = []
442
+ sharded_tensor = init_from_local_shards(
443
+ local_shards, full_numel, process_group=fsdp_state.process_group
444
+ ) # type: ignore[assignment]
445
+ # TODO: Add DTensor state_dict support for LOCAL_STATE_DICT.
446
+ if fsdp_state._state_dict_config.offload_to_cpu:
447
+ sharded_tensor = sharded_tensor.cpu()
448
+ state_dict[f"{prefix}{FLAT_PARAM}"] = sharded_tensor
449
+ return state_dict
450
+
451
+
452
+ def _local_post_load_state_dict_hook(
453
+ module: nn.Module, fsdp_state: _FSDPState, *args, **kwargs
454
+ ) -> None:
455
+ pass
456
+
457
+
458
+ def _local_pre_load_state_dict_hook(
459
+ module: nn.Module,
460
+ fsdp_state: _FSDPState,
461
+ state_dict: Dict[str, Any],
462
+ prefix: str,
463
+ ) -> None:
464
+ """
465
+ This hook finds the local flat_param for this FSDP module from the
466
+ state_dict. The flat_param should be a ShardedTensor. This hook converts
467
+ the ShardedTensor to a tensor. No copy happen unless padding is required.
468
+ """
469
+ _lazy_init(fsdp_state, module)
470
+ _replace_by_prefix(state_dict, prefix, f"{prefix}{FSDP_PREFIX}")
471
+ fqn = f"{prefix}{FSDP_PREFIX}{FLAT_PARAM}"
472
+ if fqn not in state_dict:
473
+ assert not _has_fsdp_params(fsdp_state, module), (
474
+ "No `FlatParameter` in `state_dict` for this FSDP instance "
475
+ "but it has parameters"
476
+ )
477
+ return
478
+ load_tensor = state_dict[fqn]
479
+ assert isinstance(
480
+ load_tensor, ShardedTensor
481
+ ), "Tensors in local_state_dict should be ShardedTensor."
482
+
483
+ # Convert the ShardedTensor to a Tensor.
484
+ flat_param = _module_handle(fsdp_state, module).flat_param
485
+ assert flat_param is not None
486
+ valid_data_size = flat_param.numel() - flat_param._shard_numel_padded
487
+ shards = load_tensor.local_shards()
488
+ if valid_data_size > 0:
489
+ assert len(shards), "load_local_state_dict assume one shard per ShardedTensor."
490
+ load_tensor = shards[0].tensor
491
+
492
+ # Get the metadata of the flat_param to decide whether to pad the loaded
493
+ # tensor.
494
+ if flat_param._shard_numel_padded > 0:
495
+ assert load_tensor.numel() < flat_param.numel(), (
496
+ f"Local shard size = {flat_param.numel()} and the tensor in "
497
+ f"the state_dict is {load_tensor.numel()}."
498
+ )
499
+ load_tensor = F.pad(load_tensor, [0, flat_param._shard_numel_padded])
500
+ else:
501
+ load_tensor = flat_param
502
+ # TODO: Add DTensor state_dict support for LOCAL_STATE_DICT.
503
+ state_dict[fqn] = load_tensor
504
+
505
+
506
+ def _sharded_pre_state_dict_hook(
507
+ fsdp_state: _FSDPState,
508
+ module: nn.Module,
509
+ *args,
510
+ **kwargs,
511
+ ) -> None:
512
+ """
513
+ Hook that runs before model.state_dict() is called. Check
514
+ ``_full_pre_load_state_dict_hook`` for the detail.
515
+ """
516
+ if (
517
+ _has_fsdp_params(fsdp_state, module)
518
+ and not _module_handle(fsdp_state, module).uses_sharded_strategy
519
+ ):
520
+ raise RuntimeError(
521
+ "``sharded_state_dict`` can only be used when parameters are flatten "
522
+ "and sharded."
523
+ )
524
+ _common_pre_state_dict_hook(module, fsdp_state)
525
+ # Setting offload_to_cpu here does not work even if offload_to_cpu is True.
526
+ # We have to create ShardedTensor first then move it to CPU.
527
+ _common_unshard_pre_state_dict_hook(
528
+ module,
529
+ fsdp_state,
530
+ offload_to_cpu=False,
531
+ rank0_only=False,
532
+ )
533
+
534
+
535
+ @no_type_check
536
+ def _sharded_post_state_dict_hook(
537
+ module: nn.Module,
538
+ fsdp_state: _FSDPState,
539
+ state_dict: Dict[str, Any],
540
+ prefix: str,
541
+ ) -> Dict[str, Any]:
542
+ """
543
+ The hook replaces the unflattened, unsharded parameter in the state_dict
544
+ with a unflattened, sharded parameter (a ShardedTensor).
545
+ """
546
+
547
+ def param_hook(state_dict: Dict[str, Any], prefix: str, fqn: str):
548
+ param = state_dict[fqn]
549
+ if not fsdp_state._state_dict_config._use_dtensor:
550
+ sharded_tensor = _ext_chunk_tensor(
551
+ tensor=param,
552
+ rank=fsdp_state.rank,
553
+ world_size=fsdp_state.world_size,
554
+ num_devices_per_node=fsdp_state._device_handle.device_count(),
555
+ pg=fsdp_state.process_group,
556
+ fsdp_extension=fsdp_state._fsdp_extension,
557
+ )
558
+ else:
559
+ sharded_tensor = _ext_chunk_dtensor(
560
+ tensor=param,
561
+ rank=fsdp_state.rank,
562
+ device_mesh=fsdp_state._device_mesh,
563
+ fsdp_extension=fsdp_state._fsdp_extension,
564
+ )
565
+ if fsdp_state._state_dict_config.offload_to_cpu:
566
+ sharded_tensor = sharded_tensor.cpu()
567
+ state_dict[fqn] = sharded_tensor
568
+
569
+ return _common_unshard_post_state_dict_hook(
570
+ module, fsdp_state, state_dict, prefix, param_hook
571
+ )
572
+
573
+
574
+ @no_type_check
575
+ def _sharded_post_load_state_dict_hook(
576
+ module: nn.Module, fsdp_state: _FSDPState, *args, **kwargs
577
+ ) -> None:
578
+ if _has_fsdp_params(fsdp_state, module):
579
+ with SimpleProfiler.profile("_exit_unshard_params_ctx"):
580
+ _exit_unshard_params_ctx(module, fsdp_state)
581
+
582
+
583
+ @no_type_check
584
+ def _sharded_pre_load_state_dict_hook(
585
+ module: nn.Module,
586
+ fsdp_state: _FSDPState,
587
+ state_dict: Dict[str, Any],
588
+ prefix: str,
589
+ ) -> None:
590
+ """
591
+ The hook combines the unflattened, sharded parameters (ShardedTensor) to
592
+ a new FlatParameter and shards the new FlatParameter to the local chunk.
593
+ """
594
+ _lazy_init(fsdp_state, module)
595
+ if not _is_composable(fsdp_state):
596
+ _replace_by_prefix(state_dict, prefix, prefix + f"{FSDP_PREFIX}")
597
+ if not _has_fsdp_params(fsdp_state, module):
598
+ return
599
+
600
+ handle = _module_handle(fsdp_state, module)
601
+ if not handle.uses_sharded_strategy:
602
+ raise RuntimeError(
603
+ "load_sharded_state_dict can only be called when parameters "
604
+ "are flattened and sharded."
605
+ )
606
+ fqn_to_param_ext = dict(
607
+ zip(handle.flat_param._fqns, handle.flat_param._param_extensions)
608
+ )
609
+
610
+ for fqn, _, _ in _param_name_infos(module, fsdp_state):
611
+ if not _is_composable(fsdp_state):
612
+ fqn_from_global_root = f"{prefix}{FSDP_PREFIX}{fqn}"
613
+ else:
614
+ fqn_from_global_root = f"{prefix}{fqn}"
615
+ try:
616
+ param = state_dict.pop(fqn_from_global_root)
617
+ except KeyError:
618
+ logger.warning(
619
+ f"Did not find param with FQN {fqn_from_global_root}, skipping it. " # noqa: G004
620
+ "The weight will not be filled if you expect it to be."
621
+ )
622
+ continue # TODO: Improve unittesting for state_dict finetuning
623
+ # cases: https://github.com/pytorch/pytorch/issues/109134
624
+
625
+ if not fsdp_state._state_dict_config._use_dtensor:
626
+ # All-gather the param (ShardedTensor)
627
+ param, shards = _ext_pre_load_state_dict_transform(
628
+ param, fsdp_state._fsdp_extension
629
+ )
630
+
631
+ assert len(shards) < 2, (
632
+ "Expects 0 or 1 shard per rank "
633
+ f"but got {len(shards)} shards on rank {fsdp_state.rank}."
634
+ )
635
+ param_numel = param.size().numel()
636
+ dim_0_size = param.size()[0]
637
+ chunk_size = (
638
+ math.ceil(dim_0_size / fsdp_state.world_size)
639
+ * param_numel
640
+ // dim_0_size
641
+ )
642
+ if len(shards) == 1:
643
+ local_tensor = shards[0].tensor.flatten()
644
+ with SimpleProfiler.profile(SimpleProfiler.Type.H2D):
645
+ local_tensor = local_tensor.to(fsdp_state.compute_device)
646
+ num_padding = chunk_size - local_tensor.numel()
647
+ if num_padding > 0:
648
+ local_tensor = F.pad(local_tensor, [0, num_padding])
649
+ else:
650
+ local_tensor = torch.zeros(
651
+ chunk_size, dtype=param.dtype, device=fsdp_state.compute_device
652
+ )
653
+ tensor = torch.empty(
654
+ chunk_size * fsdp_state.world_size,
655
+ dtype=local_tensor.dtype,
656
+ device=fsdp_state.compute_device,
657
+ )
658
+ with SimpleProfiler.profile(SimpleProfiler.Type.ALLGATHER):
659
+ dist.all_gather_into_tensor(
660
+ tensor, local_tensor, group=fsdp_state.process_group
661
+ )
662
+ tensor = tensor.narrow(0, 0, param_numel).reshape(param.size())
663
+ state_dict[fqn_from_global_root] = tensor
664
+ else:
665
+ if param.device != fsdp_state._device_mesh.device_type:
666
+ param = param.to(fsdp_state._device_mesh.device_type)
667
+
668
+ root_mesh = _mesh_resources.get_root_mesh(fsdp_state._device_mesh)
669
+ local_tensor = _ext_all_gather_dtensor(
670
+ param, root_mesh, fsdp_state._fsdp_extension
671
+ )
672
+
673
+ if fqn_to_param_ext.get(fqn) is not None:
674
+ ext = fqn_to_param_ext[fqn]
675
+ local_tensor = _ext_post_unflatten_transform(
676
+ local_tensor, ext, fsdp_state._fsdp_extension
677
+ )
678
+ state_dict[fqn_from_global_root] = local_tensor
679
+
680
+ with SimpleProfiler.profile("_enter_unshard_params_ctx"):
681
+ _enter_unshard_params_ctx(module, fsdp_state, writeback=True)
682
+
683
+
684
+ @contextlib.contextmanager
685
+ def _replace_with_full_state_dict_type(fsdp_state: _FSDPState) -> Generator:
686
+ old_state_dict_config = fsdp_state._state_dict_config
687
+ old_state_dict_type = fsdp_state._state_dict_type
688
+ fsdp_state._state_dict_config = FullStateDictConfig()
689
+ fsdp_state._state_dict_type = StateDictType.FULL_STATE_DICT
690
+ yield
691
+ fsdp_state._state_dict_config = old_state_dict_config
692
+ fsdp_state._state_dict_type = old_state_dict_type
693
+
694
+
695
+ @no_type_check
696
+ @torch.no_grad()
697
+ def _post_state_dict_hook(
698
+ module: nn.Module,
699
+ state_dict: Dict[str, Any],
700
+ prefix: str,
701
+ *args: Any,
702
+ ) -> Dict[str, Any]:
703
+ """
704
+ _post_state_dict_hook() is called after the state_dict() of this
705
+ FSDP module is executed. ``fsdp_state._state_dict_type`` is used to decide
706
+ what postprocessing will be done.
707
+ """
708
+ fsdp_state = _get_module_fsdp_state_if_fully_sharded_module(module)
709
+ if fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD:
710
+ context = _replace_with_full_state_dict_type(fsdp_state)
711
+ warnings.warn(
712
+ "When using ``NO_SHARD`` for ``ShardingStrategy``, full_state_dict will"
713
+ "be returned."
714
+ )
715
+ else:
716
+ context = contextlib.nullcontext()
717
+
718
+ with context:
719
+ _post_state_dict_hook_fn = {
720
+ StateDictType.FULL_STATE_DICT: _full_post_state_dict_hook,
721
+ StateDictType.LOCAL_STATE_DICT: _local_post_state_dict_hook,
722
+ StateDictType.SHARDED_STATE_DICT: _sharded_post_state_dict_hook,
723
+ }
724
+ processed_state_dict = _post_state_dict_hook_fn[fsdp_state._state_dict_type](
725
+ module, fsdp_state, state_dict, prefix
726
+ )
727
+
728
+ if fsdp_state._is_root:
729
+ logger.info("FSDP finished processing state_dict(), prefix=%s", prefix)
730
+ for key, tensor in sorted(processed_state_dict.items()):
731
+ if key.startswith(prefix) and isinstance(tensor, torch.Tensor):
732
+ local_shape = tensor.shape
733
+ if isinstance(tensor, ShardedTensor):
734
+ local_shape = None
735
+ shards = tensor.local_shards()
736
+ if shards:
737
+ local_shape = shards[0].tensor.shape
738
+ elif isinstance(tensor, DTensor):
739
+ local_shape = tensor.to_local().shape
740
+ logger.info(
741
+ "FQN=%s: type=%s, shape=%s, local_shape=%s, dtype=%s, device=%s",
742
+ key,
743
+ type(tensor),
744
+ tensor.shape,
745
+ local_shape,
746
+ tensor.dtype,
747
+ tensor.device,
748
+ )
749
+
750
+ return processed_state_dict
751
+
752
+
753
+ @no_type_check
754
+ @torch.no_grad()
755
+ def _pre_state_dict_hook(
756
+ module: nn.Module,
757
+ *args,
758
+ **kwargs,
759
+ ) -> None:
760
+ """
761
+ This is called before the core state dict saving logic of ``module``.
762
+ ``fsdp_state._state_dict_type`` is used to decide what postprocessing will
763
+ be done.
764
+ """
765
+ fsdp_state = _get_module_fsdp_state_if_fully_sharded_module(module)
766
+ if fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD:
767
+ context = _replace_with_full_state_dict_type(fsdp_state)
768
+ warnings.warn(
769
+ "When using ``NO_SHARD`` for ``ShardingStrategy``, full_state_dict will"
770
+ "be returned."
771
+ )
772
+ else:
773
+ _set_use_dtensor(fsdp_state)
774
+ context = contextlib.nullcontext()
775
+
776
+ with context:
777
+ _pre_state_dict_hook_fn = {
778
+ StateDictType.FULL_STATE_DICT: _full_pre_state_dict_hook,
779
+ StateDictType.LOCAL_STATE_DICT: _local_pre_state_dict_hook,
780
+ StateDictType.SHARDED_STATE_DICT: _sharded_pre_state_dict_hook,
781
+ }
782
+ _pre_state_dict_hook_fn[fsdp_state._state_dict_type](
783
+ fsdp_state,
784
+ module,
785
+ *args,
786
+ **kwargs,
787
+ )
788
+
789
+
790
+ @no_type_check
791
+ def _set_use_dtensor(fsdp_state: _FSDPState) -> None:
792
+ # If device_mesh is passed in when initalizing FSDP, we automatically turn the
793
+ # _use_dtensor flag to be true for ShardedStateDictConfig().
794
+ if getattr(fsdp_state, "_device_mesh", None):
795
+ state_dict_type = fsdp_state._state_dict_type
796
+ if state_dict_type == StateDictType.LOCAL_STATE_DICT:
797
+ raise RuntimeError(
798
+ "Found state_dict_type LOCAL_STATE_DICT",
799
+ "DeviceMesh is not compatible with LOCAL_STATE_DICT.",
800
+ "Please set state_dict_type to SHARDED_STATE_DICT to get DTensor state_dict.",
801
+ )
802
+ else:
803
+ fsdp_state._state_dict_config._use_dtensor = True
804
+
805
+
806
+ @no_type_check
807
+ @torch.no_grad()
808
+ def _pre_load_state_dict_hook(
809
+ module: nn.Module,
810
+ state_dict: Dict[str, Any],
811
+ prefix: str,
812
+ *args: Any,
813
+ ) -> None:
814
+ """
815
+ This is called before ``module._load_from_state_dict()``.
816
+ ``fsdp_state._state_dict_type`` is used to decide what preprocessing will
817
+ be done.
818
+ """
819
+ fsdp_state = _get_module_fsdp_state_if_fully_sharded_module(module)
820
+ if fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD:
821
+ context = _replace_with_full_state_dict_type(fsdp_state)
822
+ warnings.warn(
823
+ "When using ``NO_SHARD`` for ``ShardingStrategy``, full_state_dict will"
824
+ "be returned."
825
+ )
826
+ else:
827
+ _set_use_dtensor(fsdp_state)
828
+ context = contextlib.nullcontext()
829
+
830
+ _lazy_init(fsdp_state, module)
831
+ if fsdp_state._is_root:
832
+ SimpleProfiler.reset()
833
+
834
+ with context:
835
+ _pre_load_state_dict_hook_fn = {
836
+ StateDictType.FULL_STATE_DICT: _full_pre_load_state_dict_hook,
837
+ StateDictType.LOCAL_STATE_DICT: _local_pre_load_state_dict_hook,
838
+ StateDictType.SHARDED_STATE_DICT: _sharded_pre_load_state_dict_hook,
839
+ }
840
+ # Code that is common for all state_dict impls
841
+ if fsdp_state._device_handle.is_available():
842
+ fsdp_state._device_handle.synchronize()
843
+ # Dispatch into state_dict specific implementation of pre-hook.
844
+ _pre_load_state_dict_hook_fn[fsdp_state._state_dict_type](
845
+ module, fsdp_state, state_dict, prefix
846
+ )
847
+
848
+
849
+ @no_type_check
850
+ @torch.no_grad()
851
+ def _post_load_state_dict_hook(
852
+ module: nn.Module,
853
+ incompatible_keys: Tuple[List[str], List[str]],
854
+ *args: Any,
855
+ ) -> None:
856
+ fsdp_state = _get_module_fsdp_state_if_fully_sharded_module(module)
857
+ if fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD:
858
+ context = _replace_with_full_state_dict_type(fsdp_state)
859
+ warnings.warn(
860
+ "When using ``NO_SHARD`` for ``ShardingStrategy``, full_state_dict will"
861
+ "be returned."
862
+ )
863
+ else:
864
+ context = contextlib.nullcontext()
865
+
866
+ with context:
867
+ _post_load_state_dict_hook_fn = {
868
+ StateDictType.FULL_STATE_DICT: _full_post_load_state_dict_hook,
869
+ StateDictType.LOCAL_STATE_DICT: _local_post_load_state_dict_hook,
870
+ StateDictType.SHARDED_STATE_DICT: _sharded_post_load_state_dict_hook,
871
+ }
872
+ # Code that is common for all state_dict impls
873
+ # Dispatch into state_dict type specific implementation of post-hook for
874
+ # loading state_dict.
875
+ _post_load_state_dict_hook_fn[fsdp_state._state_dict_type](module, fsdp_state)
876
+
877
+ # When reporting incompatible keys, trim FSDP prefixes.
878
+ missing_keys = incompatible_keys[0]
879
+ unexpected_keys = incompatible_keys[1]
880
+ for i in range(len(missing_keys)):
881
+ missing_keys[i] = clean_tensor_name(missing_keys[i])
882
+
883
+ for i in range(len(unexpected_keys)):
884
+ unexpected_keys[i] = clean_tensor_name(unexpected_keys[i])
885
+
886
+ if fsdp_state._is_root:
887
+ SimpleProfiler.dump_and_reset("FSDP model load_state_dict profiling: ")
888
+
889
+
890
+ def _register_all_state_dict_hooks(state: _FSDPState):
891
+ """
892
+ Registers pre-save, post-save, pre-load, and post-load state dict hooks.
893
+ """
894
+ for hook_registration_fn_str, hook, hook_registration_fn_kwargs in (
895
+ ("register_state_dict_pre_hook", _pre_state_dict_hook, {}),
896
+ ("_register_state_dict_hook", _post_state_dict_hook, {}),
897
+ (
898
+ "_register_load_state_dict_pre_hook",
899
+ _pre_load_state_dict_hook,
900
+ {"with_module": True},
901
+ ),
902
+ ("register_load_state_dict_post_hook", _post_load_state_dict_hook, {}),
903
+ ):
904
+ _register_state_dict_hooks_base(
905
+ state, hook_registration_fn_str, hook, hook_registration_fn_kwargs
906
+ )
907
+
908
+
909
+ @no_type_check
910
+ def _register_state_dict_hooks_base(
911
+ state: _FSDPState,
912
+ hook_registration_fn_name: str,
913
+ hook: Callable,
914
+ hook_registration_fn_kwargs: Dict[str, Any],
915
+ ) -> None:
916
+ """Registers ``hook`` using ``hook_registration_fn``."""
917
+ if not _is_composable(state):
918
+ getattr(state, hook_registration_fn_name)(hook, **hook_registration_fn_kwargs)
919
+ else:
920
+ handle = state._handle
921
+ if handle:
922
+ getattr(handle._fully_sharded_module, hook_registration_fn_name)(
923
+ hook, **hook_registration_fn_kwargs
924
+ )
vllm/lib/python3.10/site-packages/torch/distributed/fsdp/_trace_utils.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import functools
3
+ from contextlib import contextmanager
4
+ from dataclasses import dataclass, field
5
+ from typing import Any, Callable, Dict, List, NamedTuple, Optional, Set, Tuple
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+
10
+
11
+ @dataclass
12
+ class TracingConfig:
13
+ """
14
+ This represents a symbolic tracing configuration.
15
+
16
+ Args:
17
+ tracer (torch.fx.Tracer): An instance of :class:`torch.fx.Tracer` to
18
+ use for symbolic tracing. The default value is the native
19
+ :class:`torch.fx.Tracer` constructed with default arguments.
20
+ However, the user may want to pass a different value such as the
21
+ ``HFTracer`` for models in the HuggingFace Transformers_ library.
22
+ .. _Transformers: https://huggingface.co/docs/transformers/index
23
+ concrete_args (Optional[Dict[str, Any]]): Concrete arguments that
24
+ should not be treated as ``torch.fx.Proxy`` when tracing the
25
+ module ``forward()``. Passing ``concrete_args`` allows partially
26
+ specializing the forward, e.g. to remove control flow or data
27
+ structures. This ``concrete_args`` here is the same argument used
28
+ in :meth:`~torch.fx.Tracer.trace`.
29
+ """
30
+
31
+ tracer: torch.fx.Tracer = field(default_factory=torch.fx.Tracer)
32
+ concrete_args: Optional[Dict[str, Any]] = None
33
+
34
+
35
+ class _ParamUsageInfo(NamedTuple):
36
+ """
37
+ This is used for ``_ExecutionInfo.module_to_param_usage_infos`` to record
38
+ execution information. The ``dict`` maps modules to a list of these
39
+ ``_ParamUsageInfo`` instances, where each instance represents a group of
40
+ parameters used together.
41
+
42
+ Specifically, for each module key in the ``dict``, each instance of this
43
+ class represents either:
44
+ (1) the module and some sublist of its ``named_parameters()`` used
45
+ together in execution (see ``_patched_create_proxy()``), or
46
+ (2) a submodule and all of ``submodule.named_parameters()`` (see
47
+ ``_patched_call_module()``).
48
+
49
+ Type (1) corresponds to directly using parameters in ops without calling
50
+ ``forward()``, and type (2) corresponds to calling ``forward()``. The
51
+ mapped-to lists in the ``dict`` follow the execution order.
52
+ """
53
+
54
+ module: nn.Module
55
+ named_params: List[Tuple[str, nn.Parameter]]
56
+
57
+
58
+ class _ExecutionInfo:
59
+ """
60
+ This represents the execution order information from the forward pass.
61
+
62
+ Attributes:
63
+ curr_module (nn.Module): Current module being traced.
64
+ module_forward_order (List[nn.Module]): The modules in (pre-)forward
65
+ order, i.e. the order in which their ``forward()`` methods are
66
+ called. Each call to a module's ``forward()`` corresponds to one
67
+ element in the list.
68
+ module_to_param_usage_infos (Dict[nn.Module, List[_ParamUsageInfo]]):
69
+ Maps a module to a list of module execution infos. See
70
+ :class:`_ParamUsageInfo` for details.
71
+ param_forward_order (List[nn.Parameter]): The parameters in forward
72
+ execution order, where only a parameter's first participation is
73
+ included.
74
+ visited_params (Set[nn.Parameter]): The parameters visited so far
75
+ during the trace. This is only used during tracing for fast
76
+ membership check. Invariant: The parameters in
77
+ ``param_forward_order`` are exactly those in ``visited_params``.
78
+ """
79
+
80
+ def __init__(self, root_module: nn.Module) -> None:
81
+ self.curr_module: nn.Module = root_module
82
+ self.module_forward_order: List[nn.Module] = [root_module]
83
+ self.module_to_param_usage_infos: Dict[nn.Module, List[_ParamUsageInfo]] = {
84
+ root_module: []
85
+ }
86
+ self.param_forward_order: List[nn.Parameter] = []
87
+ self.visited_params: Set[nn.Parameter] = set()
88
+
89
+
90
+ class _ExecOrderTracer:
91
+ def __init__(self) -> None:
92
+ self.exec_info: Optional[_ExecutionInfo] = None
93
+
94
+ @contextmanager
95
+ def patch_tracer(self, tracer: torch.fx.Tracer, root_module: nn.Module):
96
+ self.exec_info = _ExecutionInfo(root_module)
97
+ orig_call_module = tracer.call_module
98
+ orig_create_proxy = tracer.create_proxy
99
+ tracer.call_module = functools.partial( # type: ignore[method-assign]
100
+ self._patched_call_module, orig_call_module, self.exec_info
101
+ )
102
+ fqn_to_param = dict(root_module.named_parameters())
103
+ tracer.create_proxy = functools.partial( # type: ignore[method-assign]
104
+ self._patched_create_proxy,
105
+ orig_create_proxy,
106
+ self.exec_info,
107
+ fqn_to_param,
108
+ )
109
+ try:
110
+ yield
111
+ finally:
112
+ tracer.call_module = orig_call_module # type: ignore[method-assign]
113
+ tracer.create_proxy = orig_create_proxy # type: ignore[method-assign]
114
+
115
+ def _patched_call_module(
116
+ self,
117
+ call_module: Callable,
118
+ exec_info: _ExecutionInfo,
119
+ # Below are the expected arguments to `call_module()`
120
+ module: nn.Module,
121
+ forward: Callable,
122
+ args: Tuple[Any, ...],
123
+ kwargs: Dict[str, Any],
124
+ ) -> Any:
125
+ """
126
+ Overrides ``call_module`` to save execution information to
127
+ ``exec_info``. Note that ``call_module`` is called during symbolic
128
+ tracing for each non-root module.
129
+
130
+ Args:
131
+ call_module (Callable): Original ``call_module`` to override.
132
+ exec_info (_ExecutionInfo): Used to record execution information.
133
+ module (nn.Module): Module corresponding to this ``call_module``.
134
+ forward (Callable): ``forward()`` method of ``module`` to be called
135
+ for this ``call_module``.
136
+ args (Tuple[Any, ...]): Positional arguments for ``forward``.
137
+ kwargs (Dict[str, Any]): Keyword arguments for ``forward``.
138
+
139
+ Returns:
140
+ Same return value as ``call_module``.
141
+ """
142
+ exec_info.module_forward_order.append(module)
143
+ named_params = list(module.named_parameters())
144
+ curr_module = exec_info.curr_module
145
+ if named_params:
146
+ assert (
147
+ curr_module in exec_info.module_to_param_usage_infos
148
+ ), "The current module should have already been processed by a patched `call_module`"
149
+ exec_info.module_to_param_usage_infos[exec_info.curr_module].append(
150
+ _ParamUsageInfo(module, named_params)
151
+ )
152
+ prev_curr_module = curr_module
153
+ exec_info.curr_module = module
154
+ exec_info.module_to_param_usage_infos[module] = []
155
+ output = call_module(module, forward, args, kwargs)
156
+ exec_info.curr_module = prev_curr_module
157
+ return output
158
+
159
+ def _patched_create_proxy(
160
+ self,
161
+ create_proxy: Callable,
162
+ exec_info: _ExecutionInfo,
163
+ fqn_to_param: Dict[str, nn.Parameter],
164
+ # Below are the expected arguments to `create_proxy()`
165
+ kind: str,
166
+ target: torch.fx.node.Target,
167
+ args: Tuple[Any, ...],
168
+ kwargs: Dict[str, Any],
169
+ name: Optional[str] = None,
170
+ type_expr: Optional[Any] = None,
171
+ proxy_factory_fn: Optional[Callable[[torch.fx.Node], torch.fx.Proxy]] = None,
172
+ ) -> torch.fx.Proxy:
173
+ """
174
+ Overrides ``create_proxy`` to save execution information to
175
+ ``exec_info``. Note that ``create_proxy`` is called during symbolic
176
+ tracing for each leaf function/method/module.
177
+
178
+ Args:
179
+ create_proxy (Callable): Original ``create_proxy`` to override.
180
+ exec_info (_ExecutionInfo): Used to record execution information.
181
+ fqn_to_param (Dict[str, nn.Parameter]): ``dict`` version of the
182
+ root module's ``named_parameters()`` with FQN as key and
183
+ parameter as value.
184
+ kind (str): Kind of the target method ('call_function',
185
+ 'call_method', 'get_attr', 'call_module', 'placeholder', or
186
+ 'output'). See :class:`torch.fx.Graph` for details. This is
187
+ passed to ``create_proxy``.
188
+ target (torch.fx.node.Target): Contains the string name of the
189
+ function/method/module. This is passed to ``create_proxy``.
190
+ args (Tuple[Any, ...]): Positional arguments for the function/
191
+ method/module. This is passed to ``create_proxy``.
192
+ kwargs (Dict[str, Any]): Keyword arguments for the function/method/
193
+ module. This is passed to ``create_proxy``
194
+ name (Optional[str]): An optional string name for the ``Node``
195
+ created in ``create_proxy``. This is passed to
196
+ ``create_proxy``.
197
+ type_expr (Optional[Any]): An optional type annotation representing
198
+ the Python type that the output of the node has. This is passed
199
+ to ``create_proxy``.
200
+ proxy_factory_fn (Callable[[torch.fx.Node], torch.fx.Proxy]):
201
+ An alternative proxy constructor used in ``create_proxy``. This
202
+ is passed to ``create_proxy``.
203
+
204
+ Returns:
205
+ torch.fx.Proxy: Created ``Node`` wrapped in a ``Proxy`` object.
206
+ """
207
+ proxy = create_proxy(
208
+ kind, target, args, kwargs, name, type_expr, proxy_factory_fn
209
+ )
210
+ curr_module = exec_info.curr_module
211
+ if kind in ("call_function", "call_method"):
212
+ if args is not None:
213
+ named_params: List[Tuple[str, nn.Parameter]] = []
214
+ for arg in args:
215
+ if (
216
+ isinstance(arg, torch.fx.Proxy)
217
+ and arg.node.target in fqn_to_param
218
+ ):
219
+ param = fqn_to_param[arg.node.target] # type: ignore[index]
220
+ named_params.append((arg.node.target, param)) # type: ignore[arg-type]
221
+ if param not in exec_info.visited_params:
222
+ exec_info.visited_params.add(param)
223
+ exec_info.param_forward_order.append(param)
224
+ if named_params:
225
+ exec_info.module_to_param_usage_infos[curr_module].append(
226
+ _ParamUsageInfo(curr_module, named_params)
227
+ )
228
+ elif kind == "call_module":
229
+ named_params = list(curr_module.named_parameters())
230
+ if named_params:
231
+ exec_info.module_to_param_usage_infos[curr_module].append(
232
+ _ParamUsageInfo(curr_module, named_params)
233
+ )
234
+ for _, param in named_params:
235
+ if param not in exec_info.visited_params:
236
+ exec_info.visited_params.add(param)
237
+ exec_info.param_forward_order.append(param)
238
+ return proxy
vllm/lib/python3.10/site-packages/torch/distributed/fsdp/_traversal_utils.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ NOTE: This file must be imported like
3
+ ``import torch.distributed.fsdp._traversal_utils`` and not like
4
+ ``from torch.distirbuted.fsdp._traversal_utils import ...`` to avoid circular
5
+ imports. For brevity, we may import the file as ``traversal_utils``.
6
+ """
7
+
8
+ import collections
9
+ from typing import Deque, List, Set, Tuple
10
+
11
+ import torch.nn as nn
12
+ from torch.distributed._composable.contract import _get_registry
13
+ from torch.distributed.fsdp._common_utils import _FSDPState, _get_module_fsdp_state
14
+
15
+
16
+ """
17
+ [Note: FSDP State Traversal]
18
+ For the wrapper code path, ``_FSDPState`` is the ``FullyShardedDataParallel``
19
+ module wrapping a fully sharded module, and for the non-wrapper code path,
20
+ ``_FSDPState`` is an object that gets embedded on a fully sharded module.
21
+ See [Note: Fully Sharded Module] for the definition.
22
+
23
+ There are three common traversal idioms: Given a root module,
24
+ - ``_get_fsdp_states()`` returns all ``_FSDPState`` s in the tree.
25
+ - ``get_fsdp_root_states()`` returns all local root ``_FSDPState`` s in the
26
+ tree (i.e. those with ``_is_root == True``).
27
+ - ``_get_fsdp_handles()``returns all ``FlatParamHandle`` s in the tree.
28
+
29
+ All of these methods must take in the root module (i.e. an ``nn.Module``) and
30
+ not a general ``_FSDPState`` because ``_FSDPState`` does not support a graph
31
+ traversal, whereas ``nn.Module`` has ``nn.Module.modules()`` for traversal.
32
+ """
33
+
34
+
35
+ def _composable(module: nn.Module) -> bool:
36
+ """
37
+ Returns if ``module`` can compose with ``fully_shard``.
38
+ """
39
+ # TODO: Add any other composable APIs that are mutually exclusive.
40
+ registry = _get_registry(module)
41
+ if registry is None:
42
+ return True
43
+ return "replicate" not in registry
44
+
45
+
46
+ # TODO (awgu): We may be able to remove this function if we retired the
47
+ # `use_orig_params=False` code path since so far we only need the module for
48
+ # `FlatParameter` registration, which is not needed for `use_orig_params=True`.
49
+ def _get_fsdp_states_with_modules(
50
+ module: nn.Module,
51
+ ) -> Tuple[List[_FSDPState], List[nn.Module]]:
52
+ """
53
+ Returns a tuple containing:
54
+ 1. A list of the ``_FSDPState`` instances in the module tree rooted at
55
+ ``module`` without any duplicates and following the ``module.modules()``
56
+ traversal order (which is assumed to be depth-first).
57
+ 2. A corresponding list of the modules owning the states in the first list.
58
+
59
+ For the wrapper code path, both returned lists are the same, each
60
+ containing all ``FullyShardedDataParallel`` instances. For the composable
61
+ code path, this returns a list of all composable state instances and a list
62
+ of the corresponding fully sharded modules. See [Note: Fully Sharded
63
+ Module].
64
+
65
+ NOTE: The traversal does not proceed into any module annotated by an
66
+ incompatible API (e.g. ``replicate``).
67
+ """
68
+ fsdp_states: List[_FSDPState] = []
69
+ fsdp_modules: List[nn.Module] = []
70
+ # Track the visited FSDP states since multiple modules may share the same
71
+ # one and we want to return a de-duplicated list
72
+ visited_fsdp_states: Set[_FSDPState] = set()
73
+ # Track the visited modules in case of shared modules, which implies the
74
+ # module graph is no longer a tree
75
+ visited_modules: Set[nn.Module] = set()
76
+
77
+ # Perform depth-first search from `module` to ensure that we do not
78
+ # traverse into an incompatible API's subtree (use DFS instead of BFS to
79
+ # match `.modules()` order)
80
+ deque: Deque[nn.Module] = collections.deque([module])
81
+ while deque:
82
+ submodule = deque.popleft()
83
+ visited_modules.add(submodule)
84
+ if not _composable(submodule):
85
+ continue
86
+ for child_module in reversed(list(submodule.children())):
87
+ if child_module not in visited_modules:
88
+ deque.appendleft(child_module)
89
+ optional_state = _get_module_fsdp_state(submodule)
90
+ if optional_state is not None and optional_state not in visited_fsdp_states:
91
+ visited_fsdp_states.add(optional_state)
92
+ fsdp_states.append(optional_state)
93
+ fsdp_modules.append(submodule)
94
+ return fsdp_states, fsdp_modules
95
+
96
+
97
+ def _get_fsdp_states(module: nn.Module) -> List[_FSDPState]:
98
+ """See :func:`_get_fsdp_states_with_modules`."""
99
+ fsdp_states, _ = _get_fsdp_states_with_modules(module)
100
+ return fsdp_states
101
+
102
+
103
+ def _get_fsdp_handles(module: nn.Module) -> List:
104
+ """
105
+ Returns all ``FlatParamHandle`` s in the module tree rooted at ``module``
106
+ following the rules in :func:`_get_fsdp_state`.
107
+ """
108
+ handles = [
109
+ fsdp_state._handle
110
+ for fsdp_state in _get_fsdp_states(module)
111
+ if fsdp_state._handle is not None
112
+ ]
113
+ return handles
vllm/lib/python3.10/site-packages/torch/distributed/fsdp/_unshard_param_utils.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import contextlib
3
+ import warnings
4
+ from typing import cast, Generator
5
+
6
+ import torch
7
+ import torch.distributed.fsdp._traversal_utils as traversal_utils
8
+ import torch.nn as nn
9
+ from torch.distributed.fsdp._common_utils import (
10
+ _FSDPState,
11
+ _get_module_fsdp_state,
12
+ _has_fsdp_params,
13
+ _module_handle,
14
+ HandleTrainingState,
15
+ TrainingState,
16
+ )
17
+ from torch.distributed.fsdp._runtime_utils import (
18
+ _lazy_init,
19
+ _reset_flat_param_grad_info_if_needed,
20
+ _reshard,
21
+ _reshard_grads,
22
+ _unshard,
23
+ _unshard_grads,
24
+ )
25
+ from torch.distributed.utils import _p_assert
26
+
27
+ from ._flat_param import FlatParamHandle
28
+
29
+
30
+ FLAT_PARAM = "_flat_param"
31
+
32
+
33
+ @torch.no_grad()
34
+ def _writeback_to_local_shard(
35
+ handle: FlatParamHandle,
36
+ writeback_grad: bool,
37
+ ):
38
+ """
39
+ For the handle, writes back the this rank's shard of the unsharded
40
+ flattened parameter to the sharded flattened parameter. If
41
+ ``writeback_grad=True``, then writes back to the sharded gradient as
42
+ well.
43
+
44
+ Precondition: The handle's ``FlatParameter`` 's data points to the
45
+ padded unsharded flattened parameter.
46
+ """
47
+
48
+ def _get_shard(flat_param_or_grad: torch.Tensor) -> torch.Tensor:
49
+ if handle.uses_sharded_strategy:
50
+ # For sharded strategies, get the *unpadded* shard instead of
51
+ # the *padded* shard to persist user changes to the padding
52
+ # (though FSDP does not explicitly support this)
53
+ shard, _ = FlatParamHandle._get_unpadded_shard(
54
+ flat_param_or_grad,
55
+ handle.rank,
56
+ handle.world_size,
57
+ )
58
+ return shard
59
+ # For `NO_SHARD`, the `flat_param` or its gradient may be modified,
60
+ # so we write it back directly
61
+ return flat_param_or_grad
62
+
63
+ param_shard = _get_shard(handle.flat_param)
64
+ handle.flat_param._local_shard[: param_shard.numel()].copy_(param_shard) # type: ignore[attr-defined]
65
+ if writeback_grad:
66
+ existing_grad = handle.sharded_grad
67
+ if existing_grad is not None:
68
+ assert handle.flat_param.grad is not None
69
+ grad_shard = _get_shard(handle.flat_param.grad)
70
+ existing_grad[: grad_shard.numel()].copy_(grad_shard)
71
+
72
+
73
+ def _deregister_flat_param(state: _FSDPState, module: nn.Module) -> None:
74
+ """
75
+ De-registers the flattened parameter from the wrapped module, hiding it
76
+ from ``nn.Module`` methods.
77
+
78
+ We do not use ``del`` because we want ``FLAT_PARAM`` to always be an
79
+ attribute but dynamically change whether it is visible to ``nn.Module``
80
+ methods.
81
+ """
82
+ if _has_fsdp_params(state, module):
83
+ # TODO: figure out the case for the composable APIs.
84
+ cast(nn.Module, module.module)._parameters.pop(FLAT_PARAM, None)
85
+
86
+
87
+ def _register_flat_param(state: _FSDPState, module: nn.Module) -> None:
88
+ """
89
+ Registers the flattened parameter to the wrapped module, making it
90
+ visible to ``nn.Module`` methods.
91
+
92
+ We do not use :meth:`nn.Module.register_parameter` because we want
93
+ ``FLAT_PARAM`` to always be an attribute but dynamically change whether
94
+ it is visible to ``nn.Module`` methods.
95
+ """
96
+ handle = _module_handle(state, module)
97
+ if _has_fsdp_params(state, module):
98
+ # TODO: figure out the case for the composable APIs.
99
+ cast(nn.Module, module.module)._parameters[FLAT_PARAM] = handle.flat_param
100
+
101
+
102
+ @contextlib.contextmanager
103
+ def _unflatten_as_params(state: _FSDPState, module: nn.Module) -> Generator:
104
+ """
105
+ Assumes that the flattened parameter is unsharded. When in the context,
106
+ de-registers the flattened parameter and unflattens the original
107
+ parameters as ``nn.Parameter`` views into the flattened parameter.
108
+ After the context, re-registers the flattened parameter and restores
109
+ the original parameters as ``Tensor`` views into the flattened
110
+ parameter.
111
+ """
112
+ handle = _module_handle(state, module)
113
+ if not handle:
114
+ yield
115
+ else:
116
+ _deregister_flat_param(state, module)
117
+ try:
118
+ with handle.unflatten_as_params():
119
+ yield
120
+ finally:
121
+ if not handle._use_orig_params:
122
+ _register_flat_param(state, module)
123
+
124
+
125
+ def _validate_unshard_params_args(
126
+ state: _FSDPState,
127
+ writeback: bool,
128
+ rank0_only: bool,
129
+ offload_to_cpu: bool,
130
+ with_grads: bool,
131
+ ) -> None:
132
+ if with_grads and (offload_to_cpu or not state._use_orig_params):
133
+ raise NotImplementedError(
134
+ f"with_grads={with_grads}, "
135
+ f"use_orig_params={state._use_orig_params}, "
136
+ f"offload_to_cpu={offload_to_cpu} "
137
+ f"is not supported yet"
138
+ )
139
+ if offload_to_cpu and state._handle and (not state._handle.uses_sharded_strategy):
140
+ raise NotImplementedError(
141
+ "offload_to_cpu=True and NO_SHARD is not supported yet"
142
+ )
143
+ if writeback and rank0_only:
144
+ # TODO: Rank 0 can broadcast the `FlatParameter` to allow all ranks to
145
+ # persist the changes.
146
+ raise NotImplementedError(
147
+ "writeback=True and rank0_only=True is not supported yet"
148
+ )
149
+ if offload_to_cpu and not rank0_only:
150
+ warnings.warn(
151
+ "offload_to_cpu=True and rank0_only=False may result in the"
152
+ "unsharded parameters being redundantly copied to CPU memory for "
153
+ "GPUs sharing the same CPU memory, which risks CPU OOM. We "
154
+ "recommend using offload_to_cpu=True with rank0_only=True."
155
+ )
156
+
157
+
158
+ @contextlib.contextmanager
159
+ def _unshard_fsdp_state_params(
160
+ module: nn.Module,
161
+ state: _FSDPState,
162
+ writeback: bool,
163
+ rank0_only: bool,
164
+ offload_to_cpu: bool,
165
+ with_grads: bool,
166
+ ):
167
+ """
168
+ This unshards the parameters for a single FSDP state ``state`` that
169
+ corresponds to ``module``.
170
+ """
171
+ _validate_unshard_params_args(
172
+ state, writeback, rank0_only, offload_to_cpu, with_grads
173
+ )
174
+ state._device_handle.synchronize()
175
+ # If handles are shared by other module(s), the handle may be already unsharded.
176
+ maybe_handle = _module_handle(state, module)
177
+ handle = None
178
+ if (
179
+ maybe_handle
180
+ and maybe_handle._training_state != HandleTrainingState.SUMMON_FULL_PARAMS
181
+ ):
182
+ handle = maybe_handle
183
+ if not handle:
184
+ yield
185
+ return
186
+
187
+ assert (
188
+ handle._training_state == HandleTrainingState.IDLE
189
+ ), f"Expects the handle training to be IDLE but got {handle._training_state}"
190
+
191
+ handle._training_state = HandleTrainingState.SUMMON_FULL_PARAMS
192
+
193
+ _reset_flat_param_grad_info_if_needed(handle)
194
+ free_unsharded_flat_param = handle.needs_unshard()
195
+ # No need to call `wait_stream()` since we unshard in the computation
196
+ # stream directly
197
+ computation_stream = state._device_handle.current_stream()
198
+ _unshard(state, handle, computation_stream, computation_stream)
199
+ if with_grads:
200
+ _unshard_grads(handle)
201
+
202
+ if rank0_only and state.rank != 0:
203
+ # Free the unsharded flattened parameter early
204
+ _reshard(state, handle, free_unsharded_flat_param)
205
+ if with_grads:
206
+ _reshard_grads(handle)
207
+ try:
208
+ yield
209
+ finally:
210
+ handle._training_state = HandleTrainingState.IDLE
211
+ else:
212
+ # Unflatten the unsharded flattened parameters
213
+ with contextlib.ExitStack() as stack:
214
+ # Invariant: rank == 0 or !rank0_only
215
+ if offload_to_cpu and handle.uses_sharded_strategy:
216
+ stack.enter_context(handle.to_cpu())
217
+ # NOTE: Since PyTorch enforces that a parameter and its
218
+ # gradients need to match metadata (e.g. device), we must
219
+ # move gradients to CPU *after* we move parameters.
220
+ # NOTE: This assumes 1 `FlatParameter`
221
+ if not state._use_orig_params:
222
+ stack.enter_context(_unflatten_as_params(state, module))
223
+ try:
224
+ yield
225
+ finally:
226
+ stack.close()
227
+ if writeback:
228
+ _writeback_to_local_shard(handle, with_grads)
229
+ _reshard(state, handle, free_unsharded_flat_param)
230
+ if with_grads:
231
+ _reshard_grads(handle)
232
+ handle._training_state = HandleTrainingState.IDLE
233
+
234
+
235
+ @contextlib.contextmanager
236
+ def _unshard_params_for_summon(
237
+ module: nn.Module,
238
+ state: _FSDPState,
239
+ writeback: bool,
240
+ rank0_only: bool,
241
+ offload_to_cpu: bool,
242
+ with_grads: bool,
243
+ ):
244
+ _validate_unshard_params_args(
245
+ state, writeback, rank0_only, offload_to_cpu, with_grads
246
+ )
247
+ _lazy_init(state, module)
248
+ if state.training_state == TrainingState.FORWARD_BACKWARD:
249
+ raise AssertionError(
250
+ "Cannot manually unshard parameters during forward/backward"
251
+ )
252
+ elif state.training_state == TrainingState.SUMMON_FULL_PARAMS:
253
+ raise AssertionError(
254
+ "Cannot manually unshard parameters when already unsharding parameters"
255
+ )
256
+ with _unshard_fsdp_state_params(
257
+ module=module,
258
+ state=state,
259
+ writeback=writeback,
260
+ rank0_only=rank0_only,
261
+ offload_to_cpu=offload_to_cpu,
262
+ with_grads=with_grads,
263
+ ):
264
+ try:
265
+ state.training_state = TrainingState.SUMMON_FULL_PARAMS
266
+ yield
267
+ finally:
268
+ state.training_state = TrainingState.IDLE
269
+
270
+
271
+ @contextlib.contextmanager
272
+ def _unshard_params(
273
+ module: nn.Module,
274
+ recurse: bool,
275
+ writeback: bool,
276
+ rank0_only: bool,
277
+ offload_to_cpu: bool,
278
+ with_grads: bool,
279
+ ):
280
+ """
281
+ This unshards FSDP-managed parameters for all modules with FSDP applied in
282
+ the module tree rooted at ``module``.
283
+ """
284
+ if not recurse:
285
+ optional_state = _get_module_fsdp_state(module)
286
+ if optional_state is None:
287
+ with contextlib.nullcontext():
288
+ yield
289
+ return
290
+ states_and_modules = ([optional_state], [module])
291
+ else:
292
+ states_and_modules = traversal_utils._get_fsdp_states_with_modules(module)
293
+ with contextlib.ExitStack() as stack:
294
+ for state, module in zip(*states_and_modules):
295
+ stack.enter_context(
296
+ _unshard_params_for_summon(
297
+ module=module,
298
+ state=state,
299
+ writeback=writeback,
300
+ rank0_only=rank0_only,
301
+ offload_to_cpu=offload_to_cpu,
302
+ with_grads=with_grads,
303
+ )
304
+ )
305
+ yield
306
+
307
+
308
+ def _deregister_orig_params(state: _FSDPState, module: nn.Module) -> None:
309
+ """
310
+ Deregisters the original parameters; registers the ``FlatParameter``.
311
+ """
312
+ handle = _module_handle(state, module)
313
+ if not handle:
314
+ return
315
+ _p_assert(
316
+ handle._use_orig_params,
317
+ f"Inconsistent `_use_orig_params` -- FSDP: {state._use_orig_params} "
318
+ f"handle: {handle._use_orig_params}",
319
+ )
320
+ handle._deregister_orig_params()
321
+ _register_flat_param(state, module)
322
+
323
+
324
+ def _register_orig_params(state: _FSDPState, module: nn.Module) -> None:
325
+ """
326
+ Deregisters the ``FlatParameter``; registers the original parameters.
327
+ """
328
+ handle = _module_handle(state, module)
329
+ if not handle:
330
+ return
331
+ _deregister_flat_param(state, module)
332
+ if handle.is_sharded(handle.flat_param):
333
+ handle._use_sharded_views()
334
+ handle._use_sharded_grad_views()
335
+ else:
336
+ handle._use_unsharded_views(as_params=True)
vllm/lib/python3.10/site-packages/torch/distributed/fsdp/api.py ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This file includes public APIs for FSDP such as the classes used for the
3
+ constructor arguments.
4
+ """
5
+
6
+ from dataclasses import dataclass
7
+ from enum import auto, Enum
8
+ from typing import Optional, Sequence, Type
9
+
10
+ import torch
11
+ from torch.nn.modules.batchnorm import _BatchNorm
12
+
13
+
14
+ __all__ = [
15
+ "ShardingStrategy",
16
+ "BackwardPrefetch",
17
+ "MixedPrecision",
18
+ "CPUOffload",
19
+ "StateDictType",
20
+ "StateDictConfig",
21
+ "FullStateDictConfig",
22
+ "LocalStateDictConfig",
23
+ "ShardedStateDictConfig",
24
+ "OptimStateDictConfig",
25
+ "FullOptimStateDictConfig",
26
+ "LocalOptimStateDictConfig",
27
+ "ShardedOptimStateDictConfig",
28
+ "StateDictSettings",
29
+ ]
30
+
31
+
32
+ class ShardingStrategy(Enum):
33
+ """
34
+ This specifies the sharding strategy to be used for distributed training by
35
+ :class:`FullyShardedDataParallel`.
36
+
37
+ - ``FULL_SHARD``: Parameters, gradients, and optimizer states are sharded.
38
+ For the parameters, this strategy unshards (via all-gather) before the
39
+ forward, reshards after the forward, unshards before the backward
40
+ computation, and reshards after the backward computation. For gradients,
41
+ it synchronizes and shards them (via reduce-scatter) after the backward
42
+ computation. The sharded optimizer states are updated locally per rank.
43
+ - ``SHARD_GRAD_OP``: Gradients and optimizer states are sharded during
44
+ computation, and additionally, parameters are sharded outside
45
+ computation. For the parameters, this strategy unshards before the
46
+ forward, does not reshard them after the forward, and only reshards them
47
+ after the backward computation. The sharded optimizer states are updated
48
+ locally per rank. Inside ``no_sync()``, the parameters are not resharded
49
+ after the backward computation.
50
+ - ``NO_SHARD``: Parameters, gradients, and optimizer states are not sharded
51
+ but instead replicated across ranks similar to PyTorch's
52
+ :class:`DistributedDataParallel` API. For gradients, this strategy
53
+ synchronizes them (via all-reduce) after the backward computation. The
54
+ unsharded optimizer states are updated locally per rank.
55
+ - ``HYBRID_SHARD``: Apply ``FULL_SHARD`` within a node, and replicate parameters across
56
+ nodes. This results in reduced communication volume as expensive all-gathers and
57
+ reduce-scatters are only done within a node, which can be more performant for medium
58
+ -sized models.
59
+ - ``_HYBRID_SHARD_ZERO2``: Apply ``SHARD_GRAD_OP`` within a node, and replicate parameters across
60
+ nodes. This is like ``HYBRID_SHARD``, except this may provide even higher throughput
61
+ since the unsharded parameters are not freed after the forward pass, saving the
62
+ all-gathers in the pre-backward.
63
+ """
64
+
65
+ FULL_SHARD = auto()
66
+ SHARD_GRAD_OP = auto()
67
+ NO_SHARD = auto()
68
+ HYBRID_SHARD = auto()
69
+ _HYBRID_SHARD_ZERO2 = auto()
70
+
71
+
72
+ class BackwardPrefetch(Enum):
73
+ """
74
+ This configures explicit backward prefetching, which improves throughput by
75
+ enabling communication and computation overlap in the backward pass at the
76
+ cost of slightly increased memory usage.
77
+
78
+ - ``BACKWARD_PRE``: This enables the most overlap but increases memory
79
+ usage the most. This prefetches the next set of parameters *before* the
80
+ current set of parameters' gradient computation. This overlaps the *next
81
+ all-gather* and the *current gradient computation*, and at the peak, it
82
+ holds the current set of parameters, next set of parameters, and current
83
+ set of gradients in memory.
84
+ - ``BACKWARD_POST``: This enables less overlap but requires less memory
85
+ usage. This prefetches the next set of parameters *after* the current
86
+ set of parameters' gradient computation. This overlaps the *current
87
+ reduce-scatter* and the *next gradient computation*, and it frees the
88
+ current set of parameters before allocating memory for the next set of
89
+ parameters, only holding the next set of parameters and current set of
90
+ gradients in memory at the peak.
91
+ - FSDP's ``backward_prefetch`` argument accepts ``None``, which disables
92
+ the backward prefetching altogether. This has no overlap and does not
93
+ increase memory usage. In general, we do not recommend this setting since
94
+ it may degrade throughput significantly.
95
+
96
+ For more technical context: For a single process group using NCCL backend,
97
+ any collectives, even if issued from different streams, contend for the
98
+ same per-device NCCL stream, which implies that the relative order in which
99
+ the collectives are issued matters for overlapping. The two backward
100
+ prefetching values correspond to different issue orders.
101
+ """
102
+
103
+ # NOTE: For both modes, the ordering that defines "current" and "next" is
104
+ # not always exact in the current implementation. A mistargeted prefetch
105
+ # simply means that the parameter memory is allocated earlier than needed,
106
+ # possibly increasing peak memory usage, but does not affect correctness.
107
+ BACKWARD_PRE = auto()
108
+ BACKWARD_POST = auto()
109
+
110
+
111
+ @dataclass
112
+ class MixedPrecision:
113
+ """
114
+ This configures FSDP-native mixed precision training.
115
+
116
+ Attributes:
117
+ param_dtype (Optional[torch.dtype]): This specifies the dtype for model
118
+ parameters during forward and backward and thus the dtype for
119
+ forward and backward computation. Outside forward and backward, the
120
+ *sharded* parameters are kept in full precision (e.g. for the
121
+ optimizer step), and for model checkpointing, the parameters are
122
+ always saved in full precision. (Default: ``None``)
123
+ reduce_dtype (Optional[torch.dtype]): This specifies the dtype for
124
+ gradient reduction (i.e. reduce-scatter or all-reduce). If this is
125
+ ``None`` but ``param_dtype`` is not ``None``, then this takes on
126
+ the ``param_dtype`` value, still running gradient reduction in low
127
+ precision. This is permitted to differ from ``param_dtype``, e.g.
128
+ to force gradient reduction to run in full precision. (Default:
129
+ ``None``)
130
+ buffer_dtype (Optional[torch.dtype]): This specifies the dtype for
131
+ buffers. FSDP does not shard buffers. Rather, FSDP casts them to
132
+ ``buffer_dtype`` in the first forward pass and keeps them in that
133
+ dtype thereafter. For model checkpointing, the buffers are saved
134
+ in full precision except for ``LOCAL_STATE_DICT``. (Default:
135
+ ``None``)
136
+ keep_low_precision_grads (bool): If ``False``, then FSDP upcasts
137
+ gradients to full precision after the backward pass in preparation
138
+ for the optimizer step. If ``True``, then FSDP keeps the gradients
139
+ in the dtype used for gradient reduction, which can save memory if
140
+ using a custom optimizer that supports running in low precision.
141
+ (Default: ``False``)
142
+ cast_forward_inputs (bool): If ``True``, then this FSDP module casts
143
+ its forward args and kwargs to ``param_dtype``. This is to ensure
144
+ that parameter and input dtypes match for forward computation, as
145
+ required by many ops. This may need to be set to ``True`` when only
146
+ applying mixed precision to some but not all FSDP modules, in which
147
+ case a mixed-precision FSDP submodule needs to recast its inputs.
148
+ (Default: ``False``)
149
+ cast_root_forward_inputs (bool): If ``True``, then the root FSDP module
150
+ casts its forward args and kwargs to ``param_dtype``, overriding
151
+ the value of ``cast_forward_inputs``. For non-root FSDP modules,
152
+ this does not do anything. (Default: ``True``)
153
+ _module_classes_to_ignore: (Sequence[Type[nn.Module]]): This specifies
154
+ module classes to ignore for mixed precision when using an
155
+ ``auto_wrap_policy``: Modules of these classes will have FSDP
156
+ applied to them separately with mixed precision disabled (meaning
157
+ that the final FSDP construction would deviate from the specified
158
+ policy). If ``auto_wrap_policy`` is not specified, then this does
159
+ not do anything. This API is experimental and subject to change.
160
+ (Default: ``(_BatchNorm,)``)
161
+
162
+ .. note:: This API is experimental and subject to change.
163
+
164
+ .. note:: Only floating point tensors are cast to their specified dtypes.
165
+
166
+ .. note:: In ``summon_full_params``, parameters are forced to full
167
+ precision, but buffers are not.
168
+
169
+ .. note:: Layer norm and batch norm accumulate in ``float32`` even when
170
+ their inputs are in a low precision like ``float16`` or ``bfloat16``.
171
+ Disabling FSDP's mixed precision for those norm modules only means that
172
+ the affine parameters are kept in ``float32``. However, this incurs
173
+ separate all-gathers and reduce-scatters for those norm modules, which
174
+ may be inefficient, so if the workload permits, the user should prefer
175
+ to still apply mixed precision to those modules.
176
+
177
+ .. note:: By default, if the user passes a model with any ``_BatchNorm``
178
+ modules and specifies an ``auto_wrap_policy``, then the batch norm
179
+ modules will have FSDP applied to them separately with mixed precision
180
+ disabled. See the ``_module_classes_to_ignore`` argument.
181
+
182
+ .. note:: ``MixedPrecision`` has ``cast_root_forward_inputs=True`` and
183
+ ``cast_forward_inputs=False`` by default. For the root FSDP instance,
184
+ its ``cast_root_forward_inputs`` takes precedence over its
185
+ ``cast_forward_inputs``. For non-root FSDP instances, their
186
+ ``cast_root_forward_inputs`` values are ignored. The default setting is
187
+ sufficient for the typical case where each FSDP instance has the same
188
+ ``MixedPrecision`` configuration and only needs to cast inputs to the
189
+ ``param_dtype`` at the beginning of the model's forward pass.
190
+
191
+ .. note:: For nested FSDP instances with different ``MixedPrecision``
192
+ configurations, we recommend setting individual ``cast_forward_inputs``
193
+ values to configure casting inputs or not before each instance's
194
+ forward. In such a case, since the casts happen before each FSDP
195
+ instance's forward, a parent FSDP instance should have its non-FSDP
196
+ submodules run before its FSDP submodules to avoid the activation dtype
197
+ being changed due to a different ``MixedPrecision`` configuration.
198
+
199
+ Example::
200
+
201
+ >>> # xdoctest: +SKIP("undefined variables")
202
+ >>> model = nn.Sequential(nn.Linear(3, 3), nn.Linear(3, 3))
203
+ >>> model[1] = FSDP(
204
+ >>> model[1],
205
+ >>> mixed_precision=MixedPrecision(param_dtype=torch.float16, cast_forward_inputs=True),
206
+ >>> )
207
+ >>> model = FSDP(
208
+ >>> model,
209
+ >>> mixed_precision=MixedPrecision(param_dtype=torch.bfloat16, cast_forward_inputs=True),
210
+ >>> )
211
+
212
+ The above shows a working example. On the other hand, if ``model[1]``
213
+ were replaced with ``model[0]``, meaning that the submodule using
214
+ different ``MixedPrecision`` ran its forward first, then ``model[1]``
215
+ would incorrectly see ``float16`` activations instead of ``bfloat16``
216
+ ones.
217
+
218
+ """
219
+
220
+ param_dtype: Optional[torch.dtype] = None
221
+ reduce_dtype: Optional[torch.dtype] = None
222
+ buffer_dtype: Optional[torch.dtype] = None
223
+ keep_low_precision_grads: bool = False
224
+ cast_forward_inputs: bool = False
225
+ cast_root_forward_inputs: bool = True
226
+ _module_classes_to_ignore: Sequence[Type[torch.nn.Module]] = (_BatchNorm,)
227
+
228
+
229
+ @dataclass
230
+ class CPUOffload:
231
+ """
232
+ This configures CPU offloading.
233
+
234
+ Attributes:
235
+ offload_params (bool): This specifies whether to offload parameters to
236
+ CPU when not involved in computation. If ``True``, then this
237
+ offloads gradients to CPU as well, meaning that the optimizer step
238
+ runs on CPU.
239
+ """
240
+
241
+ offload_params: bool = False
242
+
243
+
244
+ class StateDictType(Enum):
245
+ """
246
+ This enum indicates that which type of ``state_dict`` the FSDP module is
247
+ currently processing (returning or loading).
248
+ The default value is FULL_STATE_DICT to comply the PyTorch convention.
249
+ ..note::
250
+ FSDP currently supports three types of ``state_dict``:
251
+ 1. ``state_dict/load_state_dict`: this pair of APIs return and load
252
+ the non-sharded, unflattened parameters. The semantics is the
253
+ same as using DDP.
254
+ 2. ``_local_state_dict/_load_local_state_dict``: this pair of APIs return
255
+ and load local sharded, flattened parameters. The values returned
256
+ by ``_local_state_dict`` can be directly used by FSDP and is only
257
+ meaningful to FSDP (because parameters are flattened). Note that
258
+ these APIs are meant for use via the :func:`state_dict_type`
259
+ context manager as follows:
260
+ >>> # xdoctest: +SKIP("undefined variables")
261
+ >>> with fsdp.state_dict_type(StateDictType.LOCAL_STATE_DICT):
262
+ ... state = fsdp.state_dict() # loads local state dict
263
+ 3. ``_sharded_state_dict/_load_sharded_state_dict``: this pair of APIs
264
+ return and load sharded, unflattened parameters. The ``state_dict``
265
+ return by ``sharded_state_dict`` can be used by all other parallel
266
+ schemes (resharding may be required).
267
+ """
268
+
269
+ FULL_STATE_DICT = auto()
270
+ LOCAL_STATE_DICT = auto()
271
+ SHARDED_STATE_DICT = auto()
272
+
273
+
274
+ @dataclass
275
+ class StateDictConfig:
276
+ """
277
+ ``StateDictConfig`` is the base class for all ``state_dict`` configuration
278
+ classes. Users should instantiate a child class (e.g.
279
+ ``FullStateDictConfig``) in order to configure settings for the
280
+ corresponding ``state_dict`` type supported by FSDP.
281
+
282
+ Attributes:
283
+ offload_to_cpu (bool): If ``True``, then FSDP offloads the state dict
284
+ values to CPU, and if ``False``, then FSDP keeps them on GPU.
285
+ (Default: ``False``)
286
+ """
287
+
288
+ offload_to_cpu: bool = False
289
+
290
+
291
+ @dataclass
292
+ class FullStateDictConfig(StateDictConfig):
293
+ """
294
+ ``FullStateDictConfig`` is a config class meant to be used with
295
+ ``StateDictType.FULL_STATE_DICT``. We recommend enabling both
296
+ ``offload_to_cpu=True`` and ``rank0_only=True`` when saving full state
297
+ dicts to save GPU memory and CPU memory, respectively. This config class
298
+ is meant to be used via the :func:`state_dict_type` context manager as
299
+ follows:
300
+
301
+ >>> # xdoctest: +SKIP("undefined variables")
302
+ >>> from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
303
+ >>> fsdp = FSDP(model, auto_wrap_policy=...)
304
+ >>> cfg = FullStateDictConfig(offload_to_cpu=True, rank0_only=True)
305
+ >>> with FSDP.state_dict_type(fsdp, StateDictType.FULL_STATE_DICT, cfg):
306
+ >>> state = fsdp.state_dict()
307
+ >>> # `state` will be empty on non rank 0 and contain CPU tensors on rank 0.
308
+ >>> # To reload checkpoint for inference, finetuning, transfer learning, etc:
309
+ >>> model = model_fn() # Initialize model in preparation for wrapping with FSDP
310
+ >>> if dist.get_rank() == 0:
311
+ >>> # Load checkpoint only on rank 0 to avoid memory redundancy
312
+ >>> state_dict = torch.load("my_checkpoint.pt")
313
+ >>> model.load_state_dict(state_dict)
314
+ >>> # All ranks initialize FSDP module as usual. `sync_module_states` argument
315
+ >>> # communicates loaded checkpoint states from rank 0 to rest of the world.
316
+ >>> fsdp = FSDP(model, device_id=torch.cuda.current_device(), auto_wrap_policy=..., sync_module_states=True)
317
+ >>> # After this point, all ranks have FSDP model with loaded checkpoint.
318
+
319
+ Attributes:
320
+ rank0_only (bool): If ``True``, then only rank 0 saves the full state
321
+ dict, and nonzero ranks save an empty dict. If ``False``, then all
322
+ ranks save the full state dict. (Default: ``False``)
323
+ """
324
+
325
+ rank0_only: bool = False
326
+
327
+
328
+ @dataclass
329
+ class LocalStateDictConfig(StateDictConfig):
330
+ pass
331
+
332
+
333
+ @dataclass
334
+ class ShardedStateDictConfig(StateDictConfig):
335
+ """
336
+ ``ShardedStateDictConfig`` is a config class meant to be used with
337
+ ``StateDictType.SHARDED_STATE_DICT``.
338
+
339
+ Attributes:
340
+ _use_dtensor (bool): If ``True``, then FSDP saves the state dict values
341
+ as ``DTensor``, and if ``False``, then FSDP saves them as
342
+ ``ShardedTensor``. (Default: ``False``)
343
+
344
+ .. warning:: ``_use_dtensor`` is a private field of :class:`ShardedStateDictConfig`
345
+ and it is used by FSDP to determine the type of state dict values. Users should not
346
+ manually modify ``_use_dtensor``.
347
+ """
348
+
349
+ _use_dtensor: bool = False
350
+
351
+
352
+ @dataclass
353
+ class OptimStateDictConfig:
354
+ """
355
+ ``OptimStateDictConfig`` is the base class for all ``optim_state_dict``
356
+ configuration classes. Users should instantiate a child class (e.g.
357
+ ``FullOptimStateDictConfig``) in order to configure settings for the
358
+ corresponding ``optim_state_dict`` type supported by FSDP.
359
+
360
+ Attributes:
361
+ offload_to_cpu (bool): If ``True``, then FSDP offloads the state dict's
362
+ tensor values to CPU, and if ``False``, then FSDP keeps them on the
363
+ original device (which is GPU unless parameter CPU offloading is
364
+ enabled). (Default: ``True``)
365
+ """
366
+
367
+ offload_to_cpu: bool = True
368
+
369
+
370
+ @dataclass
371
+ class FullOptimStateDictConfig(OptimStateDictConfig):
372
+ """
373
+ Attributes:
374
+ rank0_only (bool): If ``True``, then only rank 0 saves the full state
375
+ dict, and nonzero ranks save an empty dict. If ``False``, then all
376
+ ranks save the full state dict. (Default: ``False``)
377
+ """
378
+
379
+ rank0_only: bool = False
380
+
381
+
382
+ @dataclass
383
+ class LocalOptimStateDictConfig(OptimStateDictConfig):
384
+ offload_to_cpu: bool = False
385
+
386
+
387
+ @dataclass
388
+ class ShardedOptimStateDictConfig(OptimStateDictConfig):
389
+ """
390
+ ``ShardedOptimStateDictConfig`` is a config class meant to be used with
391
+ ``StateDictType.SHARDED_STATE_DICT``.
392
+
393
+ Attributes:
394
+ _use_dtensor (bool): If ``True``, then FSDP saves the state dict values
395
+ as ``DTensor``, and if ``False``, then FSDP saves them as
396
+ ``ShardedTensor``. (Default: ``False``)
397
+
398
+ .. warning:: ``_use_dtensor`` is a private field of :class:`ShardedOptimStateDictConfig`
399
+ and it is used by FSDP to determine the type of state dict values. Users should not
400
+ manually modify ``_use_dtensor``.
401
+ """
402
+
403
+ _use_dtensor: bool = False
404
+
405
+
406
+ @dataclass
407
+ class StateDictSettings:
408
+ state_dict_type: StateDictType
409
+ state_dict_config: StateDictConfig
410
+ optim_state_dict_config: OptimStateDictConfig
vllm/lib/python3.10/site-packages/torch/distributed/fsdp/fully_sharded_data_parallel.py ADDED
The diff for this file is too large to render. See raw diff
 
vllm/lib/python3.10/site-packages/torch/distributed/fsdp/sharded_grad_scaler.py ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import logging
3
+ from collections import abc, defaultdict
4
+ from typing import Any, Dict, Iterable, List, Optional, overload, Sequence, Tuple, Union
5
+
6
+ import torch
7
+ import torch.distributed as dist
8
+ from torch.amp.grad_scaler import _MultiDeviceReplicator, GradScaler, OptState
9
+ from torch.distributed.distributed_c10d import ProcessGroup
10
+
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ def _refresh_per_optimizer_state() -> Dict[str, Any]:
16
+ return {"stage": OptState.READY, "found_inf_per_device": {}}
17
+
18
+
19
+ def _is_supported_device(tensor: torch.Tensor) -> bool:
20
+ return tensor.is_cuda or tensor.device.type in (
21
+ "xla",
22
+ "cpu",
23
+ "hpu",
24
+ "mtia",
25
+ torch._C._get_privateuse1_backend_name(),
26
+ )
27
+
28
+
29
+ class _GeneralMultiDeviceReplicator(_MultiDeviceReplicator):
30
+ """
31
+ Lazily serves tensor to request device. This class extends
32
+ _MultiDeviceReplicator to allow support for "cpu" as a device.
33
+ """
34
+
35
+ def __init__(self, master_tensor: torch.Tensor) -> None:
36
+ assert _is_supported_device(master_tensor)
37
+ self.master = master_tensor
38
+ self._per_device_tensors: Dict[torch.device, torch.Tensor] = {}
39
+
40
+
41
+ class ShardedGradScaler(GradScaler):
42
+ """
43
+ ShardedGradScaler helps perform gradient scaling in a shard aware manner. It extends
44
+ functionality from GradScaler:
45
+ * Supports Pytorch DDP and FSDP implementations
46
+ * Support CPU offloaded tensors (as used in fully sharded data parallel[FSDP])
47
+ * Supports the custom Mixed Precision loss dtype (fp16, bf16) that FSDP returns
48
+ * Sync inf/nan for scaled gradient tensors on any torch.device (where tensors are placed) across
49
+ nodes
50
+
51
+ Example::
52
+
53
+ # Creates a ShardedGradScaler once at the beginning of training.
54
+ scaler = ShardedGradScaler()
55
+
56
+ for epoch in epochs:
57
+ for input, target in data:
58
+ optimizer.zero_grad()
59
+ output = model(input)
60
+ loss = loss_fn(output, target)
61
+
62
+ # Scales loss. Calls backward() on scaled loss to create scaled gradients.
63
+ scaler.scale(loss).backward()
64
+
65
+ # scaler.step() first unscales gradients of the optimizer's params.
66
+ # If gradients don't contain infs/NaNs, optimizer.step() is then called,
67
+ # otherwise, optimizer.step() is skipped.
68
+ scaler.step(optimizer)
69
+
70
+ # Updates the scale for next iteration.
71
+ scaler.update()
72
+
73
+ See :class:`GradScaler` for explanation of scaling/unscaling and more use cases.
74
+
75
+ Args:
76
+ init_scale (float, optional, default=2.**16): Initial scale factor.
77
+ growth_factor (float, optional, default=2.0): Factor by which the scale is multiplied during
78
+ :meth:`update` if no inf/NaN gradients occur for ``growth_interval`` consecutive iterations.
79
+ backoff_factor (float, optional, default=0.5): Factor by which the scale is multiplied during
80
+ :meth:`update` if inf/NaN gradients occur in an iteration.
81
+ growth_interval (int, optional, default=2000): Number of consecutive iterations without inf/NaN gradients
82
+ that must occur for the scale to be multiplied by ``growth_factor``.
83
+ enabled (bool, optional): If ``False``, disables gradient scaling. :meth:`step` simply
84
+ invokes the underlying ``optimizer.step()``, and other methods become no-ops.
85
+ Default: ``True``
86
+ process_group (ProcessGroup, optional, default=torch.distributed.group.WORLD):
87
+ process group for sharding
88
+ """
89
+
90
+ def __init__(
91
+ self,
92
+ device: str = "cuda",
93
+ init_scale: float = 2.0**16,
94
+ backoff_factor: float = 0.5,
95
+ growth_factor: float = 2.0,
96
+ growth_interval: int = 2000,
97
+ enabled: bool = True,
98
+ process_group: Optional[ProcessGroup] = dist.group.WORLD,
99
+ ) -> None:
100
+ super().__init__(
101
+ device,
102
+ init_scale=init_scale,
103
+ backoff_factor=backoff_factor,
104
+ growth_factor=growth_factor,
105
+ growth_interval=growth_interval,
106
+ enabled=enabled,
107
+ )
108
+ if self._enabled:
109
+ self.process_group = process_group
110
+ self._per_optimizer_states = defaultdict(_refresh_per_optimizer_state)
111
+
112
+ @overload
113
+ def scale(self, outputs: torch.Tensor) -> torch.Tensor:
114
+ ...
115
+
116
+ @overload
117
+ def scale(self, outputs: List[torch.Tensor]) -> List[torch.Tensor]:
118
+ ...
119
+
120
+ @overload
121
+ def scale(self, outputs: Tuple[torch.Tensor, ...]) -> Tuple[torch.Tensor, ...]:
122
+ ...
123
+
124
+ @overload
125
+ def scale(self, outputs: Iterable[torch.Tensor]) -> Iterable[torch.Tensor]:
126
+ ...
127
+
128
+ def scale(
129
+ self, outputs: Union[torch.Tensor, Iterable[torch.Tensor]]
130
+ ) -> Union[torch.Tensor, Iterable[torch.Tensor]]:
131
+ if not self._enabled:
132
+ return outputs
133
+
134
+ if isinstance(outputs, torch.Tensor):
135
+ assert _is_supported_device(outputs)
136
+ if self._scale is None:
137
+ self._lazy_init_scale_growth_tracker(outputs.device)
138
+ assert self._scale is not None
139
+ scaled_output = outputs * self._scale.to(
140
+ device=outputs.device, non_blocking=True
141
+ )
142
+ # Here we ensure the return dtype is the same as the outputs dtype.
143
+ # For the FSDP + Mixed Precision use case, the loss output is in the Mixed Precision
144
+ # format (fp16, bf16) and so the scaled loss should be of the same dtype.
145
+ return scaled_output.type(outputs.dtype)
146
+
147
+ stash: List[_GeneralMultiDeviceReplicator] = []
148
+
149
+ def apply_scale(val: Union[torch.Tensor, Iterable[torch.Tensor]]):
150
+ if isinstance(val, torch.Tensor):
151
+ assert _is_supported_device(val)
152
+ if len(stash) == 0:
153
+ if self._scale is None:
154
+ self._lazy_init_scale_growth_tracker(val.device)
155
+ assert self._scale is not None
156
+ stash.append(_GeneralMultiDeviceReplicator(self._scale))
157
+ scaled_val = val * stash[0].get(val.device)
158
+ # Here we ensure the return dtype is the same as the outputs dtype.
159
+ # For the FSDP + Mixed Precision use case, the loss output is in the Mixed Precision
160
+ # format (fp16, bf16) and so the scaled loss should be of the same dtype.
161
+ return scaled_val.type(val.dtype)
162
+ if isinstance(val, abc.Iterable):
163
+ iterator = map(apply_scale, val)
164
+ if isinstance(val, (list, tuple)):
165
+ return type(val)(iterator)
166
+ return iterator
167
+ raise ValueError("outputs must be a Tensor or an iterable of Tensors")
168
+
169
+ return apply_scale(outputs)
170
+
171
+ def _foreach_non_finite_check_and_unscale_cpu_(
172
+ self,
173
+ grads: Sequence[torch.Tensor],
174
+ found_inf: torch.Tensor,
175
+ inv_scale: torch.Tensor,
176
+ ) -> None:
177
+ if len(grads) == 0:
178
+ return
179
+ assert inv_scale.numel() == 1, "inv_scale must be a 1-element tensor."
180
+ assert found_inf.numel() == 1, "found_inf must be a 1-element tensor."
181
+
182
+ for grad in grads:
183
+ if grad.device.type != "cpu":
184
+ logger.error(
185
+ "tensor device is %s but was expected to be ``cpu``",
186
+ grad.device,
187
+ )
188
+ raise ValueError(
189
+ "Gradients were found on a non-CPU device when"
190
+ " expected to be on CPU."
191
+ )
192
+ if (
193
+ torch.isinf(grad).any().item() is True
194
+ or torch.isnan(grad).any().item() is True
195
+ ):
196
+ found_inf.data = torch.tensor([1.0])
197
+ break
198
+ else:
199
+ grad.data *= inv_scale.item()
200
+
201
+ def _unscale_grads_(
202
+ self,
203
+ optimizer: torch.optim.Optimizer,
204
+ inv_scale: torch.Tensor,
205
+ found_inf: torch.Tensor,
206
+ allow_fp16: bool = True,
207
+ ) -> Dict[torch.device, torch.Tensor]:
208
+ per_device_inv_scale = _GeneralMultiDeviceReplicator(inv_scale)
209
+ per_device_found_inf = _GeneralMultiDeviceReplicator(found_inf)
210
+
211
+ # To set up _amp_foreach_non_finite_check_and_unscale_, split grads by device and dtype.
212
+ # There could be thousands of grads, so we'd like to iterate through them just once.
213
+ # However, we don't know their devices or dtypes in advance.
214
+
215
+ # https://stackoverflow.com/questions/5029934/defaultdict-of-defaultdict
216
+ # Google says mypy struggles with defaultdicts type annotations.
217
+ per_device_and_dtype_grads = defaultdict(lambda: defaultdict(list)) # type: ignore[var-annotated]
218
+ with torch.no_grad():
219
+ for group in optimizer.param_groups:
220
+ for param in group["params"]:
221
+ if param.grad is None:
222
+ continue
223
+ if (not allow_fp16) and param.grad.dtype == torch.float16:
224
+ raise ValueError("Attempting to unscale FP16 gradients.")
225
+ if param.grad.is_sparse:
226
+ # is_coalesced() == False means the sparse grad has values with duplicate indices.
227
+ # coalesce() deduplicates indices and adds all values that have the same index.
228
+ # For scaled fp16 values, there's a good chance coalescing will cause overflow,
229
+ # so we should check the coalesced _values().
230
+ if param.grad.dtype is torch.float16:
231
+ # coalesce is not supported in torch.float16
232
+ param_grad_fp32 = param.grad.type(torch.float32).coalesce()
233
+ param.grad = param_grad_fp32.type(torch.float16)
234
+ to_unscale = param.grad._values()
235
+ else:
236
+ to_unscale = param.grad
237
+
238
+ per_device_and_dtype_grads[to_unscale.device][
239
+ to_unscale.dtype
240
+ ].append(to_unscale)
241
+
242
+ for device, per_dtype_grads in per_device_and_dtype_grads.items():
243
+ for grads in per_dtype_grads.values():
244
+ if grads[0].device.type == "cpu":
245
+ self._foreach_non_finite_check_and_unscale_cpu_(
246
+ grads,
247
+ per_device_found_inf.get(device),
248
+ per_device_inv_scale.get(device),
249
+ )
250
+ else:
251
+ torch._amp_foreach_non_finite_check_and_unscale_(
252
+ grads,
253
+ per_device_found_inf.get(device),
254
+ per_device_inv_scale.get(device),
255
+ )
256
+ # There exist contexts (e.g. w/ `use_orig_params=True`) wherein some
257
+ # ranks may have no (non-zero sized) parameter shards, necessitating the
258
+ # initialization of `per_device_found_inf._per_device_tensors` here
259
+ if not per_device_found_inf._per_device_tensors:
260
+ assert self._scale is not None
261
+ per_device_found_inf.get(self._scale.device)
262
+ return per_device_found_inf._per_device_tensors
263
+
264
+ def unscale_(self, optimizer: torch.optim.Optimizer) -> None:
265
+ if not self._enabled:
266
+ return
267
+
268
+ self._check_scale_growth_tracker("unscale_")
269
+
270
+ optimizer_state = self._per_optimizer_states[id(optimizer)]
271
+
272
+ if optimizer_state["stage"] is OptState.UNSCALED:
273
+ raise RuntimeError(
274
+ "unscale_() has already been called on this optimizer since the last update()."
275
+ )
276
+ elif optimizer_state["stage"] is OptState.STEPPED:
277
+ raise RuntimeError("unscale_() is being called after step().")
278
+
279
+ # FP32 division can be imprecise for certain compile options, so we carry out the reciprocal in FP64.
280
+ assert self._scale is not None
281
+ inv_scale = self._scale.double().reciprocal().float()
282
+ found_inf = torch.full(
283
+ (1,), 0.0, dtype=torch.float32, device=self._scale.device
284
+ )
285
+
286
+ optimizer_state["found_inf_per_device"] = self._unscale_grads_(
287
+ optimizer, inv_scale, found_inf, True
288
+ )
289
+ optimizer_state["stage"] = OptState.UNSCALED
290
+
291
+ # Synchronize the detected inf across the ranks
292
+ optimizer_state = self._per_optimizer_states[id(optimizer)]
293
+ works = []
294
+ found_inf_on_cpus = []
295
+ found_inf_on_devices = []
296
+
297
+ for found_inf in optimizer_state["found_inf_per_device"].values():
298
+ if self._device != "cpu" and found_inf.device.type == "cpu":
299
+ found_inf_on_cpus.append(found_inf)
300
+ found_inf_on_device = found_inf.to(self._device)
301
+ found_inf_on_devices.append(found_inf_on_device)
302
+ works.append(
303
+ dist.all_reduce(
304
+ found_inf_on_device, async_op=True, group=self.process_group
305
+ )
306
+ )
307
+ else:
308
+ works.append(
309
+ dist.all_reduce(found_inf, async_op=True, group=self.process_group)
310
+ )
311
+ for work in works:
312
+ work.wait()
313
+ if found_inf_on_cpus:
314
+ torch._foreach_copy_(found_inf_on_cpus, found_inf_on_devices)
315
+
316
+ def _amp_update_scale_cpu_(self, found_inf: torch.Tensor) -> None:
317
+ """
318
+ If found_inf is 1.0 (True), then scale is multiplied by backoff_factor and growth_tracker is set to zero.
319
+ Otherwise, scale is multiplied by the growth factor when the growth interval is reached.
320
+ """
321
+ assert self._scale is not None and self._growth_tracker is not None
322
+
323
+ if found_inf.item() >= 1.0:
324
+ self._scale *= self._backoff_factor
325
+ self._growth_tracker.fill_(0)
326
+ else:
327
+ successful = self._growth_tracker + 1
328
+ if successful == self._growth_interval:
329
+ self._scale *= self._growth_factor
330
+ self._growth_tracker.fill_(0)
331
+ else:
332
+ self._growth_tracker = successful
333
+
334
+ def update(self, new_scale: Optional[Union[float, torch.Tensor]] = None) -> None:
335
+ """
336
+ Updates the scale factor.
337
+ If any optimizer steps were skipped the scale is multiplied by ``backoff_factor``
338
+ to reduce it. If ``growth_interval`` unskipped iterations occurred consecutively,
339
+ the scale is multiplied by ``growth_factor`` to increase it.
340
+ Passing ``new_scale`` sets the new scale value manually. (``new_scale`` is not
341
+ used directly, it's used to fill GradScaler's internal scale tensor. So if
342
+ ``new_scale`` was a tensor, later in-place changes to that tensor will not further
343
+ affect the scale GradScaler uses internally.)
344
+ Args:
345
+ new_scale (float or :class:`torch.Tensor`, optional, default=None): New scale factor.
346
+ .. warning::
347
+ :meth:`update` should only be called at the end of the iteration, after ``scaler.step(optimizer)`` has
348
+ been invoked for all optimizers used this iteration.
349
+ """
350
+
351
+ if not self._enabled:
352
+ return
353
+
354
+ _scale, _growth_tracker = self._check_scale_growth_tracker("update") # type: ignore[var-annotated]
355
+
356
+ if new_scale is not None:
357
+ # Accept a new user-defined scale.
358
+ if isinstance(new_scale, float):
359
+ self._scale.fill_(new_scale) # type: ignore[union-attr]
360
+ else:
361
+ reason = "new_scale should be a float or a 1-element torch.cuda.FloatTensor or \
362
+ torch.FloatTensor with requires_grad=False."
363
+ assert new_scale.device.type == self._device, reason
364
+ assert new_scale.numel() == 1, reason
365
+ assert new_scale.requires_grad is False, reason
366
+ self._scale.copy_(new_scale) # type: ignore[union-attr]
367
+ else:
368
+ # Consume shared inf/nan data collected from optimizers to update the scale.
369
+ # If all found_inf tensors are on the same device as self._scale, this operation is asynchronous.
370
+ found_infs = [
371
+ found_inf.to(device=_scale.device, non_blocking=True)
372
+ for state in self._per_optimizer_states.values()
373
+ for found_inf in state["found_inf_per_device"].values()
374
+ ]
375
+
376
+ assert len(found_infs) > 0, "No inf checks were recorded prior to update."
377
+
378
+ found_inf_combined = found_infs[0]
379
+ if len(found_infs) > 1:
380
+ for i in range(1, len(found_infs)):
381
+ found_inf_combined += found_infs[i]
382
+
383
+ if _scale.device.type == "cpu":
384
+ self._amp_update_scale_cpu_(found_inf_combined)
385
+ else:
386
+ torch._amp_update_scale_(
387
+ self._scale, # type: ignore[arg-type]
388
+ self._growth_tracker, # type: ignore[arg-type]
389
+ found_inf_combined,
390
+ self._growth_factor, # type: ignore[arg-type]
391
+ self._backoff_factor, # type: ignore[arg-type]
392
+ self._growth_interval, # type: ignore[arg-type]
393
+ )
394
+
395
+ # To prepare for next iteration, clear the data collected from optimizers this iteration.
396
+ self._per_optimizer_states = defaultdict(_refresh_per_optimizer_state)
vllm/lib/python3.10/site-packages/torch/distributed/fsdp/wrap.py ADDED
@@ -0,0 +1,608 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # Copyright (c) Facebook, Inc. and its affiliates.
3
+ #
4
+ # This source code is licensed under the BSD license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import contextlib
8
+ import copy
9
+ from abc import ABC, abstractmethod
10
+ from typing import (
11
+ Any,
12
+ Callable,
13
+ cast,
14
+ Dict,
15
+ Generator,
16
+ Iterable,
17
+ Optional,
18
+ Sequence,
19
+ Set,
20
+ Tuple,
21
+ Type,
22
+ Union,
23
+ )
24
+
25
+ import torch.nn as nn
26
+
27
+
28
+ __all__ = [
29
+ "always_wrap_policy",
30
+ "lambda_auto_wrap_policy",
31
+ "transformer_auto_wrap_policy",
32
+ "size_based_auto_wrap_policy",
33
+ "enable_wrap",
34
+ "wrap",
35
+ "CustomPolicy",
36
+ "ModuleWrapPolicy",
37
+ ]
38
+
39
+
40
+ # NOTE: We intentionally keep this function simple and isolate the complexity
41
+ # to `fn` to enable using this function generically. We may move this to a
42
+ # non-FSDP-specific folder and/or make it public in the future.
43
+ def _post_order_apply(
44
+ root_module: nn.Module,
45
+ fn: Callable[[nn.Module], Optional[nn.Module]],
46
+ ):
47
+ """
48
+ This applies ``fn`` to every module in the module tree of ``root_module``
49
+ following a post-order traversal. If ``fn`` returns an :class:`nn.Module`,
50
+ then this replaces the original module with the newly returned one in the
51
+ tree. Otherwise, ``fn`` should return ``None``, in which case the module is
52
+ not changed.
53
+ """
54
+ # Track visited modules to avoid visiting shared modules multiple times
55
+ visited_modules: Set[nn.Module] = {root_module}
56
+
57
+ def _post_order_apply_inner(
58
+ module: nn.Module,
59
+ module_name: str,
60
+ parent_module: Optional[nn.Module],
61
+ ):
62
+ for child_module_name, child_module in module.named_children():
63
+ if child_module not in visited_modules:
64
+ visited_modules.add(child_module)
65
+ _post_order_apply_inner(child_module, child_module_name, module)
66
+ optional_module = fn(module)
67
+ if optional_module is not None:
68
+ assert isinstance(parent_module, nn.Module), (
69
+ "Non-root modules should have their parent module set but got "
70
+ f"{parent_module} for {module}"
71
+ )
72
+ assert module_name, (
73
+ "Non-root modules should have their module name set but got "
74
+ f"an empty module name for {module}"
75
+ )
76
+ assert isinstance(
77
+ optional_module, nn.Module
78
+ ), f"fn should return None or an nn.Module but got {optional_module}"
79
+ setattr(parent_module, module_name, optional_module)
80
+
81
+ _post_order_apply_inner(root_module, "", None)
82
+
83
+
84
+ def _construct_wrap_fn(
85
+ root_module: nn.Module,
86
+ target_module_to_kwargs: Dict[nn.Module, Dict[str, Any]],
87
+ fsdp_fn: Callable,
88
+ ) -> Callable[[nn.Module], Optional[nn.Module]]:
89
+ """
90
+ This constructs the "wrap" function to pass to :func:`_post_order_apply`
91
+ based on ``target_module_to_kwargs``, which should be constructed from the
92
+ wrapping policy.
93
+ """
94
+
95
+ def fn(module: nn.Module) -> Optional[nn.Module]:
96
+ # Explicitly avoid wrapping the root module since for FSDP, it is
97
+ # handled by the caller
98
+ if module in target_module_to_kwargs and module is not root_module:
99
+ kwargs = target_module_to_kwargs[module]
100
+ return fsdp_fn(module, **kwargs)
101
+ return None
102
+
103
+ return fn
104
+
105
+
106
+ def _run_mixed_precision_override_policy(
107
+ root_module: nn.Module,
108
+ module_classes: Iterable[Type[nn.Module]],
109
+ ignored_modules: Set[nn.Module],
110
+ root_kwargs: Dict[str, Any],
111
+ target_module_to_kwargs: Dict[nn.Module, Dict[str, Any]],
112
+ ):
113
+ module_classes_tuple = tuple(set(module_classes))
114
+ for module in root_module.modules():
115
+ if module in ignored_modules:
116
+ continue
117
+ elif isinstance(module, module_classes_tuple):
118
+ # This policy overrides any existing policy
119
+ if module not in target_module_to_kwargs:
120
+ # Only inherit from the root kwargs if not already specified
121
+ target_module_to_kwargs[module] = root_kwargs
122
+ target_module_to_kwargs[module]["mixed_precision"] = None
123
+ return target_module_to_kwargs
124
+
125
+
126
+ def always_wrap_policy(*args, **kwargs) -> bool:
127
+ """
128
+ A simple recursive wrap policy that always returns ``True``. This means
129
+ that every submodule is wrapped by the wrapper class in
130
+ :func:`_recursive_wrap`.
131
+ """
132
+ return True
133
+
134
+
135
+ class _Policy(ABC):
136
+ """
137
+ This defines an abstract base class that represents a policy for applying
138
+ a module-level API.
139
+ """
140
+
141
+ @abstractmethod
142
+ def _run_policy(
143
+ self,
144
+ root_module: nn.Module,
145
+ ignored_modules: Set[nn.Module],
146
+ root_kwargs: Dict[str, Any],
147
+ ) -> Dict[nn.Module, Dict[str, Any]]:
148
+ """
149
+ This should return a dict ``target_module_to_kwargs`` that maps from
150
+ each target module to wrap to its kwargs.
151
+ """
152
+ ...
153
+
154
+
155
+ def _module_wrap_policy(
156
+ module: nn.Module,
157
+ recurse: bool,
158
+ nonwrapped_numel: int,
159
+ module_classes: Set[Type[nn.Module]],
160
+ ) -> bool:
161
+ """
162
+ This auto wrap policy wraps every module that is an instance of any type in
163
+ ``module_classes`` as its own FSDP instance. The root module given by
164
+ ``module`` is always wrapped as an FSDP instance regardless. Since the
165
+ wrapping proceeds bottom up, each FSDP instance manages the parameters in
166
+ its subtree excluding any already managed by a child FSDP instance.
167
+
168
+ Args:
169
+ module (nn.Module): Current module being considered.
170
+ recurse (bool): If ``False``, then this function must decide whether
171
+ ``module`` should be wrapped as an FSDP instance or not. If
172
+ ``True``, then the function is still recursing down the module
173
+ tree as a part of the DFS.
174
+ nonwrapped_numel (int): Parameter numel not yet wrapped.
175
+ module_classes (Set[Type[nn.Module]]): Set of module classes that are
176
+ wrapped as FSDP instances.
177
+
178
+ Returns:
179
+ ``True`` if ``recurse=True``, and whether ``module`` should be wrapped
180
+ if ``recurse=False``.
181
+ """
182
+ if recurse:
183
+ return True # always recurse
184
+ return isinstance(module, tuple(module_classes))
185
+
186
+
187
+ class ModuleWrapPolicy(_Policy):
188
+ """
189
+ This policy applies to every module of the specified module classes,
190
+ passing in the kwargs given to the root.
191
+ """
192
+
193
+ def __init__(self, module_classes: Iterable[Type[nn.Module]]):
194
+ module_classes_set = set(module_classes)
195
+ self._module_classes = module_classes_set
196
+ self._module_classes_str = str(module_classes_set)
197
+
198
+ def _run_policy(
199
+ self,
200
+ root_module: nn.Module,
201
+ ignored_modules: Set[nn.Module],
202
+ root_kwargs: Dict[str, Any],
203
+ ) -> Dict[nn.Module, Dict[str, Any]]:
204
+ module_classes = tuple(self._module_classes)
205
+ target_module_to_kwargs: Dict[nn.Module, Dict[str, Any]] = {}
206
+ for module in root_module.modules():
207
+ if module in ignored_modules:
208
+ continue
209
+ elif isinstance(module, module_classes):
210
+ # Shallow copy to avoid coupling changes across modules
211
+ target_module_to_kwargs[module] = copy.copy(root_kwargs)
212
+ return target_module_to_kwargs
213
+
214
+ def __call__(self, module, recurse, *args, **kwargs):
215
+ # nonwrapped_numel is not used.
216
+ return _module_wrap_policy(
217
+ module, recurse, nonwrapped_numel=-1, module_classes=self._module_classes
218
+ )
219
+
220
+ def __repr__(self) -> str:
221
+ return super().__repr__() + f"({self._module_classes_str})"
222
+
223
+
224
+ class CustomPolicy(_Policy):
225
+ """
226
+ This policy takes in a lambda function that maps a given ``nn.Module`` to
227
+ either ``False``, ``True``, or a kwarg dictionary.
228
+ - If the function returns ``False`` or an empty dictionary, then the module
229
+ does not have the API applied.
230
+ - If the function returns ``True``, then the module has the API applied
231
+ with the root's kwargs.
232
+ - If the function returns a non-empty dictionary, then the module has the
233
+ API applied, and the dictionary overrides the root's kwargs.
234
+
235
+ Example::
236
+
237
+ >>> # xdoctest: +SKIP("undefined variables")
238
+ >>> model = init_transformer_model(...)
239
+ >>> def lambda_fn(module: nn.Module):
240
+ >>> if module is model.lm_head:
241
+ >>> return {"sharding_strategy": ShardingStrategy.SHARD_GRAD_OP}
242
+ >>> elif isinstance(module, TransformerBlock):
243
+ >>> return True
244
+ >>> return False
245
+ >>> policy = CustomPolicy(lambda_fn)
246
+ >>> fsdp_model = FSDP(model, auto_wrap_policy=policy)
247
+ """
248
+
249
+ def __init__(self, lambda_fn: Callable[[nn.Module], Union[bool, Dict[str, Any]]]):
250
+ self._lambda_fn = lambda_fn
251
+
252
+ def _run_policy(
253
+ self,
254
+ root_module: nn.Module,
255
+ ignored_modules: Set[nn.Module],
256
+ root_kwargs: Dict[str, Any],
257
+ ) -> Dict[nn.Module, Dict[str, Any]]:
258
+ target_module_to_kwargs: Dict[nn.Module, Dict[str, Any]] = {}
259
+ for module in root_module.modules():
260
+ if module in ignored_modules:
261
+ continue
262
+ res = self._lambda_fn(module)
263
+ if not isinstance(res, (dict, bool)):
264
+ raise ValueError(
265
+ "The lambda_fn passed to CustomPolicy should return "
266
+ f"False/True or a kwarg dict, but it returned {res}"
267
+ )
268
+ if not res:
269
+ continue
270
+ kwargs = copy.copy(root_kwargs)
271
+ if isinstance(res, dict):
272
+ # Override the root kwargs with the ones specified by the
273
+ # lambda function
274
+ kwargs.update(res)
275
+ target_module_to_kwargs[module] = kwargs
276
+ return target_module_to_kwargs
277
+
278
+
279
+ def lambda_auto_wrap_policy(
280
+ module: nn.Module, recurse: bool, nonwrapped_numel: int, lambda_fn: Callable
281
+ ) -> bool:
282
+ """
283
+ A convenient auto wrap policy to wrap submodules based on an arbitrary user
284
+ function. If `lambda_fn(submodule) == True``, the submodule will be wrapped as
285
+ a `wrapper_cls` unit.
286
+
287
+ Return if a module should be wrapped during auto wrapping.
288
+
289
+ The first three parameters are required by :func:`_recursive_wrap`.
290
+
291
+ Args:
292
+ module (nn.Module): Current module being considered.
293
+ recurse (bool): If ``False``, then this function must decide whether
294
+ ``module`` should be wrapped as an FSDP instance or not. If
295
+ ``True``, then the function is still recursing down the module
296
+ tree as a part of the DFS.
297
+ nonwrapped_numel (int): Parameter numel not yet wrapped.
298
+
299
+ lambda_fn (Callable[[nn.Module], bool]): If this returns ``True``, then
300
+ this module will be wrapped.
301
+ """
302
+ if recurse:
303
+ return True # always recurse
304
+ return lambda_fn(module)
305
+
306
+
307
+ def transformer_auto_wrap_policy(
308
+ module: nn.Module,
309
+ recurse: bool,
310
+ nonwrapped_numel: int,
311
+ transformer_layer_cls: Set[Type[nn.Module]],
312
+ ) -> bool:
313
+ """
314
+ See :func:`_module_wrap_policy`, where ``transformer_layer_cls`` is the
315
+ same as ``module_classes``. Note that shared parameters must be wrapped in
316
+ the same FSDP instance, so this auto wrap policy can help wrap shared
317
+ embeddings into the same FSDP instance for transformer models.
318
+ """
319
+ return _module_wrap_policy(module, recurse, nonwrapped_numel, transformer_layer_cls)
320
+
321
+
322
+ def _wrap_module_cls_individually(
323
+ module: nn.Module, module_classes: Sequence[type], recurse: bool, *args, **kwargs
324
+ ):
325
+ if recurse:
326
+ # always recurse
327
+ return True
328
+ else:
329
+ # if not recursing, decide whether we should wrap based on whether the type of module
330
+ # is in `module_classes`.
331
+ return isinstance(module, tuple(module_classes))
332
+
333
+
334
+ def _or_policy(
335
+ module: nn.Module,
336
+ recurse: bool,
337
+ nonwrapped_numel: int,
338
+ policies,
339
+ ) -> bool:
340
+ """
341
+ A policy that wraps ``module`` if any policy in the passed in iterable of
342
+ ``policies`` returns ``True``.
343
+ """
344
+ return any(
345
+ policy(module=module, recurse=recurse, nonwrapped_numel=nonwrapped_numel)
346
+ for policy in policies
347
+ )
348
+
349
+
350
+ def size_based_auto_wrap_policy(
351
+ module: nn.Module,
352
+ recurse: bool,
353
+ nonwrapped_numel: int,
354
+ # Additional custom arguments
355
+ min_num_params: int = int(1e8),
356
+ force_leaf_modules: Optional[Set[Type[nn.Module]]] = None,
357
+ exclude_wrap_modules: Optional[Set[Type[nn.Module]]] = None,
358
+ ) -> bool:
359
+ """
360
+ A size-based auto wrap policy.
361
+
362
+ Args:
363
+ module (nn.Module): Current module being considered.
364
+ recurse (bool): If ``False``, then this function must decide whether
365
+ ``module`` should be wrapped as an FSDP instance or not. If
366
+ ``True``, then the function is still recursing down the module
367
+ tree as a part of the DFS.
368
+ nonwrapped_numel (int): Parameter numel not yet wrapped.
369
+
370
+ min_num_params (int): Customizable policy input that controls the size
371
+ threshold over which a module is ready to be wrapped. This is in
372
+ units of numel.
373
+ force_leaf_modules (Set[Type[nn.Module]]): Set of module types to keep
374
+ as leaves, i.e. their children will never be wrapped.
375
+ exclude_wrap_modules (Set[Type[nn.Module]]): Set of module types to be
376
+ excluded in wrapping.
377
+
378
+ Returns:
379
+ Whether ``module`` should be wrapped.
380
+ """
381
+ force_leaf_modules = (
382
+ size_based_auto_wrap_policy.FORCE_LEAF_MODULES # type: ignore[attr-defined]
383
+ if force_leaf_modules is None
384
+ else force_leaf_modules
385
+ )
386
+ exclude_wrap_modules = (
387
+ size_based_auto_wrap_policy.EXCLUDE_WRAP_MODULES # type: ignore[attr-defined]
388
+ if exclude_wrap_modules is None
389
+ else exclude_wrap_modules
390
+ )
391
+
392
+ # Keep the argument `min_num_params` for BC for now, but it represents the
393
+ # minimum non-wrapped *numel* before triggering a wrapping
394
+ min_nonwrapped_numel = min_num_params
395
+ is_large = nonwrapped_numel >= min_nonwrapped_numel
396
+ if recurse:
397
+ # We should recurse if the module is big enough but not in force_leaf_modules list.
398
+ return is_large and not isinstance(module, tuple(force_leaf_modules))
399
+ else:
400
+ # If we are not recursing, determine if we should wrap.
401
+ return is_large and not isinstance(module, tuple(exclude_wrap_modules))
402
+
403
+
404
+ # Set those defaults to the size_based_auto_wrap_policy function. Make them easy to be imported.
405
+ size_based_auto_wrap_policy.EXCLUDE_WRAP_MODULES = {nn.ModuleList, nn.ModuleDict} # type: ignore[attr-defined]
406
+ size_based_auto_wrap_policy.FORCE_LEAF_MODULES = {nn.MultiheadAttention} # type: ignore[attr-defined]
407
+
408
+
409
+ @contextlib.contextmanager
410
+ def enable_wrap(
411
+ *, wrapper_cls: Any, **wrapper_kwargs: Any
412
+ ) -> Generator[None, None, None]:
413
+ """
414
+ Context manager to wrap modules using a wrapper.
415
+
416
+ Useful for when you'd like to apply the same configuration arguments to all
417
+ child modules that you wrap. A particularly important use case is wrapping
418
+ large layers so that they get sharded (in-place) during initialization, to
419
+ avoid running out of system memory. Large layers can indicate that they
420
+ should be sharded via the ``wrap`` annotation and this context manager can
421
+ provide the exact configuration for these nested instances.
422
+
423
+ Usage::
424
+
425
+ with enable_wrap(wrapper_cls, **params):
426
+ # Wraps layer in FSDP by default if within context
427
+ self.l1 = wrap(torch.nn.Linear(5, 5))
428
+
429
+ Args:
430
+ wrapper_cls:
431
+ Class that `wrap` annotation will `wrap` modules with, such as
432
+ `FullyShardedDataParallel`.
433
+ **wrapper_kwargs:
434
+ Configuration settings that will be passed to all ``wrap``
435
+ instances inside the context
436
+ """
437
+ kwargs = {
438
+ "wrapper_cls": wrapper_cls,
439
+ **wrapper_kwargs,
440
+ }
441
+ with _ConfigAutoWrap(**kwargs):
442
+ yield
443
+
444
+
445
+ def wrap(module: nn.Module, **wrap_overrides: Any) -> nn.Module:
446
+ """
447
+ Annotate that a module should be wrapped. Annotated modules will only be
448
+ wrapped if inside of an :func:`enable_wrap` context manager. This allows
449
+ a module to be initialized both with and without a wrapper without code
450
+ change.
451
+
452
+ The class that this function wraps the passed in ``nn.Module`` with is the
453
+ passed in ``wrapper_cls`` argument into ``enable_wrap``. Both
454
+ ``enable_wrap`` and ``wrap`` can take in kwargs specifying how to construct
455
+ the ``wrapper_cls`` instance. In the case of duplicate kwargs in
456
+ ``enable_wrap`` and ``wrap``, the argument passed into ``wrap`` will be
457
+ respected.
458
+
459
+ Usage::
460
+
461
+ with enable_wrap(wrapper_cls=FSDP, **fsdp_config):
462
+ # Wraps layer in FSDP by default if within context
463
+ self.l1 = wrap(torch.nn.Linear(5, 5))
464
+
465
+ Args:
466
+ module (nn.Module): module to wrap (if in :func:`enable_wrap` context)
467
+ **wrap_overrides: configuration overrides that will take priority over
468
+ the values provided by the :func:`enable_wrap` context
469
+ """
470
+ if _ConfigAutoWrap.in_autowrap_context:
471
+ assert _ConfigAutoWrap.wrapper_cls is not None
472
+
473
+ wrap_overrides = {**_ConfigAutoWrap.kwargs, **wrap_overrides}
474
+ return _wrap(
475
+ module,
476
+ _ConfigAutoWrap.wrapper_cls,
477
+ **wrap_overrides,
478
+ )
479
+ return module
480
+
481
+
482
+ def _wrap(module: nn.Module, wrapper_cls: Callable, **kwargs) -> nn.Module:
483
+ assert wrapper_cls is not None
484
+ if hasattr(module, "_wrap_overrides"):
485
+ # If module has a _wrap_overrides attribute, we force overriding the
486
+ # FSDP config with these attributes for this module. Currently this
487
+ # is only used to disable mixed precision for BatchNorm when
488
+ # auto_wrapping.
489
+ overrides = {**kwargs, **module._wrap_overrides} # type: ignore[arg-type]
490
+ return wrapper_cls(module, **overrides)
491
+
492
+ return wrapper_cls(module, **kwargs)
493
+
494
+
495
+ def _recursive_wrap(
496
+ module: nn.Module,
497
+ auto_wrap_policy: Callable,
498
+ wrapper_cls: Callable,
499
+ ignored_modules: Set[nn.Module],
500
+ ignored_params: Set[nn.Parameter],
501
+ only_wrap_children: bool = False,
502
+ **kwargs: Any,
503
+ ) -> Tuple[nn.Module, int]:
504
+ """
505
+ Wraps submodules of ``module`` for which ``auto_wrap_policy`` returns
506
+ ``True`` with ``wrapper_cls``.
507
+
508
+ Args:
509
+ module (nn.Module): Module to recursively wrap.
510
+ auto_wrap_policy (Callable): A callable representing a policy that
511
+ determines which modules to recursively wrap with ``wrapper_cls``.
512
+ ignored_modules (Set[torch.nn.Module]): Modules to ignore when
513
+ wrapping.
514
+ ignored_params (Set[torch.nn.Parameter]): Parameters to ignore when
515
+ wrapping; these should be the parameters contained in the modules
516
+ in ``ignored_modules``.
517
+ Returns:
518
+ (nn.Module, int):
519
+ ``module`` after wrapping and the numel recursively wrapped.
520
+ """
521
+ assert auto_wrap_policy is not None, "Must specify auto_wrap_policy."
522
+ assert wrapper_cls is not None, "Must specify wrapper_cls"
523
+ # Make sure no child is already wrapped.
524
+ for _, child in module.named_modules():
525
+ if child in ignored_modules:
526
+ continue
527
+ try:
528
+ assert not isinstance(child, cast(type, wrapper_cls))
529
+ except TypeError:
530
+ # wrapper_cls is a function as opposed to a class type, just bypass above check.
531
+ pass
532
+
533
+ # We count all params, assuming none of them are already wrapped.
534
+ nonwrapped_numel = sum(
535
+ p.numel() for p in module.parameters() if p not in ignored_params
536
+ )
537
+
538
+ assert auto_wrap_policy is not None
539
+ if auto_wrap_policy(module=module, recurse=True, nonwrapped_numel=nonwrapped_numel):
540
+ total_wrapped_numel = 0
541
+ # Iterate through the children, recursively wrap if necessary
542
+ for name, child in module.named_children():
543
+ if child in ignored_modules:
544
+ continue
545
+ wrapped_child, num_wrapped_params = _recursive_wrap(
546
+ module=child,
547
+ auto_wrap_policy=auto_wrap_policy,
548
+ wrapper_cls=wrapper_cls,
549
+ ignored_modules=ignored_modules,
550
+ ignored_params=ignored_params,
551
+ **kwargs,
552
+ )
553
+ setattr(module, name, wrapped_child)
554
+ # Keep track of how many parameters have been wrapped
555
+ total_wrapped_numel += num_wrapped_params
556
+ # decide if we need to wrap the current module,
557
+ # since the left over parameters exceed the number of params to wrap
558
+ remainder = nonwrapped_numel - total_wrapped_numel
559
+ if not only_wrap_children and auto_wrap_policy(
560
+ module=module, recurse=False, nonwrapped_numel=remainder
561
+ ):
562
+ # Leaf node or final wrapping of the remainder both happen here.
563
+ return _wrap(module, wrapper_cls, **kwargs), nonwrapped_numel
564
+ else:
565
+ return module, total_wrapped_numel
566
+ return module, 0
567
+
568
+
569
+ class _ConfigAutoWrap:
570
+ """
571
+ Helper class to wrap modules based on default config args via a context manager.
572
+ See :func:`enable_wrap` for more information.
573
+ """
574
+
575
+ in_autowrap_context: bool = False # Context flag
576
+ wrapper_cls: Optional[Callable] = None # The wrapper class
577
+ kwargs: Dict[str, Any] = {} # Wrapper's args
578
+
579
+ def __init__(self, **kwargs: Dict[str, Any]):
580
+ self.kwargs = kwargs
581
+
582
+ @staticmethod
583
+ def enable_autowrap_context(kwargs: Any) -> None:
584
+ if _ConfigAutoWrap.in_autowrap_context:
585
+ raise NotImplementedError(
586
+ "You are already within an autowrap context and we currently do not supported nested autowrap."
587
+ )
588
+ _ConfigAutoWrap.in_autowrap_context = True
589
+ # Get and save the wrapper cls for the context.
590
+ assert (
591
+ "wrapper_cls" in kwargs.keys()
592
+ ), "Expected to pass in wrapper_cls arg into _ConfigAutoWrap."
593
+ _ConfigAutoWrap.wrapper_cls = cast(Callable, kwargs["wrapper_cls"])
594
+ del kwargs["wrapper_cls"]
595
+ # Save the rest.
596
+ _ConfigAutoWrap.kwargs = kwargs
597
+
598
+ @staticmethod
599
+ def disable_autowrap_context() -> None:
600
+ _ConfigAutoWrap.in_autowrap_context = False
601
+ _ConfigAutoWrap.wrapper_cls = None
602
+ _ConfigAutoWrap.kwargs = {}
603
+
604
+ def __enter__(self) -> None:
605
+ self.enable_autowrap_context(self.kwargs)
606
+
607
+ def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
608
+ self.disable_autowrap_context()
vllm/lib/python3.10/site-packages/torch/distributed/nn/__pycache__/functional.cpython-310.pyc ADDED
Binary file (14.9 kB). View file
 
vllm/lib/python3.10/site-packages/torch/distributed/rpc/internal.py ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import collections
3
+ import copyreg
4
+ import io
5
+ import pickle
6
+ import sys
7
+ import threading
8
+ import traceback
9
+ from enum import Enum
10
+
11
+ import torch
12
+ import torch.distributed as dist
13
+ from torch._C._distributed_rpc import _get_current_rpc_agent
14
+
15
+
16
+ __all__ = ["RPCExecMode", "serialize", "deserialize", "PythonUDF", "RemoteException"]
17
+
18
+ # Thread local tensor tables to store tensors while pickling torch.Tensor
19
+ # objects
20
+ _thread_local_tensor_tables = threading.local()
21
+ _pickler = pickle.Pickler
22
+ _unpickler = pickle.Unpickler
23
+
24
+
25
+ class RPCExecMode(Enum):
26
+ SYNC = "sync"
27
+ ASYNC = "async"
28
+ ASYNC_JIT = "async_jit"
29
+ REMOTE = "remote"
30
+
31
+
32
+ class _InternalRPCPickler:
33
+ r"""
34
+ This class provides serialize() and deserialize() interfaces to serialize
35
+ data to be "binary string + tensor table" format
36
+ So for RPC python UDF function and args, non tensor data will be serialized
37
+ into regular binary string, tensor data will be put into thread local tensor
38
+ tables, this serialization format is consistent with builtin operator and args
39
+ using JIT pickler. This format will make tensor handling in C++ much easier,
40
+ e.g. attach tensor to distributed autograd graph in C++
41
+ """
42
+
43
+ def __init__(self):
44
+ # Ignore type error because dispatch_table is defined in third-party package
45
+ self._dispatch_table = copyreg.dispatch_table.copy() # type: ignore[attr-defined]
46
+ self._dispatch_table[torch.Tensor] = self._tensor_reducer
47
+ # Used for registering customized picklers.
48
+ self._class_reducer_dict = {}
49
+
50
+ def _register_reducer(self, obj_class, reducer):
51
+ # For the same class, only register the reducer once.
52
+ if obj_class not in self._class_reducer_dict:
53
+ self._class_reducer_dict[obj_class] = reducer
54
+
55
+ @classmethod
56
+ def _tensor_receiver(cls, tensor_index):
57
+ global _thread_local_tensor_tables
58
+ return _thread_local_tensor_tables.recv_tables[tensor_index]
59
+
60
+ def _tensor_reducer(self, tensor):
61
+ global _thread_local_tensor_tables
62
+ _thread_local_tensor_tables.send_tables.append(tensor)
63
+ tensor_index = len(_thread_local_tensor_tables.send_tables) - 1
64
+ return (_InternalRPCPickler._tensor_receiver, (tensor_index,))
65
+
66
+ @classmethod
67
+ def _py_rref_receiver(cls, rref_fork_data):
68
+ return dist.rpc.PyRRef._deserialize(rref_fork_data)
69
+
70
+ def _py_rref_reducer(self, py_rref):
71
+ rref_fork_data = py_rref._serialize()
72
+ return (_InternalRPCPickler._py_rref_receiver, (rref_fork_data,))
73
+
74
+ def _rref_reducer(self, rref):
75
+ return self._py_rref_reducer(rref)
76
+
77
+ @classmethod
78
+ def _script_module_receiver(cls, script_module_serialized):
79
+ """
80
+ Given a serialized representation of a ScriptModule created with torch.jit.save,
81
+ loads and returns the ScriptModule.
82
+ """
83
+ f = io.BytesIO(script_module_serialized)
84
+ m = torch.jit.load(f)
85
+ return m
86
+
87
+ def _script_module_reducer(self, script_module):
88
+ """
89
+ Serializes a ScriptModule.
90
+ """
91
+ f = io.BytesIO()
92
+ torch.jit.save(script_module, f)
93
+ return (_InternalRPCPickler._script_module_receiver, (f.getvalue(),))
94
+
95
+ def serialize(self, obj):
96
+ r"""
97
+ Serialize non tensor data into binary string, tensor data into
98
+ tensor table
99
+ """
100
+ f = io.BytesIO()
101
+ p = _pickler(f)
102
+ p.dispatch_table = self._dispatch_table
103
+
104
+ # rpc api could accept user picklers inheriting from _InternalRPCPickler to serialize rref,
105
+ # user picklers could have different initialization function from _InternalRPCPickler,
106
+ # but all the user picklers should call serialize() and use _rref_reducer to pickle rref
107
+ # in python. also, when _internal_rpc_pickler is imported to rpc/api.py, rpc.RRef is not
108
+ # compiled yet, it is not good place to access rpc.RRef inside _InternalRPCPickler constructor,
109
+ # so putting rref's dispatch table here
110
+ #
111
+ # The return value of a `rpc.remote(..)` call is type of `rpc.PyRRef`.
112
+ # The deserialized RRef object on an RPC receiver side is type of `rpc.PyRRef`.
113
+ # Ignore type error because dispatch_table is defined in third-party package
114
+ p.dispatch_table[dist.rpc.PyRRef] = self._py_rref_reducer # type: ignore[index]
115
+ # An RRef created locally by RRef Python constructor is type of `rpc.RRef`.
116
+ # Ignore type error because dispatch_table is defined in third-party package
117
+ p.dispatch_table[dist.rpc.RRef] = self._rref_reducer # type: ignore[index]
118
+
119
+ # Add dispatch pickling for ScriptModule or its subclass.
120
+ if isinstance(obj, torch.jit.ScriptModule):
121
+ # Ignore type error because dispatch_table is defined in third-party package
122
+ p.dispatch_table[obj.__class__] = self._script_module_reducer # type: ignore[index]
123
+
124
+ # Install customized picklers.
125
+ for class_name in self._class_reducer_dict.keys():
126
+ p.dispatch_table[class_name] = self._class_reducer_dict[class_name] # type: ignore[index]
127
+
128
+ # save _thread_local_tensor_tables.send_tables if it is in nested call
129
+ global _thread_local_tensor_tables
130
+ if hasattr(_thread_local_tensor_tables, "send_tables"):
131
+ old_send_tables = _thread_local_tensor_tables.send_tables
132
+ else:
133
+ old_send_tables = None
134
+ _thread_local_tensor_tables.send_tables = []
135
+
136
+ p.dump(obj)
137
+
138
+ # restore _thread_local_tensor_tables.send_tables if return
139
+ # from nested call, otherwise clean up the table
140
+ tensors = _thread_local_tensor_tables.send_tables
141
+ if old_send_tables is not None:
142
+ _thread_local_tensor_tables.send_tables = old_send_tables
143
+ else:
144
+ del _thread_local_tensor_tables.send_tables
145
+
146
+ return (f.getvalue(), tensors)
147
+
148
+ def deserialize(self, binary_data, tensor_table):
149
+ r"""
150
+ Deserialize binary string + tensor table to original obj
151
+ """
152
+ # save _thread_local_tensor_tables.recv_tables if it is in nested call
153
+ global _thread_local_tensor_tables
154
+ if hasattr(_thread_local_tensor_tables, "recv_tables"):
155
+ old_recv_tables = _thread_local_tensor_tables.recv_tables
156
+ else:
157
+ old_recv_tables = None
158
+ _thread_local_tensor_tables.recv_tables = tensor_table
159
+
160
+ try:
161
+ unpickler = _unpickler(io.BytesIO(binary_data))
162
+ ret = unpickler.load()
163
+ except AttributeError as e:
164
+ # Occurs when function is not found on module/class during
165
+ # unpickling.
166
+ except_str = (
167
+ str(e)
168
+ + """ Default RPC pickler does not serialize
169
+ function code. Ensure that UDFs are defined on both caller and
170
+ callee modules."""
171
+ )
172
+ ret = AttributeError(except_str)
173
+ # Ensure the stack trace gets preserved
174
+ ret.__cause__ = e
175
+
176
+ # restore _thread_local_tensor_tables.recv_tables if return
177
+ # from nested call, otherwise clean up the table
178
+ if old_recv_tables is not None:
179
+ _thread_local_tensor_tables.recv_tables = old_recv_tables
180
+ else:
181
+ del _thread_local_tensor_tables.recv_tables
182
+
183
+ return ret
184
+
185
+
186
+ # Create _internal_rpc_pickler only once to initialize _dispatch_table only once
187
+ _internal_rpc_pickler = _InternalRPCPickler()
188
+
189
+
190
+ def serialize(obj):
191
+ return _internal_rpc_pickler.serialize(obj)
192
+
193
+
194
+ def deserialize(binary_data, tensor_table):
195
+ return _internal_rpc_pickler.deserialize(binary_data, tensor_table)
196
+
197
+
198
+ def _run_function(python_udf):
199
+ r"""
200
+ This function is exclusively called from C++.
201
+ See ``torch/csrc/distributed/rpc/python_rpc_handler.cpp``.
202
+
203
+ Runs a Python UDF and returns its return value.
204
+ Wraps any exception in ``RemoteException`` if the function raises.
205
+ """
206
+ try:
207
+ if isinstance(python_udf, AttributeError):
208
+ raise python_udf
209
+ result = python_udf.func(*python_udf.args, **python_udf.kwargs)
210
+ except Exception as e:
211
+ # except str = exception info + traceback string
212
+ except_str = (
213
+ f"On {_get_current_rpc_agent().get_worker_info()}:\n"
214
+ f"{repr(e)}\n{traceback.format_exc()}"
215
+ )
216
+ print(except_str, file=sys.stderr)
217
+ result = RemoteException(except_str, type(e))
218
+ return result
219
+
220
+
221
+ def _handle_exception(result):
222
+ if isinstance(result, RemoteException):
223
+ exception_msg = result.msg.encode("utf-8").decode("unicode_escape")
224
+ # We wrap exception re-creation here in case some exception classes
225
+ # cannot be constructed directly from a string.
226
+ exc = None
227
+ try:
228
+ exc = result.exception_type(exception_msg)
229
+ except BaseException as e:
230
+ raise RuntimeError( # noqa: B904
231
+ f"Failed to create original exception type. Error msg was {str(e)}"
232
+ f" Original exception on remote side was {exception_msg}"
233
+ ) from e
234
+
235
+ if exc is not None:
236
+ raise exc
237
+
238
+
239
+ def _build_rpc_profiling_key(
240
+ exec_type, func_name, current_worker_name, dst_worker_name
241
+ ):
242
+ """
243
+ Builds the key that RPC calls are profiled with using the autograd profiler.
244
+ This will be the name of the corresponding Event recorded in the profiler.
245
+
246
+ Args:
247
+ exec_type (RPCExecMode): Type of RPC/RRef call
248
+ func_name (str): Name of function being profiled.
249
+ current_worker_name (str): Name of current worker.
250
+ dst_worker_name (str): Name of the destination worker.
251
+
252
+ Returns:
253
+ String representing profiling key
254
+ """
255
+ profile_key = (
256
+ f"rpc_{exec_type.value}#{func_name}({current_worker_name} -> {dst_worker_name})"
257
+ )
258
+ return profile_key
259
+
260
+
261
+ def _start_record_function(exec_type, func_name, current_worker_name, dest_worker_name):
262
+ """
263
+ This function should be called from RPC/RRef functions to create a
264
+ RecordFunction object for profiling. This function also runs the before
265
+ callbacks that start the profiling, though the user is responsible for
266
+ running the appropriate callbacks when the function to be profiled finishes.
267
+
268
+ Args:
269
+ exec_type (RPCExecMode): Type of RPC/RRef call
270
+ func_name (str): Name of function being profiled.
271
+ current_worker_name (str): Name of current worker.
272
+ dest_worker_name (str): Name of the destination worker.
273
+
274
+ Returns:
275
+ An instance of `torch.autograd._RecordFunction`.
276
+ """
277
+ assert torch.autograd._profiler_enabled(), "Autograd profiler should be enabled."
278
+ profile_key = f"rpc_{exec_type.value}#{str(func_name)}({current_worker_name} -> {dest_worker_name})"
279
+ rf = torch.autograd._RecordFunction() # type: ignore[attr-defined]
280
+ torch.autograd._run_before_callbacks(rf, profile_key) # type: ignore[attr-defined]
281
+ return rf
282
+
283
+
284
+ PythonUDF = collections.namedtuple("PythonUDF", ["func", "args", "kwargs"])
285
+ RemoteException = collections.namedtuple("RemoteException", ["msg", "exception_type"])
vllm/lib/python3.10/site-packages/torch/distributed/tensor/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.08 kB). View file
 
vllm/lib/python3.10/site-packages/torch/distributed/tensor/__pycache__/_api.cpython-310.pyc ADDED
Binary file (38 kB). View file
 
vllm/lib/python3.10/site-packages/torch/distributed/tensor/__pycache__/_collective_utils.cpython-310.pyc ADDED
Binary file (9.55 kB). View file
 
vllm/lib/python3.10/site-packages/torch/distributed/tensor/__pycache__/_dtensor_spec.cpython-310.pyc ADDED
Binary file (9.11 kB). View file
 
vllm/lib/python3.10/site-packages/torch/distributed/tensor/__pycache__/_op_schema.cpython-310.pyc ADDED
Binary file (16.1 kB). View file
 
vllm/lib/python3.10/site-packages/torch/distributed/tensor/__pycache__/_redistribute.cpython-310.pyc ADDED
Binary file (6.48 kB). View file