godlykmathews commited on
Commit
21fc3a1
·
verified ·
1 Parent(s): 6281591

Upload folder using huggingface_hub (part 17)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. venv/lib/python3.14/site-packages/torch/distributed/fsdp/_init_utils.py +1236 -0
  2. venv/lib/python3.14/site-packages/torch/distributed/fsdp/_limiter_utils.py +32 -0
  3. venv/lib/python3.14/site-packages/torch/distributed/fsdp/_optim_utils.py +2112 -0
  4. venv/lib/python3.14/site-packages/torch/distributed/fsdp/_runtime_utils.py +1654 -0
  5. venv/lib/python3.14/site-packages/torch/distributed/fsdp/_shard_utils.py +139 -0
  6. venv/lib/python3.14/site-packages/torch/distributed/fsdp/_state_dict_utils.py +932 -0
  7. venv/lib/python3.14/site-packages/torch/distributed/fsdp/_trace_utils.py +240 -0
  8. venv/lib/python3.14/site-packages/torch/distributed/fsdp/_traversal_utils.py +112 -0
  9. venv/lib/python3.14/site-packages/torch/distributed/fsdp/_unshard_param_utils.py +340 -0
  10. venv/lib/python3.14/site-packages/torch/distributed/fsdp/_wrap_utils.py +264 -0
  11. venv/lib/python3.14/site-packages/torch/distributed/fsdp/api.py +416 -0
  12. venv/lib/python3.14/site-packages/torch/distributed/fsdp/fully_sharded_data_parallel.py +0 -0
  13. venv/lib/python3.14/site-packages/torch/distributed/fsdp/sharded_grad_scaler.py +377 -0
  14. venv/lib/python3.14/site-packages/torch/distributed/fsdp/wrap.py +608 -0
  15. venv/lib/python3.14/site-packages/torch/distributed/launch.py +207 -0
  16. venv/lib/python3.14/site-packages/torch/distributed/launcher/__init__.py +14 -0
  17. venv/lib/python3.14/site-packages/torch/distributed/launcher/api.py +391 -0
  18. venv/lib/python3.14/site-packages/torch/distributed/logging_handlers.py +16 -0
  19. venv/lib/python3.14/site-packages/torch/distributed/nn/__init__.py +7 -0
  20. venv/lib/python3.14/site-packages/torch/distributed/nn/api/__init__.py +0 -0
  21. venv/lib/python3.14/site-packages/torch/distributed/nn/api/remote_module.py +762 -0
  22. venv/lib/python3.14/site-packages/torch/distributed/nn/functional.py +538 -0
  23. venv/lib/python3.14/site-packages/torch/distributed/nn/jit/__init__.py +0 -0
  24. venv/lib/python3.14/site-packages/torch/distributed/nn/jit/instantiator.py +171 -0
  25. venv/lib/python3.14/site-packages/torch/distributed/nn/jit/templates/__init__.py +0 -0
  26. venv/lib/python3.14/site-packages/torch/distributed/nn/jit/templates/remote_module_template.py +108 -0
  27. venv/lib/python3.14/site-packages/torch/distributed/optim/__init__.py +44 -0
  28. venv/lib/python3.14/site-packages/torch/distributed/optim/_deprecation_warning.py +16 -0
  29. venv/lib/python3.14/site-packages/torch/distributed/optim/apply_optimizer_in_backward.py +121 -0
  30. venv/lib/python3.14/site-packages/torch/distributed/optim/functional_adadelta.py +110 -0
  31. venv/lib/python3.14/site-packages/torch/distributed/optim/functional_adagrad.py +114 -0
  32. venv/lib/python3.14/site-packages/torch/distributed/optim/functional_adam.py +201 -0
  33. venv/lib/python3.14/site-packages/torch/distributed/optim/functional_adamax.py +122 -0
  34. venv/lib/python3.14/site-packages/torch/distributed/optim/functional_adamw.py +202 -0
  35. venv/lib/python3.14/site-packages/torch/distributed/optim/functional_rmsprop.py +129 -0
  36. venv/lib/python3.14/site-packages/torch/distributed/optim/functional_rprop.py +106 -0
  37. venv/lib/python3.14/site-packages/torch/distributed/optim/functional_sgd.py +165 -0
  38. venv/lib/python3.14/site-packages/torch/distributed/optim/named_optimizer.py +333 -0
  39. venv/lib/python3.14/site-packages/torch/distributed/optim/optimizer.py +254 -0
  40. venv/lib/python3.14/site-packages/torch/distributed/optim/post_localSGD_optimizer.py +111 -0
  41. venv/lib/python3.14/site-packages/torch/distributed/optim/utils.py +65 -0
  42. venv/lib/python3.14/site-packages/torch/distributed/optim/zero_redundancy_optimizer.py +1700 -0
  43. venv/lib/python3.14/site-packages/torch/distributed/optim/zero_redundancy_optimizer.pyi +85 -0
  44. venv/lib/python3.14/site-packages/torch/distributed/pipelining/_IR.py +1274 -0
  45. venv/lib/python3.14/site-packages/torch/distributed/pipelining/__init__.py +30 -0
  46. venv/lib/python3.14/site-packages/torch/distributed/pipelining/_backward.py +460 -0
  47. venv/lib/python3.14/site-packages/torch/distributed/pipelining/_debug.py +22 -0
  48. venv/lib/python3.14/site-packages/torch/distributed/pipelining/_schedule_visualizer.py +447 -0
  49. venv/lib/python3.14/site-packages/torch/distributed/pipelining/_unflatten.py +30 -0
  50. venv/lib/python3.14/site-packages/torch/distributed/pipelining/_utils.py +938 -0
venv/lib/python3.14/site-packages/torch/distributed/fsdp/_init_utils.py ADDED
@@ -0,0 +1,1236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import collections
3
+ import itertools
4
+ import os
5
+ import warnings
6
+ from collections.abc import Callable, Generator, Iterable, Iterator
7
+ from typing import Any, no_type_check, TYPE_CHECKING
8
+
9
+ import torch
10
+ import torch.distributed as dist
11
+ import torch.distributed.fsdp._exec_order_utils as exec_order_utils
12
+ import torch.distributed.fsdp._traversal_utils as traversal_utils
13
+ import torch.distributed.fsdp.fully_sharded_data_parallel as fsdp_file
14
+ import torch.nn as nn
15
+ from torch._opaque_base import OpaqueBase
16
+ from torch.distributed.algorithms._comm_hooks import default_hooks
17
+ from torch.distributed.device_mesh import DeviceMesh
18
+ from torch.distributed.distributed_c10d import _get_default_group
19
+ from torch.distributed.fsdp._common_utils import (
20
+ _FSDPDeviceHandle,
21
+ _FSDPState,
22
+ _get_module_fsdp_state,
23
+ _is_fsdp_flattened,
24
+ _named_parameters_with_duplicates,
25
+ clean_tensor_name,
26
+ TrainingState,
27
+ )
28
+ from torch.distributed.fsdp._flat_param import (
29
+ _FSDP_USE_FULL_PREC_IN_EVAL,
30
+ FlatParameter,
31
+ FlatParamHandle,
32
+ HandleShardingStrategy,
33
+ )
34
+ from torch.distributed.fsdp._limiter_utils import _FreeEventQueue
35
+ from torch.distributed.fsdp.api import (
36
+ BackwardPrefetch,
37
+ CPUOffload,
38
+ FullOptimStateDictConfig,
39
+ FullStateDictConfig,
40
+ MixedPrecision,
41
+ ShardingStrategy,
42
+ StateDictConfig,
43
+ StateDictType,
44
+ )
45
+ from torch.distributed.fsdp.wrap import _Policy
46
+ from torch.distributed.tensor.parallel.fsdp import DTensorExtensions
47
+ from torch.distributed.utils import _sync_params_and_buffers
48
+ from torch.utils._python_dispatch import is_traceable_wrapper_subclass
49
+
50
+
51
+ if TYPE_CHECKING:
52
+ from torch.utils.hooks import RemovableHandle
53
+
54
+ _TORCHDISTX_AVAIL = True
55
+ try:
56
+ from torchdistx import deferred_init, fake # type: ignore[import]
57
+ except ImportError:
58
+ _TORCHDISTX_AVAIL = False
59
+
60
+ PARAM_BROADCAST_BUCKET_SIZE = 250 * 1024 * 1024
61
+ FSDP_SYNCED = "_fsdp_synced"
62
+ # Specification of process groups for hybrid sharding strategies.
63
+ HybridShardProcessGroupType = tuple[dist.ProcessGroup, dist.ProcessGroup]
64
+ # Overall specification of process group.
65
+ ProcessGroupType = dist.ProcessGroup | HybridShardProcessGroupType | None
66
+
67
+
68
+ # TODO (awgu): Refactor this later
69
+ SHARDING_STRATEGY_MAP = {
70
+ ShardingStrategy.NO_SHARD: HandleShardingStrategy.NO_SHARD,
71
+ ShardingStrategy.FULL_SHARD: HandleShardingStrategy.FULL_SHARD,
72
+ ShardingStrategy.SHARD_GRAD_OP: HandleShardingStrategy.SHARD_GRAD_OP,
73
+ ShardingStrategy.HYBRID_SHARD: HandleShardingStrategy.HYBRID_SHARD,
74
+ ShardingStrategy._HYBRID_SHARD_ZERO2: HandleShardingStrategy._HYBRID_SHARD_ZERO2,
75
+ }
76
+ HYBRID_SHARDING_STRATEGIES = [
77
+ ShardingStrategy.HYBRID_SHARD,
78
+ ShardingStrategy._HYBRID_SHARD_ZERO2,
79
+ ]
80
+ NO_RESHARD_AFTER_FORWARD_STRATEGIES = (
81
+ ShardingStrategy.SHARD_GRAD_OP,
82
+ ShardingStrategy._HYBRID_SHARD_ZERO2,
83
+ )
84
+
85
+
86
+ # NOTE: Since non-self attributes cannot be type annotated, several attributes
87
+ # on `state` are defined first as local variables before being assigned.
88
+
89
+
90
+ @no_type_check
91
+ def _init_process_group_state(
92
+ state: _FSDPState,
93
+ process_group: ProcessGroupType,
94
+ sharding_strategy: ShardingStrategy,
95
+ policy: _Policy | None,
96
+ device_mesh: DeviceMesh | None = None,
97
+ ) -> _FSDPState:
98
+ if process_group is not None and device_mesh is not None:
99
+ raise ValueError(
100
+ "Cannot pass both process_group and device_mesh at the "
101
+ "same time. Please just pass only one of them."
102
+ )
103
+ is_hybrid_strategy = sharding_strategy in HYBRID_SHARDING_STRATEGIES
104
+ if is_hybrid_strategy:
105
+ if process_group is None and policy is None and device_mesh is None:
106
+ # Raise an error here, since this is manual wrapping with no process group
107
+ # passed in, there is no way to ensure all wrapped FSDP instances use the same
108
+ # process groups.
109
+ raise ValueError(
110
+ f"Manual wrapping with {sharding_strategy} "
111
+ "requires explicit specification of process group or device_mesh."
112
+ )
113
+ else:
114
+ state = _init_process_group_state_for_hybrid_shard(
115
+ state, process_group, device_mesh
116
+ )
117
+ else:
118
+ if device_mesh:
119
+ state._device_mesh = device_mesh
120
+ state.process_group = device_mesh.get_group(mesh_dim=0)
121
+ else:
122
+ state.process_group = (
123
+ process_group if process_group is not None else _get_default_group()
124
+ )
125
+
126
+ state.rank = state.process_group.rank()
127
+ state.world_size = state.process_group.size()
128
+ data_parallel_world_size = state.world_size
129
+ if is_hybrid_strategy:
130
+ data_parallel_world_size *= state._inter_node_pg.size()
131
+ state._gradient_predivide_factor = (
132
+ default_hooks.DefaultState._get_gradient_predivide_factor(
133
+ data_parallel_world_size
134
+ )
135
+ )
136
+ state._gradient_postdivide_factor = (
137
+ data_parallel_world_size / state._gradient_predivide_factor
138
+ )
139
+ return state
140
+
141
+
142
+ @no_type_check
143
+ def _init_process_group_state_for_hybrid_shard(
144
+ state: _FSDPState,
145
+ process_group: ProcessGroupType,
146
+ device_mesh: DeviceMesh,
147
+ ) -> _FSDPState:
148
+ if device_mesh:
149
+ if _is_valid_hybrid_shard_device_mesh(device_mesh):
150
+ state._device_mesh = device_mesh
151
+ # We currently only allow _inter_node_pg to be the outermost dimension, and the
152
+ # process_group(intra_node) to be the innermost dimension.
153
+ state._inter_node_pg = device_mesh.get_group(mesh_dim=0)
154
+ state.process_group = device_mesh.get_group(mesh_dim=1)
155
+ else:
156
+ raise ValueError(
157
+ f"Expected device_mesh to have ndim=2 but got {device_mesh.ndim}"
158
+ )
159
+ elif process_group is None:
160
+ default_group = _get_default_group()
161
+ intra_node_group, inter_node_group = _init_intra_and_inter_node_groups(
162
+ default_group, state._device_handle.device_count()
163
+ )
164
+ # we shard across intra-node
165
+ state.process_group = intra_node_group
166
+ # save _inter_node_pg to allreduce across.
167
+ state._inter_node_pg = inter_node_group
168
+ else:
169
+ # Check type and assign state.process_group and state._inter_node_pg.
170
+ if _is_valid_hybrid_shard_pg_type(process_group):
171
+ # Assuming that user passed in as intra node group and inter node group
172
+ # as documented.
173
+ state.process_group, state._inter_node_pg = process_group
174
+ else:
175
+ raise ValueError(
176
+ "Expected process_group to be passed in as either None or "
177
+ f"Tuple[dist.ProcessGroup, dist.ProcessGroup] but got {type(process_group)}"
178
+ )
179
+ # Create state for allreduce
180
+ state._inter_node_state = _get_default_comm_hook_state(
181
+ process_group=state._inter_node_pg,
182
+ )
183
+ return state
184
+
185
+
186
+ @no_type_check
187
+ def _is_valid_hybrid_shard_pg_type(process_group: Any) -> bool:
188
+ return (
189
+ isinstance(process_group, tuple)
190
+ and len(process_group) == 2
191
+ and all(isinstance(pg, dist.ProcessGroup) for pg in process_group)
192
+ )
193
+
194
+
195
+ @no_type_check
196
+ def _is_valid_hybrid_shard_device_mesh(device_mesh: DeviceMesh) -> bool:
197
+ return isinstance(device_mesh, DeviceMesh) and device_mesh.ndim == 2
198
+
199
+
200
+ @no_type_check
201
+ def _init_intra_node_process_group(num_devices_per_node: int) -> dist.ProcessGroup:
202
+ """
203
+ Return a process group across the current node.
204
+
205
+ For example, given each row is a distinct node:
206
+ 0 1 2 3 4 5 6 7
207
+ 8 9 10 11 12 13 14 15
208
+ This API would return an intra-node subgroup across
209
+ [0, 1, ..., 7] or [8, 9, ..., 15] depending on the process's rank.
210
+ For example, rank 3 would get [0, 1, ..., 7].
211
+ """
212
+ intra_node_subgroup, _ = dist.new_subgroups(num_devices_per_node)
213
+ return intra_node_subgroup
214
+
215
+
216
+ @no_type_check
217
+ def _init_inter_node_process_group(
218
+ global_process_group: dist.ProcessGroup,
219
+ num_devices_per_node: int,
220
+ ) -> dist.ProcessGroup:
221
+ """
222
+ Return an inter-node process group where each contained rank has the same local rank.
223
+
224
+ For example, given each row is a distinct node:
225
+ 0 1 2 3 4 5 6 7
226
+ 8 9 10 11 12 13 14 15
227
+ This API would return inter-node process group [0, 8], [1, 9], [2, 10], and so forth
228
+ depending on the process's rank. For example, rank 1 would get [1, 9], rank 5
229
+ would get [5, 13].
230
+ """
231
+ # the inter-node pg that is returned
232
+ inter_node_pg = None
233
+ sharding_backend = dist.get_backend(global_process_group)
234
+ world_size = dist.get_world_size(global_process_group)
235
+ # Assuming fully homogeneous setup
236
+ num_nodes = world_size // num_devices_per_node
237
+ my_local_rank = dist.get_rank(global_process_group) % num_devices_per_node
238
+ for local_rank in range(num_devices_per_node):
239
+ ranks_for_inter_group = [
240
+ local_rank + (i * num_devices_per_node) for i in range(num_nodes)
241
+ ]
242
+ # every rank always needs to call dist.new_group
243
+ grp = dist.new_group(ranks=ranks_for_inter_group, backend=sharding_backend)
244
+ if local_rank == my_local_rank:
245
+ inter_node_pg = grp
246
+
247
+ if inter_node_pg is None:
248
+ raise AssertionError(
249
+ f"{my_local_rank} expected to assign inter-node pg, but did not"
250
+ )
251
+ return inter_node_pg
252
+
253
+
254
+ def _init_intra_and_inter_node_groups(
255
+ global_process_group: dist.ProcessGroup,
256
+ num_devices_per_node: int,
257
+ ) -> tuple[dist.ProcessGroup, dist.ProcessGroup]:
258
+ """
259
+ Initialize intra and inter-node process groups and return the ones corresponding to this process's rank.
260
+
261
+ This function can be used to initialize process groups for ``HYBRID_SHARD`` or
262
+ ``_HYBRID_SHARD_ZERO2`` in FSDP.
263
+ This function assumes each node has an equal number of CUDA-enabled devices.
264
+ Returns:
265
+ Tuple[dist.ProcessGroup, dist.ProcessGroup]: Intra and inter-node process group.
266
+ """
267
+ return (
268
+ _init_intra_node_process_group(num_devices_per_node),
269
+ _init_inter_node_process_group(global_process_group, num_devices_per_node),
270
+ )
271
+
272
+
273
+ @no_type_check
274
+ def _init_ignored_module_states(
275
+ state: _FSDPState,
276
+ module: nn.Module,
277
+ ignored_modules: Iterable[torch.nn.Module] | None,
278
+ ignored_states: Iterable[torch.nn.Parameter]
279
+ | Iterable[torch.nn.Module]
280
+ | None = None,
281
+ ) -> _FSDPState:
282
+ if ignored_modules is not None and ignored_states is not None:
283
+ raise ValueError(
284
+ "Cannot pass both ignored_modules and ignored_states at the "
285
+ "same time. Please just pass ignored_states."
286
+ )
287
+ ignored_parameters = None
288
+ passed_as_ignored_states = ignored_states is not None
289
+ if passed_as_ignored_states:
290
+ ignored_states_list = list(ignored_states)
291
+ _check_ignored_states(ignored_states_list, True)
292
+ else:
293
+ ignored_states_list = []
294
+ _check_ignored_states(
295
+ list(ignored_modules) if ignored_modules is not None else [], False
296
+ )
297
+ if len(ignored_states_list) > 0:
298
+ if isinstance(ignored_states_list[0], nn.Parameter):
299
+ ignored_parameters = ignored_states_list
300
+ else:
301
+ ignored_modules = ignored_states_list
302
+ state._ignored_modules = _get_ignored_modules(module, ignored_modules)
303
+ state._ignored_params = _get_ignored_params(
304
+ module,
305
+ state._ignored_modules,
306
+ ignored_parameters,
307
+ )
308
+ state._ignored_buffer_names = _get_ignored_buffer_names(
309
+ module,
310
+ state._ignored_modules,
311
+ )
312
+ # TODO: FSDP's contract for buffers is not well-defined. They are
313
+ # implicitly ignored for most functionality since they are not sharded;
314
+ # however, FSDP still imposes some semantics on buffers (e.g. buffer mixed
315
+ # precision). We should formalize this contract and decide if we need to
316
+ # compute and store `_ignored_buffers`.
317
+ return state
318
+
319
+
320
+ def _check_ignored_states(
321
+ ignored_states: list[Any], passed_as_ignored_states: bool
322
+ ) -> None:
323
+ """
324
+ Check that the ignored states are uniformly parameters or uniformly modules.
325
+
326
+ We may remove this check in the future if we permit mixing.
327
+ """
328
+ if len(ignored_states) == 0:
329
+ return
330
+ if passed_as_ignored_states:
331
+ all_params = all(isinstance(state, nn.Parameter) for state in ignored_states)
332
+ all_modules = all(isinstance(state, nn.Module) for state in ignored_states)
333
+ if not all_params and not all_modules:
334
+ # Sort for consistent ordering for unit test regex matching
335
+ sorted_types = sorted({type(state) for state in ignored_states}, key=repr)
336
+ raise ValueError(
337
+ "ignored_states expects all nn.Parameter or all nn.Module list "
338
+ f"elements but got types {sorted_types}"
339
+ )
340
+ else:
341
+ if not all(isinstance(state, nn.Module) for state in ignored_states):
342
+ sorted_types = sorted({type(state) for state in ignored_states}, key=repr)
343
+ raise ValueError(
344
+ "ignored_modules expects nn.Module list elements but got "
345
+ f"types {sorted_types}"
346
+ )
347
+
348
+
349
+ @no_type_check
350
+ def _init_device_handle(
351
+ state: _FSDPState,
352
+ module: nn.Module,
353
+ ignored_params: set[nn.Parameter],
354
+ device_id: int | torch.device | None,
355
+ ) -> _FSDPState:
356
+ """
357
+ Determine device handle used for initializing FSDP.
358
+
359
+ If a device is specified by ``device_id``,
360
+ then returns device handle corresponds to that device type. Otherwise, If the
361
+ module is already on a non-CPU device, then the device type is that non-CPU device type.
362
+ If the module is on CPU or meta, then the device type is the current accelerator device.
363
+ See the :ref:`Accelerators<accelerators>` for details.
364
+
365
+
366
+ This method will be called once ignored parameters was determined, as the device handle maybe needed
367
+ for other initialization.
368
+ """
369
+ determined_device = None
370
+ if device_id is not None:
371
+ determined_device = (
372
+ device_id
373
+ if isinstance(device_id, torch.device)
374
+ else torch.device(device_id)
375
+ )
376
+ if determined_device is None:
377
+ for param in _get_orig_params(module, ignored_params):
378
+ if param.device.type in {"cpu", "meta"}:
379
+ continue
380
+ if determined_device is None:
381
+ determined_device = param.device
382
+ else:
383
+ if param.device.type != determined_device.type:
384
+ raise RuntimeError(
385
+ f"FSDP does not support modules with different device types "
386
+ f"but got params on {determined_device.type} and {param.device.type}"
387
+ )
388
+ determined_device = determined_device or torch._C._get_accelerator()
389
+ if determined_device.type == "cpu":
390
+ raise RuntimeError(
391
+ "FSDP needs a non-CPU accelerator device, but no accelerator device is detected."
392
+ )
393
+
394
+ state._device_handle = _FSDPDeviceHandle.from_device(determined_device)
395
+ return state
396
+
397
+
398
+ @no_type_check
399
+ def _init_buffer_state(
400
+ state: _FSDPState,
401
+ module: nn.Module,
402
+ ) -> _FSDPState:
403
+ state._buffer_names = _get_buffer_names(module)
404
+ # Save a mapping from clean fully-qualified buffer name (starting from
405
+ # `module`) to its original dtype for restoring that dtype during model
406
+ # checkpointing when buffer mixed precision is enabled. The names should
407
+ # be clean since the casting happens in a `summon_full_params()` context.
408
+ _buffer_name_to_orig_dtype: dict[str, torch.dtype] = {}
409
+ for buffer_name, buffer in module.named_buffers():
410
+ buffer_name = clean_tensor_name(buffer_name)
411
+ _buffer_name_to_orig_dtype[buffer_name] = buffer.dtype
412
+ state._buffer_name_to_orig_dtype = _buffer_name_to_orig_dtype
413
+ return state
414
+
415
+
416
+ @no_type_check
417
+ def _init_core_state(
418
+ state: _FSDPState,
419
+ sharding_strategy: ShardingStrategy | None,
420
+ mixed_precision: MixedPrecision | None,
421
+ cpu_offload: CPUOffload | None,
422
+ limit_all_gathers: bool,
423
+ use_orig_params: bool,
424
+ backward_prefetch_limit: int,
425
+ forward_prefetch_limit: int,
426
+ ) -> _FSDPState:
427
+ # We clamp the strategy to `NO_SHARD` for world size of 1 since they are
428
+ # currently functionally equivalent. This may change if/when we integrate
429
+ # FSDP with MoE.
430
+ if state.world_size == 1:
431
+ if sharding_strategy != ShardingStrategy.NO_SHARD:
432
+ warnings.warn(
433
+ "FSDP is switching to use `NO_SHARD` instead of "
434
+ f"{sharding_strategy or ShardingStrategy.FULL_SHARD} since "
435
+ "the world size is 1.",
436
+ stacklevel=2,
437
+ )
438
+ sharding_strategy = ShardingStrategy.NO_SHARD
439
+ elif sharding_strategy == ShardingStrategy.NO_SHARD:
440
+ warnings.warn(
441
+ "The `NO_SHARD` sharding strategy is deprecated. If having issues, "
442
+ "please use `DistributedDataParallel` instead.",
443
+ FutureWarning,
444
+ # Level 1 is here, level 2 is from `FullyShardedDataParallel`, and
445
+ # level 3 is from the true caller
446
+ stacklevel=3,
447
+ )
448
+ state.sharding_strategy = sharding_strategy or ShardingStrategy.FULL_SHARD
449
+ state.mixed_precision = mixed_precision or MixedPrecision()
450
+ if mixed_precision is not None:
451
+ torch._C._log_api_usage_once(
452
+ f"torch.distributed.fsdp.mixed_precision.{str(state.mixed_precision)}"
453
+ )
454
+ state._use_full_prec_in_eval = (
455
+ os.environ.get(_FSDP_USE_FULL_PREC_IN_EVAL, "") == "1"
456
+ )
457
+ state.cpu_offload = cpu_offload or CPUOffload()
458
+ state.limit_all_gathers = limit_all_gathers
459
+ state._use_orig_params = use_orig_params
460
+ state.training_state = TrainingState.IDLE
461
+ state._is_root = None
462
+ state._free_event_queue = _FreeEventQueue()
463
+ state._debug_level = dist.get_debug_level()
464
+ state._exec_order_data = exec_order_utils._ExecOrderData(
465
+ state._debug_level,
466
+ backward_prefetch_limit,
467
+ forward_prefetch_limit,
468
+ )
469
+ state._unshard_event = None
470
+ # Mapping from fully sharded module to the handles it is responsible to
471
+ # unshard and reshard (see [Note: Fully Sharded Module])
472
+ _fully_sharded_module_to_handle: dict[nn.Module, FlatParamHandle] = {}
473
+ state._fully_sharded_module_to_handle = _fully_sharded_module_to_handle
474
+ # Invariant: `state.params` contains exactly the `FlatParameter`s of the
475
+ # handles in `state._handle`
476
+ _handle: FlatParamHandle | None = None
477
+ state._handle = _handle
478
+ params: list[FlatParameter] = []
479
+ state.params = params
480
+ return state
481
+
482
+
483
+ @no_type_check
484
+ def _init_runtime_state(
485
+ state: _FSDPState,
486
+ ) -> _FSDPState:
487
+ _root_pre_forward_handles: list[RemovableHandle] = []
488
+ state._root_pre_forward_handles = _root_pre_forward_handles
489
+ _pre_forward_handles: list[RemovableHandle] = []
490
+ state._pre_forward_handles = _pre_forward_handles
491
+ _post_forward_handles: list[RemovableHandle] = []
492
+ state._post_forward_handles = _post_forward_handles
493
+ state._sync_gradients = True
494
+ state._comm_hook = None
495
+ state._comm_hook_state = None
496
+ # Used to prevent running the pre-backward hook multiple times
497
+ return state
498
+
499
+
500
+ @no_type_check
501
+ def _init_prefetching_state(
502
+ state: _FSDPState,
503
+ backward_prefetch: BackwardPrefetch,
504
+ forward_prefetch: bool,
505
+ ) -> _FSDPState:
506
+ state.backward_prefetch = backward_prefetch
507
+ state.forward_prefetch = forward_prefetch
508
+ # The data structures use tuples of handles to generalize over the case
509
+ # where a module's forward involves multiple handles.
510
+ return state
511
+
512
+
513
+ @no_type_check
514
+ # pyrefly: ignore [bad-function-definition]
515
+ def _init_extension(state: _FSDPState, device_mesh: DeviceMesh = None) -> _FSDPState:
516
+ # TODO: we need to add additional check once we support FSDP + PiPPy.
517
+ # This check is currently sufficient, since we only support FSDP + TP.
518
+ root_mesh = device_mesh._get_root_mesh() if device_mesh is not None else None
519
+ # if a root mesh is not the same as device_mesh,
520
+ # meaning the device_mesh is sliced out from the root mesh.
521
+ if device_mesh and root_mesh != state._device_mesh:
522
+ state._fsdp_extension = DTensorExtensions(state._device_handle)
523
+ else:
524
+ # We need to explicitly set _fsdp_extension to None.
525
+ # Otherwise, we will run into an infinite recursion when getting the attribute.
526
+ state._fsdp_extension = None
527
+ return state
528
+
529
+
530
+ @no_type_check
531
+ def _init_state_dict_state(state: _FSDPState) -> _FSDPState:
532
+ state._state_dict_type = StateDictType.FULL_STATE_DICT
533
+ state_dict_config: StateDictConfig = FullStateDictConfig()
534
+ state._optim_state_dict_config = FullOptimStateDictConfig()
535
+ state._state_dict_config = state_dict_config
536
+ unshard_params_ctx: dict[nn.Module, Generator] = {}
537
+ state._unshard_params_ctx = unshard_params_ctx
538
+
539
+ return state
540
+
541
+
542
+ def _verify_managed_params(module: nn.Module, params: list[nn.Parameter]) -> None:
543
+ """
544
+ Verify if the parameters are accepted by FSDP. The only restriction now
545
+ is that the parameter cannot be a scalar tensor (param.shape == []).
546
+ """
547
+ for param in params:
548
+ if len(param.shape) == 0:
549
+ param_name = ""
550
+ for name, param_ in module.named_parameters():
551
+ if param is param_:
552
+ param_name = name
553
+ break
554
+ if not param_name:
555
+ raise AssertionError("Expected param_name to be set")
556
+ raise ValueError(
557
+ "FSDP doesn't support scalar parameters. "
558
+ f"Change {param_name} to a 1D tensor with numel equal to 1."
559
+ )
560
+
561
+
562
+ @no_type_check
563
+ def _init_param_handle_from_module(
564
+ state: _FSDPState,
565
+ fully_sharded_module: nn.Module,
566
+ device_id: int | torch.device | None,
567
+ param_init_fn: Callable[[nn.Module], None] | None,
568
+ sync_module_states: bool,
569
+ ) -> _FSDPState:
570
+ """Initialize a ``FlatParamHandle`` from a module ``fully_sharded_module``."""
571
+ _check_single_device_module(fully_sharded_module, state._ignored_params, device_id)
572
+ device_from_device_id = _get_device_from_device_id(
573
+ device_id, state.rank, state._device_handle
574
+ )
575
+ is_meta_module, is_torchdistX_deferred_init = _need_to_materialize_module(
576
+ fully_sharded_module, state._ignored_params, state._ignored_modules
577
+ )
578
+ # Materialize the module if needed
579
+ if (is_meta_module or is_torchdistX_deferred_init) and param_init_fn is not None:
580
+ _materialize_with_param_init_fn(
581
+ fully_sharded_module, param_init_fn, state._ignored_modules
582
+ )
583
+ elif is_meta_module:
584
+ _materialize_meta_module(
585
+ fully_sharded_module,
586
+ device_id,
587
+ state._ignored_modules,
588
+ state._device_handle,
589
+ )
590
+ elif is_torchdistX_deferred_init:
591
+ deferred_init.materialize_module(
592
+ fully_sharded_module,
593
+ check_fn=lambda submodule: _get_module_fsdp_state(submodule) is None
594
+ and submodule not in state._ignored_modules,
595
+ )
596
+
597
+ ignored_buffers = {
598
+ buffer
599
+ for ignored_module in state._ignored_modules
600
+ for buffer in ignored_module.buffers()
601
+ }
602
+
603
+ _move_module_to_device(
604
+ fully_sharded_module,
605
+ state._ignored_params,
606
+ ignored_buffers,
607
+ device_from_device_id,
608
+ )
609
+ state.compute_device = _get_compute_device(
610
+ fully_sharded_module,
611
+ state._ignored_params,
612
+ device_from_device_id,
613
+ state.rank,
614
+ state._device_handle,
615
+ )
616
+
617
+ managed_params = list(_get_orig_params(fully_sharded_module, state._ignored_params))
618
+ _verify_managed_params(fully_sharded_module, managed_params)
619
+ if sync_module_states:
620
+ if state.sharding_strategy in HYBRID_SHARDING_STRATEGIES:
621
+ # Broadcast inter-node first, then intra-node. The inter-node
622
+ # broadcast propagates rank 0's states to each node's local
623
+ # rank 0, so the subsequent intra-node broadcast has the
624
+ # correct source values on every node. Reversing this order
625
+ # causes local rank 0 on non-source nodes to broadcast
626
+ # uninitialized states (e.g. from meta-device materialization).
627
+ _sync_module_params_and_buffers(
628
+ fully_sharded_module, managed_params, state._inter_node_pg
629
+ )
630
+ # _sync_module_params_and_buffers marks each buffer with
631
+ # FSDP_SYNCED=True to avoid redundant syncs in nested
632
+ # wrapping. Reset the flag here so the intra-node broadcast
633
+ # below also includes buffers.
634
+ for buffer in fully_sharded_module.buffers():
635
+ if hasattr(buffer, FSDP_SYNCED):
636
+ setattr(buffer, FSDP_SYNCED, False)
637
+ _sync_module_params_and_buffers(
638
+ fully_sharded_module, managed_params, state.process_group
639
+ )
640
+ _init_param_handle_from_params(state, managed_params, fully_sharded_module)
641
+ return state
642
+
643
+
644
+ @no_type_check
645
+ def _init_param_handle_from_params(
646
+ state: _FSDPState,
647
+ params: list[nn.Parameter],
648
+ fully_sharded_module: nn.Module,
649
+ ):
650
+ if len(params) == 0:
651
+ return
652
+ handle = FlatParamHandle(
653
+ params,
654
+ fully_sharded_module,
655
+ state.compute_device,
656
+ SHARDING_STRATEGY_MAP[state.sharding_strategy],
657
+ state.cpu_offload.offload_params,
658
+ state.mixed_precision.param_dtype,
659
+ state.mixed_precision.reduce_dtype,
660
+ state.mixed_precision.keep_low_precision_grads,
661
+ state.process_group,
662
+ state._use_orig_params,
663
+ fsdp_extension=state._fsdp_extension,
664
+ )
665
+ handle.shard()
666
+ if state._handle:
667
+ raise AssertionError("Expected state._handle to be None")
668
+ state.params.append(handle.flat_param)
669
+ state._handle = handle
670
+ state._fully_sharded_module_to_handle[handle._fully_sharded_module] = handle
671
+ cpu_device = torch.device("cpu")
672
+ if state.cpu_offload.offload_params and handle.flat_param.device != cpu_device:
673
+ handle.flat_param_to(cpu_device)
674
+
675
+
676
+ def _get_ignored_modules(
677
+ root_module: nn.Module,
678
+ _ignored_modules: Iterable[torch.nn.Module] | None,
679
+ ) -> set[nn.Module]:
680
+ """
681
+ Check that ``_ignored_modules`` is an iterable of ``nn.Module`` s without any FSDP instances.
682
+
683
+ Return the modules contained in their module
684
+ subtrees as a :class:`set`. Nested FSDP instances are excluded, but their
685
+ already-computed ignored modules are included.
686
+
687
+ ``_ignored_modules`` represents the argument passed by the user to FSDP.
688
+ """
689
+ msg_prefix = "`ignored_modules` should be an iterable of `torch.nn.Module`s "
690
+ try:
691
+ ignored_root_modules = (
692
+ set(_ignored_modules) if _ignored_modules is not None else set()
693
+ )
694
+ except TypeError as e:
695
+ raise TypeError(msg_prefix + f"but got {type(_ignored_modules)}") from e
696
+ for module in ignored_root_modules:
697
+ if not isinstance(module, torch.nn.Module):
698
+ raise TypeError(msg_prefix + f"but got an iterable with {type(module)}")
699
+ if _get_module_fsdp_state(module):
700
+ # TODO: We may relax this by taking the FSDP instance's wrapped
701
+ # module to provide more flexibility to the user.
702
+ raise ValueError("`ignored_modules` should not include FSDP modules")
703
+ # Treat modules that cannot compose with `fully_shard` as ignored modules,
704
+ # meaning that their subtrees are ignored
705
+ for module in root_module.modules():
706
+ if not traversal_utils._composable(module):
707
+ ignored_root_modules.add(module)
708
+ # NOTE: Even if `ignored_root_modules` is empty, do not return early so
709
+ # that this FSDP instance can get any ignored modules from its children.
710
+
711
+ # Include child modules and exclude nested FSDP modules themselves
712
+ ignored_modules = {
713
+ child
714
+ for module in ignored_root_modules
715
+ for child in module.modules()
716
+ if not isinstance(child, fsdp_file.FullyShardedDataParallel)
717
+ }
718
+ if root_module in ignored_modules:
719
+ warnings.warn(
720
+ "Trying to ignore the top-level module passed into the FSDP "
721
+ "constructor itself will result in all parameters being "
722
+ f"ignored and is not well-supported: {module}",
723
+ stacklevel=2,
724
+ )
725
+ # Include nested FSDP modules' ignored modules
726
+ for submodule in root_module.modules():
727
+ optional_fsdp_state = _get_module_fsdp_state(submodule)
728
+ if optional_fsdp_state is not None:
729
+ if not hasattr(optional_fsdp_state, "_ignored_modules"):
730
+ raise AssertionError(
731
+ "Expected optional_fsdp_state to have _ignored_modules attribute"
732
+ )
733
+ ignored_modules.update(optional_fsdp_state._ignored_modules)
734
+ return ignored_modules
735
+
736
+
737
+ def _get_ignored_params(
738
+ root_module: torch.nn.Module,
739
+ ignored_modules: set[torch.nn.Module],
740
+ ignored_parameters: Iterable[torch.nn.Parameter] | None = None,
741
+ ) -> set[torch.nn.Parameter]:
742
+ """
743
+ Return the parameters of the modules in ``ignored_modules`` and the parameters in ``ignored_parameters``.
744
+
745
+ :class:`FlatParameter` s are excluded from the result.
746
+ """
747
+ all_ignored_params: set[torch.nn.Parameter] = set()
748
+
749
+ params_in_ignored_modules = {
750
+ p for m in ignored_modules for p in m.parameters() if not _is_fsdp_flattened(p)
751
+ }
752
+
753
+ all_ignored_params.update(params_in_ignored_modules)
754
+
755
+ if ignored_parameters is not None:
756
+ params_in_ignored_parameters = {
757
+ p for p in ignored_parameters if not _is_fsdp_flattened(p)
758
+ }
759
+ all_ignored_params.update(params_in_ignored_parameters)
760
+
761
+ # Always include nested FSDP modules' ignored parameters
762
+ for submodule in root_module.modules():
763
+ optional_fsdp_state = _get_module_fsdp_state(submodule)
764
+ if optional_fsdp_state is not None:
765
+ if not hasattr(optional_fsdp_state, "_ignored_params"):
766
+ raise AssertionError(
767
+ "Expected optional_fsdp_state to have _ignored_params attribute"
768
+ )
769
+ all_ignored_params.update(optional_fsdp_state._ignored_params)
770
+
771
+ return all_ignored_params
772
+
773
+
774
+ def _get_ignored_buffer_names(
775
+ root_module: torch.nn.Module,
776
+ ignored_modules: set[torch.nn.Module],
777
+ ) -> set[str]:
778
+ """Return the cleaned buffer FQNs in ``ignored_modules``."""
779
+ all_ignored_buffer_names: set[str] = set()
780
+
781
+ buffers_in_ignored_modules = {
782
+ buffer for m in ignored_modules for buffer in m.buffers()
783
+ }
784
+
785
+ all_ignored_buffer_names.update(
786
+ {
787
+ clean_tensor_name(buffer_name)
788
+ for buffer_name, buffer in root_module.named_buffers()
789
+ if buffer in buffers_in_ignored_modules
790
+ }
791
+ )
792
+
793
+ # Always include nested FSDP modules' ignored buffer names
794
+ for submodule in root_module.modules():
795
+ optional_fsdp_state = _get_module_fsdp_state(submodule)
796
+ if optional_fsdp_state is not None:
797
+ if not hasattr(optional_fsdp_state, "_ignored_buffer_names"):
798
+ raise AssertionError(
799
+ "Expected optional_fsdp_state to have _ignored_buffer_names attribute"
800
+ )
801
+ all_ignored_buffer_names.update(optional_fsdp_state._ignored_buffer_names)
802
+
803
+ return all_ignored_buffer_names
804
+
805
+
806
+ def _get_buffer_names(root_module: nn.Module) -> set[str]:
807
+ """Return the fully prefixed names of all buffers in the module hierarchy rooted at ``root_module`` as a class:`set`."""
808
+ return {
809
+ clean_tensor_name(buffer_name) for buffer_name, _ in root_module.named_buffers()
810
+ }
811
+
812
+
813
+ def _check_single_device_module(
814
+ module: nn.Module,
815
+ ignored_params: set[nn.Parameter],
816
+ device_id: int | torch.device | None,
817
+ ) -> None:
818
+ """
819
+ Raise an error if ``module`` has original parameters on multiple devices, ignoring the parameters in ``ignored_params``.
820
+
821
+ Thus, after this method, the
822
+ module must be either fully on the CPU or fully on a non-CPU device.
823
+ """
824
+ devices = {param.device for param in _get_orig_params(module, ignored_params)}
825
+ # We allow module to be partially on CPU and partially on GPU if device_id is not
826
+ # None, since the device_id arg will result in the CPU portion being moved to
827
+ # GPU. This is useful in cases where part of the module may be parallelized
828
+ # by another algorithm and may already be on GPU. We'd like to enforce device_id
829
+ # to not be None, otherwise we'd flatten parameters in a mixed module which is
830
+ # not supported.
831
+ if len(devices) == 2 and torch.device("cpu") in devices:
832
+ if device_id is None:
833
+ raise RuntimeError(
834
+ "To support a module with both CPU and GPU params, "
835
+ "please pass in device_id argument."
836
+ )
837
+ elif len(devices) > 1:
838
+ raise RuntimeError(
839
+ f"FSDP only supports single device modules but got params on {devices}"
840
+ )
841
+
842
+
843
+ def _get_device_from_device_id(
844
+ device_id: int | torch.device | None,
845
+ rank: int,
846
+ device_handle: _FSDPDeviceHandle,
847
+ ) -> torch.device | None:
848
+ """
849
+ Return a ``torch.device`` for the specified ``device_id``.
850
+
851
+ Processes ``device_id`` and returns either the corresponding device or
852
+ ``None`` if ``device_id`` is ``None``.
853
+ """
854
+ if device_id is None:
855
+ return None
856
+ device = (
857
+ device_id if isinstance(device_id, torch.device) else torch.device(device_id)
858
+ )
859
+ if device.type != "cpu" and device.index is None:
860
+ warnings.warn(
861
+ f"FSDP got the argument `device_id` {device_id} on rank "
862
+ f"{rank}, which does not have an explicit index. "
863
+ f"FSDP will use the current device {device_handle.current_device()}. "
864
+ f"If this is incorrect, please explicitly call `torch.{device.type}.set_device()` "
865
+ "before FSDP initialization or pass in the explicit device "
866
+ "index as the `device_id` argument.",
867
+ stacklevel=2,
868
+ )
869
+ device = torch.device(device_handle.current_device())
870
+ return device
871
+
872
+
873
+ def _need_to_materialize_module(
874
+ module: nn.Module,
875
+ ignored_params: set[nn.Parameter],
876
+ ignored_modules: set[nn.Module],
877
+ ) -> tuple[bool, bool]:
878
+ """
879
+ Return if ``module`` has parameters on meta device and if ``module`` is using torchdistX deferred initialization.
880
+
881
+ At most of the returned bools can
882
+ be ``True``. If either is ``True``, then ``module`` needs to be
883
+ materialized.
884
+ """
885
+ managed_params = list(_get_orig_params(module, ignored_params))
886
+ is_meta_module = any(param.is_meta for param in managed_params)
887
+ # TODO: We need to establish a contract for FSDP and buffers. For now, we
888
+ # skip checking for meta buffers from ignored modules. We should consider
889
+ # refactoring the initialization holistically to avoid so many traversals.
890
+ for submodule in module.modules():
891
+ if submodule in ignored_modules:
892
+ continue
893
+ for buf in submodule.buffers(recurse=False):
894
+ is_meta_module |= buf.is_meta
895
+ is_torchdistX_deferred_init = (
896
+ not is_meta_module
897
+ and _TORCHDISTX_AVAIL
898
+ and any(fake.is_fake(param) for param in managed_params)
899
+ )
900
+ return is_meta_module, is_torchdistX_deferred_init
901
+
902
+
903
+ def _materialize_with_param_init_fn(
904
+ root_module: nn.Module,
905
+ param_init_fn: Callable[[nn.Module], None],
906
+ ignored_modules: set[nn.Module],
907
+ ) -> None:
908
+ if not callable(param_init_fn):
909
+ raise ValueError(
910
+ f"Expected {param_init_fn} to be callable but got {type(param_init_fn)}"
911
+ )
912
+ modules_to_materialize = _get_modules_to_materialize(root_module, ignored_modules)
913
+ for module in modules_to_materialize:
914
+ param_init_fn(module)
915
+
916
+
917
+ def _materialize_meta_module(
918
+ root_module: nn.Module,
919
+ device_from_device_id: torch.device | None,
920
+ ignored_modules: set[nn.Module],
921
+ device_handle: _FSDPDeviceHandle,
922
+ ):
923
+ # Run default meta device initialization
924
+ materialization_device = device_from_device_id or torch.device(
925
+ device_handle.current_device()
926
+ )
927
+ modules_to_materialize = _get_modules_to_materialize(root_module, ignored_modules)
928
+ module = None
929
+ try:
930
+ # Assume that each module's `reset_parameters()` only initializes its
931
+ # own parameters and not those of its children
932
+ with torch.no_grad():
933
+ for module in modules_to_materialize:
934
+ # As a contract to the user, only call `reset_parameters()` if
935
+ # the module has directly managed parameters/buffers
936
+ module_state_iter = itertools.chain(
937
+ module.parameters(recurse=False),
938
+ # pyrefly: ignore [bad-argument-type]
939
+ module.buffers(recurse=False),
940
+ )
941
+ has_module_states = len(list(module_state_iter)) > 0
942
+ if has_module_states:
943
+ module.to_empty(device=materialization_device, recurse=False)
944
+ module.reset_parameters() # type: ignore[operator]
945
+ except BaseException as e:
946
+ warnings.warn(
947
+ "Unable to call `reset_parameters()` for module on meta "
948
+ f"device with error {str(e)}. Please ensure that your module of"
949
+ f"type {type(module)} implements a `reset_parameters()` method.",
950
+ stacklevel=2, # type: ignore[possibly-undefined]
951
+ )
952
+ raise e
953
+
954
+
955
+ def _get_modules_to_materialize(
956
+ root_module: nn.Module, ignored_modules: set[nn.Module]
957
+ ) -> list[nn.Module]:
958
+ # Run BFS to collect the modules to materialize via `reset_parameters()`,
959
+ # stopping at any module with FSDP already applied or at ignored modules.
960
+ modules_to_materialize: list[nn.Module] = []
961
+ queue = collections.deque([root_module])
962
+ visited_modules: set[nn.Module] = {root_module}
963
+ while queue:
964
+ module = queue.popleft()
965
+ modules_to_materialize.append(module)
966
+ for child_module in module.children():
967
+ if (
968
+ child_module not in visited_modules
969
+ and _get_module_fsdp_state(child_module) is None
970
+ and child_module not in ignored_modules
971
+ ):
972
+ visited_modules.add(child_module)
973
+ queue.append(child_module)
974
+ return modules_to_materialize
975
+
976
+
977
+ def _move_module_to_device(
978
+ module: nn.Module,
979
+ ignored_params: set[nn.Parameter],
980
+ ignored_buffers: set[torch.Tensor],
981
+ device_from_device_id: torch.device | None,
982
+ ) -> None:
983
+ """
984
+ Move ``module`` depending on ``device_from_device_id`` and its current device.
985
+
986
+ This includes moving ignored modules' parameters.
987
+
988
+ - If ``device_from_device_id`` is not ``None``, then this moves
989
+ ``module`` to the device.
990
+ - If ``device_from_device_id`` is ``None``, then this does not move
991
+ ``module`` but warns the user if it is on CPU.
992
+
993
+ Precondition: ``_check_single_device_module()``.
994
+ """
995
+ cpu_device = torch.device("cpu")
996
+ if device_from_device_id is not None:
997
+ # BFS from `module` without traversing any nested FSDP instances to
998
+ # collect the parameters/buffers that have not yet been managed
999
+ queue: collections.deque[nn.Module] = collections.deque()
1000
+ queue.append(module)
1001
+ params: list[nn.Parameter] = []
1002
+ buffers: list[torch.Tensor] = []
1003
+ while queue:
1004
+ curr_module = queue.popleft()
1005
+ # NOTE: We include a check to only move parameters/buffers that are
1006
+ # on CPU device. If they are on a CUDA device different from the
1007
+ # one specified by `device_id`, then this does NOT move them. This
1008
+ # is so that we can raise an error in `_get_compute_device()`.
1009
+ params.extend(
1010
+ param
1011
+ for param in curr_module.parameters(recurse=False)
1012
+ if param.device == cpu_device
1013
+ )
1014
+ buffers.extend(
1015
+ buffer
1016
+ for buffer in curr_module.buffers(recurse=False)
1017
+ if buffer.device == cpu_device
1018
+ )
1019
+ for submodule in curr_module.children():
1020
+ if not isinstance(submodule, fsdp_file.FullyShardedDataParallel):
1021
+ queue.append(submodule)
1022
+ params_to_move = [p for p in params if p not in ignored_params]
1023
+ bufs_to_move = [p for p in buffers if p not in ignored_buffers]
1024
+ _move_states_to_device(params_to_move, bufs_to_move, device_from_device_id)
1025
+ return
1026
+ param = next(_get_orig_params(module, ignored_params), None)
1027
+ if param is not None and param.device == cpu_device:
1028
+ _warn_cpu_init()
1029
+
1030
+
1031
+ def _move_states_to_device(
1032
+ params: list[nn.Parameter],
1033
+ buffers: list[torch.Tensor],
1034
+ device_from_device_id: torch.device | None,
1035
+ ) -> None:
1036
+ """
1037
+ Move states to the specified device.
1038
+
1039
+ Precondition: ``_check_single_device_module()`` and module's parameters and
1040
+ buffers have been materialized if needed.
1041
+ """
1042
+ if len(params) == 0 and len(buffers) == 0:
1043
+ return
1044
+ if len(params) > 0:
1045
+ current_device = params[0].device
1046
+ elif len(buffers) > 0:
1047
+ current_device = buffers[0].device
1048
+ cpu_device = torch.device("cpu")
1049
+ if device_from_device_id is not None:
1050
+ # Move the parameters and buffers like the `.data` code path in
1051
+ # `nn.Module._apply()`, which underlies `nn.Module.to()`
1052
+ for param in params:
1053
+ with torch.no_grad():
1054
+ param.data = param.to(device_from_device_id)
1055
+ if param.grad is not None:
1056
+ param.grad.data = param.grad.to(device_from_device_id)
1057
+ for buffer in buffers:
1058
+ buffer.data = buffer.to(device_from_device_id)
1059
+ elif current_device == cpu_device: # type: ignore[possibly-undefined]
1060
+ _warn_cpu_init()
1061
+
1062
+
1063
+ def _warn_cpu_init():
1064
+ warnings.warn(
1065
+ "The passed-in `module` is on CPU and will thus have FSDP's sharding "
1066
+ "initialization run on CPU, which may be slower than on GPU. We "
1067
+ "recommend passing in the `device_id` argument for FSDP to move "
1068
+ "`module` to GPU for the sharding initialization. `module` must also "
1069
+ "be on GPU device to work with the `sync_module_states=True` flag "
1070
+ "since that requires GPU communication.",
1071
+ stacklevel=2,
1072
+ )
1073
+
1074
+
1075
+ def _get_compute_device(
1076
+ module: nn.Module,
1077
+ ignored_params: set[nn.Parameter],
1078
+ device_from_device_id: torch.device | None,
1079
+ rank: int,
1080
+ device_handle: _FSDPDeviceHandle,
1081
+ ) -> torch.device:
1082
+ """
1083
+ Determine and return this FSDP instance's compute device.
1084
+
1085
+ If the module is already on a non-CPU device, then the compute device is that non-CPU
1086
+ device. If the module is on CPU, then the compute device is the current
1087
+ device.
1088
+
1089
+ Since this method should be called after materializing the module, any
1090
+ non-CPU device should not be meta device. For now, the compute device is
1091
+ always a CUDA or CUDA-like device with its explicit index.
1092
+
1093
+ Precondition: ``_check_single_device_module()`` and
1094
+ ``_move_module_to_device()``.
1095
+ """
1096
+ param = next(_get_orig_params(module, ignored_params), None)
1097
+ if param is not None and param.device.type != "cpu":
1098
+ compute_device = param.device # Determined by model param placement
1099
+ else:
1100
+ compute_device = torch.device(device_handle.current_device())
1101
+ if device_from_device_id is not None and compute_device != device_from_device_id:
1102
+ raise ValueError(
1103
+ f"Inconsistent compute device and `device_id` on rank {rank}: "
1104
+ f"{compute_device} vs {device_from_device_id}"
1105
+ )
1106
+ return compute_device
1107
+
1108
+
1109
+ # TODO: See how to deprecate!
1110
+ def _sync_module_params_and_buffers(
1111
+ module: nn.Module,
1112
+ params: list[nn.Parameter],
1113
+ process_group: dist.ProcessGroup,
1114
+ ) -> None:
1115
+ """
1116
+ Synchronize module states (i.e. parameters ``params`` and all not-yet-synced buffers) by broadcasting from rank 0 to all ranks.
1117
+
1118
+ Precondition: ``sync_module_states == True`` and ``self.process_group`` has
1119
+ been set.
1120
+ """
1121
+ module_states: list[torch.Tensor] = []
1122
+ for buffer in module.buffers():
1123
+ # Avoid re-synchronizing buffers in case of nested wrapping
1124
+ if not getattr(buffer, FSDP_SYNCED, False):
1125
+ setattr(buffer, FSDP_SYNCED, True)
1126
+ detached_buffer = buffer.detach()
1127
+ if is_traceable_wrapper_subclass(detached_buffer):
1128
+ # NOTE: Here we assume no nested subclasses, at most one level of subclass
1129
+ # in both model's buffers and params
1130
+ attrs, _ = detached_buffer.__tensor_flatten__() # type: ignore[attr-defined]
1131
+ for attr in attrs:
1132
+ match getattr(detached_buffer, attr):
1133
+ case torch.Tensor() as v:
1134
+ module_states.append(v)
1135
+ case OpaqueBase():
1136
+ pass
1137
+ case unexpected:
1138
+ raise AssertionError(
1139
+ f"expected Tensor or OpaqueBase, got {type(unexpected)}"
1140
+ )
1141
+ else:
1142
+ module_states.append(detached_buffer)
1143
+
1144
+ for param in params:
1145
+ detached_param = param.detach()
1146
+ if is_traceable_wrapper_subclass(detached_param):
1147
+ attrs, _ = detached_param.__tensor_flatten__() # type: ignore[attr-defined]
1148
+ for attr in attrs:
1149
+ match getattr(detached_param, attr):
1150
+ case torch.Tensor() as v:
1151
+ module_states.append(v)
1152
+ case OpaqueBase():
1153
+ pass
1154
+ case unexpected:
1155
+ raise AssertionError(
1156
+ f"expected Tensor or OpaqueBase, got {type(unexpected)}"
1157
+ )
1158
+ else:
1159
+ module_states.append(detached_param)
1160
+
1161
+ _check_module_states_for_sync_module_states(module_states)
1162
+ _sync_params_and_buffers(
1163
+ process_group,
1164
+ module_states,
1165
+ PARAM_BROADCAST_BUCKET_SIZE,
1166
+ src=0,
1167
+ )
1168
+
1169
+
1170
+ def _check_module_states_for_sync_module_states(
1171
+ module_states: list[torch.Tensor],
1172
+ ) -> None:
1173
+ if module_states and any(
1174
+ tensor.device == torch.device("cpu") for tensor in module_states
1175
+ ):
1176
+ raise ValueError(
1177
+ "The module has CPU parameters or buffers when `sync_module_states=True`, "
1178
+ "which requires them to be on GPU. Please specify the `device_id` argument "
1179
+ "or move the module to GPU before passing it to FSDP."
1180
+ )
1181
+
1182
+
1183
+ def _get_orig_params(
1184
+ module: nn.Module,
1185
+ ignored_params: set[nn.Parameter],
1186
+ ) -> Iterator[nn.Parameter]:
1187
+ """
1188
+ Return an iterator over the original parameters in ``module``.
1189
+
1190
+ The iterator does not return
1191
+ the parameters in ``ignored_params``, any ``FlatParameter`` s (which may be
1192
+ present due to nested FSDP wrapping), or any original parameters already
1193
+ flattened (only relevant when ``use_orig_params=True``).
1194
+ """
1195
+ param_gen = module.parameters()
1196
+ try:
1197
+ while True:
1198
+ param = next(param_gen)
1199
+ if param not in ignored_params and not _is_fsdp_flattened(param):
1200
+ yield param
1201
+ except StopIteration:
1202
+ pass
1203
+
1204
+
1205
+ def _check_orig_params_flattened(
1206
+ fsdp_module,
1207
+ ignored_params: set[nn.Parameter],
1208
+ ) -> None:
1209
+ """
1210
+ Check that original parameters in ``fsdp_module`` have been flattened.
1211
+
1212
+ The flattened parameters are made
1213
+ invisible to ``named_parameters()`` for the module hierarchy rooted at
1214
+ ``fsdp_module``. This should be called as a sanity check after flattening
1215
+ the wrapped module's parameters.
1216
+ """
1217
+ for param_name, param in _named_parameters_with_duplicates(fsdp_module):
1218
+ if param not in ignored_params and not _is_fsdp_flattened(param):
1219
+ raise RuntimeError(
1220
+ f"Found an unflattened parameter: {param_name}; "
1221
+ f"{param.size()} {param.__class__}"
1222
+ )
1223
+
1224
+
1225
+ def _get_default_comm_hook(sharding_strategy: ShardingStrategy):
1226
+ return (
1227
+ default_hooks.allreduce_hook
1228
+ if sharding_strategy == ShardingStrategy.NO_SHARD
1229
+ else default_hooks.reduce_scatter_hook
1230
+ )
1231
+
1232
+
1233
+ def _get_default_comm_hook_state(
1234
+ process_group: dist.ProcessGroup,
1235
+ ) -> default_hooks.DefaultState:
1236
+ return default_hooks.DefaultState(process_group=process_group)
venv/lib/python3.14/site-packages/torch/distributed/fsdp/_limiter_utils.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+
3
+ import torch
4
+
5
+
6
+ class _FreeEventQueue:
7
+ """
8
+ This tracks all pending frees corresponding to inflight all-gathers. The
9
+ queueing pattern is iterative enqueues with a single dequeue per iteration
10
+ once the limit ``_max_num_inflight_all_gathers`` is reached.
11
+ """
12
+
13
+ def __init__(self) -> None:
14
+ self._queue: collections.deque[torch.Event] = collections.deque()
15
+ self._max_num_inflight_all_gathers = 2 # empirically chosen
16
+
17
+ def enqueue(self, free_event: torch.Event) -> None:
18
+ """Enqueues a free event."""
19
+ self._queue.append(free_event)
20
+
21
+ def dequeue_if_needed(self) -> torch.Event | None:
22
+ """Dequeues a single event if the limit is reached."""
23
+ if len(self._queue) >= self._max_num_inflight_all_gathers:
24
+ return self._dequeue()
25
+ return None
26
+
27
+ def _dequeue(self) -> torch.Event | None:
28
+ """Dequeues a free event if possible."""
29
+ if self._queue:
30
+ event = self._queue.popleft()
31
+ return event
32
+ return None
venv/lib/python3.14/site-packages/torch/distributed/fsdp/_optim_utils.py ADDED
@@ -0,0 +1,2112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import copy
3
+ import functools
4
+ import logging
5
+ import warnings
6
+ from collections.abc import Iterable, Iterator, Sequence
7
+ from contextlib import ExitStack
8
+ from dataclasses import dataclass, field
9
+ from itertools import chain
10
+ from typing import Any, cast, NamedTuple, no_type_check, TYPE_CHECKING
11
+
12
+ import torch
13
+ import torch.distributed as dist
14
+ import torch.distributed.fsdp._traversal_utils as traversal_utils
15
+ import torch.nn as nn
16
+ from torch.distributed._state_dict_utils import _gather_state_dict
17
+ from torch.distributed.distributed_c10d import _get_pg_default_device
18
+ from torch.distributed.fsdp._common_utils import (
19
+ _apply_to_modules,
20
+ _FSDPState,
21
+ _get_module_fsdp_state_if_fully_sharded_module,
22
+ _get_param_to_fqns,
23
+ _module_handle,
24
+ _named_parameters_with_duplicates,
25
+ clean_tensor_name,
26
+ )
27
+ from torch.distributed.fsdp._debug_utils import SimpleProfiler
28
+ from torch.distributed.fsdp._flat_param import FlatParameter, FlatParamHandle
29
+ from torch.distributed.fsdp._fsdp_extensions import (
30
+ _ext_chunk_dtensor,
31
+ _ext_chunk_tensor,
32
+ )
33
+ from torch.distributed.fsdp._runtime_utils import (
34
+ _lazy_init,
35
+ _reset_flat_param_grad_info_if_needed,
36
+ )
37
+ from torch.distributed.fsdp.api import (
38
+ ShardingStrategy,
39
+ StateDictSettings,
40
+ StateDictType,
41
+ )
42
+ from torch.distributed.tensor import DTensor, Replicate
43
+ from torch.utils._pytree import tree_map_only
44
+
45
+
46
+ if TYPE_CHECKING:
47
+ from torch.distributed._shard.sharded_tensor import ShardedTensor
48
+
49
+
50
+ logger = logging.getLogger(__name__)
51
+
52
+
53
+ @dataclass
54
+ class FSDPParamInfo:
55
+ state: _FSDPState
56
+ handle: FlatParamHandle
57
+ param_indices: dict[str, int]
58
+ param_requires_grad: list[bool]
59
+
60
+
61
+ def sorted_items(dictionary: dict[str, Any]) -> Iterator[tuple[str, Any]]:
62
+ keys = sorted(dictionary.keys())
63
+ for k in keys:
64
+ yield k, dictionary[k]
65
+
66
+
67
+ @dataclass
68
+ class _ConsolidatedOptimState:
69
+ """
70
+ This holds the consolidated optimizer state on the target rank. Positive-
71
+ dimension tensor state is communicated across ranks, while zero-dimension
72
+ tensor state and non-tensor state is taken directly from the target rank.
73
+
74
+ PyTorch version 1.12 moved to using zero-dimension tensors for scalar
75
+ values, but user implemented optimizers may still use float (i.e. a
76
+ non-tensor). Thus, we support both and handle them identically.
77
+
78
+ Attributes:
79
+ tensor_state (Dict[str, torch.Tensor]): Mapping from positive-dimension
80
+ tensor state name to the unsharded flat tensor representing the
81
+ state.
82
+ zero_dim_tensor_state (Dict[str, torch.Tensor]): Mapping from zero-
83
+ dimension tensor state name to its value.
84
+ non_tensor_state (Dict[str, Any]): Mapping from non-tensor state
85
+ name to its value.
86
+ """
87
+
88
+ tensor_state: dict[str, torch.Tensor] = field(default_factory=dict)
89
+ zero_dim_tensor_state: dict[str, torch.Tensor] = field(default_factory=dict)
90
+ non_tensor_state: dict[str, Any] = field(default_factory=dict)
91
+
92
+
93
+ class _PosDimTensorInfo(NamedTuple):
94
+ """
95
+ Metadata for positive-dimension tensors used internally for
96
+ :meth:`scatter_full_optim_state_dict`.
97
+
98
+ Attributes:
99
+ shape (torch.Size): Sharded tensor shape (which is equal to the
100
+ unsharded tensor shape if the tensor is optimizer state for a
101
+ non-FSDP parameter and is hence not sharded).
102
+ dtype (torch.dtype): Data type of the tensor.
103
+ """
104
+
105
+ shape: torch.Size
106
+ dtype: torch.dtype
107
+
108
+
109
+ class _OptimStateKey(NamedTuple):
110
+ """
111
+ This represents an optimizer state key that may be used commonly across
112
+ ranks. It is based on the unflattened parameter names rather than parameter
113
+ IDs to make it independent of each rank's own optimizer construction.
114
+ """
115
+
116
+ unflat_param_names: tuple[str, ...]
117
+ is_fsdp_managed: bool
118
+
119
+
120
+ def _unflatten_optim_state(
121
+ fsdp_param_info: FSDPParamInfo,
122
+ flat_param_state: dict[str, Any],
123
+ to_save: bool,
124
+ shard_state: bool,
125
+ cpu_offload: bool,
126
+ ) -> list[dict[str, Any]]:
127
+ """
128
+ Unflattens the optimizer state, consisting of the "state" part and the
129
+ "param_groups" part. Unflattening the "state" part involves consolidating
130
+ the state on the target rank and remapping from flattened to unflattened
131
+ parameter IDs, and the "param_groups" part only involves remapping from
132
+ flattened to unflattened parameter IDs.
133
+
134
+ Args:
135
+ fsdp_param_info (FSDPParamInfo): The FSDP state, the handle, and a
136
+ mapping from FQN to original parameter index.
137
+ flat_param_state (Dict[str, Any]): Entry for the flat parameter in the
138
+ "state" part of the optimizer state dict.
139
+ to_save (bool): Whether to save the state on this rank.
140
+
141
+ Returns:
142
+ List[Dict[str, Any]]: A :class:`list` holding the entries in the
143
+ "state" part of the optimizer state dict corresponding to the
144
+ unflattened parameters comprising the flat parameter if on the target
145
+ rank or an empty :class:`list` otherwise. The final optimizer state
146
+ dict will need to map these entries using the proper unflattened
147
+ parameter IDs.
148
+ """
149
+ if shard_state and not to_save:
150
+ raise AssertionError("If ``shard_state`` is True, ``to_save`` has to be True.")
151
+ consolidated_state = _communicate_optim_state(
152
+ fsdp_param_info,
153
+ flat_param_state,
154
+ )
155
+ if to_save:
156
+ unflat_param_state = _unflatten_communicated_optim_state(
157
+ fsdp_param_info,
158
+ consolidated_state,
159
+ shard_state,
160
+ )
161
+ for optim_state in unflat_param_state:
162
+ # We can't use .items() below cuz we'd run into a concurrent modification error
163
+ if cpu_offload:
164
+ for key in list(optim_state.keys()):
165
+ state = optim_state[key]
166
+ if not isinstance(state, torch.Tensor):
167
+ continue
168
+ optim_state[key] = state.cpu()
169
+ return unflat_param_state
170
+ else:
171
+ return []
172
+
173
+
174
+ def _is_zero_dim_tensor(x: Any) -> bool:
175
+ return torch.is_tensor(x) and x.dim() == 0
176
+
177
+
178
+ def _communicate_optim_state(
179
+ fsdp_param_info: FSDPParamInfo,
180
+ flat_param_state: dict[str, Any],
181
+ ) -> _ConsolidatedOptimState:
182
+ """
183
+ Communicates the optimizer state for a flat parameter across ranks. All
184
+ ranks will hold the entire non-sharded optimizer state on GPU.
185
+
186
+ If ``N`` is the number of tensor optimizer states in the optimizer state
187
+ dict, then the communication complexity is 0 if ``N = 0`` and ``N + 1``
188
+ otherwise (where the plus 1 comes from all-gathering the padding per rank).
189
+
190
+ Args:
191
+ fsdp_param_info (FSDPParamInfo): The FSDP state, the handle, and a
192
+ mapping from FQN to original parameter index.
193
+ flat_param_state (Dict[str, Any]): The entry in the "state" part of the
194
+ optimizer state dict corresponding to the flat parameter.
195
+
196
+ Returns:
197
+ ConsolidatedOptimState: Consolidated optimizer state for the target
198
+ flat parameter.
199
+ """
200
+ fsdp_state = fsdp_param_info.state
201
+ flat_param = fsdp_param_info.handle.flat_param
202
+ state = _ConsolidatedOptimState()
203
+ tensor_state, zero_dim_tensor_state, non_tensor_state = (
204
+ state.tensor_state,
205
+ state.zero_dim_tensor_state,
206
+ state.non_tensor_state,
207
+ )
208
+
209
+ for state_name, value in sorted_items(flat_param_state):
210
+ # Positive-dimension tensor state: communicate across ranks
211
+ if torch.is_tensor(value) and value.dim() > 0:
212
+ # If the parameter is not sharded, then neither is the
213
+ # positive-dimension tensor state, so no need to communicate it --
214
+ # we take the target rank's value
215
+ if (
216
+ fsdp_state.world_size == 1
217
+ or fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD
218
+ ):
219
+ tensor_state[state_name] = value
220
+ continue
221
+ if fsdp_state.compute_device is None:
222
+ raise AssertionError("compute_device has not been initialized")
223
+ if value.device.type != fsdp_state.compute_device.type:
224
+ value = value.to(fsdp_state.compute_device)
225
+ # Assume that positive-dimension tensor optimizer state
226
+ # has the same shape as the sharded flat parameter
227
+ buffer_size = flat_param._full_param_padded.size() # type: ignore[attr-defined]
228
+ tensor_buffer = value.new_zeros(*buffer_size)
229
+ dist.all_gather_into_tensor(
230
+ tensor_buffer, value, group=fsdp_state.process_group
231
+ )
232
+ fsdp_state._device_handle.synchronize()
233
+ unpadded_numel = cast(
234
+ nn.Parameter, flat_param._unpadded_unsharded_size
235
+ ).numel()
236
+ tensor_state[state_name] = tensor_buffer[:unpadded_numel]
237
+ # Zero-dimension tensor state and non-tensor state: take this rank's
238
+ # value directly
239
+ else:
240
+ if _is_zero_dim_tensor(value):
241
+ zero_dim_tensor_state[state_name] = value.detach().clone()
242
+ else:
243
+ non_tensor_state[state_name] = value
244
+ return state
245
+
246
+
247
+ def _unflatten_communicated_optim_state(
248
+ fsdp_param_info: FSDPParamInfo,
249
+ state: _ConsolidatedOptimState,
250
+ shard_state: bool,
251
+ ) -> list[dict[str, Any]]:
252
+ """
253
+ Unflattens the communicated optimizer state (given by ``tensor_state``,
254
+ ``non_tensor_state``, and ``zero_dim_tensor_state``) for a single flat
255
+ parameter. This should only be called on the target rank.
256
+
257
+ Args:
258
+ fsdp_param_info (FSDPParamInfo): The FSDP state, the handle, and a
259
+ mapping from FQN to original parameter index.
260
+ state (_ConsolidatedOptimState): Consolidated optimizer state.
261
+
262
+ Returns:
263
+ List[Dict[str, Any]]: A :class:`list` holding the entries in the
264
+ "state" part of the optimizer state dict corresponding to the
265
+ unflattened parameters comprising the flat parameter. The final
266
+ optimizer state dict will need to map these entries using the proper
267
+ unflattened parameter IDs.
268
+ """
269
+ fsdp_state = fsdp_param_info.state
270
+ handle = fsdp_param_info.handle
271
+ flat_param = handle.flat_param
272
+ unflat_param_state: list[dict[str, Any]] = []
273
+ flat_param_views: dict[str, Iterator] = {}
274
+ num_unflat_params = flat_param._num_params
275
+ tensor_state, zero_dim_tensor_state, non_tensor_state = (
276
+ state.tensor_state,
277
+ state.zero_dim_tensor_state,
278
+ state.non_tensor_state,
279
+ )
280
+
281
+ for _ in range(num_unflat_params):
282
+ unflat_state_param = {}
283
+ # Add positive-dimension tensor state: unflatten with views
284
+ for state_name, flat_tensor in sorted_items(tensor_state):
285
+ views_generated = state_name in flat_param_views
286
+ if not views_generated:
287
+ views = handle._get_unflat_views(flat_tensor)
288
+ flat_param_views[state_name] = views
289
+ else:
290
+ views = flat_param_views[state_name]
291
+ optim_state: torch.Tensor | ShardedTensor | DTensor = next(views)
292
+ if shard_state:
293
+ osd_config = fsdp_state._optim_state_dict_config
294
+ if getattr(osd_config, "_use_dtensor", False):
295
+ if fsdp_state._device_mesh is None:
296
+ raise AssertionError(
297
+ f"Expected _device_mesh to be not None, got {fsdp_state._device_mesh}"
298
+ )
299
+ optim_state = _ext_chunk_dtensor(
300
+ optim_state,
301
+ fsdp_state.rank,
302
+ fsdp_state._device_mesh,
303
+ fsdp_state._fsdp_extension,
304
+ )
305
+ else:
306
+ if fsdp_state.process_group is None:
307
+ raise AssertionError(
308
+ f"Expected process_group to be not None, got {fsdp_state.process_group}"
309
+ )
310
+ optim_state = _ext_chunk_tensor(
311
+ optim_state,
312
+ fsdp_state.rank,
313
+ fsdp_state.world_size,
314
+ fsdp_state._device_handle.device_count(),
315
+ fsdp_state.process_group,
316
+ fsdp_state._fsdp_extension,
317
+ )
318
+ unflat_state_param[state_name] = optim_state
319
+
320
+ # Add zero-dimension tensor state: take the target rank's value
321
+ unflat_state_param.update(sorted_items(zero_dim_tensor_state))
322
+ # Add non-tensor state: take the target rank's value
323
+ unflat_state_param.update(sorted_items(non_tensor_state))
324
+ unflat_param_state.append(unflat_state_param)
325
+ return unflat_param_state
326
+
327
+
328
+ def _broadcast_processed_state(
329
+ fsdp_state: _FSDPState,
330
+ optim_state: dict[str, Any],
331
+ group: dist.ProcessGroup | None,
332
+ ) -> dict[str, Any]:
333
+ objects: list[Any] = [None]
334
+ if dist.get_rank(group) == 0:
335
+ objects[0] = tree_map_only(
336
+ torch.Tensor,
337
+ lambda v: v.cpu() if v.dim() == 0 else _PosDimTensorInfo(v.shape, v.dtype), # type: ignore[union-attr]
338
+ optim_state,
339
+ )
340
+ dist.broadcast_object_list(objects, src=0, group=group)
341
+ if dist.get_rank(group) == 0:
342
+ return optim_state
343
+ else:
344
+ return objects[0]
345
+
346
+
347
+ def _broadcast_state(
348
+ fsdp_state: _FSDPState, state: Any, group: dist.ProcessGroup | None
349
+ ) -> Any:
350
+ if dist.get_rank(group) == 0:
351
+ if not isinstance(state, torch.Tensor) or state.dim() == 0:
352
+ return state
353
+ tensor = state.to(fsdp_state.compute_device)
354
+ else:
355
+ if isinstance(state, torch.Tensor):
356
+ if state.dim() != 0:
357
+ raise AssertionError(
358
+ "For non-zero ranks, a tensor state should have zero dimension, "
359
+ f"but got the state with shape {state.shape}."
360
+ )
361
+ return state
362
+ elif not isinstance(state, _PosDimTensorInfo):
363
+ return state
364
+ tensor = torch.zeros(
365
+ state.shape, dtype=state.dtype, device=fsdp_state.compute_device
366
+ )
367
+ dist.broadcast(tensor, src=0, group=group)
368
+ return tensor
369
+
370
+
371
+ def _shard_orig_param_state(
372
+ fsdp_param_info: FSDPParamInfo,
373
+ fqn: str,
374
+ optim_state: dict[str, Any],
375
+ ) -> dict[str, Any]:
376
+ """
377
+ Shard the optimizer state for the original parameter with the name ``fqn``.
378
+ This API should only be used when ``use_orig_params`` is True.
379
+ """
380
+ if not optim_state:
381
+ return {}
382
+ fsdp_state = fsdp_param_info.state
383
+ flat_param = fsdp_param_info.handle.flat_param
384
+ param_idx = fsdp_param_info.param_indices[fqn]
385
+ shard_param_info = flat_param._shard_param_infos[param_idx] # type: ignore[attr-defined]
386
+ optim_state = _gather_state_dict(
387
+ optim_state, pg=fsdp_state.process_group, device=fsdp_state.compute_device
388
+ )
389
+ if not shard_param_info.in_shard:
390
+ return {}
391
+ # Flatten and shard the state.
392
+ new_optim_state: dict[str, Any] = {}
393
+ intra_param_start_idx = shard_param_info.intra_param_start_idx
394
+ intra_param_end_idx = shard_param_info.intra_param_end_idx
395
+ for state_name, value in optim_state.items():
396
+ if (
397
+ torch.is_tensor(value)
398
+ and value.dim() > 0
399
+ and fsdp_state.sharding_strategy != ShardingStrategy.NO_SHARD
400
+ ):
401
+ value = value.flatten()[
402
+ intra_param_start_idx : intra_param_end_idx # type: ignore[operator]
403
+ + 1
404
+ ].clone()
405
+ new_optim_state[state_name] = value
406
+ return new_optim_state
407
+
408
+
409
+ def _flatten_optim_state_dict(
410
+ optim_state_dict: dict[str, Any],
411
+ model: nn.Module,
412
+ use_orig_params: bool = False,
413
+ optim: torch.optim.Optimizer | None = None,
414
+ rank0_only: bool = False,
415
+ group: dist.ProcessGroup | None = None,
416
+ ) -> dict[str, Any]:
417
+ """
418
+ Flattens the full optimizer state dict, still keying by unflattened parameter
419
+ names.
420
+
421
+ If ``use_orig_params`` is True, each rank will have all FSDP-managed
422
+ parameters but some of these parameters may be empty due to the sharding.
423
+ For a regular optim.Optimizer, states for those empty parameters will
424
+ not be initialized. So, when aggregating the FQNs across ranks, no assert
425
+ will be raised on a rank even if it does not have all the states -- it is
426
+ valid and FSDP know how to aggregate them. However, FSDP has to ignore
427
+ handling those parameters that are not managed by FSDP and do not exist on
428
+ the local rank -- it is managed by other parallelism and FSDP does not
429
+ know ho to handle/aggregate them.
430
+
431
+ Note that ``_flatten_tensor_optim_state`` does not need ``optim`` to
432
+ flatten/shard the state. However, NamedOptimizer and KeyedOptimizer require
433
+ all the states even if the corresponding parameters are empty. To this end,
434
+ ``optim`` will be used to get the initial state of the empty parameters.
435
+ ``optim`` should only be non-None if the ``optim` is KeyedOptimizer or
436
+ NamedOptimizer.
437
+
438
+ Returns:
439
+ Dict[str, Any]: The flattened optimizer state dict.
440
+ """
441
+ SimpleProfiler.reset()
442
+
443
+ unflat_osd = optim_state_dict
444
+ if "state" not in unflat_osd and not rank0_only:
445
+ raise ValueError(
446
+ '`optim_state_dict` must have the keys "state"'
447
+ "to be a valid optimizer state dict"
448
+ )
449
+ param_to_fqns = _get_param_to_fqns(model)
450
+ fqn_to_fsdp_param_info = _get_fqn_to_fsdp_param_info(model)
451
+ fsdp_state = next(iter(fqn_to_fsdp_param_info.values())).state
452
+
453
+ # Broadcast unflat_osd without non-scalar tensor if rank0_only is True.
454
+ if rank0_only:
455
+ unflat_osd = _broadcast_processed_state(fsdp_state, unflat_osd, group=group)
456
+
457
+ # Construct the "state" part
458
+ flat_osd_state: dict[_OptimStateKey | str, Any] = {}
459
+ unflat_osd_state = unflat_osd["state"]
460
+ all_state_keys = set(unflat_osd_state.keys())
461
+
462
+ for param, fqns in param_to_fqns.items():
463
+ fqn = fqns[0]
464
+ if fqn not in unflat_osd_state:
465
+ continue
466
+ all_state_keys.difference_update(fqns)
467
+
468
+ if rank0_only:
469
+ for fqn in fqns:
470
+ if not unflat_osd_state[fqn]:
471
+ continue
472
+ for state_name in unflat_osd_state[fqn]:
473
+ unflat_osd_state[fqn][state_name] = _broadcast_state(
474
+ fsdp_state, unflat_osd_state[fqn][state_name], group=group
475
+ )
476
+ fqn = fqns[0]
477
+ if fqn in fqn_to_fsdp_param_info:
478
+ fsdp_param_info = fqn_to_fsdp_param_info[fqn]
479
+ if use_orig_params:
480
+ with SimpleProfiler.profile(SimpleProfiler.Type.RESHARDING):
481
+ flat_state = _shard_orig_param_state(
482
+ fsdp_param_info,
483
+ fqn,
484
+ unflat_osd_state[fqn],
485
+ )
486
+ else:
487
+ flat_state = _flatten_optim_state(
488
+ fsdp_param_info,
489
+ unflat_osd_state,
490
+ fqns,
491
+ )
492
+ key = _OptimStateKey(tuple(fqns), True)
493
+ # Only include non-empty states since as expected by
494
+ # `torch.optim.Optimizer` s unless the optimizer is KeyedOptimizer
495
+ # or NamedOptimizer.
496
+ if flat_state:
497
+ flat_osd_state[key] = flat_state
498
+ elif use_orig_params:
499
+ if len(fqns) != 1:
500
+ raise AssertionError(
501
+ f"use_orig_params is True but there are multiple FQNs, {fqns}."
502
+ )
503
+ if optim is not None: # NamedOptimizer or KeyedOptimizer case.
504
+ state = optim.state.get(param, None) # type: ignore[call-overload]
505
+ if state is not None:
506
+ flat_osd_state[key] = copy.deepcopy(state)
507
+ else:
508
+ warnings.warn(
509
+ f"optim_state[{key}] is not on rank{fsdp_state.rank}.",
510
+ stacklevel=2,
511
+ )
512
+
513
+ else:
514
+ raise RuntimeError(
515
+ f"The state of {key} is empty. This should happen when "
516
+ "use_orig_params=True."
517
+ )
518
+ else: # do not flatten non-FSDP parameters' states
519
+ if len(fqns) != 1:
520
+ raise AssertionError(f"Expected len(fqns) == 1, got {len(fqns)}")
521
+ key = _OptimStateKey(tuple(fqns), False)
522
+ flat_osd_state[key] = copy.copy(unflat_osd_state[fqn])
523
+
524
+ if rank0_only:
525
+ for fqn in fqns:
526
+ if not unflat_osd_state[fqn]:
527
+ continue
528
+ for state_name, param_state in list(unflat_osd_state[fqn].items()):
529
+ if fsdp_state.rank > 0:
530
+ # Deference the tensor so that PyTorch can collect the memory.
531
+ del unflat_osd_state[fqn][state_name]
532
+ else:
533
+ # Move the tensor in the original osd back to CPU to make the
534
+ # original osd unaffected.
535
+ unflat_osd_state[fqn][state_name] = param_state.cpu()
536
+
537
+ # Handle user-defined state, states that are not associated with parameters.
538
+ for key in all_state_keys:
539
+ user_state = unflat_osd_state[key]
540
+ if isinstance(user_state, torch.Tensor) and rank0_only and use_orig_params:
541
+ user_state = _broadcast_state(fsdp_state, user_state, group=group)
542
+ flat_osd_state[key] = copy.copy(user_state)
543
+
544
+ SimpleProfiler.dump_and_reset("FSDP _flatten_optim_state_dict() profiling: ")
545
+ # Construct the "param_groups" part -- copy as is since it will be
546
+ # rekeyed later according to the target rank's optimizer
547
+ # Only copy param_groups if it exists in unflat_osd
548
+ if "param_groups" in unflat_osd:
549
+ flat_osd_param_groups = copy.deepcopy(unflat_osd["param_groups"])
550
+ return {"state": flat_osd_state, "param_groups": flat_osd_param_groups}
551
+ else:
552
+ return {"state": flat_osd_state}
553
+
554
+
555
+ def _flatten_optim_state(
556
+ fsdp_param_info: FSDPParamInfo,
557
+ unflat_osd_state: dict[str, dict[str, Any]],
558
+ unflat_param_names: list[str],
559
+ ) -> dict[str, Any]:
560
+ """
561
+ Flattens the optimizer state in ``full_optim_state_dict`` for a single
562
+ flat parameter in ``fsdp_param_info`` corresponding to the unflattened
563
+ parameter names in ``unflat_param_names``.
564
+
565
+ Args:
566
+ fsdp_param_info (FSDPParamInfo): The FSDP state, the handle, and a
567
+ mapping from FQN to original parameter index.
568
+ unflat_osd_state (Dict[str, Dict[str, Any]]): The "state" part of the
569
+ optimizer state dict corresponding to the unflattened parameters.
570
+ unflat_param_names (List[str]): A :class:`list` of unflattened
571
+ parameter names corresponding to the flat parameter ``flat_param``.
572
+
573
+ Returns:
574
+ Dict[str, Any]: A :class:`dict` mapping state names to their values for
575
+ a particular flat parameter. The sharded optimizer state dict's "state"
576
+ part will map a key to this returned value.
577
+ """
578
+ fsdp_state = fsdp_param_info.state
579
+ handle = fsdp_param_info.handle
580
+ flat_param = handle.flat_param
581
+ num_unflat_params = len(unflat_param_names)
582
+ if num_unflat_params <= 0:
583
+ raise AssertionError(
584
+ "Expects at least one unflattened parameter corresponding to the flat parameter"
585
+ )
586
+ unflat_param_shapes = flat_param._shapes
587
+ num_unflat_param_shapes = len(unflat_param_shapes)
588
+ if num_unflat_params != num_unflat_param_shapes:
589
+ raise AssertionError(
590
+ f"Expects {num_unflat_params} shapes but got {num_unflat_param_shapes}"
591
+ )
592
+
593
+ # Check if these unflattened parameters have any optimizer state
594
+ has_state = [
595
+ bool(unflat_param_name in unflat_osd_state)
596
+ for unflat_param_name in unflat_param_names
597
+ ]
598
+ # If none of the unflattened parameters comprising this flat parameter have
599
+ # any state, then we do not want an entry in the optimizer state dict
600
+ if not any(has_state):
601
+ return {} # no need to flatten any state
602
+ # There may still be some unflattened parameters with state and some
603
+ # without
604
+ unflat_param_states = [
605
+ _gather_state_dict(
606
+ unflat_osd_state[unflat_param_name],
607
+ pg=fsdp_state.process_group,
608
+ device=fsdp_state.compute_device,
609
+ )
610
+ if unflat_param_name in unflat_osd_state
611
+ else None
612
+ for unflat_param_name in unflat_param_names
613
+ ]
614
+ # Check that the unflattened parameters have the same state names
615
+ state_names = None
616
+ # pyrefly: ignore [bad-assignment]
617
+ for unflat_param_state in unflat_param_states:
618
+ if unflat_param_state is None:
619
+ continue
620
+ if state_names is None:
621
+ state_names = set(unflat_param_state.keys())
622
+ else:
623
+ if state_names != set(unflat_param_state.keys()):
624
+ raise ValueError(
625
+ "Differing optimizer state names for the unflattened "
626
+ f"parameters: {unflat_param_names}"
627
+ )
628
+ if state_names is None:
629
+ raise AssertionError(f"Expected state_names to be not None, got {state_names}")
630
+
631
+ # Flatten the state
632
+ flat_state: dict[str, torch.Tensor | None] = {}
633
+ for state_name in state_names:
634
+ state_values = [
635
+ unflat_param_state[state_name] if unflat_param_state is not None else None
636
+ for unflat_param_state in unflat_param_states
637
+ ]
638
+ non_none_state_values = [v for v in state_values if v is not None]
639
+ # If all ranks have None, this is a None value
640
+ if not non_none_state_values:
641
+ flat_state[state_name] = None
642
+ continue
643
+ are_pos_dim_tensors = are_zero_dim_tensors = are_non_tensors = True
644
+ for v in non_none_state_values:
645
+ are_pos_dim_tensors &= torch.is_tensor(v) and v.dim() > 0
646
+ are_zero_dim_tensors &= _is_zero_dim_tensor(v)
647
+ are_non_tensors &= not torch.is_tensor(v)
648
+ types = {type(v) for v in non_none_state_values}
649
+ if len(types) != 1 or not (
650
+ are_pos_dim_tensors or are_zero_dim_tensors or are_non_tensors
651
+ ):
652
+ raise ValueError(
653
+ f"Differing optimizer state types for state {state_name}, "
654
+ f"values {non_none_state_values}, and unflattened parameter "
655
+ f"names {unflat_param_names}"
656
+ )
657
+ if are_pos_dim_tensors:
658
+ flat_tensor = _flatten_tensor_optim_state(
659
+ state_name,
660
+ state_values, # type: ignore[arg-type]
661
+ unflat_param_names,
662
+ unflat_param_shapes,
663
+ handle,
664
+ )
665
+ # Shard the flattened tensor immediately to minimize max memory
666
+ # usage
667
+ if (
668
+ fsdp_state.world_size != 1
669
+ and fsdp_state.sharding_strategy != ShardingStrategy.NO_SHARD
670
+ ):
671
+ sharded_flat_tensor, _ = FlatParamHandle._get_shard(
672
+ flat_tensor,
673
+ fsdp_state.rank,
674
+ fsdp_state.world_size,
675
+ )
676
+ else:
677
+ sharded_flat_tensor = flat_tensor
678
+ flat_state[state_name] = sharded_flat_tensor
679
+ elif are_zero_dim_tensors:
680
+ flat_state[state_name] = _flatten_zero_dim_tensor_optim_state(
681
+ state_name,
682
+ state_values, # type: ignore[arg-type]
683
+ unflat_param_names,
684
+ )
685
+ else:
686
+ if not are_non_tensors:
687
+ raise AssertionError(
688
+ f"Expected are_non_tensors to be True, got {are_non_tensors}"
689
+ )
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
+ if flat_tensor.shape != flat_param_shape:
778
+ raise AssertionError(
779
+ f"tensor optim state: {flat_tensor.shape} 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: list[dict[str, Any]] | Iterable[nn.Parameter] | None,
882
+ using_optim_input: bool,
883
+ is_named_optimizer: bool = False,
884
+ ) -> dict[str, Any]:
885
+ """
886
+ Rekeys the optimizer state dict from unflattened parameter names to flat
887
+ parameter IDs according to the calling rank's ``optim``, which may be
888
+ different across ranks. In particular, the unflattened parameter names are
889
+ represented as :class:`_OptimStateKey` s.
890
+ """
891
+ param_to_fqns = _get_param_to_fqns(model)
892
+ flat_param_to_fqn = _get_flat_param_to_fqn(model)
893
+ param_to_param_key: dict[nn.Parameter, int | str] = cast(
894
+ dict[nn.Parameter, int | str],
895
+ (
896
+ _get_param_to_param_id_from_optim_input(model, optim_input)
897
+ if using_optim_input
898
+ else _get_param_to_param_key(
899
+ optim, model, is_named_optimizer, param_to_fqns, flat_param_to_fqn
900
+ )
901
+ ),
902
+ )
903
+ # All parameter keys in `param_to_param_key` should be in
904
+ # `param_to_fqns` -- strict inequality follows when not all parameters are
905
+ # passed to the optimizer
906
+ if len(param_to_param_key) > len(param_to_fqns):
907
+ raise AssertionError(
908
+ f"Expected len(param_to_param_key) <= len(param_to_fqns), got {len(param_to_param_key)} > {len(param_to_fqns)}"
909
+ )
910
+
911
+ unflat_param_names_to_flat_param_key: dict[
912
+ tuple[str, ...], int | str
913
+ ] = {} # for "state"
914
+ unflat_param_name_to_flat_param_key: dict[str, int | str] = {} # for "param_groups"
915
+ for param, unflat_param_names in param_to_fqns.items():
916
+ if param not in param_to_param_key:
917
+ # This parameter was not passed to the optimizer
918
+ continue
919
+ flat_param_key = param_to_param_key[param]
920
+ unflat_param_names_to_flat_param_key[tuple(unflat_param_names)] = flat_param_key
921
+ for unflat_param_name in unflat_param_names:
922
+ unflat_param_name_to_flat_param_key[unflat_param_name] = flat_param_key
923
+
924
+ sharded_osd_state = sharded_osd["state"]
925
+ rekeyed_osd_state: dict[str | int, Any] = {}
926
+ for key, param_state in sharded_osd_state.items():
927
+ if isinstance(key, str):
928
+ rekeyed_osd_state[key] = param_state
929
+ continue
930
+ flat_param_key = unflat_param_names_to_flat_param_key.get(
931
+ key.unflat_param_names, key.unflat_param_names
932
+ )
933
+
934
+ rekeyed_osd_state[flat_param_key] = param_state
935
+
936
+ # Only process param_groups if it exists in sharded_osd
937
+ if "param_groups" in sharded_osd:
938
+ rekeyed_osd_param_groups: list[dict[str, Any]] = []
939
+ for unflat_param_group in sharded_osd["param_groups"]:
940
+ flat_param_group = copy.deepcopy(unflat_param_group)
941
+ flat_param_keys = sorted(
942
+ {
943
+ unflat_param_name_to_flat_param_key[unflat_param_name]
944
+ for unflat_param_name in unflat_param_group["params"]
945
+ }
946
+ )
947
+ flat_param_group["params"] = flat_param_keys
948
+ rekeyed_osd_param_groups.append(flat_param_group)
949
+ return {"state": rekeyed_osd_state, "param_groups": rekeyed_osd_param_groups}
950
+ else:
951
+ return {"state": rekeyed_osd_state}
952
+
953
+
954
+ def _get_param_id_to_param_from_optim_input(
955
+ model: nn.Module,
956
+ optim_input: list[dict[str, Any]] | Iterable[nn.Parameter] | None = None,
957
+ ) -> dict[int, nn.Parameter]:
958
+ """
959
+ Constructs a mapping from parameter IDs to parameters. This may be used
960
+ both for models with ``FlatParameter`` s and without.
961
+
962
+ NOTE: This method is only preserved for backward compatibility. The method
963
+ :meth:`_get_param_key_to_param` is the preferred code path that does not
964
+ rely on ``optim_input``.
965
+
966
+ NOTE: We critically assume that, whether the optimizer input is a list of
967
+ parameters or a list of parameter groups, :class:`torch.optim.Optimizer`
968
+ enumerates the parameter IDs in order. In other words, for a parameter list
969
+ input, the parameter IDs should be in that list order, and for a parameter
970
+ groups input, the parameter IDs should be in order within each parameter
971
+ group and in order across parameter groups.
972
+
973
+ Args:
974
+ model (nn.Module): Model whose parameters are passed into the
975
+ optimizer.
976
+ optim_input (Optional[Union[List[Dict[str, Any]],
977
+ Iterable[nn.Parameter]]]): Input passed into the optimizer
978
+ representing either a :class:`list` of parameter groups or an
979
+ iterable of parameters; if ``None``, then this method assumes the
980
+ input was ``model.parameters()``. (Default: ``None``)
981
+
982
+ Returns:
983
+ List[nn.Parameter]: Mapping from parameter IDs to parameters,
984
+ where the parameter ID is implicitly the index in the :class:`list`.
985
+ """
986
+ # Assume the standard case of passing `model.parameters()` to the optimizer
987
+ # if `optim_input` is not specified
988
+ if optim_input is None:
989
+ return dict(enumerate(model.parameters()))
990
+ try:
991
+ # pyrefly: ignore [redundant-cast]
992
+ params = cast(list[nn.Parameter], list(optim_input))
993
+ except TypeError as e:
994
+ raise TypeError(
995
+ "Optimizer input should be an iterable of Tensors or dicts, "
996
+ f"but got {optim_input}"
997
+ ) from e
998
+ if len(params) == 0:
999
+ raise ValueError("Optimizer input should not be empty")
1000
+
1001
+ # Check if the optimizer input represents tensors or parameter groups
1002
+ all_tensors = True
1003
+ all_dicts = True
1004
+ for param in params:
1005
+ all_tensors &= isinstance(param, torch.Tensor)
1006
+ all_dicts &= isinstance(param, dict)
1007
+ if not all_tensors and not all_dicts:
1008
+ raise TypeError("Optimizer input should be an iterable of Tensors or dicts")
1009
+ if all_tensors:
1010
+ return dict(enumerate(params))
1011
+ if not all_dicts:
1012
+ raise AssertionError(f"Expected all_dicts to be True, got {all_dicts}")
1013
+ param_id_to_param: list[nn.Parameter] = []
1014
+ for param_group in params:
1015
+ has_params_key = "params" in param_group # type: ignore[operator]
1016
+ if not has_params_key:
1017
+ raise AssertionError(
1018
+ 'A parameter group should map "params" to a list of the parameters in the group'
1019
+ )
1020
+ # Implicitly map `flat_param_id` (current length of the list) to
1021
+ # `param`
1022
+ param_id_to_param.extend(param_group["params"]) # type: ignore[index]
1023
+ return dict(enumerate(param_id_to_param))
1024
+
1025
+
1026
+ def _get_flat_param_to_fqn(model: torch.nn.Module) -> dict[FlatParameter, str]:
1027
+ """
1028
+ Constructs a mapping from ``FlatParameter`` to a cleaned (devoid of prefixes
1029
+ from wrappers) fully qualified name (FQN). Note that this FQN is "non-canonical"
1030
+ because ``FlatParameter`` s do not come from the original module but are
1031
+ registered only after FSDP has been applied. This function returns the FSDP-given
1032
+ name for the ``FlatParameter`` (usually module._flat_param) as opposed to the
1033
+ canonical FQNs returned for ``FlatParameter`` s in ``_common_utils._get_param_to_fqns(...)``).
1034
+
1035
+ Consequently, this function will only return a non-empty mapping if FSDP was
1036
+ applied with ``use_orig_params=False`` as, otherwise, the original parameters
1037
+ are used within the module and there would be no ``FlatParameter`` s in the module.
1038
+
1039
+ """
1040
+
1041
+ def module_fn(module, prefix, tree_level, flat_param_to_fqn):
1042
+ for param_name, param in _named_parameters_with_duplicates(
1043
+ module, recurse=False
1044
+ ):
1045
+ if not isinstance(param, FlatParameter):
1046
+ continue
1047
+ fqn = clean_tensor_name(prefix + param_name)
1048
+ flat_param_to_fqn[param] = fqn
1049
+
1050
+ def return_fn(flat_param_to_fqn):
1051
+ return flat_param_to_fqn
1052
+
1053
+ flat_param_to_fqn_ret: dict[FlatParameter, str] = {}
1054
+ return _apply_to_modules(
1055
+ model,
1056
+ module_fn,
1057
+ return_fn,
1058
+ [fqn for fqn, _ in _named_parameters_with_duplicates(model)],
1059
+ flat_param_to_fqn_ret,
1060
+ )
1061
+
1062
+
1063
+ def _get_param_key_to_param(
1064
+ optim: torch.optim.Optimizer,
1065
+ model: nn.Module | None = None,
1066
+ is_named_optimizer: bool = False,
1067
+ param_to_fqns: dict[nn.Parameter, list[str]] | None = None,
1068
+ flat_param_to_fqn: dict[FlatParameter, str] | None = None,
1069
+ ) -> dict[int | str, nn.Parameter]:
1070
+ """
1071
+ Constructs a mapping from parameter keys to parameters. For the regular
1072
+ optimizers, the keys are parameter IDs. For NamedOptimizer, the keys
1073
+ are FQNs. This API may be used both for models with ``FlatParameter`` s and
1074
+ without.
1075
+ """
1076
+ clean_fqn_to_curr_fqn: dict[str, str] = {}
1077
+ if is_named_optimizer:
1078
+ if param_to_fqns is None or flat_param_to_fqn is None:
1079
+ raise AssertionError(
1080
+ "The optimizer is a NamedOptimizer, `param_to_fqns` must not be None."
1081
+ )
1082
+ if model is None:
1083
+ raise AssertionError(f"Expected model to be not None, got {model}")
1084
+ for key, _ in _named_parameters_with_duplicates(model):
1085
+ clean_fqn_to_curr_fqn[clean_tensor_name(key)] = key
1086
+
1087
+ param_key_to_param: dict[str | int, nn.Parameter] = {}
1088
+ pid = 0
1089
+ for param_group in optim.param_groups:
1090
+ if is_named_optimizer:
1091
+ for param in param_group["params"]:
1092
+ if flat_param_to_fqn is None:
1093
+ raise AssertionError(
1094
+ f"Expected flat_param_to_fqn to be not None, got {flat_param_to_fqn}"
1095
+ )
1096
+ if param in flat_param_to_fqn:
1097
+ # FlatParameter case
1098
+ key = flat_param_to_fqn[param]
1099
+ else:
1100
+ if param_to_fqns is None:
1101
+ raise AssertionError(
1102
+ f"Expected param_to_fqns to be not None, got {param_to_fqns}"
1103
+ )
1104
+ # use_orig_params case
1105
+ if len(param_to_fqns[param]) != 1:
1106
+ raise AssertionError(
1107
+ f"Expected len(param_to_fqns[param]) == 1, got {len(param_to_fqns[param])}"
1108
+ )
1109
+ key = param_to_fqns[param][0]
1110
+ try:
1111
+ key = clean_fqn_to_curr_fqn[key]
1112
+ except KeyError as e:
1113
+ raise KeyError(
1114
+ f"Can't find {key} from {list(clean_fqn_to_curr_fqn.keys())}."
1115
+ ) from e
1116
+ param_key_to_param[key] = param
1117
+ else:
1118
+ for param in param_group["params"]:
1119
+ param_key_to_param[pid] = param
1120
+ pid += 1
1121
+
1122
+ return param_key_to_param
1123
+
1124
+
1125
+ def _get_param_to_param_key(
1126
+ optim: torch.optim.Optimizer,
1127
+ model: nn.Module | None = None,
1128
+ is_named_optimizer: bool = False,
1129
+ param_to_fqns: dict[nn.Parameter, list[str]] | None = None,
1130
+ flat_param_to_fqn: dict[FlatParameter, str] | None = None,
1131
+ ) -> dict[nn.Parameter, int | str]:
1132
+ """
1133
+ Constructs the inverse mapping of :func:`_get_param_key_to_param`. This API
1134
+ only supports the case where `optim` is a regular optimizer, not NamedOptimizer.
1135
+ So the parameter keys will be parameter ids.
1136
+ """
1137
+ param_id_to_param = _get_param_key_to_param(
1138
+ optim, model, is_named_optimizer, param_to_fqns, flat_param_to_fqn
1139
+ )
1140
+ return {param: param_id for param_id, param in param_id_to_param.items()}
1141
+
1142
+
1143
+ def _get_param_to_param_id_from_optim_input(
1144
+ model: nn.Module,
1145
+ optim_input: list[dict[str, Any]] | Iterable[nn.Parameter] | None = 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, str | int],
1155
+ param_key_to_param: dict[str | int, nn.Parameter],
1156
+ group: dist.ProcessGroup | None,
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
+ if not (param_key >= 0 and param_key < len(param_key_to_param)):
1170
+ raise AssertionError("Check the `param_key_to_param` construction")
1171
+ # We cannot use FSDPState.compute_device as this API is a global view.
1172
+ device = _get_pg_default_device(group)
1173
+ num_missing = torch.tensor([len(missing_keys)], dtype=torch.int32, device=device)
1174
+ dist.all_reduce(num_missing, group=group)
1175
+ if num_missing.item() > 0:
1176
+ obj_list = [None for _ in range(dist.get_world_size(group))]
1177
+ dist.all_gather_object(obj_list, missing_keys, group=group)
1178
+ error_msg = (
1179
+ "FSDP currently requires each rank to have at least the "
1180
+ "optimizer states needed by rank 0's optimizer but some ranks "
1181
+ "are missing some of those states"
1182
+ )
1183
+ for rank, keys in enumerate(obj_list):
1184
+ keys = cast(list[_OptimStateKey], keys)
1185
+ if len(keys) > 0:
1186
+ error_msg += (
1187
+ f"\nRank {rank} is missing states for the parameters: "
1188
+ f"{[key.unflat_param_names for key in keys]}"
1189
+ )
1190
+ raise RuntimeError(error_msg)
1191
+
1192
+
1193
+ def _map_param_key_to_optim_keys(
1194
+ optim_state_dict: dict[str, Any],
1195
+ group: dist.ProcessGroup | None,
1196
+ param_key_to_param: dict[int | str, nn.Parameter],
1197
+ param_to_fqns: dict[nn.Parameter, list[str]],
1198
+ fqn_to_fsdp_param_info: dict[str, FSDPParamInfo],
1199
+ merge_keys: bool = False,
1200
+ ) -> tuple[list[_OptimStateKey], dict[_OptimStateKey, int | str]]:
1201
+ """
1202
+ Construct the local mapping between the ``_OptimStateKey`` and parameter keys
1203
+ and all the ``_OptimStateKey`` across ranks. If ``merge_keys`` is False, rank0
1204
+ must contain all the ``_OptimStateKey``, an exception will be raised otherwise.
1205
+ Note that ``merge_keys`` should equal to ``use_orig_params``.
1206
+ """
1207
+ rank = dist.get_rank(group)
1208
+ optim_state_key_to_param_key: dict[_OptimStateKey, int | str] = {} # local
1209
+ all_optim_state_keys: list[_OptimStateKey] = []
1210
+
1211
+ for param_key, param in param_key_to_param.items():
1212
+ # Do not include parameters without state to avoid empty mappings
1213
+ # just like in normal `torch.optim.Optimizer.state_dict()`
1214
+ if param_key not in optim_state_dict["state"]:
1215
+ continue
1216
+ fqns = param_to_fqns[param]
1217
+ is_fsdp_managed = isinstance(param, FlatParameter)
1218
+ if is_fsdp_managed:
1219
+ if fqns[0] not in fqn_to_fsdp_param_info:
1220
+ raise AssertionError(
1221
+ f"Expected {fqns[0]} to be in fqn_to_fsdp_param_info, got keys: {list(fqn_to_fsdp_param_info.keys())}"
1222
+ )
1223
+ is_fsdp_managed = fqns[0] in fqn_to_fsdp_param_info
1224
+ optim_state_key = _OptimStateKey(
1225
+ unflat_param_names=tuple(fqns),
1226
+ is_fsdp_managed=is_fsdp_managed,
1227
+ )
1228
+ if rank == 0 or merge_keys:
1229
+ all_optim_state_keys.append(optim_state_key)
1230
+ optim_state_key_to_param_key[optim_state_key] = param_key
1231
+
1232
+ if merge_keys:
1233
+ all_keys: list[list[_OptimStateKey]] = [
1234
+ [] for _ in range(dist.get_world_size(group))
1235
+ ]
1236
+ dist.all_gather_object(all_keys, all_optim_state_keys, group=group)
1237
+ merge_all_optim_state_keys = [*chain.from_iterable(all_keys)]
1238
+ all_optim_state_keys = sorted(set(merge_all_optim_state_keys))
1239
+ else:
1240
+ key_obj_list: list[list[_OptimStateKey] | None] = (
1241
+ [all_optim_state_keys] if rank == 0 else [None]
1242
+ )
1243
+ dist.broadcast_object_list(key_obj_list, src=0, group=group)
1244
+ if key_obj_list[0] is None:
1245
+ raise AssertionError(
1246
+ f"Expected key_obj_list[0] to be not None, got {key_obj_list[0]}"
1247
+ )
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[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
+ *chain.from_iterable(nested_unflat_param_names)
1276
+ ] # flatten the list of lists
1277
+ param_groups.append(unflat_param_group)
1278
+ return param_groups
1279
+
1280
+
1281
+ def _is_named_optimizer(optim_state_dict: dict[str, Any]) -> bool:
1282
+ """
1283
+ Returns whether the state_dict is from a NamedOptimizer.
1284
+ This function checks that the keys in the state_dict['state'] are strings
1285
+ (which usually are FQNs) versus integers (which usually refer to param_ids
1286
+ from a vanilla torch.optim.Optimizer).
1287
+ """
1288
+ state = optim_state_dict.get("state")
1289
+ if not state:
1290
+ # If we cannot find a state, assume it is not NamedOptimizer as
1291
+ # NamedOptimizer has eager initialization.
1292
+ return False
1293
+ try:
1294
+ key = next(iter(state.keys()))
1295
+ except Exception as e:
1296
+ raise Exception(optim_state_dict) from e # noqa: TRY002
1297
+ return isinstance(key, str)
1298
+
1299
+
1300
+ @dataclass
1301
+ class StateInfo:
1302
+ # The key of these dictionaries are the state name, e.g., `exp_avg`.
1303
+ tensors: dict[str, _PosDimTensorInfo]
1304
+ scalar_tensors: dict[str, torch.Tensor]
1305
+ non_tensors: dict[str, Any]
1306
+
1307
+
1308
+ def _allgather_state_info(
1309
+ fsdp_state: _FSDPState,
1310
+ input_states: dict[str, Any],
1311
+ ) -> list[dict[str, StateInfo]]:
1312
+ """
1313
+ Given the ``input_states``, allgather StateInfo for each state. The function
1314
+ uses all_gather_object to gather StateInfo so no GPU tensors are sent.
1315
+ """
1316
+
1317
+ processed_state_dict: dict[str, StateInfo] = {}
1318
+ gathered_state_info: list[dict[str, StateInfo]] = [
1319
+ {} for _ in range(fsdp_state.world_size)
1320
+ ]
1321
+
1322
+ for fqn, optim_state in input_states.items():
1323
+ # Allgather the scalar tensor state, non-tensor states and tensors metadata.
1324
+ processed_state = StateInfo({}, {}, {})
1325
+ for state_name, value in sorted_items(optim_state):
1326
+ if torch.is_tensor(value):
1327
+ if value.dim() == 0:
1328
+ # Ensure that `step` is on CPU.
1329
+ processed_state.scalar_tensors[state_name] = value.cpu()
1330
+ else:
1331
+ processed_state.tensors[state_name] = _PosDimTensorInfo(
1332
+ value.shape, value.dtype
1333
+ )
1334
+ else:
1335
+ processed_state.non_tensors[state_name] = value
1336
+ processed_state_dict[fqn] = processed_state
1337
+ dist.all_gather_object(
1338
+ gathered_state_info,
1339
+ processed_state_dict,
1340
+ group=fsdp_state.process_group,
1341
+ )
1342
+ return gathered_state_info
1343
+
1344
+
1345
+ def _convert_all_state_info(
1346
+ fsdp_param_info: FSDPParamInfo,
1347
+ gathered_state_info: list[dict[str, StateInfo]],
1348
+ input_states: dict[str, Any],
1349
+ output_states: dict[str, dict[str, Any]],
1350
+ ) -> tuple[torch.dtype | None, dict[str, list[torch.Tensor | None]]]:
1351
+ """
1352
+ Given the ``gathered_state_info`` and ``input_states``, the API converted
1353
+ the StateInfo into the original state if the state is not a non-scalar
1354
+ tensor. For a multi-dimensional tensor, the local state will be stored in
1355
+ ``state_buffer`` in a correct order for later allgather purpose.
1356
+ """
1357
+
1358
+ state_buffers: dict[str, list[torch.Tensor | None]] = {}
1359
+
1360
+ for fqn, gathered_state in output_states.items():
1361
+ state_info = [s[fqn] for s in gathered_state_info]
1362
+ all_tensor_states = sorted({n for state in state_info for n in state.tensors})
1363
+ empty_ranks: set[int] = set()
1364
+ dtype: torch.dtype | None = None
1365
+ # First check all the non-scalar states and get the information of
1366
+ # states on each rank.
1367
+ for state_name in all_tensor_states:
1368
+ numels = []
1369
+ _empty_ranks: set[int] = set()
1370
+ for rank, object_state in enumerate(state_info):
1371
+ numels.append(0)
1372
+ info = object_state.tensors.get(state_name, None)
1373
+ if info is not None:
1374
+ numels[-1] = info.shape.numel()
1375
+ if not dtype:
1376
+ dtype = info.dtype
1377
+ else:
1378
+ if dtype != info.dtype:
1379
+ raise AssertionError(
1380
+ f"Expected dtype == info.dtype, got {dtype} != {info.dtype}"
1381
+ )
1382
+ if numels[-1] == 0:
1383
+ _empty_ranks.add(rank)
1384
+
1385
+ if not (not empty_ranks or empty_ranks == _empty_ranks):
1386
+ raise AssertionError(
1387
+ f"Expected empty_ranks to be empty or equal to _empty_ranks, got {empty_ranks} vs {_empty_ranks}"
1388
+ )
1389
+ empty_ranks = _empty_ranks
1390
+ if state_name not in state_buffers:
1391
+ state_buffers[state_name] = [
1392
+ None for _ in fsdp_param_info.param_indices
1393
+ ]
1394
+ local_state = input_states[fqn].get(state_name, None)
1395
+ # N.B. We need to move the state to compute_device. The reason is
1396
+ # not yet clear and we need to figure out why the state may be on a
1397
+ # different device.
1398
+ if local_state is not None:
1399
+ local_state = local_state.to(fsdp_param_info.state.compute_device)
1400
+ state_buffers[state_name][fsdp_param_info.param_indices[fqn]] = local_state
1401
+
1402
+ # Restoring the scalar and non-tensor states. If the corresponding
1403
+ # non-scalar states do not exist on the rank, we also skip the scalar
1404
+ # non-tensor states on that rank.
1405
+ for rank, object_state in enumerate(state_info):
1406
+ if rank in empty_ranks:
1407
+ continue
1408
+ for name, non_tensor_value in object_state.non_tensors.items():
1409
+ curr_non_tensor_value = gathered_state.get(name, None)
1410
+ if not (
1411
+ curr_non_tensor_value is None
1412
+ or curr_non_tensor_value == non_tensor_value
1413
+ ):
1414
+ raise AssertionError(
1415
+ f"Rank {rank} has different values for {name}: {non_tensor_value}."
1416
+ + f" Other ranks: {curr_non_tensor_value}"
1417
+ )
1418
+ gathered_state[name] = non_tensor_value
1419
+
1420
+ for name, scalar_tensor_value in object_state.scalar_tensors.items():
1421
+ curr_scalar_tensor_value = gathered_state.get(name, None)
1422
+ if not (
1423
+ curr_scalar_tensor_value is None
1424
+ or torch.equal(scalar_tensor_value, curr_scalar_tensor_value)
1425
+ ):
1426
+ raise AssertionError(
1427
+ f"Rank {rank} has different values for {name}: {scalar_tensor_value}."
1428
+ + f" Other ranks: {curr_scalar_tensor_value}"
1429
+ )
1430
+ gathered_state[name] = scalar_tensor_value
1431
+
1432
+ return dtype, state_buffers # type: ignore[possibly-undefined]
1433
+
1434
+
1435
+ def _unflatten_orig_param_states(
1436
+ fsdp_param_info: FSDPParamInfo,
1437
+ output_states: dict[str, dict[str, Any]],
1438
+ state_name: str,
1439
+ shard_state: bool,
1440
+ to_save: bool,
1441
+ cpu_offload: bool,
1442
+ ) -> None:
1443
+ """
1444
+ Given a output state dict, ``output_states``, which the keys are FQNs to the
1445
+ original parameters (not FlatParameters nor parameter ID), and the values
1446
+ are gathered states, unflatten the states to the original dimensions.
1447
+
1448
+ This function performs the unflattening process in-place.
1449
+ """
1450
+ if not to_save:
1451
+ return
1452
+ flat_param = fsdp_param_info.handle.flat_param
1453
+ fsdp_state = fsdp_param_info.state
1454
+ for fqn, gathered_state in output_states.items():
1455
+ value = gathered_state[state_name]
1456
+ param_idx = fsdp_param_info.param_indices[fqn]
1457
+
1458
+ # TODO: This solution is not general and only apply to PTD TP solution.
1459
+ if isinstance(value, DTensor):
1460
+ placement = value.placements[0]
1461
+ # If gathered state is a DTensor and its TP placement is not Replicate(), we need to
1462
+ # gather the tensor on its TP dimension before chunking them into DTensor again.
1463
+ if placement != Replicate():
1464
+ placement_dim = placement.dim # type: ignore[attr-defined]
1465
+ value.redistribute(placements=(Replicate(),))
1466
+ reshape_size = list(flat_param._shapes[param_idx])
1467
+ reshape_size[placement_dim] *= value.device_mesh.size(0)
1468
+ reshape_size = torch.Size(reshape_size)
1469
+ value = value.reshape(reshape_size)
1470
+ # If gathered state is a replicate DTensor, we directly reshape it.
1471
+ else:
1472
+ value = value.reshape(flat_param._shapes[param_idx])
1473
+ else:
1474
+ # If gathered state is a tensor, we directly reshape it into unflatten state.
1475
+ value = value.reshape(flat_param._shapes[param_idx])
1476
+
1477
+ if shard_state:
1478
+ osd_config = fsdp_state._optim_state_dict_config
1479
+ if getattr(osd_config, "_use_dtensor", False):
1480
+ if fsdp_state._device_mesh is None:
1481
+ raise AssertionError(
1482
+ f"Expected _device_mesh to be not None, got {fsdp_state._device_mesh}"
1483
+ )
1484
+ value = _ext_chunk_dtensor(
1485
+ value,
1486
+ fsdp_state.rank,
1487
+ fsdp_state._device_mesh,
1488
+ fsdp_state._fsdp_extension,
1489
+ )
1490
+ else:
1491
+ if fsdp_state.process_group is None:
1492
+ raise AssertionError(
1493
+ f"Expected process_group to be not None, got {fsdp_state.process_group}"
1494
+ )
1495
+ value = _ext_chunk_tensor(
1496
+ value,
1497
+ fsdp_state.rank,
1498
+ fsdp_state.world_size,
1499
+ fsdp_state._device_handle.device_count(),
1500
+ fsdp_state.process_group,
1501
+ fsdp_state._fsdp_extension,
1502
+ )
1503
+ elif not cpu_offload:
1504
+ with SimpleProfiler.profile("clone"):
1505
+ value = value.detach().clone()
1506
+
1507
+ if cpu_offload:
1508
+ with SimpleProfiler.profile(SimpleProfiler.Type.D2H):
1509
+ value = value.cpu()
1510
+ gathered_state[state_name] = value
1511
+
1512
+
1513
+ def _allgather_orig_param_states(
1514
+ fsdp_param_info: FSDPParamInfo,
1515
+ gathered_state_info: list[dict[str, StateInfo]],
1516
+ input_states: dict[str, Any],
1517
+ shard_state: bool,
1518
+ to_save: bool,
1519
+ cpu_offload: bool,
1520
+ ) -> dict[str, dict[str, Any]]:
1521
+ """
1522
+ Given the ``gathered_state_info`` and ``input_states``, the API allgathers
1523
+ all tensor states and restore non-tensor states from ``gathered_state_info``.
1524
+ """
1525
+ fsdp_state = fsdp_param_info.state
1526
+ if fsdp_state.rank == 0 and dist.get_debug_level() == dist.DebugLevel.DETAIL:
1527
+ logger.info(
1528
+ "Memory Summary before calling to _allgather_orig_param_states %s",
1529
+ fsdp_state._device_handle.memory_summary(),
1530
+ )
1531
+
1532
+ output_states: dict[str, dict[str, Any]] = {fqn: {} for fqn in input_states}
1533
+
1534
+ dtype, state_buffers = _convert_all_state_info(
1535
+ fsdp_param_info, gathered_state_info, input_states, output_states
1536
+ )
1537
+
1538
+ if len(state_buffers) == 0:
1539
+ return output_states
1540
+
1541
+ has_state_params: list[bool] = [
1542
+ fqn in output_states for fqn, idx in fsdp_param_info.param_indices.items()
1543
+ ]
1544
+
1545
+ # Loop through the ``state_buffers`` and construct the flattened, concatenated,
1546
+ # sharded states. The size of the constructed state will be the same size as
1547
+ # flat_param (also sharded).
1548
+ # Then we perform an allgather_into_tensor to get the full flat_param state.
1549
+ # The full flat_param state is the result of concatenation of multiple states
1550
+ # the order of of flat_param._fqns.
1551
+ # The final step is to split the flat_param state into original param states
1552
+ # and return the result.
1553
+ flat_param = fsdp_param_info.handle.flat_param
1554
+ empty_func = functools.partial(
1555
+ torch.empty, dtype=dtype, device=fsdp_state.compute_device
1556
+ )
1557
+ gathered_tensor = empty_func(flat_param._padded_unsharded_size)
1558
+ # Synchronize can be slow but this will be easier for us to debug.
1559
+ fsdp_state._device_handle.synchronize()
1560
+ for state_name, buffers in state_buffers.items():
1561
+ local_buffers: list[torch.Tensor] = []
1562
+ begin = fsdp_state.rank * flat_param._sharded_size.numel()
1563
+ # End is inclusive.
1564
+ end = begin + flat_param._sharded_size.numel() - 1
1565
+ # param_idx corresponds to the parameter index in the FlatParameter.
1566
+ mem_offset, param_idx = 0, 0
1567
+ for numel, is_padding in zip(
1568
+ flat_param._numels_with_padding, flat_param._is_padding_mask
1569
+ ):
1570
+ frozen_and_no_state = not is_padding and (
1571
+ not fsdp_param_info.param_requires_grad[param_idx]
1572
+ and not has_state_params[param_idx]
1573
+ )
1574
+
1575
+ if is_padding or frozen_and_no_state:
1576
+ # This memory range is a padding or the param is frozen and does
1577
+ # not require gradient. For the later case, we treat it as a
1578
+ # padding and add empty values to the local_buffers.
1579
+
1580
+ padding_begin, padding_end = mem_offset, mem_offset + numel - 1
1581
+ if padding_begin <= begin <= padding_end:
1582
+ # The range is an align padding before the first parameter in
1583
+ # the shard. The shard includes parts of this align padding.
1584
+ padding_len = (
1585
+ padding_end - begin + 1
1586
+ if end >= padding_end
1587
+ else end - begin + 1
1588
+ )
1589
+ elif padding_begin <= end <= padding_end:
1590
+ # The range is an align padding after the last parameter in
1591
+ # the shard. The shard includes parts of this align padding.
1592
+ padding_len = (
1593
+ end - padding_begin + 1
1594
+ if begin <= padding_begin
1595
+ else end - begin + 1
1596
+ )
1597
+ elif begin < padding_begin <= padding_end < end:
1598
+ # The range is an align padding that is completely in the
1599
+ # shard.
1600
+ padding_len = numel
1601
+ else:
1602
+ padding_len = 0
1603
+ if padding_len:
1604
+ local_buffers.append(empty_func(padding_len))
1605
+
1606
+ if not is_padding:
1607
+ # This memory range is a parameter in FlatParameter. So there
1608
+ # should be an corresponding state in the optimizer unless the
1609
+ # parameter is frozen, which we treat it as a padding above.
1610
+
1611
+ # We need to check if this rank owns the buffer. If this is None:
1612
+ # 1.) the rank does not own any part of the original parameter.
1613
+ # As a result, there is no corresponding optimizer state on
1614
+ # the rank as well.
1615
+ # 2.) the parameter is frozen AND no optimizer state for the
1616
+ # parameter. If a parameter is frozen, there can still be
1617
+ # optimizer state if the parameter is not frozen in the
1618
+ # previous steps.
1619
+ if buffers[param_idx] is not None:
1620
+ local_buffers.append(cast(torch.Tensor, buffers[param_idx]))
1621
+ param_idx += 1
1622
+
1623
+ mem_offset += numel
1624
+
1625
+ shard_numel_padded = flat_param._sharded_size.numel() - (
1626
+ sum(t.numel() for t in local_buffers)
1627
+ )
1628
+
1629
+ if flat_param._shard_numel_padded != shard_numel_padded:
1630
+ raise AssertionError(
1631
+ "Manually calculated _sharded_numel_padded is incorrect. "
1632
+ f"_shard_numel_padded={flat_param._shard_numel_padded}, "
1633
+ f"shard_numel_padded={shard_numel_padded}, "
1634
+ f"_sharded_size.numel={flat_param._sharded_size.numel()}, "
1635
+ f"_numels_with_padding={flat_param._numels_with_padding}, "
1636
+ f"begin={begin}, end={end},"
1637
+ )
1638
+ if shard_numel_padded > 0:
1639
+ # Add right-handed padding.
1640
+ local_buffers.append(empty_func(shard_numel_padded))
1641
+ local_shard = torch.cat(local_buffers)
1642
+ if local_shard.numel() * fsdp_state.world_size != gathered_tensor.numel():
1643
+ raise AssertionError(
1644
+ "The size of local shard times the world size should equal to the "
1645
+ "gathered tensor size. The inconsistency may be from a bug of "
1646
+ "FlatParameter's metadata or the reconstruction logic in optimizer "
1647
+ "state dict."
1648
+ )
1649
+ fsdp_state._device_handle.synchronize()
1650
+ with SimpleProfiler.profile(SimpleProfiler.Type.ALLGATHER):
1651
+ dist.all_gather_into_tensor(
1652
+ gathered_tensor, local_shard, group=fsdp_state.process_group
1653
+ )
1654
+ # Synchronize can be slow but this will be easier for us to debug.
1655
+ fsdp_state._device_handle.synchronize()
1656
+
1657
+ unpadded_tensor = gathered_tensor[: flat_param._unpadded_unsharded_size.numel()]
1658
+ flat_param_handle = fsdp_param_info.handle
1659
+ orig_states = flat_param_handle._get_unflat_views_aligned(unpadded_tensor)
1660
+ if len(orig_states) != len(fsdp_param_info.param_indices):
1661
+ raise AssertionError(
1662
+ "The number of parameters from FlatParameter is not consistent to "
1663
+ "the number of states used by optimizer state dict reconstruction "
1664
+ "logic."
1665
+ )
1666
+ for fqn, idx in fsdp_param_info.param_indices.items():
1667
+ if fsdp_param_info.param_requires_grad[idx] or fqn in output_states:
1668
+ output_states[fqn][state_name] = orig_states[idx]
1669
+
1670
+ _unflatten_orig_param_states(
1671
+ fsdp_param_info,
1672
+ output_states,
1673
+ state_name,
1674
+ shard_state,
1675
+ to_save,
1676
+ cpu_offload,
1677
+ )
1678
+
1679
+ del gathered_tensor
1680
+ return output_states
1681
+
1682
+
1683
+ def _gather_all_orig_param_state(
1684
+ fsdp_param_info: FSDPParamInfo,
1685
+ input_states: dict[str, Any],
1686
+ shard_state: bool,
1687
+ to_save: bool,
1688
+ cpu_offload: bool,
1689
+ ) -> dict[str, Any]:
1690
+ """
1691
+ Given a optimizer state dict, ``input_states``, which the keys are FQNs to the
1692
+ original parameters (not FlatParameters nor parameter ID), gather all the
1693
+ states and unflatten them to the original dimensions. Note that all the
1694
+ params referred by the ``input_states`` must be managed by FSDP.
1695
+ """
1696
+ fsdp_state = fsdp_param_info.state
1697
+ if (
1698
+ fsdp_state.world_size == 1
1699
+ or fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD
1700
+ ):
1701
+ return input_states if to_save else {}
1702
+
1703
+ with SimpleProfiler.profile(SimpleProfiler.Type.RESHARDING):
1704
+ with SimpleProfiler.profile(SimpleProfiler.Type.ALLGATHER_OBJ):
1705
+ gathered_state_info = _allgather_state_info(fsdp_state, input_states)
1706
+ output_states = _allgather_orig_param_states(
1707
+ fsdp_param_info,
1708
+ gathered_state_info,
1709
+ input_states,
1710
+ shard_state,
1711
+ to_save,
1712
+ cpu_offload,
1713
+ )
1714
+ if to_save:
1715
+ for key, idx in fsdp_param_info.param_indices.items():
1716
+ if key in output_states:
1717
+ continue
1718
+ if not fsdp_param_info.param_requires_grad[idx]:
1719
+ continue
1720
+
1721
+ raise RuntimeError(
1722
+ f"{key} is not in the output state. "
1723
+ "The FSDPParamInfo has the param keys "
1724
+ f"{sorted(fsdp_param_info.param_indices.keys())} while "
1725
+ "the output_states has the param keys "
1726
+ f"{sorted(output_states.keys())}."
1727
+ )
1728
+ return output_states
1729
+ else:
1730
+ return {}
1731
+
1732
+
1733
+ def _convert_state_with_orig_params(
1734
+ all_optim_state_keys: list[_OptimStateKey],
1735
+ optim_state_key_to_param_key: dict[_OptimStateKey, int | str],
1736
+ fqn_to_fsdp_param_info: dict[str, FSDPParamInfo],
1737
+ optim_state_dict: dict[str | int, Any],
1738
+ to_save: bool,
1739
+ shard_state: bool,
1740
+ cpu_offload: bool = True,
1741
+ ) -> dict[str, Any]:
1742
+ fsdp_osd_state: dict[str, Any] = {}
1743
+ # This variable is used to deduplicate the FSDPParamInfo as one FSDPParamInfo
1744
+ # usually corresponds to multiple parameters. We could not use FSDPParamInfo
1745
+ # as the key because FSDPParamInfo is not hashable. As a result, we fall back
1746
+ # to `id(FSDPParamInfo)`, which the type is an integer.
1747
+ all_states: dict[int, dict[str, Any]] = {}
1748
+ # Iterate in rank 0's flat parameter ID order to ensure aligned all-gathers
1749
+ # across ranks
1750
+ for optim_state_key in all_optim_state_keys:
1751
+ param_key: str | int | None = optim_state_key_to_param_key.get(optim_state_key)
1752
+
1753
+ if param_key is None and not optim_state_key.is_fsdp_managed:
1754
+ continue
1755
+
1756
+ if optim_state_key.is_fsdp_managed:
1757
+ fqn = optim_state_key.unflat_param_names[0]
1758
+ fsdp_param_info = fqn_to_fsdp_param_info.get(fqn)
1759
+ if fsdp_param_info is None:
1760
+ # This can happen if the not all FSDP instances have all the
1761
+ # parameters. This can happen with FSDP + some MPMD style
1762
+ # parallelism.
1763
+
1764
+ # TODO: it is unclear if we need to do the same check with
1765
+ # non-FSDP managed keys.
1766
+ continue
1767
+ state = {} if param_key is None else optim_state_dict[param_key]
1768
+ if id(fsdp_param_info) not in all_states:
1769
+ all_states[id(fsdp_param_info)] = {}
1770
+ all_states[id(fsdp_param_info)][fqn] = state
1771
+
1772
+ elif to_save:
1773
+ if len(optim_state_key.unflat_param_names) != 1:
1774
+ raise AssertionError(
1775
+ f"Expected len(optim_state_key.unflat_param_names) == 1, got {len(optim_state_key.unflat_param_names)}"
1776
+ )
1777
+ unflat_param_name = optim_state_key.unflat_param_names[0]
1778
+ with SimpleProfiler.profile("none_fsdp_managed_copy"):
1779
+ param_key = cast(str | int, param_key)
1780
+ fsdp_osd_state[unflat_param_name] = copy.copy(
1781
+ optim_state_dict[param_key]
1782
+ )
1783
+ if cpu_offload:
1784
+ for state_name, value in sorted_items(
1785
+ fsdp_osd_state[unflat_param_name]
1786
+ ):
1787
+ if not torch.is_tensor(value):
1788
+ continue
1789
+ fsdp_osd_state[unflat_param_name][state_name] = value.cpu()
1790
+
1791
+ # Instead of gathering the state of each parameter individually, we perform
1792
+ # the gathering all at once to speed up the process.
1793
+ for _all_states in all_states.values():
1794
+ fqn = next(iter(_all_states.keys()))
1795
+ fsdp_param_info = fqn_to_fsdp_param_info[fqn]
1796
+ if len(fsdp_param_info.param_requires_grad) <= 0:
1797
+ raise AssertionError(
1798
+ "With use_orig_params, FSDPParamInfo should have requires_grad "
1799
+ "information. However, the length is zero."
1800
+ )
1801
+ for key, idx in fsdp_param_info.param_indices.items():
1802
+ if key in _all_states:
1803
+ continue
1804
+ if not fsdp_param_info.param_requires_grad[idx]:
1805
+ continue
1806
+ raise RuntimeError(
1807
+ f"{key} is not in the optimizer state. "
1808
+ "The FSDPParamInfo has the param keys "
1809
+ f"{sorted(fsdp_param_info.param_indices.keys())} while "
1810
+ "the optimizer has the param keys "
1811
+ f"{sorted(_all_states.keys())}."
1812
+ )
1813
+ fsdp_osd_state.update(
1814
+ _gather_all_orig_param_state(
1815
+ fsdp_param_info,
1816
+ _all_states,
1817
+ shard_state,
1818
+ to_save,
1819
+ cpu_offload,
1820
+ )
1821
+ )
1822
+
1823
+ return fsdp_osd_state
1824
+
1825
+
1826
+ def _convert_state_with_flat_params(
1827
+ all_optim_state_keys: list[_OptimStateKey],
1828
+ optim_state_key_to_param_key: dict[_OptimStateKey, int | str],
1829
+ fqn_to_fsdp_param_info: dict[str, FSDPParamInfo],
1830
+ optim_state_dict: dict[str | int, Any],
1831
+ to_save: bool,
1832
+ shard_state: bool,
1833
+ cpu_offload: bool = True,
1834
+ ) -> dict[str, Any]:
1835
+ fsdp_osd_state: dict[str, Any] = {}
1836
+ # Iterate in rank 0's flat parameter ID order to ensure aligned all-gathers
1837
+ # across ranks
1838
+ for optim_state_key in all_optim_state_keys:
1839
+ param_key: str | int | None = optim_state_key_to_param_key.get(optim_state_key)
1840
+
1841
+ if param_key is None:
1842
+ raise AssertionError(
1843
+ "If use_orig_params is False, we must be able to find the "
1844
+ f"corresponding param id. {optim_state_key} {param_key}"
1845
+ )
1846
+
1847
+ if optim_state_key.is_fsdp_managed:
1848
+ # If there are multiple unflat_param_names (not use_orig_params),
1849
+ # they share the same FSDPParamInfo. So the first unflat_param_name
1850
+ # is sufficient to fetch the FSDPParamInfo.
1851
+ fqn = optim_state_key.unflat_param_names[0]
1852
+ fsdp_param_info = fqn_to_fsdp_param_info[fqn]
1853
+ unflat_state = _unflatten_optim_state(
1854
+ fsdp_param_info,
1855
+ optim_state_dict[param_key],
1856
+ to_save,
1857
+ shard_state,
1858
+ cpu_offload,
1859
+ )
1860
+ if to_save:
1861
+ if len(unflat_state) != len(optim_state_key.unflat_param_names):
1862
+ raise AssertionError(
1863
+ f"Expected len(unflat_state) == len(optim_state_key.unflat_param_names), "
1864
+ f"got {len(unflat_state)} != {len(optim_state_key.unflat_param_names)}"
1865
+ )
1866
+ fsdp_osd_state.update(
1867
+ zip(
1868
+ optim_state_key.unflat_param_names,
1869
+ unflat_state,
1870
+ )
1871
+ )
1872
+ elif to_save:
1873
+ if len(optim_state_key.unflat_param_names) != 1:
1874
+ raise AssertionError(
1875
+ f"Expected len(optim_state_key.unflat_param_names) == 1, got {len(optim_state_key.unflat_param_names)}"
1876
+ )
1877
+ unflat_param_name = optim_state_key.unflat_param_names[0]
1878
+ fsdp_osd_state[unflat_param_name] = copy.copy(optim_state_dict[param_key])
1879
+ if cpu_offload:
1880
+ for state_name, value in sorted_items(
1881
+ fsdp_osd_state[unflat_param_name]
1882
+ ):
1883
+ if not torch.is_tensor(value):
1884
+ continue
1885
+ fsdp_osd_state[unflat_param_name][state_name] = value.cpu()
1886
+
1887
+ return fsdp_osd_state
1888
+
1889
+
1890
+ @torch.no_grad()
1891
+ def _optim_state_dict(
1892
+ model: nn.Module,
1893
+ optim: torch.optim.Optimizer,
1894
+ optim_state_dict: dict[str, Any],
1895
+ optim_input: list[dict[str, Any]] | Iterable[nn.Parameter] | None,
1896
+ rank0_only: bool,
1897
+ shard_state: bool,
1898
+ group: dist.ProcessGroup | None,
1899
+ using_optim_input: bool,
1900
+ use_orig_params: bool = False,
1901
+ cpu_offload: bool = True,
1902
+ ) -> dict[str, Any]:
1903
+ """
1904
+ Consolidates the optimizer state and returns it as a :class:`dict`
1905
+ following the convention of :meth:`torch.optim.Optimizer.state_dict`,
1906
+ i.e. with keys ``"state"`` and ``"param_groups"``.
1907
+ The flat parameters in ``FSDP`` modules contained in ``model`` are mapped
1908
+ back to their unflattened parameters.
1909
+
1910
+ Parameter keys are not well-defined. For a regular optimizer, the optimizer
1911
+ state_dict contains a mapping from parameter IDs to parameter states.
1912
+ Parameter IDs are the order of parameters in ``optim.param_groups()`` across
1913
+ all the groups. This API also allows user to pass ``optim_input`` for the
1914
+ mapping between parameters and parameter IDs. Using ``optim_input`` is being
1915
+ deprecated.
1916
+
1917
+ If the optimizer is a ``NamedOptimizer``, the optimizer state_dict does not
1918
+ contain parameter IDs mapping but a mapping from parameter FQNs to parameter
1919
+ states. This API finds the mapping from FQNs to parameters if the optimizer
1920
+ is a ``NamedOptimizer``.
1921
+
1922
+ If ``use_orig_params`` is True, each rank will have all FSDP-managed
1923
+ parameters but some of these parameters may be empty due to the sharding.
1924
+ For a regular optim.Optimizer, states for those empty parameters will
1925
+ not be initialized. So, when aggregating the FQNs across ranks, no assert
1926
+ will be raised on a rank even if it does not have all the states -- it is
1927
+ valid and FSDP knows how to aggregate them. However, FSDP has to ignore
1928
+ handling those parameters that are not managed by FSDP and do not exist on
1929
+ the local rank -- those are managed by other parallelisms and FSDP does not
1930
+ know how to handle/aggregate them.
1931
+
1932
+ Args:
1933
+ model (nn.Module): Root module (which may or may not be a
1934
+ :class:`FullyShardedDataParallel` instance) whose parameters
1935
+ were passed into the optimizer ``optim``.
1936
+ optim (torch.optim.Optimizer): Optimizer for ``model`` 's
1937
+ parameters.
1938
+ rank0_only (bool): If ``True``, saves the populated :class:`dict`
1939
+ only on rank 0; if ``False``, saves it on all ranks. (Default:
1940
+ ``True``)
1941
+ shard_state (bool): If ``True``, shard and distribute all
1942
+ non-zero-dimension states.
1943
+
1944
+ Returns:
1945
+ Dict[str, Any]: A :class:`dict` containing the optimizer state for
1946
+ ``model`` 's original unflattened parameters and including keys
1947
+ "state" and "param_groups" following the convention of
1948
+ :meth:`torch.optim.Optimizer.state_dict`. If ``rank0_only=False``,
1949
+ then nonzero ranks return an empty :class:`dict`.
1950
+ """
1951
+ SimpleProfiler.reset()
1952
+ cm = ExitStack()
1953
+ cm.enter_context(SimpleProfiler.profile(SimpleProfiler.Type.ALL))
1954
+ _reset_flat_param_grad_info_if_needed(traversal_utils._get_fsdp_handles(model))
1955
+ to_save = not rank0_only or dist.get_rank(group) == 0 or shard_state
1956
+
1957
+ with SimpleProfiler.profile("preprocessing"):
1958
+ param_to_fqns = _get_param_to_fqns(model)
1959
+ flat_param_to_fqn = _get_flat_param_to_fqn(model)
1960
+ is_named_optimizer = _is_named_optimizer(optim_state_dict)
1961
+
1962
+ param_key_to_param = cast(
1963
+ dict[int | str, nn.Parameter],
1964
+ (
1965
+ _get_param_id_to_param_from_optim_input(model, optim_input)
1966
+ if using_optim_input
1967
+ else _get_param_key_to_param(
1968
+ optim, model, is_named_optimizer, param_to_fqns, flat_param_to_fqn
1969
+ )
1970
+ ),
1971
+ )
1972
+ fqn_to_fsdp_param_info = _get_fqn_to_fsdp_param_info(model)
1973
+
1974
+ with SimpleProfiler.profile("preprocessing_with_comm"):
1975
+ (
1976
+ all_optim_state_keys,
1977
+ optim_state_key_to_param_key,
1978
+ ) = _map_param_key_to_optim_keys(
1979
+ optim_state_dict,
1980
+ group,
1981
+ param_key_to_param,
1982
+ param_to_fqns,
1983
+ fqn_to_fsdp_param_info,
1984
+ merge_keys=use_orig_params,
1985
+ )
1986
+
1987
+ with SimpleProfiler.profile("state_converting"):
1988
+ convert_fn = (
1989
+ _convert_state_with_orig_params
1990
+ if use_orig_params
1991
+ else _convert_state_with_flat_params
1992
+ )
1993
+ fsdp_osd_state = convert_fn(
1994
+ all_optim_state_keys,
1995
+ optim_state_key_to_param_key,
1996
+ fqn_to_fsdp_param_info,
1997
+ optim_state_dict["state"],
1998
+ to_save,
1999
+ shard_state,
2000
+ cpu_offload,
2001
+ )
2002
+
2003
+ # At this point, communication is complete and ranks can return early if nothing
2004
+ # will be saved on that rank.
2005
+ if not to_save:
2006
+ return {}
2007
+
2008
+ fsdp_osd: dict[str, Any] = {"state": fsdp_osd_state}
2009
+
2010
+ flat_param_fqns = set(flat_param_to_fqn.values())
2011
+ for key, value in optim_state_dict["state"].items():
2012
+ if key in fsdp_osd_state:
2013
+ continue
2014
+ if key in flat_param_fqns:
2015
+ continue
2016
+ if key in param_key_to_param:
2017
+ continue
2018
+ # This key is not recognized by FSDP. It may be a user-defined state
2019
+ # or some parameters state that FSDP is unable to map from
2020
+ # ``optim.param_groups``.
2021
+ warnings.warn(
2022
+ f"Found a optim state, {key}, that FSDP cannot process. FSDP "
2023
+ "will directly copy everything to the returned state_dict. In "
2024
+ "most cases, this is a user-defined state that is not "
2025
+ "associated with any particular parameter. Another possible "
2026
+ "case is this state is managed by TorchRec. Otherwise, there may "
2027
+ " be a mismatched assumption of optim_state_dict of this mode.",
2028
+ stacklevel=2,
2029
+ )
2030
+ fsdp_osd_state[key] = value
2031
+
2032
+ if "param_groups" in optim_state_dict:
2033
+ fsdp_osd["param_groups"] = _unflatten_param_groups(
2034
+ optim_state_dict, param_key_to_param, param_to_fqns
2035
+ )
2036
+
2037
+ cm.close()
2038
+ SimpleProfiler.dump_and_reset("FSDP _optim_state_dict() profiling: ")
2039
+
2040
+ return fsdp_osd
2041
+
2042
+
2043
+ def _get_fqn_to_fsdp_param_info(model: nn.Module) -> dict[str, FSDPParamInfo]:
2044
+ """
2045
+ Construct the mapping from a param's fqn to its corresponding ``FSDPParamInfo``
2046
+ if the param is managed by FSDP. Shared parameters, or original parameters that
2047
+ are shared across multiple nn.Modules, are required to belong to one and only
2048
+ one FSDP instance and thus correspond to one ``FlatParameter``. Within the one
2049
+ ``FlatParameter``, ``FlatParameter._fqns`` only stores the first FQN of a shared
2050
+ parameter. Thus, the keys in the mapping are guaranteed to map to unique parameters.
2051
+ """
2052
+
2053
+ def module_fn(module, prefix, tree_level, fqn_to_param_info):
2054
+ fsdp_state = _get_module_fsdp_state_if_fully_sharded_module(module)
2055
+ if fsdp_state is None:
2056
+ return
2057
+ _lazy_init(fsdp_state, module)
2058
+ handle = _module_handle(fsdp_state, module)
2059
+ if not handle:
2060
+ return
2061
+ flat_param = handle.flat_param
2062
+ fsdp_param_info = FSDPParamInfo(fsdp_state, handle, {}, [])
2063
+ # NOTE: `idx` indexes into the data structures *without* padding
2064
+ # elements
2065
+ for idx, local_fqn in enumerate(flat_param._fqns):
2066
+ fqn = clean_tensor_name(prefix + local_fqn)
2067
+ if fqn in fqn_to_param_info:
2068
+ if fqn_to_param_info[fqn].handle.flat_param is not flat_param:
2069
+ raise AssertionError(
2070
+ f"Expected fqn_to_param_info[fqn].handle.flat_param is flat_param for {fqn}"
2071
+ )
2072
+ fqn_to_param_info[fqn] = fsdp_param_info
2073
+ fsdp_param_info.param_indices[fqn] = idx
2074
+ if flat_param._params is not None:
2075
+ fsdp_param_info.param_requires_grad.append(
2076
+ flat_param._params[idx].requires_grad
2077
+ )
2078
+
2079
+ def return_fn(fqn_to_param_info):
2080
+ return fqn_to_param_info
2081
+
2082
+ fqn_to_param_info: dict[str, FSDPParamInfo] = {}
2083
+ # FlatParameter._fqns stores the local fqn, starting from the root of the
2084
+ # FSDP. Using _apply_to_modules() with model (may not be the FSDP root
2085
+ # module) allows us to construct the global fqn.
2086
+ return _apply_to_modules(
2087
+ model,
2088
+ module_fn,
2089
+ return_fn,
2090
+ [fqn for fqn, _ in _named_parameters_with_duplicates(model)],
2091
+ fqn_to_param_info,
2092
+ )
2093
+
2094
+
2095
+ @no_type_check
2096
+ def _set_optim_use_dtensor(
2097
+ fsdp_state: _FSDPState,
2098
+ state_dict_settings: StateDictSettings,
2099
+ ) -> None:
2100
+ # If device_mesh is passed in when initializing FSDP, we automatically turn the
2101
+ # _use_dtensor flag to be true for ShardedOptimStateDictConfig() if state_dict_type
2102
+ # has to be set to SHARDED_STATE_DICT.
2103
+ if getattr(fsdp_state, "_device_mesh", None):
2104
+ state_dict_type = state_dict_settings.state_dict_type
2105
+ if state_dict_type == StateDictType.LOCAL_STATE_DICT:
2106
+ raise RuntimeError(
2107
+ "Found state_dict_type LOCAL_STATE_DICT. "
2108
+ "DeviceMesh is not compatible with LOCAL_STATE_DICT. "
2109
+ "Please set state_dict_type to SHARDED_STATE_DICT to get DTensor state_dict."
2110
+ )
2111
+ else:
2112
+ state_dict_settings.optim_state_dict_config._use_dtensor = True
venv/lib/python3.14/site-packages/torch/distributed/fsdp/_runtime_utils.py ADDED
@@ -0,0 +1,1654 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import functools
3
+ import logging
4
+ from collections.abc import Callable
5
+ from enum import auto, Enum
6
+ from typing import Any, no_type_check
7
+
8
+ import torch
9
+ import torch.distributed as dist
10
+ import torch.distributed.fsdp._traversal_utils as traversal_utils
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+ from torch.autograd import Variable
14
+ from torch.autograd.graph import register_multi_grad_hook
15
+ from torch.distributed.algorithms._comm_hooks import LOW_PRECISION_HOOKS
16
+ from torch.distributed.fsdp._common_utils import (
17
+ _assert_in_training_states,
18
+ _FSDPState,
19
+ _get_module_fsdp_state,
20
+ _is_composable,
21
+ _log_post_backward_hook,
22
+ _no_dispatch_record_stream,
23
+ clean_tensor_name,
24
+ TrainingState,
25
+ )
26
+ from torch.distributed.fsdp._flat_param import (
27
+ FlatParameter,
28
+ FlatParamHandle,
29
+ HandleShardingStrategy,
30
+ HandleTrainingState,
31
+ RESHARD_AFTER_FORWARD_HANDLE_STRATEGIES,
32
+ )
33
+ from torch.distributed.fsdp._init_utils import HYBRID_SHARDING_STRATEGIES
34
+ from torch.distributed.fsdp.api import BackwardPrefetch
35
+ from torch.distributed.utils import (
36
+ _apply_to_tensors,
37
+ _cast_forward_inputs,
38
+ _p_assert,
39
+ _to_kwargs,
40
+ )
41
+ from torch.utils import _pytree as pytree
42
+
43
+
44
+ logger = logging.getLogger(__name__)
45
+
46
+ # Do not include "process_group" to enable hybrid shard and MoE cases
47
+ HOMOGENEOUS_ATTR_NAMES = (
48
+ "_use_orig_params",
49
+ "limit_all_gathers",
50
+ "_use_full_prec_in_eval",
51
+ )
52
+
53
+
54
+ class _PrefetchMode(Enum):
55
+ BACKWARD = auto()
56
+ FORWARD = auto()
57
+
58
+
59
+ def _get_fsdp_root_states_with_modules(
60
+ module: nn.Module,
61
+ ) -> tuple[list[_FSDPState], list[nn.Module]]:
62
+ """
63
+ Returns a tuple containing:
64
+ 1. A list of the root ``_FSDPState`` instances in the module tree rooted at
65
+ ``module`` without any duplicates and following the ``module.modules()``
66
+ traversal order (which is assumed to be depth-first).
67
+ 2. A corresponding list of the root modules owning the states in the first
68
+ list.
69
+
70
+ This is similar to :func:`_get_fsdp_states_with_modules` except that we
71
+ must call :func:`_is_fsdp_root` to force a lazy initialization to determine
72
+ the FSDP root in case lazy initialization has not yet happened.
73
+ """
74
+ fsdp_root_states: list[_FSDPState] = []
75
+ fsdp_root_modules: list[nn.Module] = []
76
+ visited_fsdp_states: set[_FSDPState] = set()
77
+ # NOTE: This function assumes that `module.modules()` proceeds top-down.
78
+ for submodule in module.modules():
79
+ optional_state = _get_module_fsdp_state(submodule)
80
+ if (
81
+ optional_state is not None
82
+ and optional_state not in visited_fsdp_states
83
+ and _is_fsdp_root(optional_state, submodule)
84
+ ):
85
+ visited_fsdp_states.add(optional_state)
86
+ fsdp_root_states.append(optional_state)
87
+ fsdp_root_modules.append(submodule)
88
+ return fsdp_root_states, fsdp_root_modules
89
+
90
+
91
+ def _get_fsdp_root_states(module: nn.Module) -> list[_FSDPState]:
92
+ """See :func:`_get_fsdp_root_states_with_modules`."""
93
+ fsdp_root_states, _ = _get_fsdp_root_states_with_modules(module)
94
+ return fsdp_root_states
95
+
96
+
97
+ def _is_fsdp_root(state: _FSDPState, module: nn.Module) -> bool:
98
+ """
99
+ Returns if ``state`` corresponds to that of an FSDP root.
100
+
101
+ For the wrapper code path, ``state`` and ``module`` should be the same. For
102
+ the non-wrapper code path, ``state`` should be ``module`` 's state.
103
+ """
104
+ # Force a lazy initialization to determine the FSDP root
105
+ _lazy_init(state, module)
106
+ if state._is_root is None:
107
+ raise AssertionError("Expected _is_root to be set after lazy init")
108
+ return state._is_root
109
+
110
+
111
+ @no_type_check
112
+ def _lazy_init(
113
+ state: _FSDPState,
114
+ root_module: nn.Module,
115
+ ) -> _FSDPState:
116
+ """
117
+ Performs initialization lazily, typically right before the first forward
118
+ pass. The laziness is needed to ensure that the parameter device/dtype and
119
+ the FSDP hierarchy have finalized. This method's actual logic only runs on
120
+ the root FSDP instance, which performs initialization for all non-root FSDP
121
+ instances to avoid partial initialization.
122
+
123
+ For the non-composable code path, ``state`` and ``root_module`` should be
124
+ the same, namely the FSDP instance itself.
125
+ """
126
+ if state._is_root is not None:
127
+ return # no-op: already lazily initialized
128
+ if not state._device_handle.is_available():
129
+ # Allow the FSDP constructor to run even without CUDA but check this
130
+ # once we start real execution
131
+ raise RuntimeError("FSDP does not support CPU only execution")
132
+ # The following logic is only run on the root FSDP instance since it will
133
+ # set `_is_root=False` for the non-root instances
134
+ state._is_root = True
135
+ _assert_in_training_states(state, [TrainingState.IDLE])
136
+ _check_flat_params_on_expected_device(state, root_module)
137
+ state._all_fsdp_states = traversal_utils._get_fsdp_states(root_module)
138
+ _init_streams(state)
139
+ buffers, buffer_dtypes = _get_buffers_and_dtypes_for_computation(state, root_module)
140
+ _cast_buffers_to_dtype_and_device(buffers, buffer_dtypes, state.compute_device)
141
+ state._exec_order_data.init(state, root_module, state.process_group)
142
+ _share_state_and_init_handle_attrs(state, root_module)
143
+ return state
144
+
145
+
146
+ def _check_flat_params_on_expected_device(state: _FSDPState, module: nn.Module):
147
+ """
148
+ Checks that all ``FlatParameter``s in ``module`` 's tree managed by
149
+ ``state`` are on the expected device for *lazy initialization*.
150
+ """
151
+ cpu_device = torch.device("cpu")
152
+ for handle in traversal_utils._get_fsdp_handles(module):
153
+ if (
154
+ not handle._offload_params
155
+ and handle.flat_param.device != state.compute_device
156
+ ):
157
+ raise RuntimeError(
158
+ "An FSDP-managed module unexpectedly has parameters on "
159
+ f"{handle.flat_param.device}. Make sure to move the module to "
160
+ f"{state.compute_device} before training."
161
+ )
162
+ elif handle._offload_params and handle.flat_param.device != cpu_device:
163
+ raise RuntimeError(
164
+ "An FSDP-managed module with parameter CPU offloading enabled "
165
+ f"has parameters on {handle.flat_param.device}. Make sure to "
166
+ f"not move the module from CPU when offloading parameters."
167
+ )
168
+
169
+
170
+ @no_type_check
171
+ def _share_state_and_init_handle_attrs(
172
+ root_state: _FSDPState,
173
+ root_module: nn.Module,
174
+ ) -> None:
175
+ """
176
+ Shares data structure state from the ``root_state`` to all FSDP states in
177
+ ``root_module`` 's module tree, and initializes handle attributes. These
178
+ are done together to require a single loop over the states.
179
+ """
180
+ handle = root_state._handle
181
+ if handle:
182
+ handle.init_flat_param_attributes()
183
+ attr_name_to_values: dict[str, set[Any]] = {}
184
+ for attr_name in HOMOGENEOUS_ATTR_NAMES:
185
+ attr_name_to_values[attr_name] = set()
186
+ root_state._all_handles = root_state._exec_order_data.all_handles # share reference
187
+ # Update _has_optim_in_backward for each handle.
188
+ for handle in root_state._all_handles:
189
+ flat_param = handle.flat_param
190
+ if hasattr(flat_param, "_in_backward_optimizers"):
191
+ raise RuntimeError(
192
+ "FSDP optimizer in backward only supported with use_orig_params=True!"
193
+ )
194
+ handle._has_optim_in_backward = flat_param._params is not None and any(
195
+ hasattr(param, "_in_backward_optimizers") for param in flat_param._params
196
+ )
197
+ if handle._has_optim_in_backward:
198
+ torch._C._log_api_usage_once("fsdp.optimizer_in_backward")
199
+ for fsdp_state in root_state._all_fsdp_states:
200
+ for attr_name in HOMOGENEOUS_ATTR_NAMES:
201
+ _p_assert(
202
+ hasattr(fsdp_state, attr_name),
203
+ f"FSDP state missing attribute {attr_name}",
204
+ )
205
+ attr_name_to_values[attr_name].add(getattr(fsdp_state, attr_name))
206
+ if fsdp_state is root_state:
207
+ continue
208
+ # Relax the assert for non-root FSDP instances in case the nested
209
+ # initialized module is wrapped again in FSDP later (e.g. after
210
+ # training to run inference)
211
+ _p_assert(
212
+ fsdp_state._is_root is None or not fsdp_state._is_root,
213
+ "Non-root FSDP instance's `_is_root` should not have been "
214
+ "set yet or should have been set to `False`",
215
+ )
216
+ fsdp_state._is_root = False
217
+ fsdp_state._unshard_stream = root_state._unshard_stream
218
+ fsdp_state._post_backward_stream = root_state._post_backward_stream
219
+ fsdp_state._pre_unshard_stream = root_state._pre_unshard_stream
220
+ fsdp_state._all_reduce_stream = root_state._all_reduce_stream
221
+ fsdp_state._default_stream = root_state._default_stream
222
+ fsdp_state._exec_order_data = root_state._exec_order_data
223
+ fsdp_state._free_event_queue = root_state._free_event_queue
224
+ if fsdp_state._fsdp_extension is not None:
225
+ fsdp_state._fsdp_extension.compute_stream = root_state._default_stream
226
+ handle = fsdp_state._handle
227
+ if handle:
228
+ handle.init_flat_param_attributes()
229
+ for attr_name, attr_values in attr_name_to_values.items():
230
+ if len(attr_values) != 1:
231
+ raise ValueError(
232
+ f"Expects one homogeneous value for {attr_name} but got {attr_values}"
233
+ )
234
+
235
+
236
+ @no_type_check
237
+ def _init_streams(
238
+ state: _FSDPState,
239
+ ) -> None:
240
+ """
241
+ Initializes CUDA streams for overlapping communication, computation, and
242
+ data transfers. The streams should be shared across FSDP instances.
243
+ """
244
+ if not state._is_root:
245
+ raise AssertionError("Expected state to be root")
246
+ if not state._device_handle.is_available():
247
+ raise AssertionError("Expected device handle to be available")
248
+ uses_hybrid_sharding = any(
249
+ fsdp_state.sharding_strategy in HYBRID_SHARDING_STRATEGIES
250
+ for fsdp_state in state._all_fsdp_states
251
+ )
252
+ # Prioritize all-gathers/reduce-scatters over async all-reduce for HSDP and
253
+ # preserve the default priority of 0 otherwise
254
+ high_priority = -1 if state.limit_all_gathers and uses_hybrid_sharding else 0
255
+ # Default stream for computation
256
+ state._default_stream = state._device_handle.current_stream()
257
+ if state._fsdp_extension is not None:
258
+ # set the compute stream to the FSDP extension
259
+ state._fsdp_extension.compute_stream = state._default_stream
260
+
261
+ # Stream for unshard logic, including allocating the all-gather destination
262
+ # tensors and the all-gathers themselves
263
+ state._unshard_stream = state._device_handle.Stream(priority=high_priority)
264
+ # Stream for overlapping gradient reduction with the backward pass gradient
265
+ # computation
266
+ state._post_backward_stream = state._device_handle.Stream(priority=high_priority)
267
+ # Stream for pre-unshard logic, namely allocations and writes for CPU
268
+ # offloading (H2D copy) and mixed precision (low precision cast)
269
+ state._pre_unshard_stream = state._device_handle.Stream(priority=high_priority)
270
+ # Stream to run HSDP's all-reduce as async (if using HSDP)
271
+ state._all_reduce_stream = (
272
+ state._device_handle.Stream() if uses_hybrid_sharding else state._default_stream
273
+ )
274
+
275
+
276
+ @no_type_check
277
+ def _unshard(
278
+ state: _FSDPState,
279
+ handle: FlatParamHandle,
280
+ unshard_stream: torch.Stream,
281
+ pre_unshard_stream: torch.Stream,
282
+ ) -> None:
283
+ """
284
+ Unshards the handles in ``handles``. If the handles are in
285
+ :meth:`summon_full_params` and are using mixed precision, then they are
286
+ forced to full precision.
287
+
288
+ Postcondition: handle's ``FlatParameter`` 's data is the padded
289
+ unsharded flat parameter on the compute device.
290
+ """
291
+ if not handle:
292
+ return
293
+ with state._device_handle.stream(pre_unshard_stream):
294
+ ran_pre_unshard = handle.pre_unshard()
295
+ if ran_pre_unshard:
296
+ unshard_stream.wait_stream(pre_unshard_stream)
297
+ if state.limit_all_gathers:
298
+ event = state._free_event_queue.dequeue_if_needed()
299
+ if event:
300
+ with torch.profiler.record_function(
301
+ "FullyShardedDataParallel.rate_limiter"
302
+ ):
303
+ event.synchronize()
304
+ with state._device_handle.stream(unshard_stream):
305
+ handle.unshard()
306
+ handle.post_unshard()
307
+
308
+
309
+ @no_type_check
310
+ def _reshard(
311
+ state: _FSDPState,
312
+ handle: FlatParamHandle,
313
+ free_unsharded_flat_param: bool,
314
+ ):
315
+ """
316
+ Reshards the handle. ``free_unsharded_flat_param`` indicates whether to
317
+ free the handle's padded unsharded flat parameter.
318
+ """
319
+ handle.reshard(free_unsharded_flat_param)
320
+ if state.limit_all_gathers and free_unsharded_flat_param:
321
+ if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
322
+ # We don't run a even queue for freeing under torch compile atm
323
+ # But maybe we need to? TODO(voz): Look into this
324
+ free_event = state._device_handle.Event()
325
+ free_event.record()
326
+ state._free_event_queue.enqueue(free_event)
327
+ handle.post_reshard()
328
+ # Flat parameter freed or not, we always have to "unshard" the parameter
329
+ # upon next access to get its shape correct.
330
+ handle._prefetched = False
331
+
332
+
333
+ def _unshard_grads(
334
+ handle: FlatParamHandle | None,
335
+ ) -> None:
336
+ if handle:
337
+ handle.unshard_grad()
338
+
339
+
340
+ def _reshard_grads(
341
+ handle: FlatParamHandle | None,
342
+ ) -> None:
343
+ if handle:
344
+ handle.reshard_grad()
345
+
346
+
347
+ @no_type_check
348
+ def _pre_forward(
349
+ state: _FSDPState,
350
+ handle: FlatParamHandle | None,
351
+ unshard_fn: Callable,
352
+ module: nn.Module,
353
+ args: tuple[Any, ...],
354
+ kwargs: dict[str, Any],
355
+ ) -> tuple[tuple[Any, ...], dict[str, Any]]:
356
+ """
357
+ Runs the pre-forward logic. This includes an opportunity to unshard
358
+ currently sharded parameters such as those for the current forward and
359
+ registering post-backward hooks for these current parameters. This function
360
+ also converts forward ``args`` and ``kwargs`` to the given precision.
361
+
362
+ Args:
363
+ handles (List[FlatParamHandle]): Handles giving the parameters used in
364
+ the current forward.
365
+ unshard_fn (Optional[Callable]): A callable to unshard any currently
366
+ sharded parameters or ``None`` to not do any unsharding.
367
+ module (nn.Module): Module whose forward this method runs right before;
368
+ expected by the hook signature.
369
+ args (Tuple[Any, ...]): Module forward ``args``.
370
+ kwargs (Dict[str, Any]): Module forward ``kwargs``.
371
+ """
372
+ with torch.profiler.record_function("FullyShardedDataParallel._pre_forward"):
373
+ # For `fully_shard` + `checkpoint`, skip pre-forward logic in the
374
+ # recomputed forward
375
+ if handle and handle._training_state == HandleTrainingState.BACKWARD_PRE:
376
+ # For both checkpoint implementations, we do not need to re-cast
377
+ # inputs here since they will be checkpointed in the low precision
378
+ # either by AC or normally by autograd as long as the AC region is
379
+ # nested within FSDP
380
+ return args, kwargs
381
+ state.training_state = TrainingState.FORWARD_BACKWARD
382
+ state._exec_order_data.record_pre_forward(handle, module.training)
383
+ if handle:
384
+ handle._training_state = HandleTrainingState.FORWARD
385
+ if unshard_fn is not None:
386
+ unshard_fn(state, handle)
387
+ # Register post-backward hooks to reshard the parameters and reduce-scatter
388
+ # their gradients. They must be re-registered every forward pass in case
389
+ # the `grad_fn` is mutated.
390
+ _register_post_backward_hook(state, handle)
391
+ # We have to reallocate the _cpu_grad if optimizer overlap
392
+ # set the grad to None in the backward pass.
393
+ if handle and handle._offload_params and handle.flat_param._cpu_grad is None:
394
+ handle.flat_param._cpu_grad = torch.zeros_like(
395
+ handle.flat_param._local_shard, device=torch.device("cpu")
396
+ ).pin_memory()
397
+
398
+ should_cast_forward_inputs = (
399
+ state._handle and not state._handle._force_full_precision
400
+ )
401
+
402
+ if should_cast_forward_inputs and state.mixed_precision.cast_forward_inputs:
403
+ # Recursively convert args and kwargs to specified precision.
404
+ input_dtype: torch.dtype | None = state.mixed_precision.param_dtype
405
+ args, kwargs = _cast_forward_inputs(input_dtype, *args, **kwargs)
406
+ _register_post_backward_reshard_only_hook(state, handle, args, kwargs)
407
+ return args, kwargs
408
+
409
+
410
+ @no_type_check
411
+ def _pre_forward_unshard(
412
+ state: _FSDPState,
413
+ handle: FlatParamHandle | None,
414
+ ) -> None:
415
+ """Unshards parameters in the pre-forward."""
416
+ if not handle:
417
+ return
418
+ # If the handles have been prefetched, then there is no need to call
419
+ # `_unshard()` again
420
+ if not handle._prefetched:
421
+ _unshard(state, handle, state._unshard_stream, state._pre_unshard_stream)
422
+ handle._needs_pre_forward_unshard = False
423
+ # Don't wait during trace
424
+ if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
425
+ current_stream = state._device_handle.current_stream()
426
+ if state._unshard_event is not None:
427
+ current_stream.wait_event(state._unshard_event)
428
+ state._unshard_event = None
429
+ else:
430
+ current_stream.wait_stream(state._unshard_stream)
431
+ with torch.profiler.record_function(
432
+ "FullyShardedDataParallel._pre_forward_prefetch"
433
+ ):
434
+ _prefetch_handle(state, handle, _PrefetchMode.FORWARD)
435
+
436
+
437
+ @no_type_check
438
+ def _post_forward(
439
+ state: _FSDPState,
440
+ handle: FlatParamHandle | None,
441
+ reshard_fn: Callable,
442
+ module: nn.Module,
443
+ input: Any,
444
+ output: Any,
445
+ ) -> Any:
446
+ """
447
+ Runs the post-forward logic. This includes an opportunity to reshard
448
+ currently unsharded parameters such as those used in the current forward
449
+ and registering pre-backward hooks on the forward outputs.
450
+
451
+ Args:
452
+ handles (List[FlatParamHandle]): Handles giving the parameters used in
453
+ the current forward.
454
+ reshard_fn (Optional[Callable]): A callable to reshard any currently
455
+ unsharded parameters (e.g. from the current forward) or ``None`` to
456
+ not do any resharding.
457
+ module (nn.Module): Module whose forward just ran, which should be a
458
+ fully sharded module (see [Note: Fully Sharded Module]); expected
459
+ by the hook signature.
460
+ input (Any): Unused; expected by the hook signature.
461
+ output (Any): Forward pass output; pre-backward hooks are registered on
462
+ the tensors that require gradients in this output.
463
+
464
+ Postcondition: Each ``FlatParameter`` 's data points to the sharded flat
465
+ parameter.
466
+ """
467
+ with torch.profiler.record_function("FullyShardedDataParallel._post_forward"):
468
+ # For `fully_shard` + `checkpoint`, skip post-forward logic in the
469
+ # recomputed forward
470
+ if handle and handle._training_state == HandleTrainingState.BACKWARD_PRE:
471
+ return output
472
+
473
+ state._exec_order_data.record_post_forward(handle)
474
+ if reshard_fn is not None:
475
+ reshard_fn(state, handle)
476
+ # Register pre-backward hooks to unshard the flat parameters for the
477
+ # gradient computation (if needed)
478
+ output = _register_pre_backward_hooks(state, module, output, handle)
479
+ state.training_state = TrainingState.IDLE
480
+ if handle:
481
+ handle._training_state = HandleTrainingState.IDLE
482
+ return output
483
+
484
+
485
+ @no_type_check
486
+ def _post_forward_reshard(
487
+ state: _FSDPState,
488
+ handle: FlatParamHandle,
489
+ ) -> None:
490
+ """Reshards parameters in the post-forward."""
491
+ if not handle:
492
+ return
493
+ # Do not free the root's parameters in the post-forward for `FULL_SHARD`
494
+ # with the intention that they are immediately used for backward
495
+ # computation (though this may not be true)
496
+ free_unsharded_flat_param = (
497
+ not state._is_root
498
+ and handle._sharding_strategy in RESHARD_AFTER_FORWARD_HANDLE_STRATEGIES
499
+ )
500
+ _reshard(state, handle, free_unsharded_flat_param)
501
+
502
+
503
+ @no_type_check
504
+ def _root_pre_forward(
505
+ state: _FSDPState,
506
+ module: nn.Module,
507
+ args,
508
+ kwargs,
509
+ ) -> None:
510
+ """
511
+ Runs pre-forward logic specific to the root FSDP instance, which should run
512
+ before any individual module's pre-forward. This starts with an attempt at
513
+ lazy initialization (which only runs non-vacuously once). Otherwise, if
514
+ this is called on a non-root FSDP instance, then it returns directly.
515
+
516
+ Args:
517
+ module (nn.Module): Module for which this logic tries to run. It may or
518
+ may not be the root. If not, then this method does not do anything.
519
+ """
520
+ with torch.profiler.record_function("FullyShardedDataParallel._root_pre_forward"):
521
+ _lazy_init(state, module)
522
+ _p_assert(state._is_root is not None, "Expects a root FSDP to have been set")
523
+ if not state._is_root:
524
+ # Always cast forward inputs in the root of this local FSDP unit for mixed
525
+ # precision, as this is where mixed precision could be configured.
526
+ # This is more useful for auto wrapping that is recommended in composable path.
527
+ # For manual wrapping, cast forward inputs on each local FSDP unit root will
528
+ # increase some overhead, so not turned on for model wrapper path right now where
529
+ # manual wrapping is more broadly used.
530
+ if _is_composable(state):
531
+ return _root_cast_forward_input(state, module, args, kwargs)
532
+ return args, kwargs
533
+
534
+ # We cast buffers back to full precision if we're forcing full precision. Disjointly, we check if buffers
535
+ # are in full precision and if we should cast them back to lower precision, which happens when
536
+ # exiting eval() mode.
537
+ handle = state._handle
538
+ if handle:
539
+ should_cast_buffers_to_full_prec = handle._force_full_precision
540
+ else:
541
+ # If the root has no handle (no managed parameters), then we fall
542
+ # back to checking if any child wants to force full precision as a
543
+ # workaround
544
+ handles = traversal_utils._get_fsdp_handles(module)
545
+ should_cast_buffers_to_full_prec = any(
546
+ handle._force_full_precision for handle in handles
547
+ )
548
+
549
+ if should_cast_buffers_to_full_prec:
550
+ _cast_buffers_to_dtype_and_device(
551
+ buffers=dict(module.named_buffers()).values(),
552
+ buffer_dtypes=list(state._buffer_name_to_orig_dtype.values()),
553
+ device=state.compute_device,
554
+ )
555
+ # This flag is only set when we cast buffers to full precision, to avoid the
556
+ # CPU overhead that can stem from retrieving all buffers and their types in the
557
+ # following else branch.
558
+ state._needs_buffer_dtype_restore_check = True
559
+ elif getattr(state, "_needs_buffer_dtype_restore_check", False):
560
+ # Check if buffers are in full precision and we need to cast them
561
+ # back down.
562
+ (
563
+ buffers,
564
+ buffer_dtypes_for_computation,
565
+ ) = _get_buffers_and_dtypes_for_computation(state, module)
566
+ if len(buffers) > 0 and len(buffer_dtypes_for_computation) > 0:
567
+ if any(
568
+ buffer.dtype != buffer_dtype_for_computation
569
+ for buffer, buffer_dtype_for_computation in zip(
570
+ buffers, buffer_dtypes_for_computation
571
+ )
572
+ ):
573
+ # Assume we have to cast everything if there is one mismatch
574
+ _cast_buffers_to_dtype_and_device(
575
+ buffers, buffer_dtypes_for_computation, state.compute_device
576
+ )
577
+ # We don't have to check this again until we cast buffers to full precision again.
578
+ state._needs_buffer_dtype_restore_check = False
579
+
580
+ if state.forward_prefetch:
581
+ handles = [
582
+ fsdp_state._handle
583
+ for fsdp_state in state._all_fsdp_states
584
+ if fsdp_state._handle
585
+ ]
586
+ for handle in handles:
587
+ handle._needs_pre_forward_unshard = True
588
+ handle._prefetched = False
589
+ _wait_for_computation_stream(
590
+ state._device_handle.current_stream(),
591
+ state._unshard_stream,
592
+ state._pre_unshard_stream,
593
+ )
594
+ _reset_flat_param_grad_info_if_needed(state._all_handles)
595
+
596
+ # Prepares the forward inputs by moving them to ``compute_device``
597
+ # TODO: Do not use the side stream for tensor copies for now; investigate
598
+ # the perf with/without it.
599
+ with torch.profiler.record_function("FullyShardedDataParallel._to_kwargs"):
600
+ args_tuple, kwargs_tuple = _to_kwargs(
601
+ args, kwargs, state.compute_device, False
602
+ )
603
+ args = args_tuple[0] if args_tuple else ()
604
+ kwargs = kwargs_tuple[0] if kwargs_tuple else {}
605
+
606
+ return _root_cast_forward_input(state, module, args, kwargs)
607
+
608
+
609
+ @no_type_check
610
+ def _root_cast_forward_input(
611
+ state: _FSDPState, module: torch.nn.Module, args, kwargs
612
+ ) -> tuple[Any, Any]:
613
+ if state._handle:
614
+ force_full_precision = not state._handle._force_full_precision
615
+ else:
616
+ force_full_precision = True
617
+
618
+ should_cast_forward_inputs = (
619
+ (module.training or not state._use_full_prec_in_eval) and force_full_precision
620
+ ) and state.mixed_precision.cast_root_forward_inputs
621
+
622
+ if should_cast_forward_inputs:
623
+ input_dtype: torch.dtype | None = state.mixed_precision.param_dtype
624
+ args, kwargs = _cast_forward_inputs(input_dtype, *args, **kwargs)
625
+
626
+ return args, kwargs
627
+
628
+
629
+ @no_type_check
630
+ def _pre_backward_hook(
631
+ state: _FSDPState,
632
+ module: nn.Module,
633
+ handle: FlatParamHandle,
634
+ grad,
635
+ *unused: Any,
636
+ ) -> Any:
637
+ """
638
+ Prepares ``_handle`` 's ``FlatParameter`` s for gradient computation.
639
+
640
+ Args:
641
+ module (nn.Module): Fully sharded module (see [Note: Fully Sharded
642
+ Module]).
643
+ """
644
+ # Only run the pre-backward hook once per group of handles involved in the
645
+ # same module forward computation
646
+ if (
647
+ handle
648
+ and hasattr(handle, "_ran_pre_backward_hook")
649
+ and handle._ran_pre_backward_hook
650
+ ):
651
+ return grad
652
+
653
+ with torch.profiler.record_function("FullyShardedDataParallel._pre_backward_hook"):
654
+ # Queue the post-backward callback once for the root FSDP instance to
655
+ # attach it to the outermost backward graph task so that it is called
656
+ # after all backward calls complete
657
+ if state._is_root and not state._post_backward_callback_queued:
658
+ _register_post_backward_final_callback(state, module)
659
+ _reset_flat_param_grad_info_if_needed(state._all_handles)
660
+ elif handle:
661
+ allowed_states = [TrainingState.IDLE]
662
+ if _is_composable(state):
663
+ allowed_states.append(TrainingState.FORWARD_BACKWARD)
664
+ _assert_in_training_states(state, allowed_states)
665
+ state.training_state = TrainingState.FORWARD_BACKWARD
666
+ # Queueing the post-backward callback is the only logic that is not
667
+ # per-handle in the pre-backward hook, so we can return early here if
668
+ # there are no handles.
669
+ if not handle:
670
+ return grad
671
+ handle._training_state = HandleTrainingState.BACKWARD_PRE
672
+
673
+ if handle._needs_pre_backward_unshard:
674
+ # If the handles have been prefetched, then there is no need to
675
+ # call `_unshard()` again
676
+ if not handle._prefetched:
677
+ _unshard(
678
+ state,
679
+ handle,
680
+ state._unshard_stream,
681
+ state._pre_unshard_stream,
682
+ )
683
+ # Don't wait during trace
684
+ if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
685
+ state._device_handle.current_stream().wait_stream(state._unshard_stream)
686
+
687
+ # Set this to `False` to ensure that a mistargeted prefetch does not
688
+ # actually unshard these handles
689
+ handle._needs_pre_backward_unshard = False
690
+ with torch.profiler.record_function(
691
+ "FullyShardedDataParallel._pre_backward_prefetch"
692
+ ):
693
+ _prefetch_handle(state, handle, _PrefetchMode.BACKWARD)
694
+ handle.prepare_gradient_for_backward()
695
+ handle._ran_pre_backward_hook = True
696
+ return grad
697
+
698
+
699
+ @no_type_check
700
+ @torch.no_grad()
701
+ def _post_backward_hook(
702
+ state: _FSDPState,
703
+ handle: FlatParamHandle,
704
+ flat_param,
705
+ *unused: Any,
706
+ ):
707
+ """
708
+ Reduce-scatters the gradient of ``handle`` 's ``FlatParameter``.
709
+
710
+ Precondition: The ``FlatParameter`` 's ``.grad`` attribute contains the
711
+ unsharded gradient for the local batch.
712
+
713
+ Postcondition:
714
+ - If using ``NO_SHARD``, then the ``.grad`` attribute is the reduced
715
+ unsharded gradient.
716
+ - Otherwise, the ``_saved_grad_shard`` attribute is the reduced sharded
717
+ gradient (accumulating with any existing gradient).
718
+ """
719
+ _log_post_backward_hook(state, handle, logger)
720
+ flat_param = handle.flat_param
721
+ flat_param._post_backward_called = True
722
+ with torch.autograd.profiler.record_function(
723
+ "FullyShardedDataParallel._post_backward_hook"
724
+ ):
725
+ _assert_in_training_states(state, [TrainingState.FORWARD_BACKWARD])
726
+ # For multiple applications of reentrant AC across submodules sharing
727
+ # the same `FlatParameter`, the post-backward hook may run multiple
728
+ # times in one backward, in which case we permit the state to already
729
+ # be in `BACKWARD_POST`.
730
+ _p_assert(
731
+ handle._training_state
732
+ in (HandleTrainingState.BACKWARD_PRE, HandleTrainingState.BACKWARD_POST),
733
+ f"Expects `BACKWARD_PRE` or `BACKWARD_POST` state but got {handle._training_state}",
734
+ )
735
+ handle._training_state = HandleTrainingState.BACKWARD_POST
736
+
737
+ if flat_param.grad is None:
738
+ return
739
+ if flat_param.grad.requires_grad:
740
+ raise RuntimeError("FSDP does not support gradients of gradients")
741
+
742
+ _post_backward_reshard(state, handle)
743
+ if not state._sync_gradients:
744
+ if handle._use_orig_params:
745
+ handle._use_unsharded_grad_views()
746
+ return
747
+
748
+ # Wait for all ops in the current stream (e.g. gradient computation) to
749
+ # finish before reduce-scattering the gradient
750
+ if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
751
+ state._post_backward_stream.wait_stream(
752
+ state._device_handle.current_stream()
753
+ )
754
+
755
+ with state._device_handle.stream(state._post_backward_stream):
756
+ autograd_computed_grad = flat_param.grad.data
757
+ if (
758
+ not _low_precision_hook_enabled(state)
759
+ and flat_param.grad.dtype != handle._reduce_dtype
760
+ # If we are forcing full precision but communicating grads
761
+ # (i.e. model.eval() + full precision in eval was configured), don't downcast gradient.
762
+ and not handle._force_full_precision
763
+ ):
764
+ flat_param.grad.data = flat_param.grad.to(handle._reduce_dtype)
765
+ if handle.uses_sharded_strategy:
766
+ _reduce_grad(state, handle)
767
+ else:
768
+ _reduce_grad_no_shard(state, handle)
769
+ # Since the unsharded gradient is produced in the computation
770
+ # stream and consumed in the post-backward stream, inform the
771
+ # caching allocator (before it goes out of scope)
772
+ _no_dispatch_record_stream(
773
+ autograd_computed_grad, state._post_backward_stream
774
+ )
775
+
776
+
777
+ def _post_backward_reshard_only_hook(
778
+ state: _FSDPState,
779
+ handle: FlatParamHandle,
780
+ *unused: Any,
781
+ ) -> None:
782
+ with torch.profiler.record_function(
783
+ "FullyShardedDataParallel._post_backward_hook_reshard_only"
784
+ ):
785
+ # `_pre_backward_hook` may not get executed
786
+ # if forward output does not require grad
787
+ # overwrite IDLE state for post-backward prefetching
788
+ state.training_state = TrainingState.FORWARD_BACKWARD
789
+ handle._training_state = HandleTrainingState.BACKWARD_POST
790
+ _post_backward_reshard(state, handle)
791
+
792
+
793
+ def _post_backward_reshard(
794
+ state: _FSDPState,
795
+ handle: FlatParamHandle,
796
+ *unused: Any,
797
+ ) -> None:
798
+ free_unsharded_flat_param = _should_free_in_backward(state, handle)
799
+ _reshard(state, handle, free_unsharded_flat_param)
800
+
801
+ # TODO: Post-backward prefetching does not support the multiple handles
802
+ # per module case since the post-backward hook runs per handle, not per
803
+ # group of handles.
804
+ with torch.profiler.record_function(
805
+ "FullyShardedDataParallel._post_backward_prefetch"
806
+ ):
807
+ _prefetch_handle(state, handle, _PrefetchMode.BACKWARD)
808
+
809
+
810
+ @no_type_check
811
+ def _should_free_in_backward(
812
+ state: _FSDPState,
813
+ handle: FlatParamHandle,
814
+ ) -> bool:
815
+ """
816
+ Returns whether FSDP should free the unsharded flat parameter in the
817
+ post-backward or not.
818
+ """
819
+ if not handle.uses_sharded_strategy:
820
+ return False
821
+ # If not syncing gradients, then we do not free for strategies that do not
822
+ # reshard after forward as a *heuristic* to tradeoff higher memory for
823
+ # higher throughput.
824
+ return (
825
+ state._sync_gradients
826
+ or handle._sharding_strategy in RESHARD_AFTER_FORWARD_HANDLE_STRATEGIES
827
+ )
828
+
829
+
830
+ @no_type_check
831
+ def _reduce_grad(state: _FSDPState, handle: FlatParamHandle) -> None:
832
+ """
833
+ For sharded strategies, this runs gradient reduction, sharded gradient
834
+ accumulation if needed, and the post-reduction callback.
835
+ """
836
+ flat_param = handle.flat_param
837
+ uses_hybrid_sharded_strategy = handle._sharding_strategy in (
838
+ HandleShardingStrategy.HYBRID_SHARD,
839
+ HandleShardingStrategy._HYBRID_SHARD_ZERO2,
840
+ )
841
+ # We clear `.grad` to permit multiple backwards. This avoids a race where
842
+ # the second backward pass computation precedes ahead of the first backward
843
+ # pass reduction, which is possible since the reduction is issued in a
844
+ # separate stream and is async and would result in reducing the wrong
845
+ # gradient.
846
+ unsharded_grad = flat_param.grad.data
847
+ flat_param.grad = None
848
+ padded_unsharded_grad, new_sharded_grad = _get_reduce_scatter_tensors(
849
+ state, unsharded_grad
850
+ )
851
+ if state._comm_hook is None: # default path
852
+ _div_if_needed(padded_unsharded_grad, state._gradient_predivide_factor)
853
+ pg = (
854
+ handle._fake_process_group
855
+ if handle._use_fake_reduce
856
+ else state.process_group
857
+ )
858
+ dist.reduce_scatter_tensor(
859
+ new_sharded_grad,
860
+ padded_unsharded_grad,
861
+ group=pg,
862
+ )
863
+ if uses_hybrid_sharded_strategy:
864
+ # Don't wait during trace
865
+ if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
866
+ state._all_reduce_stream.wait_stream(state._post_backward_stream)
867
+ with state._device_handle.stream(state._all_reduce_stream):
868
+ # Since the new sharded gradient is produced in the post-
869
+ # backward stream and consumed in the all-reduce stream,
870
+ # inform the caching allocator
871
+ _no_dispatch_record_stream(new_sharded_grad, state._all_reduce_stream)
872
+ dist.all_reduce(new_sharded_grad, group=state._inter_node_pg)
873
+ _div_if_needed(new_sharded_grad, state._gradient_postdivide_factor)
874
+ grad_to_offload = _accumulate_sharded_grad(
875
+ state, handle, new_sharded_grad
876
+ )
877
+ _post_reduce_grad_callback(state, handle, grad_to_offload)
878
+ return
879
+ _div_if_needed(new_sharded_grad, state._gradient_postdivide_factor)
880
+ else:
881
+ state._comm_hook(
882
+ state._comm_hook_state, padded_unsharded_grad, new_sharded_grad
883
+ )
884
+ # NOTE: HSDP variants do not support communication hook.
885
+ grad_to_offload = _accumulate_sharded_grad(state, handle, new_sharded_grad)
886
+ _post_reduce_grad_callback(state, handle, grad_to_offload)
887
+
888
+
889
+ @no_type_check
890
+ def _get_reduce_scatter_tensors(
891
+ state: _FSDPState, unsharded_grad: torch.Tensor
892
+ ) -> tuple[torch.Tensor, torch.Tensor]:
893
+ """
894
+ Returns the input and output tensors to reduce-scatter, respectively.
895
+ """
896
+ chunks = list(unsharded_grad.chunk(state.world_size))
897
+ numel_to_pad = state.world_size * chunks[0].numel() - unsharded_grad.numel()
898
+ padded_unsharded_grad = (
899
+ F.pad(unsharded_grad, [0, numel_to_pad]) if numel_to_pad > 0 else unsharded_grad
900
+ )
901
+ new_sharded_grad = torch.empty_like(chunks[0]) # padded
902
+ return padded_unsharded_grad, new_sharded_grad
903
+
904
+
905
+ @no_type_check
906
+ def _accumulate_sharded_grad(
907
+ state: _FSDPState,
908
+ handle: FlatParamHandle,
909
+ sharded_grad: torch.Tensor,
910
+ ) -> torch.Tensor:
911
+ """
912
+ Accumulates the reduce-scattered sharded gradient with any existing sharded
913
+ gradient if needed, returning the gradient to offload (if CPU offloading is
914
+ enabled).
915
+ """
916
+ flat_param = handle.flat_param
917
+ _cast_grad_to_param_dtype(state, sharded_grad, flat_param)
918
+ # Save the sharded gradient in `_saved_grad_shard` to support gradient
919
+ # accumulation -- for multiple backwards, the gradient reductions may
920
+ # happen in arbitrary order
921
+ accumulate_grad = hasattr(flat_param, "_saved_grad_shard")
922
+ if accumulate_grad:
923
+ _check_grad_to_accumulate(sharded_grad, flat_param._saved_grad_shard)
924
+ flat_param._saved_grad_shard += sharded_grad
925
+ else:
926
+ flat_param._saved_grad_shard = sharded_grad
927
+ grad_to_offload = flat_param._saved_grad_shard
928
+ return grad_to_offload
929
+
930
+
931
+ @no_type_check
932
+ def _reduce_grad_no_shard(state: _FSDPState, handle: FlatParamHandle) -> None:
933
+ """
934
+ For no-shard, this runs gradient reduction (which directly covers any
935
+ gradient accumulation implicitly) and the post-reduction callback.
936
+ """
937
+ flat_param = handle.flat_param
938
+ if state._comm_hook is None: # default path
939
+ _div_if_needed(flat_param.grad, state._gradient_predivide_factor)
940
+ dist.all_reduce(flat_param.grad, group=state.process_group)
941
+ _div_if_needed(flat_param.grad, state._gradient_postdivide_factor)
942
+ else:
943
+ state._comm_hook(state._comm_hook_state, flat_param.grad)
944
+ # For `NO_SHARD`, we can keep the low precision gradients by simply
945
+ # omitting the cast altogether
946
+ if not handle._keep_low_precision_grads:
947
+ _cast_grad_to_param_dtype(state, flat_param.grad, flat_param)
948
+ grad_to_offload = flat_param.grad.data
949
+ _post_reduce_grad_callback(state, handle, grad_to_offload)
950
+
951
+
952
+ @no_type_check
953
+ def _post_reduce_grad_callback(
954
+ state: _FSDPState,
955
+ handle: FlatParamHandle,
956
+ # Additional arguments needed for the callback logic
957
+ grad_to_offload: torch.Tensor,
958
+ ):
959
+ """
960
+ This callback captures any logic to run after the gradient reduction
961
+ finishes. Currently, this offloads the gradient to CPU if CPU offloading is
962
+ enabled and uses sharded gradient views if ``use_orig_params=True``.
963
+ """
964
+ _offload_grad(state, handle, grad_to_offload)
965
+ _post_backward_use_sharded_grad_views(handle)
966
+
967
+
968
+ @no_type_check
969
+ def _offload_grad(
970
+ state: _FSDPState,
971
+ handle: FlatParamHandle,
972
+ grad_to_offload: torch.Tensor,
973
+ ):
974
+ if not handle._offload_params:
975
+ return
976
+ # Offload the gradient to CPU to ensure parameters and gradients are on the
977
+ # same device as required by the optimizer
978
+ # TODO: Investigate why `NO_SHARD` breaks correctness when using
979
+ # `non_blocking=True` here.
980
+ # TODO (rohan-varma): When CPU offload and optimizer overlap,
981
+ # non_blocking=True won't work since the copy may have not finished before
982
+ # the optimizer step executes on CPU. If we want to use non-blocking=True
983
+ # here, we'll have to synchronize before using result on CPU.
984
+ non_blocking = handle.uses_sharded_strategy and not handle._has_optim_in_backward
985
+ handle.flat_param._cpu_grad.copy_(
986
+ grad_to_offload.detach(), non_blocking=non_blocking
987
+ ) # synchronized in the post-backward callback
988
+ # Since the gradient being offloaded may have been produced in the
989
+ # computation stream and is being consumed here in the post-backward
990
+ # stream, inform the caching allocator
991
+ _no_dispatch_record_stream(grad_to_offload.data, state._post_backward_stream)
992
+
993
+
994
+ @no_type_check
995
+ def _post_backward_use_sharded_grad_views(handle: FlatParamHandle):
996
+ if not handle._use_orig_params:
997
+ return
998
+ # Since the handle's `FlatParameter` completed its gradient computation, we
999
+ # should reset the gradient noneness mask
1000
+ handle._reset_is_grad_none()
1001
+ # Delay using sharded gradient views until after the reduce-scatter instead
1002
+ # of immediately after resharding
1003
+ handle._use_sharded_grad_views()
1004
+ if handle._has_optim_in_backward:
1005
+ handle.prepare_gradient_for_optim()
1006
+ for orig_param in handle.flat_param._params:
1007
+ # Check for `None` gradient to filter parameters not in the rank
1008
+ if orig_param.grad is not None and hasattr(
1009
+ orig_param, "_in_backward_optimizers"
1010
+ ):
1011
+ # TODO (rohan-varma): For CPU offload, this unfortunately
1012
+ # operates on CPU because the parameters and gradients have
1013
+ # already been offloaded. We should run this on GPU after
1014
+ # refactoring.
1015
+ for optim in orig_param._in_backward_optimizers:
1016
+ optim.step()
1017
+
1018
+ optim.zero_grad(set_to_none=True)
1019
+ handle._reset_flat_param_grad_info_if_needed()
1020
+ if handle._offload_params:
1021
+ handle.flat_param._cpu_grad = None
1022
+
1023
+
1024
+ def _div_if_needed(tensor: torch.Tensor, div_factor: float) -> None:
1025
+ if div_factor > 1:
1026
+ tensor.div_(div_factor)
1027
+
1028
+
1029
+ @no_type_check
1030
+ def _cast_grad_to_param_dtype(
1031
+ state: _FSDPState,
1032
+ sharded_grad: torch.Tensor,
1033
+ param: FlatParameter,
1034
+ ):
1035
+ """
1036
+ Casts ``sharded_grad`` back to the full parameter dtype so that the
1037
+ optimizer step runs with that dtype. This performs an actual cast if
1038
+ 1. parameters were in reduced precision during the forward since then
1039
+ gradients would be in that reduced precision, or
1040
+ 2. parameters were not in reduced precision but gradients were in
1041
+ reduced precision for communication.
1042
+ However, if a low precision communication hook is registered, then this
1043
+ dtype cast happens in the hook instead.
1044
+ """
1045
+ _assert_in_training_states(state, [TrainingState.FORWARD_BACKWARD])
1046
+ if not _low_precision_hook_enabled(state) and sharded_grad.dtype != param.dtype:
1047
+ low_prec_grad_data = sharded_grad.data
1048
+ sharded_grad.data = sharded_grad.data.to(dtype=param.dtype)
1049
+ # Since for `NO_SHARD`, the gradient is produced in the computation
1050
+ # stream and consumed here in the post-backward stream, inform the
1051
+ # caching allocator; for the sharded strategies, the gradient is
1052
+ # produced in the post-backward stream, so this `record_stream()`
1053
+ # should be a no-op
1054
+ _no_dispatch_record_stream(
1055
+ low_prec_grad_data, state._device_handle.current_stream()
1056
+ )
1057
+
1058
+
1059
+ def _check_grad_to_accumulate(
1060
+ new_sharded_grad: torch.Tensor,
1061
+ accumulated_grad: torch.Tensor,
1062
+ ) -> None:
1063
+ _p_assert(
1064
+ accumulated_grad.shape == new_sharded_grad.shape,
1065
+ "Shape mismatch when accumulating gradients: "
1066
+ f"existing gradient shape={accumulated_grad.shape} "
1067
+ f"new gradient shape={new_sharded_grad.shape}",
1068
+ )
1069
+ _p_assert(
1070
+ accumulated_grad.device == new_sharded_grad.device,
1071
+ "Device mismatch when accumulating gradients: "
1072
+ f"existing gradient device={accumulated_grad.device} "
1073
+ f"new gradient device={new_sharded_grad.device}",
1074
+ )
1075
+
1076
+
1077
+ @no_type_check
1078
+ def _low_precision_hook_enabled(state: _FSDPState) -> bool:
1079
+ return state._comm_hook in LOW_PRECISION_HOOKS
1080
+
1081
+
1082
+ @no_type_check
1083
+ @torch.no_grad()
1084
+ def _post_backward_final_callback(
1085
+ state: _FSDPState,
1086
+ module: nn.Module,
1087
+ ):
1088
+ """
1089
+ This waits for the post-backward to finish and performs some final cleanup.
1090
+ This runs at the end of the entire backward pass and should only be called
1091
+ on the root FSDP instance.
1092
+ """
1093
+ _p_assert(
1094
+ state._is_root,
1095
+ "The post-backward callback should only be called on the root FSDP instance",
1096
+ )
1097
+ root_state = state
1098
+
1099
+ if root_state._sync_gradients:
1100
+ current_stream = state._device_handle.current_stream()
1101
+ # TODO (rohan-varma): this also waits for the overlapped optimizer step to finish
1102
+ # since it currently runs in the post-backward stream. That can be
1103
+ # pushed to the next forward if run in a different stream
1104
+ current_stream.wait_stream(root_state._post_backward_stream)
1105
+ if root_state._all_reduce_stream is not current_stream: # uses HSDP
1106
+ current_stream.wait_stream(root_state._all_reduce_stream)
1107
+ if root_state.cpu_offload.offload_params:
1108
+ # Wait for non-blocking GPU -> CPU sharded gradient copies from the
1109
+ # post-backward hooks to finish explicitly since CPU gradients do
1110
+ # not automatically synchronize with the GPU
1111
+ state._device_handle.current_stream().synchronize()
1112
+ root_state._exec_order_data.next_iter()
1113
+
1114
+ for fsdp_state in state._all_fsdp_states:
1115
+ _catch_all_reshard(fsdp_state)
1116
+ _finalize_params(fsdp_state)
1117
+ fsdp_state.training_state = TrainingState.IDLE
1118
+ handle = fsdp_state._handle
1119
+ if handle:
1120
+ handle._ran_pre_backward_hook = False
1121
+ handle._needs_pre_backward_unshard = False
1122
+ handle._post_forward_index = None
1123
+ handle._training_state = HandleTrainingState.IDLE
1124
+ handle._prefetched = False
1125
+ # Reset for cases like one forward and multiple backwards
1126
+ root_state._post_backward_callback_queued = False
1127
+
1128
+
1129
+ @no_type_check
1130
+ def _catch_all_reshard(
1131
+ state: _FSDPState,
1132
+ ) -> None:
1133
+ """
1134
+ Reshards the parameters that may not have been resharded in the
1135
+ post-backward hook. This can happen when a module's output is used in the
1136
+ forward pass, meaning that its pre-backward hook runs (unsharding the
1137
+ parameter), but the post-backward hook does not run because the output was
1138
+ not jused in the loss computation corresponding to this backward pass.
1139
+ """
1140
+ # Wrap with a try-except to provide a more informative traceback if an
1141
+ # error is raised
1142
+ try:
1143
+ if state._handle:
1144
+ # TODO: This already-resharded check is brittle:
1145
+ # https://github.com/pytorch/pytorch/issues/83956
1146
+ already_resharded = (
1147
+ state._handle.flat_param.data_ptr()
1148
+ == state._handle.flat_param._local_shard.data_ptr()
1149
+ # If FSDP skipped using sharded views, then the flat parameter
1150
+ # still points to the sharded data, so we need to reshard to
1151
+ # use sharded views
1152
+ and not state._handle._skipped_use_sharded_views
1153
+ )
1154
+ if already_resharded:
1155
+ return
1156
+ free_unsharded_flat_param = _should_free_in_backward(state, state._handle)
1157
+ _reshard(state, state._handle, free_unsharded_flat_param)
1158
+ except Exception as e:
1159
+ _p_assert(
1160
+ False,
1161
+ f"Got exception in the catch-all reshard for {state}: {str(e)}",
1162
+ raise_assertion_error=False,
1163
+ )
1164
+ raise e
1165
+
1166
+
1167
+ @no_type_check
1168
+ def _finalize_params(
1169
+ state: _FSDPState,
1170
+ ) -> None:
1171
+ """Finalizes the parameters before the next iteration."""
1172
+ handle = state._handle
1173
+ if not handle:
1174
+ return
1175
+ flat_param = handle.flat_param
1176
+ if torch.distributed._functional_collectives.is_torchdynamo_compiling():
1177
+ if hasattr(flat_param, "_post_backward_hook_handle"):
1178
+ pbhs_handle = flat_param._post_backward_hook_handle
1179
+ pbhs_handle.remove()
1180
+ del flat_param._post_backward_hook_handle
1181
+ else:
1182
+ if hasattr(flat_param, "_post_backward_hook_state"):
1183
+ post_backward_hook_state_len = len(flat_param._post_backward_hook_state)
1184
+ expected_post_backward_hook_state_len = int(flat_param.requires_grad) + 1
1185
+ _p_assert(
1186
+ post_backward_hook_state_len == expected_post_backward_hook_state_len,
1187
+ f"Invalid: ``_post_backward_hook_state``: {flat_param._post_backward_hook_state}",
1188
+ )
1189
+ flat_param._post_backward_hook_state[-1].remove()
1190
+ delattr(flat_param, "_post_backward_hook_state")
1191
+ if flat_param.requires_grad:
1192
+ if not state._sync_gradients:
1193
+ # Preserve the gradient accumulation state if not synchronizing
1194
+ # gradients: `.grad` remains the unsharded gradient from prior
1195
+ # `no_sync()` iterations, and `_saved_grad_shard` remains the
1196
+ # sharded gradient from the last synchronized iteration
1197
+ return
1198
+ if not handle._has_optim_in_backward:
1199
+ handle.prepare_gradient_for_optim()
1200
+ _p_assert(
1201
+ hasattr(flat_param, "_post_backward_called"),
1202
+ "Expects `_post_backward_called` to be set on the `FlatParameter`",
1203
+ )
1204
+ flat_param._post_backward_called = False
1205
+
1206
+
1207
+ @no_type_check
1208
+ def _prefetch_handle(
1209
+ state: _FSDPState,
1210
+ current_handle: FlatParamHandle | None,
1211
+ prefetch_mode: _PrefetchMode,
1212
+ ) -> None:
1213
+ """
1214
+ Prefetches the next handles if needed (without synchronization). An empty
1215
+ handles key cannot prefetch.
1216
+ """
1217
+ if not current_handle:
1218
+ return
1219
+ handle = _get_handle_to_prefetch(state, current_handle)
1220
+ if not handle:
1221
+ return
1222
+ # Temporarily emulate the training state while calling `_unshard` to
1223
+ # ensure the correct `as_params` for `_use_unsharded_views()`
1224
+ prev_training_state = handle._training_state
1225
+ if prefetch_mode == _PrefetchMode.BACKWARD:
1226
+ handle._training_state = HandleTrainingState.BACKWARD_PRE
1227
+ elif prefetch_mode == _PrefetchMode.FORWARD:
1228
+ handle._training_state = HandleTrainingState.FORWARD
1229
+ else:
1230
+ raise ValueError(f"Invalid prefetch mode on rank {state.rank}: {prefetch_mode}")
1231
+ # Prefetch the next set of handles without synchronizing to allow
1232
+ # the sync to happen as late as possible to maximize overlap
1233
+ _unshard(state, handle, state._unshard_stream, state._pre_unshard_stream)
1234
+ handle._training_state = prev_training_state
1235
+ handle._prefetched = True
1236
+
1237
+
1238
+ @no_type_check
1239
+ def _get_handle_to_prefetch(
1240
+ state: _FSDPState,
1241
+ current_handle: FlatParamHandle,
1242
+ ) -> FlatParamHandle:
1243
+ """
1244
+ Returns a :class:`list` of the handles keys to prefetch for the next
1245
+ module(s), where ``current_handle`` represents the current module.
1246
+
1247
+ "Prefetching" refers to running the unshard logic early (without
1248
+ synchronization), and the "next" modules depend on the recorded execution
1249
+ order and the current training state.
1250
+ """
1251
+ training_state = _get_training_state(current_handle)
1252
+ valid_training_states = (
1253
+ HandleTrainingState.BACKWARD_PRE,
1254
+ HandleTrainingState.BACKWARD_POST,
1255
+ HandleTrainingState.FORWARD,
1256
+ )
1257
+ _p_assert(
1258
+ training_state in valid_training_states,
1259
+ f"Prefetching is only supported in {valid_training_states} but "
1260
+ f"currently in {training_state}",
1261
+ )
1262
+ eod = state._exec_order_data
1263
+ target_handle: FlatParamHandle | None = None
1264
+ if (
1265
+ training_state == HandleTrainingState.BACKWARD_PRE
1266
+ and state.backward_prefetch == BackwardPrefetch.BACKWARD_PRE
1267
+ ) or (
1268
+ training_state == HandleTrainingState.BACKWARD_POST
1269
+ and state.backward_prefetch == BackwardPrefetch.BACKWARD_POST
1270
+ ):
1271
+ target_handle_candidate = eod.get_handle_to_backward_prefetch(current_handle)
1272
+ if (
1273
+ target_handle_candidate
1274
+ and target_handle_candidate._needs_pre_backward_unshard
1275
+ and not target_handle_candidate._prefetched
1276
+ ):
1277
+ target_handle = target_handle_candidate
1278
+ else:
1279
+ target_handle = None
1280
+ elif training_state == HandleTrainingState.FORWARD and state.forward_prefetch:
1281
+ target_handle_candidate = eod.get_handle_to_forward_prefetch(current_handle)
1282
+ if (
1283
+ target_handle_candidate
1284
+ and target_handle_candidate._needs_pre_forward_unshard
1285
+ and not target_handle_candidate._prefetched
1286
+ ):
1287
+ target_handle = target_handle_candidate
1288
+ else:
1289
+ target_handle = None
1290
+
1291
+ return target_handle
1292
+
1293
+
1294
+ def _get_training_state(
1295
+ handle: FlatParamHandle,
1296
+ ) -> HandleTrainingState:
1297
+ """Returns the training state of the handles in ``handle``."""
1298
+ _p_assert(handle, "Expects a non-empty handle")
1299
+ return handle._training_state
1300
+
1301
+
1302
+ @no_type_check
1303
+ def _register_pre_forward_hook(
1304
+ state: _FSDPState,
1305
+ module: nn.Module,
1306
+ ) -> None:
1307
+ """
1308
+ Registers a pre-forward hook on ``module``.
1309
+ """
1310
+ for forward_handle in state._pre_forward_handles:
1311
+ forward_handle.remove()
1312
+ state._pre_forward_handles.clear()
1313
+ module_param_handle = state._fully_sharded_module_to_handle.get(module, None)
1314
+ hook = functools.partial(
1315
+ _pre_forward, state, module_param_handle, _pre_forward_unshard
1316
+ )
1317
+ state._pre_forward_handles.append(
1318
+ module.register_forward_pre_hook(hook, prepend=True, with_kwargs=True)
1319
+ )
1320
+
1321
+
1322
+ @no_type_check
1323
+ def _register_post_forward_hook(
1324
+ state: _FSDPState,
1325
+ module: nn.Module,
1326
+ ) -> None:
1327
+ """
1328
+ Registers a post-forward hook on ``module``. Even if the module has no
1329
+ handles, we should register the hook since it will register the module's
1330
+ pre-backward hook.
1331
+ """
1332
+ for forward_handle in state._post_forward_handles:
1333
+ forward_handle.remove()
1334
+ state._post_forward_handles.clear()
1335
+ module_param_handle = state._fully_sharded_module_to_handle.get(module, None)
1336
+ hook = functools.partial(
1337
+ _post_forward,
1338
+ state,
1339
+ module_param_handle,
1340
+ _post_forward_reshard,
1341
+ )
1342
+ state._post_forward_handles.append(module.register_forward_hook(hook))
1343
+
1344
+
1345
+ @no_type_check
1346
+ def _register_root_pre_forward_hook(
1347
+ state: _FSDPState,
1348
+ module: nn.Module,
1349
+ ):
1350
+ """
1351
+ Registers root pre-forward hook on ``module``, which should be the local
1352
+ FSDP root.
1353
+
1354
+ NOTE: For the current composable FSDP design, we have each application of
1355
+ ``fully_shard()`` to a module to indicate that that module is the local
1356
+ FSDP root. We may remove this assumption in the future, in which case we
1357
+ will need to register this root pre-forward hook on any candidate module
1358
+ that may be the local FSDP root.
1359
+ """
1360
+ for forward_handle in state._root_pre_forward_handles:
1361
+ forward_handle.remove()
1362
+ state._root_pre_forward_handles.clear()
1363
+ hook = functools.partial(_root_pre_forward, state)
1364
+ state._root_pre_forward_handles.append(
1365
+ module.register_forward_pre_hook(hook, prepend=True, with_kwargs=True)
1366
+ )
1367
+
1368
+
1369
+ @no_type_check
1370
+ def _register_pre_backward_hooks(
1371
+ state: _FSDPState,
1372
+ module: nn.Module,
1373
+ outputs: Any,
1374
+ handle: FlatParamHandle,
1375
+ ) -> None:
1376
+ """
1377
+ Registers pre-backward hooks on the tensors that require gradients in the
1378
+ forward pass outputs ``outputs``, which were computed using the
1379
+ ``FlatParameter`` s of ``handles``.
1380
+
1381
+ Args:
1382
+ module (nn.Module): Fully sharded module (see [Note: Fully Sharded
1383
+ Module]).
1384
+
1385
+ Returns:
1386
+ Forward pass outputs with pre-backward hooks registered to tensors that
1387
+ require gradients.
1388
+ """
1389
+ # If there is no gradient computation, then there is no need for
1390
+ # pre-backward logic
1391
+ if not torch.is_grad_enabled():
1392
+ return outputs
1393
+ if state._is_root:
1394
+ state._post_backward_callback_queued = False # only defined on the root
1395
+
1396
+ if handle:
1397
+ handle._needs_pre_backward_unshard = False
1398
+ # Since these handles' `FlatParameter`s participated in a forward, we
1399
+ # conservatively assume that they will be used in the backward
1400
+ handle._ran_pre_backward_hook = False
1401
+
1402
+ def _register_hook(t: torch.Tensor) -> torch.Tensor:
1403
+ if t.requires_grad:
1404
+ t.register_hook(
1405
+ torch.utils.hooks.unserializable_hook(
1406
+ functools.partial(_pre_backward_hook, state, module, handle)
1407
+ )
1408
+ )
1409
+ if handle:
1410
+ handle._needs_pre_backward_unshard = True
1411
+ return t
1412
+
1413
+ return _apply_to_tensors(_register_hook, outputs)
1414
+
1415
+
1416
+ def _register_post_backward_hook(
1417
+ state: _FSDPState,
1418
+ handle: FlatParamHandle | None,
1419
+ ) -> None:
1420
+ """
1421
+ Registers post-backward hooks on the ``FlatParameter`` s'
1422
+ ``AccumulateGrad`` objects to reshard and to reduce-scatter gradients.
1423
+
1424
+ The ``AccumulateGrad`` object represents the last function that finalizes
1425
+ the ``FlatParameter`` 's gradient, so it only runs after its entire
1426
+ gradient computation has finished.
1427
+
1428
+ We register the post-backward hook only once in the *first* forward that a
1429
+ ``FlatParameter`` participates in. This relies on the ``AccumulateGrad``
1430
+ object being preserved through multiple forwards.
1431
+
1432
+ NOTE: We follow this heuristic to prefer the *first* forward to target the
1433
+ parameter mixed precision case, where there are *separate*
1434
+ ``AccumulateGrad`` objects across the different forwards. (Without
1435
+ parameter mixed precision, the ``AccumulateGrad`` objects are the same.) If
1436
+ we instead prefer the *last* forward, then the hook runs early.
1437
+ """
1438
+ # If there is no gradient computation, then there is no need for
1439
+ # post-backward logic
1440
+ if not torch.is_grad_enabled():
1441
+ return
1442
+ if not handle:
1443
+ return
1444
+ flat_param = handle.flat_param
1445
+
1446
+ if torch.distributed._functional_collectives.is_torchdynamo_compiling():
1447
+ already_registered = hasattr(flat_param, "_post_backward_hook_handle")
1448
+ if already_registered or not flat_param.requires_grad:
1449
+ return
1450
+ hook = functools.partial(_post_backward_hook, state, handle)
1451
+ hook_handle = flat_param.register_post_accumulate_grad_hook(hook)
1452
+ flat_param._post_backward_hook_handle = hook_handle # type: ignore[attr-defined]
1453
+ else:
1454
+ already_registered = hasattr(flat_param, "_post_backward_hook_state")
1455
+ if already_registered or not flat_param.requires_grad:
1456
+ return
1457
+ # Get the `AccumulateGrad` object
1458
+ temp_flat_param = flat_param.expand_as(flat_param)
1459
+ _p_assert(
1460
+ temp_flat_param.grad_fn is not None,
1461
+ "The `grad_fn` is needed to access the `AccumulateGrad` and "
1462
+ "register the post-backward hook",
1463
+ )
1464
+ acc_grad = temp_flat_param.grad_fn.next_functions[0][0] # type: ignore[union-attr]
1465
+ if acc_grad is None:
1466
+ raise AssertionError("Expected acc_grad to be set")
1467
+ hook_handle = acc_grad.register_hook(
1468
+ functools.partial(_post_backward_hook, state, handle)
1469
+ )
1470
+ flat_param._post_backward_hook_state = (acc_grad, hook_handle) # type: ignore[attr-defined]
1471
+
1472
+
1473
+ def _register_post_backward_reshard_only_hook(
1474
+ state: _FSDPState,
1475
+ handle: FlatParamHandle | None,
1476
+ args: tuple[Any, ...],
1477
+ kwargs: dict[str, Any],
1478
+ ) -> None:
1479
+ """
1480
+ Registers post-backward hooks to reshard flat parameters that do not
1481
+ require gradient. We register these using multi-post-grad hooks on the
1482
+ input activations to ensure that all gradients that may depend on the
1483
+ parameters have been computed before resharding.
1484
+ """
1485
+ # If there is no gradient computation, then there is no need for
1486
+ # post-backward logic
1487
+ if not torch.is_grad_enabled():
1488
+ return
1489
+ # Construct `inp_tensors` lazily to avoid CPU overhead in typical case
1490
+ # where each flat parameter requires gradient
1491
+ inp_tensors: list[torch.Tensor] | None = None
1492
+ if not handle:
1493
+ return
1494
+ flat_param = handle.flat_param
1495
+
1496
+ if torch.distributed._functional_collectives.is_torchdynamo_compiling():
1497
+ already_registered = hasattr(flat_param, "_post_backward_hook_handle")
1498
+ else:
1499
+ already_registered = hasattr(flat_param, "_post_backward_hook_state")
1500
+
1501
+ if already_registered or flat_param.requires_grad:
1502
+ return
1503
+ if inp_tensors is None:
1504
+ args_flat = pytree.arg_tree_leaves(*args, **kwargs)
1505
+ inp_tensors = [
1506
+ obj for obj in args_flat if torch.is_tensor(obj) and obj.requires_grad
1507
+ ]
1508
+ if inp_tensors is None:
1509
+ raise AssertionError("Expected inp_tensors to be set")
1510
+ hook_handle = register_multi_grad_hook(
1511
+ inp_tensors, functools.partial(_post_backward_reshard_only_hook, state, handle)
1512
+ )
1513
+ if torch.distributed._functional_collectives.is_torchdynamo_compiling():
1514
+ flat_param._post_backward_hook_handle = hook_handle # type: ignore[attr-defined, assignment]
1515
+ else:
1516
+ flat_param._post_backward_hook_state = (hook_handle,) # type: ignore[attr-defined, assignment]
1517
+
1518
+
1519
+ @no_type_check
1520
+ def _register_post_backward_final_callback(
1521
+ state: _FSDPState, module: nn.Module
1522
+ ) -> None:
1523
+ """
1524
+ Registers the post-backward final callback that runs at the end of the
1525
+ backward pass. This should be called from the root FSDP instance at the
1526
+ beginning of the pre-backward.
1527
+ """
1528
+ _p_assert(
1529
+ state._is_root,
1530
+ "Only the root FSDP instance should register the post-backward callback",
1531
+ )
1532
+ if state._post_backward_callback_queued:
1533
+ return
1534
+ _assert_in_training_states(state, [TrainingState.IDLE])
1535
+ # Trace does not need this callback
1536
+ if not torch.distributed._functional_collectives.is_torchdynamo_compiling():
1537
+ state._post_backward_callback_queued = True
1538
+ Variable._execution_engine.queue_callback(
1539
+ functools.partial(_post_backward_final_callback, state, module)
1540
+ )
1541
+
1542
+
1543
+ def _wait_for_computation_stream(
1544
+ computation_stream: torch.Stream,
1545
+ unshard_stream: torch.Stream,
1546
+ pre_unshard_stream: torch.Stream,
1547
+ ):
1548
+ """
1549
+ Has the unshard and pre-unshard streams wait for the computation stream.
1550
+ For example, this should be called in the FSDP root's pre-forward to
1551
+ respect optimizer step computation.
1552
+ """
1553
+ # Tracing does not need to wait
1554
+ if torch.distributed._functional_collectives.is_torchdynamo_compiling():
1555
+ return
1556
+ unshard_stream.wait_stream(computation_stream) # type: ignore[attr-defined]
1557
+ # Having the pre-all-gather stream wait for the current stream even if we
1558
+ # do not leverage the pre-all-gather stream is tolerable since this only
1559
+ # runs once per iteration
1560
+ pre_unshard_stream.wait_stream(computation_stream) # type: ignore[attr-defined]
1561
+
1562
+
1563
+ def _reset_flat_param_grad_info_if_needed(
1564
+ handles: list[FlatParamHandle],
1565
+ ):
1566
+ """
1567
+ Clears the original parameters' gradients if needed. This method's CPU
1568
+ overhead is minimal, so we may call it throughout FSDP methods, which serve
1569
+ as callsites to free the gradient memory earlier.
1570
+ """
1571
+ if not isinstance(handles, list):
1572
+ handles = [handles]
1573
+ for handle in handles:
1574
+ if handle._use_orig_params:
1575
+ handle._reset_flat_param_grad_info_if_needed()
1576
+
1577
+
1578
+ @no_type_check
1579
+ def _get_buffers_and_dtypes_for_computation(
1580
+ state: _FSDPState,
1581
+ root_module: nn.Module,
1582
+ ) -> tuple[list[torch.Tensor], list[torch.dtype | None]]:
1583
+ """
1584
+ Returns all buffers in the module tree rooted at ``root_module`` and a
1585
+ corresponding list of the buffer dtypes for computation. Each buffer dtype
1586
+ is either ``None`` if buffer mixed precision is not enabled or the buffer
1587
+ low precision dtype otherwise.
1588
+ """
1589
+ _p_assert(state._is_root, "Expects the root to cast buffers")
1590
+ buffers: list[torch.Tensor] = []
1591
+ buffer_dtypes: list[torch.dtype | None] = []
1592
+ visited_buffers: set[torch.Tensor] = set()
1593
+ # Traverse the FSDP states bottom-up so that we prefer the owning FSDP
1594
+ # instance's mixed precision setting for each buffer
1595
+ fsdp_states, fsdp_modules = traversal_utils._get_fsdp_states_with_modules(
1596
+ root_module
1597
+ )
1598
+ for fsdp_state, fsdp_module in zip(reversed(fsdp_states), reversed(fsdp_modules)):
1599
+ for buffer_name, buffer in fsdp_module.named_buffers():
1600
+ if buffer in visited_buffers:
1601
+ continue
1602
+ visited_buffers.add(buffer)
1603
+ if clean_tensor_name(buffer_name) in fsdp_state._ignored_buffer_names:
1604
+ continue
1605
+ buffers.append(buffer)
1606
+ buffer_dtypes.append(fsdp_state.mixed_precision.buffer_dtype)
1607
+ if len(buffers) != len(buffer_dtypes):
1608
+ raise AssertionError(
1609
+ f"Expected buffers and buffer_dtypes to have the same length, got {len(buffers)} and {len(buffer_dtypes)}"
1610
+ )
1611
+ return buffers, buffer_dtypes
1612
+
1613
+
1614
+ @no_type_check
1615
+ def _get_orig_buffer_dtypes(
1616
+ state: _FSDPState,
1617
+ buffer_names: list[str],
1618
+ ) -> list[torch.dtype]:
1619
+ """
1620
+ Returns the original buffer types of the given buffer names.
1621
+ """
1622
+ buffer_dtypes: list[torch.dtype] = []
1623
+ for buffer_name in buffer_names:
1624
+ _p_assert(
1625
+ buffer_name in state._buffer_name_to_orig_dtype,
1626
+ f"{buffer_name} is missing from pre-computed dict on rank "
1627
+ f"{state.rank}, which only has keys "
1628
+ f"{state._buffer_name_to_orig_dtype.keys()}",
1629
+ )
1630
+ buffer_dtypes.append(state._buffer_name_to_orig_dtype[buffer_name])
1631
+ return buffer_dtypes
1632
+
1633
+
1634
+ def _cast_buffers_to_dtype_and_device(
1635
+ buffers: list[torch.Tensor],
1636
+ buffer_dtypes: list[torch.dtype | None],
1637
+ device: torch.device,
1638
+ ) -> None:
1639
+ """
1640
+ Casts ``buffers`` to the dtypes given by ``buffer_dtypes`` and moves them
1641
+ to ``device``. If an element in ``buffer_dtypes`` is ``None``, then the
1642
+ corresponding buffer is only moved to ``device``.
1643
+ """
1644
+ _p_assert(
1645
+ buffer_dtypes is None or len(buffers) == len(buffer_dtypes),
1646
+ f"Expects `buffers` and `buffer_dtypes` to have the same length if "
1647
+ f"`buffer_dtypes` is specified but got {len(buffers)} and "
1648
+ f"{len(buffer_dtypes)}",
1649
+ )
1650
+ for buffer, buffer_dtype in zip(buffers, buffer_dtypes):
1651
+ if not torch.is_floating_point(buffer) or buffer_dtype is None:
1652
+ buffer.data = buffer.to(device=device)
1653
+ else:
1654
+ buffer.data = buffer.to(device=device, dtype=buffer_dtype)
venv/lib/python3.14/site-packages/torch/distributed/fsdp/_shard_utils.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import copy
3
+ import itertools
4
+ import math
5
+
6
+ import torch
7
+ import torch.distributed as dist
8
+ from torch._utils import _get_device_module
9
+ from torch.distributed import distributed_c10d
10
+ from torch.distributed._shard.sharded_tensor import (
11
+ Shard,
12
+ ShardedTensor,
13
+ ShardedTensorMetadata,
14
+ TensorProperties,
15
+ )
16
+ from torch.distributed._shard.sharding_spec import ShardMetadata
17
+ from torch.distributed.tensor import DeviceMesh, DTensor, Replicate, Shard as DShard
18
+
19
+
20
+ def _get_remote_device_str(rank, device_type, num_devices_per_node):
21
+ if device_type.lower() == "cpu":
22
+ return f"rank:{rank}/{device_type}"
23
+ elif device_type.lower() == "hpu":
24
+ return f"rank:{rank}/{device_type}:{_get_device_module(device_type).current_device()}"
25
+ else:
26
+ return f"rank:{rank}/{device_type}:{rank % num_devices_per_node}"
27
+
28
+
29
+ def _create_chunk_sharded_tensor(
30
+ tensor: torch.Tensor,
31
+ rank: int,
32
+ world_size: int,
33
+ num_devices_per_node: int,
34
+ pg: dist.ProcessGroup,
35
+ device: torch.device | None = None,
36
+ ) -> ShardedTensor:
37
+ """
38
+ Shard a tensor to chunks along the first dimension. The local rank will gets its
39
+ corresponding chunk as the local shard to create a ShardedTensor.
40
+ """
41
+ chunks = tensor.chunk(world_size, dim=0)
42
+ if len(chunks) > rank:
43
+ local_shard = chunks[rank].clone()
44
+ offsets = [0 for _ in tensor.size()]
45
+ offsets[0] = math.ceil(tensor.size()[0] / world_size) * rank
46
+ local_shards = [Shard.from_tensor_and_offsets(local_shard, offsets, rank)]
47
+ else:
48
+ local_shards = []
49
+
50
+ # Create a ShardedTensor without invoking communication.
51
+ chunk_sizes = [list(chunk.size()) for chunk in chunks]
52
+ dim0_offsets = [0] + list(
53
+ itertools.accumulate([chunk_size[0] for chunk_size in chunk_sizes])
54
+ )[:-1]
55
+ offsets = [0] * (len(chunk_sizes[0]) - 1)
56
+ chunk_offsets = [[d0] + offsets for d0 in dim0_offsets]
57
+ device_type = (
58
+ distributed_c10d._get_pg_default_device(pg).type
59
+ if device is None
60
+ else device.type
61
+ )
62
+ placements = [
63
+ _get_remote_device_str(
64
+ dist.get_global_rank(pg, r),
65
+ device_type,
66
+ num_devices_per_node,
67
+ )
68
+ for r in range(len(chunk_sizes))
69
+ ]
70
+ if len(chunk_sizes) != len(chunk_offsets) or len(chunk_sizes) != len(placements):
71
+ raise AssertionError(
72
+ f"Expected chunk_sizes, chunk_offsets, and placements to have the same length, "
73
+ f"got {len(chunk_sizes)}, {len(chunk_offsets)}, {len(placements)}"
74
+ )
75
+ shard_metadata = [
76
+ ShardMetadata(offset, size, placement)
77
+ for offset, size, placement in zip(chunk_offsets, chunk_sizes, placements)
78
+ ]
79
+ sharded_tensor_metadata = ShardedTensorMetadata(
80
+ shards_metadata=shard_metadata,
81
+ size=tensor.size(),
82
+ tensor_properties=TensorProperties(
83
+ dtype=tensor.dtype,
84
+ layout=tensor.layout,
85
+ requires_grad=False,
86
+ memory_format=torch.contiguous_format,
87
+ pin_memory=tensor.is_pinned(),
88
+ ),
89
+ )
90
+ return ShardedTensor._init_from_local_shards_and_global_metadata(
91
+ local_shards, sharded_tensor_metadata=sharded_tensor_metadata, process_group=pg
92
+ )
93
+
94
+
95
+ def _create_chunk_dtensor(
96
+ tensor: torch.Tensor,
97
+ rank: int,
98
+ device_mesh: DeviceMesh,
99
+ ) -> DTensor:
100
+ """
101
+ Shard a tensor to chunks along the first dimension. The local rank will gets its
102
+ corresponding chunk as the local tensor to create a DTensor.
103
+ """
104
+ # We need to explicitly call .detach() to return a new tensor detached from the current graph.
105
+ tensor = tensor.detach().clone()
106
+
107
+ # FSDP placements: [Shard(0)]
108
+ # HSDP placements: [Replicate(), Shard(0)]
109
+ replicate_placements = [Replicate() for _ in range(device_mesh.ndim)]
110
+ shard_placements = [Replicate() for _ in range(device_mesh.ndim)]
111
+ shard_placements[-1] = DShard(0) # type: ignore[call-overload]
112
+
113
+ return DTensor.from_local(
114
+ tensor, device_mesh, replicate_placements, run_check=False
115
+ ).redistribute(
116
+ placements=shard_placements,
117
+ )
118
+
119
+
120
+ def _all_gather_dtensor(
121
+ tensor: DTensor,
122
+ root_mesh: DeviceMesh | None,
123
+ ) -> torch.Tensor:
124
+ """
125
+ All gather a DTensor in its sharded dimension and return the local tensor.
126
+ """
127
+ if root_mesh != tensor.device_mesh:
128
+ raise AssertionError("The device mesh of a tensor should be a root mesh.")
129
+
130
+ placements = list(copy.deepcopy(tensor.placements))
131
+ # FSDP placements: [Shard(0)] -> [Replicate()]
132
+ # HSDP placements: [Replicate(), Shard(0)] -> [Replicate(), Replicate()]
133
+ placements[-1] = Replicate()
134
+ tensor = tensor.redistribute(
135
+ device_mesh=tensor.device_mesh,
136
+ placements=placements,
137
+ )
138
+
139
+ return tensor.to_local()
venv/lib/python3.14/site-packages/torch/distributed/fsdp/_state_dict_utils.py ADDED
@@ -0,0 +1,932 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import contextlib
3
+ import logging
4
+ import math
5
+ import warnings
6
+ from collections.abc import Callable, Generator, Iterator
7
+ from typing import Any, cast, no_type_check
8
+
9
+ import torch
10
+ import torch.distributed as dist
11
+ import torch.distributed.algorithms._checkpoint.checkpoint_wrapper as checkpoint_wrapper
12
+ import torch.nn as nn
13
+ import torch.nn.functional as F
14
+ from torch.distributed._shard.sharded_tensor import (
15
+ init_from_local_shards,
16
+ Shard,
17
+ ShardedTensor,
18
+ )
19
+ from torch.distributed.fsdp._common_utils import (
20
+ _FSDPState,
21
+ _get_module_fsdp_state_if_fully_sharded_module,
22
+ _has_fsdp_params,
23
+ _is_composable,
24
+ _module_handle,
25
+ clean_tensor_name,
26
+ FSDP_PREFIX,
27
+ FSDP_WRAPPED_MODULE,
28
+ )
29
+ from torch.distributed.fsdp._debug_utils import SimpleProfiler
30
+ from torch.distributed.fsdp._runtime_utils import (
31
+ _cast_buffers_to_dtype_and_device,
32
+ _get_orig_buffer_dtypes,
33
+ _lazy_init,
34
+ _reset_flat_param_grad_info_if_needed,
35
+ )
36
+ from torch.distributed.fsdp.api import (
37
+ FullStateDictConfig,
38
+ ShardingStrategy,
39
+ StateDictType,
40
+ )
41
+ from torch.distributed.tensor import DTensor
42
+ from torch.distributed.utils import _replace_by_prefix
43
+
44
+ from ._fsdp_extensions import (
45
+ _ext_all_gather_dtensor,
46
+ _ext_chunk_dtensor,
47
+ _ext_chunk_tensor,
48
+ _ext_post_unflatten_transform,
49
+ _ext_pre_load_state_dict_transform,
50
+ )
51
+ from ._unshard_param_utils import _unshard_fsdp_state_params, FLAT_PARAM
52
+
53
+
54
+ logger = logging.getLogger(__name__)
55
+
56
+
57
+ def _should_unshard_params(fsdp_state: _FSDPState) -> bool:
58
+ return not (
59
+ fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD
60
+ and (_is_composable(fsdp_state) or fsdp_state._use_orig_params)
61
+ )
62
+
63
+
64
+ def _convert_to_wrapped_module_name(module_name: str) -> str:
65
+ module_name = module_name.replace(f"{FSDP_PREFIX}", "")
66
+ module_name = module_name.replace(f"{FSDP_WRAPPED_MODULE}", "")
67
+ if module_name:
68
+ module_name = f"{module_name}."
69
+ # `CheckpointWrapper` adds a prefix that has to be removed as well.
70
+ module_name = module_name.replace(checkpoint_wrapper._CHECKPOINT_PREFIX, "")
71
+ return module_name
72
+
73
+
74
+ def _param_name_infos(
75
+ module: nn.Module, fsdp_state: _FSDPState
76
+ ) -> Iterator[tuple[str, str, str]]:
77
+ if not _has_fsdp_params(fsdp_state, module):
78
+ return
79
+ for param_name, module_name in _module_handle(
80
+ fsdp_state, module
81
+ ).param_module_names():
82
+ module_name = _convert_to_wrapped_module_name(module_name)
83
+ fqn = f"{module_name}{param_name}"
84
+ yield fqn, param_name, module_name
85
+
86
+
87
+ def _shared_param_name_infos(
88
+ module: nn.Module, fsdp_state
89
+ ) -> Iterator[tuple[str, str, str]]:
90
+ for param_name, module_name in _module_handle(
91
+ fsdp_state, module
92
+ ).shared_param_module_names():
93
+ module_name = _convert_to_wrapped_module_name(module_name)
94
+ fqn = f"{module_name}{param_name}"
95
+ yield fqn, param_name, module_name
96
+
97
+
98
+ @no_type_check
99
+ def _enter_unshard_params_ctx(
100
+ module: nn.Module,
101
+ fsdp_state: _FSDPState,
102
+ writeback: bool = False,
103
+ rank0_only: bool = False,
104
+ offload_to_cpu: bool = False,
105
+ with_grads: bool = False,
106
+ ) -> None:
107
+ """
108
+ state_dict hooks cannot use the pure context call as the checkpoint flow
109
+ requires to enter the context in the pre-hook but leave the context in the
110
+ post-hook. This API enters the context of ``_unshard_fsdp_state_params``.
111
+ """
112
+ if module in fsdp_state._unshard_params_ctx:
113
+ raise AssertionError(
114
+ "Entering the ``_unshard_fsdp_state_params`` context but _unshard_params_ctx[module] "
115
+ "is not None."
116
+ )
117
+ fsdp_state._unshard_params_ctx[module] = _unshard_fsdp_state_params(
118
+ module,
119
+ fsdp_state,
120
+ writeback=writeback,
121
+ rank0_only=rank0_only,
122
+ offload_to_cpu=offload_to_cpu,
123
+ with_grads=with_grads,
124
+ )
125
+ fsdp_state._unshard_params_ctx[module].__enter__()
126
+
127
+
128
+ @no_type_check
129
+ def _exit_unshard_params_ctx(module: nn.Module, fsdp_state: _FSDPState) -> None:
130
+ """A helper function to exit ``_unshard_fsdp_state_params`` context."""
131
+ fsdp_state._unshard_params_ctx[module].__exit__(None, None, None)
132
+ fsdp_state._unshard_params_ctx.pop(module)
133
+
134
+
135
+ def _common_pre_state_dict_hook(
136
+ module: nn.Module,
137
+ fsdp_state: _FSDPState,
138
+ ) -> None:
139
+ """Performs the pre-state_dict tasks shared by all state_dict types."""
140
+ if fsdp_state._device_handle.is_available():
141
+ fsdp_state._device_handle.synchronize()
142
+ # TODO: need to check if this is always correct for composable FSDP.
143
+ _lazy_init(fsdp_state, module)
144
+ if fsdp_state._is_root:
145
+ _reset_flat_param_grad_info_if_needed(fsdp_state._all_handles)
146
+
147
+
148
+ def _common_unshard_pre_state_dict_hook(
149
+ module: nn.Module,
150
+ fsdp_state: _FSDPState,
151
+ offload_to_cpu: bool,
152
+ rank0_only: bool,
153
+ ) -> None:
154
+ """
155
+ Performs the pre-state_dict tasks shared by all state_dict types that require
156
+ ``_unshard_fsdp_state_params()``. FULL_STATE_DICT and SHARDED_STATE_DICT use this hook.
157
+ """
158
+ # For composable `fully_shard`, it does not need to unshard parameters for `NO_SHARD` cases.
159
+ if not _should_unshard_params(fsdp_state):
160
+ return
161
+ _enter_unshard_params_ctx(
162
+ module,
163
+ fsdp_state,
164
+ writeback=False,
165
+ offload_to_cpu=offload_to_cpu,
166
+ rank0_only=rank0_only,
167
+ )
168
+
169
+
170
+ @no_type_check
171
+ def _common_unshard_post_state_dict_hook(
172
+ module: nn.Module,
173
+ fsdp_state: _FSDPState,
174
+ state_dict: dict[str, Any],
175
+ prefix: str,
176
+ param_hook: Callable,
177
+ ) -> dict[str, Any]:
178
+ """
179
+ The post-state_dict flow that shared by all state_dict types that require
180
+ ``_unshard_fsdp_state_params()``. FULL_STATE_DICT and SHARDED_STATE_DICT use this
181
+ hook.
182
+ """
183
+ _replace_by_prefix(state_dict, prefix + f"{FSDP_PREFIX}", prefix)
184
+ # Return early for trivial cases
185
+ if not state_dict or not _has_fsdp_params(fsdp_state, module):
186
+ if _should_unshard_params(fsdp_state):
187
+ _exit_unshard_params_ctx(module, fsdp_state)
188
+ return state_dict
189
+
190
+ # If a rank does not have unsharded parameters(when `rank0_only=True`
191
+ # and `rank != 0`), then the rank only needed to participate in the
192
+ # all-gather and does not need to save the # state dict. We simply check
193
+ # rank0_only to ensure this issue.
194
+ rank0_only = (
195
+ fsdp_state._state_dict_type == StateDictType.FULL_STATE_DICT
196
+ and cast(FullStateDictConfig, fsdp_state._state_dict_config).rank0_only
197
+ )
198
+ # no_fsdp_return means the state_dict returned by this rank should contain
199
+ # only non-FSDP controlled parameters and buffers.
200
+ no_fsdp_return = rank0_only and fsdp_state.rank != 0
201
+ if no_fsdp_return and not fsdp_state._use_orig_params:
202
+ for clean_key in fsdp_state._buffer_names:
203
+ # This is a hack to support activation checkpoint.
204
+ clean_key = clean_key.replace(
205
+ f"{checkpoint_wrapper._CHECKPOINT_PREFIX}.", ""
206
+ )
207
+ state_dict.pop(f"{prefix}{clean_key}", None)
208
+ # Non-zero ranks have flat_param key when rank0_only=True, because rank0_only=True is
209
+ # passed in to unshard context, but nonzero ranks reshard early, causing this flat_param
210
+ # to appear in state_dict.
211
+ state_dict.pop(f"{prefix}{FLAT_PARAM}")
212
+ _exit_unshard_params_ctx(module, fsdp_state)
213
+ return state_dict
214
+
215
+ # Loop only the parameters saved in this instance's wrapped module to
216
+ # avoid processing buffers.
217
+ for fqn, param_name, module_name in _param_name_infos(module, fsdp_state):
218
+ fqn = f"{prefix}{fqn}"
219
+ if no_fsdp_return:
220
+ state_dict.pop(fqn)
221
+ continue
222
+ if fqn not in state_dict:
223
+ raise AssertionError(
224
+ f"FSDP assumes {fqn} is in the state_dict but the state_dict only "
225
+ f"has {state_dict.keys()}. "
226
+ f"prefix={prefix}, module_name={module_name}, "
227
+ f"param_name={param_name} rank={fsdp_state.rank}."
228
+ )
229
+
230
+ param_hook(state_dict, prefix, fqn)
231
+
232
+ if _should_unshard_params(fsdp_state):
233
+ _exit_unshard_params_ctx(module, fsdp_state)
234
+
235
+ cpu_device = torch.device("cpu")
236
+ buffer_clean_fqns = []
237
+ buffers = []
238
+ for clean_key in fsdp_state._buffer_names:
239
+ # This is a hack to support activation checkpoint.
240
+ clean_key = clean_tensor_name(clean_key)
241
+ fqn = f"{prefix}{clean_key}"
242
+ if fqn not in state_dict:
243
+ # A buffer can be registered as non-persistent.
244
+ continue
245
+ if no_fsdp_return:
246
+ state_dict.pop(fqn)
247
+ else:
248
+ buffer = state_dict[fqn]
249
+ if (
250
+ fsdp_state._state_dict_config.offload_to_cpu
251
+ and buffer.device != cpu_device
252
+ ):
253
+ state_dict[fqn] = buffer.to(cpu_device)
254
+ # skip upcasting for ignored buffers
255
+ if clean_key not in fsdp_state._ignored_buffer_names:
256
+ buffer_clean_fqns.append(clean_key)
257
+ buffers.append(state_dict[fqn])
258
+
259
+ if buffers:
260
+ mixed_precision_enabled_for_buffers = (
261
+ fsdp_state._mixed_precision_enabled_for_buffers()
262
+ if not _is_composable(fsdp_state)
263
+ else (fsdp_state.mixed_precision.buffer_dtype is not None)
264
+ )
265
+ if mixed_precision_enabled_for_buffers:
266
+ buffer_dtypes = _get_orig_buffer_dtypes(fsdp_state, buffer_clean_fqns)
267
+ _cast_buffers_to_dtype_and_device(
268
+ buffers, buffer_dtypes, fsdp_state.compute_device
269
+ )
270
+ for buffer, clean_fqn in zip(buffers, buffer_clean_fqns):
271
+ fqn = f"{prefix}{clean_fqn}"
272
+ logger.info("FSDP is casting the dtype of %s to %s", fqn, buffer.dtype)
273
+ state_dict[fqn] = buffer.clone()
274
+ return state_dict
275
+
276
+
277
+ @no_type_check
278
+ def _full_pre_state_dict_hook(
279
+ fsdp_state: _FSDPState,
280
+ module: nn.Module,
281
+ *args,
282
+ **kwargs,
283
+ ) -> None:
284
+ """
285
+ Hook that runs before model.state_dict() is called. pre-state_dict hook is
286
+ not actually supported by ``nn.Module``. As a result, this API is called
287
+ from ``_full_post_state_dict_hook()`` to simulate the case. Once pre-state_dict
288
+ is supported in ``nn.Module``, this hook will be registered as a hook in
289
+ ``nn.Module``.
290
+ """
291
+ if getattr(fsdp_state, "_device_mesh", False):
292
+ fsdp_state._device_mesh._get_root_mesh()
293
+
294
+ _common_pre_state_dict_hook(module, fsdp_state)
295
+ _common_unshard_pre_state_dict_hook(
296
+ module,
297
+ fsdp_state,
298
+ offload_to_cpu=fsdp_state._state_dict_config.offload_to_cpu,
299
+ rank0_only=cast(FullStateDictConfig, fsdp_state._state_dict_config).rank0_only,
300
+ )
301
+
302
+
303
+ @no_type_check
304
+ def _full_post_state_dict_hook(
305
+ module: nn.Module,
306
+ fsdp_state: _FSDPState,
307
+ state_dict: dict[str, Any],
308
+ prefix: str,
309
+ ) -> dict[str, Any]:
310
+ """
311
+ Hook that runs after model.state_dict() is called before returning result to
312
+ user. For FSDP, we may have to clone the tensors in state_dict as params go
313
+ back to sharded version after _unshard_fsdp_state_params ends, and also remove
314
+ the ``FSDP_WRAPPED_MODULE`` prefix.
315
+ """
316
+
317
+ def param_hook(
318
+ state_dict: dict[str, Any],
319
+ prefix: str,
320
+ fqn: str,
321
+ ) -> None:
322
+ clean_key = fqn
323
+ clean_prefix = clean_tensor_name(prefix)
324
+ # Strip prefix out of key if needed as buffer names and param names
325
+ # do not have prefix considered as they are not computed in `state_dict`
326
+ # call.
327
+ clean_key = clean_key.removeprefix(clean_prefix)
328
+
329
+ # Clone parameters before exiting the `_unshard_fsdp_state_params()` context.
330
+ if not getattr(state_dict[fqn], "_has_been_cloned", False):
331
+ try:
332
+ state_dict[fqn] = state_dict[fqn].detach().clone()
333
+ state_dict[fqn]._has_been_cloned = True # type: ignore[attr-defined]
334
+ except BaseException as e: # noqa: B036
335
+ warnings.warn(
336
+ f"Failed to clone() tensor with name {fqn} on rank {fsdp_state.rank}. "
337
+ "This may mean that this state_dict entry could point to invalid "
338
+ "memory regions after returning from state_dict() call if this "
339
+ "parameter is managed by FSDP. Please check clone "
340
+ f"implementation of {fqn}. Error: {str(e)}",
341
+ stacklevel=2,
342
+ )
343
+
344
+ return _common_unshard_post_state_dict_hook(
345
+ module, fsdp_state, state_dict, prefix, param_hook
346
+ )
347
+
348
+
349
+ def _full_pre_load_state_dict_hook(
350
+ module: nn.Module,
351
+ fsdp_state: _FSDPState,
352
+ state_dict: dict[str, Any],
353
+ prefix: str,
354
+ ) -> None:
355
+ _lazy_init(fsdp_state, module)
356
+ if _should_unshard_params(fsdp_state):
357
+ with SimpleProfiler.profile("_enter_unshard_params_ctx"):
358
+ _enter_unshard_params_ctx(module, fsdp_state, writeback=True)
359
+ # Add FSDP_PREFIX only for wrapper-based FSDP.
360
+ if not _is_composable(fsdp_state):
361
+ _replace_by_prefix(state_dict, prefix, prefix + f"{FSDP_PREFIX}")
362
+
363
+
364
+ def _full_post_load_state_dict_hook(
365
+ module: nn.Module, fsdp_state: _FSDPState, *args, **kwargs
366
+ ) -> None:
367
+ if _should_unshard_params(fsdp_state):
368
+ with SimpleProfiler.profile("_exit_unshard_params_ctx"):
369
+ _exit_unshard_params_ctx(module, fsdp_state)
370
+
371
+
372
+ def _local_pre_state_dict_hook(
373
+ fsdp_state: _FSDPState,
374
+ module: nn.Module,
375
+ *args,
376
+ **kwargs,
377
+ ) -> None:
378
+ """
379
+ Hook that runs before model.state_dict() is called. Right now, pre-state_dict
380
+ hook is not supported by the PyTorch core. So this API is called from
381
+ `_local_post_state_dict_hook()` to simulate the case.
382
+ """
383
+ if (
384
+ _has_fsdp_params(fsdp_state, module)
385
+ and not _module_handle(fsdp_state, module).uses_sharded_strategy
386
+ ):
387
+ raise RuntimeError(
388
+ "``local_state_dict`` can only be used when parameters are flatten "
389
+ "and sharded."
390
+ )
391
+ _common_pre_state_dict_hook(module, fsdp_state)
392
+
393
+
394
+ @no_type_check
395
+ def _local_post_state_dict_hook(
396
+ module: nn.Module,
397
+ fsdp_state: _FSDPState,
398
+ state_dict: dict[str, Any],
399
+ prefix: str,
400
+ ) -> dict[str, Any]:
401
+ """
402
+ This hook create a ShardedTensor from the local flat_param and replace
403
+ the state_dict[f"{prefix}{FLAT_PARAM}] with the ShardedTensor. No copy
404
+ will happen. The underlying storage is the same.
405
+ """
406
+
407
+ _replace_by_prefix(state_dict, f"{prefix}{FSDP_PREFIX}", prefix)
408
+ if not _has_fsdp_params(fsdp_state, module):
409
+ return state_dict
410
+
411
+ # state_dict[f"{prefix}{FLAT_PARAM}"] exists and has the same tensor
412
+ # value as the flat_param but it is a pure Tensor because
413
+ # nn.Module.state_dict() will detach the parameter. Therefore, we need
414
+ # to get flat_param to get the metadata.
415
+ if not _module_handle(fsdp_state, module):
416
+ raise AssertionError("Should have returned early")
417
+ flat_param = _module_handle(fsdp_state, module).flat_param
418
+ # Constructs a ShardedTensor from the flat_param "without" padding.
419
+ # Removing the padding allows users to change the number of ranks
420
+ # when loading the local_state_dict.
421
+ full_numel = flat_param._unpadded_unsharded_size.numel() # type: ignore[attr-defined]
422
+ shard_offset = flat_param.numel() * fsdp_state.rank
423
+ valid_data_size = flat_param.numel() - flat_param._shard_numel_padded
424
+ if valid_data_size > 0:
425
+ # If FlatParameter is returned, FlatParameter._local_shard cause a
426
+ # pickling issue (can be torch.save but not torch.load). Since there
427
+ # is no benefit for state_dict to return the actual FlatParameter class,
428
+ # a view (which is a tensor) of the FlatParameter will be returned.
429
+ flat_param = flat_param[:valid_data_size].view(valid_data_size)
430
+ local_shards = [
431
+ Shard.from_tensor_and_offsets(flat_param, [shard_offset], fsdp_state.rank)
432
+ ]
433
+ else:
434
+ local_shards = []
435
+ sharded_tensor = init_from_local_shards(
436
+ local_shards, full_numel, process_group=fsdp_state.process_group
437
+ ) # type: ignore[assignment]
438
+ # TODO: Add DTensor state_dict support for LOCAL_STATE_DICT.
439
+ if fsdp_state._state_dict_config.offload_to_cpu:
440
+ sharded_tensor = sharded_tensor.cpu()
441
+ state_dict[f"{prefix}{FLAT_PARAM}"] = sharded_tensor
442
+ return state_dict
443
+
444
+
445
+ def _local_post_load_state_dict_hook(
446
+ module: nn.Module, fsdp_state: _FSDPState, *args, **kwargs
447
+ ) -> None:
448
+ pass
449
+
450
+
451
+ def _local_pre_load_state_dict_hook(
452
+ module: nn.Module,
453
+ fsdp_state: _FSDPState,
454
+ state_dict: dict[str, Any],
455
+ prefix: str,
456
+ ) -> None:
457
+ """
458
+ This hook finds the local flat_param for this FSDP module from the
459
+ state_dict. The flat_param should be a ShardedTensor. This hook converts
460
+ the ShardedTensor to a tensor. No copy happen unless padding is required.
461
+ """
462
+ _lazy_init(fsdp_state, module)
463
+ _replace_by_prefix(state_dict, prefix, f"{prefix}{FSDP_PREFIX}")
464
+ fqn = f"{prefix}{FSDP_PREFIX}{FLAT_PARAM}"
465
+ if fqn not in state_dict:
466
+ if _has_fsdp_params(fsdp_state, module):
467
+ raise AssertionError(
468
+ "No `FlatParameter` in `state_dict` for this FSDP instance "
469
+ "but it has parameters"
470
+ )
471
+ return
472
+ load_tensor = state_dict[fqn]
473
+ if not isinstance(load_tensor, ShardedTensor):
474
+ raise AssertionError("Tensors in local_state_dict should be ShardedTensor.")
475
+
476
+ # Convert the ShardedTensor to a Tensor.
477
+ flat_param = _module_handle(fsdp_state, module).flat_param
478
+ if flat_param is None:
479
+ raise AssertionError("Expected flat_param to be set")
480
+ valid_data_size = flat_param.numel() - flat_param._shard_numel_padded
481
+ shards = load_tensor.local_shards()
482
+ if valid_data_size > 0:
483
+ if not len(shards):
484
+ raise AssertionError(
485
+ "load_local_state_dict assume one shard per ShardedTensor."
486
+ )
487
+ load_tensor = shards[0].tensor
488
+
489
+ # Get the metadata of the flat_param to decide whether to pad the loaded
490
+ # tensor.
491
+ if flat_param._shard_numel_padded > 0:
492
+ if load_tensor.numel() >= flat_param.numel():
493
+ raise AssertionError(
494
+ f"Local shard size = {flat_param.numel()} and the tensor in "
495
+ f"the state_dict is {load_tensor.numel()}."
496
+ )
497
+ load_tensor = F.pad(load_tensor, [0, flat_param._shard_numel_padded])
498
+ else:
499
+ load_tensor = flat_param
500
+ # TODO: Add DTensor state_dict support for LOCAL_STATE_DICT.
501
+ state_dict[fqn] = load_tensor
502
+
503
+
504
+ def _sharded_pre_state_dict_hook(
505
+ fsdp_state: _FSDPState,
506
+ module: nn.Module,
507
+ *args,
508
+ **kwargs,
509
+ ) -> None:
510
+ """
511
+ Hook that runs before model.state_dict() is called. Check
512
+ ``_full_pre_load_state_dict_hook`` for the detail.
513
+ """
514
+ if (
515
+ _has_fsdp_params(fsdp_state, module)
516
+ and not _module_handle(fsdp_state, module).uses_sharded_strategy
517
+ ):
518
+ raise RuntimeError(
519
+ "``sharded_state_dict`` can only be used when parameters are flatten "
520
+ "and sharded."
521
+ )
522
+ _common_pre_state_dict_hook(module, fsdp_state)
523
+ # Setting offload_to_cpu here does not work even if offload_to_cpu is True.
524
+ # We have to create ShardedTensor first then move it to CPU.
525
+ _common_unshard_pre_state_dict_hook(
526
+ module,
527
+ fsdp_state,
528
+ offload_to_cpu=False,
529
+ rank0_only=False,
530
+ )
531
+
532
+
533
+ @no_type_check
534
+ def _sharded_post_state_dict_hook(
535
+ module: nn.Module,
536
+ fsdp_state: _FSDPState,
537
+ state_dict: dict[str, Any],
538
+ prefix: str,
539
+ ) -> dict[str, Any]:
540
+ """
541
+ The hook replaces the unflattened, unsharded parameter in the state_dict
542
+ with a unflattened, sharded parameter (a ShardedTensor).
543
+ """
544
+
545
+ def param_hook(state_dict: dict[str, Any], prefix: str, fqn: str):
546
+ param = state_dict[fqn]
547
+ if not fsdp_state._state_dict_config._use_dtensor:
548
+ sharded_tensor = _ext_chunk_tensor(
549
+ tensor=param,
550
+ rank=fsdp_state.rank,
551
+ world_size=fsdp_state.world_size,
552
+ num_devices_per_node=fsdp_state._device_handle.device_count(),
553
+ pg=fsdp_state.process_group,
554
+ fsdp_extension=fsdp_state._fsdp_extension,
555
+ )
556
+ else:
557
+ sharded_tensor = _ext_chunk_dtensor(
558
+ tensor=param,
559
+ rank=fsdp_state.rank,
560
+ device_mesh=fsdp_state._device_mesh,
561
+ fsdp_extension=fsdp_state._fsdp_extension,
562
+ )
563
+ if fsdp_state._state_dict_config.offload_to_cpu:
564
+ sharded_tensor = sharded_tensor.cpu()
565
+ state_dict[fqn] = sharded_tensor
566
+
567
+ return _common_unshard_post_state_dict_hook(
568
+ module, fsdp_state, state_dict, prefix, param_hook
569
+ )
570
+
571
+
572
+ @no_type_check
573
+ def _sharded_post_load_state_dict_hook(
574
+ module: nn.Module, fsdp_state: _FSDPState, *args, **kwargs
575
+ ) -> None:
576
+ if _has_fsdp_params(fsdp_state, module):
577
+ with SimpleProfiler.profile("_exit_unshard_params_ctx"):
578
+ _exit_unshard_params_ctx(module, fsdp_state)
579
+
580
+
581
+ @no_type_check
582
+ def _sharded_pre_load_state_dict_hook(
583
+ module: nn.Module,
584
+ fsdp_state: _FSDPState,
585
+ state_dict: dict[str, Any],
586
+ prefix: str,
587
+ ) -> None:
588
+ """
589
+ The hook combines the unflattened, sharded parameters (ShardedTensor) to
590
+ a new FlatParameter and shards the new FlatParameter to the local chunk.
591
+ """
592
+ _lazy_init(fsdp_state, module)
593
+ if not _is_composable(fsdp_state):
594
+ _replace_by_prefix(state_dict, prefix, prefix + f"{FSDP_PREFIX}")
595
+ if not _has_fsdp_params(fsdp_state, module):
596
+ return
597
+
598
+ handle = _module_handle(fsdp_state, module)
599
+ if not handle.uses_sharded_strategy:
600
+ raise RuntimeError(
601
+ "load_sharded_state_dict can only be called when parameters "
602
+ "are flattened and sharded."
603
+ )
604
+ fqn_to_param_ext = dict(
605
+ zip(handle.flat_param._fqns, handle.flat_param._param_extensions)
606
+ )
607
+
608
+ for fqn, _, _ in _param_name_infos(module, fsdp_state):
609
+ if not _is_composable(fsdp_state):
610
+ fqn_from_global_root = f"{prefix}{FSDP_PREFIX}{fqn}"
611
+ else:
612
+ fqn_from_global_root = f"{prefix}{fqn}"
613
+ try:
614
+ param = state_dict.pop(fqn_from_global_root)
615
+ except KeyError:
616
+ logger.warning(
617
+ f"Did not find param with FQN {fqn_from_global_root}, skipping it. " # noqa: G004
618
+ "The weight will not be filled if you expect it to be."
619
+ )
620
+ continue # TODO: Improve unittesting for state_dict finetuning
621
+ # cases: https://github.com/pytorch/pytorch/issues/109134
622
+
623
+ if not fsdp_state._state_dict_config._use_dtensor:
624
+ # All-gather the param (ShardedTensor)
625
+ param, shards = _ext_pre_load_state_dict_transform(
626
+ param, fsdp_state._fsdp_extension
627
+ )
628
+
629
+ if len(shards) >= 2:
630
+ raise AssertionError(
631
+ "Expects 0 or 1 shard per rank "
632
+ f"but got {len(shards)} shards on rank {fsdp_state.rank}."
633
+ )
634
+ param_numel = param.size().numel()
635
+ dim_0_size = param.size()[0]
636
+ chunk_size = (
637
+ math.ceil(dim_0_size / fsdp_state.world_size)
638
+ * param_numel
639
+ // dim_0_size
640
+ )
641
+ if len(shards) == 1:
642
+ local_tensor = shards[0].tensor.flatten()
643
+ with SimpleProfiler.profile(SimpleProfiler.Type.H2D):
644
+ local_tensor = local_tensor.to(fsdp_state.compute_device)
645
+ num_padding = chunk_size - local_tensor.numel()
646
+ if num_padding > 0:
647
+ local_tensor = F.pad(local_tensor, [0, num_padding])
648
+ else:
649
+ local_tensor = torch.zeros(
650
+ chunk_size, dtype=param.dtype, device=fsdp_state.compute_device
651
+ )
652
+ tensor = torch.empty(
653
+ chunk_size * fsdp_state.world_size,
654
+ dtype=local_tensor.dtype,
655
+ device=fsdp_state.compute_device,
656
+ )
657
+ with SimpleProfiler.profile(SimpleProfiler.Type.ALLGATHER):
658
+ dist.all_gather_into_tensor(
659
+ tensor, local_tensor, group=fsdp_state.process_group
660
+ )
661
+ tensor = tensor.narrow(0, 0, param_numel).reshape(param.size())
662
+ state_dict[fqn_from_global_root] = tensor
663
+ else:
664
+ if param.device != fsdp_state._device_mesh.device_type:
665
+ param = param.to(fsdp_state._device_mesh.device_type)
666
+
667
+ root_mesh = fsdp_state._device_mesh._get_root_mesh()
668
+ local_tensor = _ext_all_gather_dtensor(
669
+ param, root_mesh, fsdp_state._fsdp_extension
670
+ )
671
+
672
+ if fqn_to_param_ext.get(fqn) is not None:
673
+ ext = fqn_to_param_ext[fqn]
674
+ local_tensor = _ext_post_unflatten_transform(
675
+ local_tensor, ext, fsdp_state._fsdp_extension
676
+ )
677
+ state_dict[fqn_from_global_root] = local_tensor
678
+
679
+ with SimpleProfiler.profile("_enter_unshard_params_ctx"):
680
+ _enter_unshard_params_ctx(module, fsdp_state, writeback=True)
681
+
682
+
683
+ @contextlib.contextmanager
684
+ def _replace_with_full_state_dict_type(fsdp_state: _FSDPState) -> Generator:
685
+ old_state_dict_config = fsdp_state._state_dict_config
686
+ old_state_dict_type = fsdp_state._state_dict_type
687
+ fsdp_state._state_dict_config = FullStateDictConfig()
688
+ fsdp_state._state_dict_type = StateDictType.FULL_STATE_DICT
689
+ yield
690
+ fsdp_state._state_dict_config = old_state_dict_config
691
+ fsdp_state._state_dict_type = old_state_dict_type
692
+
693
+
694
+ @no_type_check
695
+ @torch.no_grad()
696
+ def _post_state_dict_hook(
697
+ module: nn.Module,
698
+ state_dict: dict[str, Any],
699
+ prefix: str,
700
+ *args: Any,
701
+ ) -> dict[str, Any]:
702
+ """
703
+ _post_state_dict_hook() is called after the state_dict() of this
704
+ FSDP module is executed. ``fsdp_state._state_dict_type`` is used to decide
705
+ what postprocessing will be done.
706
+ """
707
+ fsdp_state = _get_module_fsdp_state_if_fully_sharded_module(module)
708
+ if fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD:
709
+ context = _replace_with_full_state_dict_type(fsdp_state)
710
+ warnings.warn(
711
+ "When using ``NO_SHARD`` for ``ShardingStrategy``, full_state_dict will "
712
+ "be returned.",
713
+ stacklevel=2,
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
+ device = None
734
+ if isinstance(tensor, ShardedTensor):
735
+ local_shape = None
736
+ shards = tensor.local_shards()
737
+ if shards:
738
+ local_shape = shards[0].tensor.shape
739
+ device = shards[0].tensor.device
740
+ elif isinstance(tensor, DTensor):
741
+ local_shape = tensor.to_local().shape
742
+ device = tensor.device
743
+ else:
744
+ device = tensor.device
745
+ logger.info(
746
+ "FQN=%s: type=%s, shape=%s, local_shape=%s, dtype=%s, device=%s",
747
+ key,
748
+ type(tensor),
749
+ tensor.shape,
750
+ local_shape,
751
+ tensor.dtype,
752
+ device,
753
+ )
754
+
755
+ return processed_state_dict
756
+
757
+
758
+ @no_type_check
759
+ @torch.no_grad()
760
+ def _pre_state_dict_hook(
761
+ module: nn.Module,
762
+ *args,
763
+ **kwargs,
764
+ ) -> None:
765
+ """
766
+ This is called before the core state dict saving logic of ``module``.
767
+ ``fsdp_state._state_dict_type`` is used to decide what postprocessing will
768
+ be done.
769
+ """
770
+ fsdp_state = _get_module_fsdp_state_if_fully_sharded_module(module)
771
+ if fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD:
772
+ context = _replace_with_full_state_dict_type(fsdp_state)
773
+ warnings.warn(
774
+ "When using ``NO_SHARD`` for ``ShardingStrategy``, full_state_dict will "
775
+ "be returned.",
776
+ stacklevel=2,
777
+ )
778
+ else:
779
+ _set_use_dtensor(fsdp_state)
780
+ context = contextlib.nullcontext()
781
+
782
+ with context:
783
+ _pre_state_dict_hook_fn = {
784
+ StateDictType.FULL_STATE_DICT: _full_pre_state_dict_hook,
785
+ StateDictType.LOCAL_STATE_DICT: _local_pre_state_dict_hook,
786
+ StateDictType.SHARDED_STATE_DICT: _sharded_pre_state_dict_hook,
787
+ }
788
+ _pre_state_dict_hook_fn[fsdp_state._state_dict_type](
789
+ fsdp_state,
790
+ module,
791
+ *args,
792
+ **kwargs,
793
+ )
794
+
795
+
796
+ @no_type_check
797
+ def _set_use_dtensor(fsdp_state: _FSDPState) -> None:
798
+ # If device_mesh is passed in when initializing FSDP, we automatically turn the
799
+ # _use_dtensor flag to be true for ShardedStateDictConfig().
800
+ if getattr(fsdp_state, "_device_mesh", None):
801
+ state_dict_type = fsdp_state._state_dict_type
802
+ if state_dict_type == StateDictType.LOCAL_STATE_DICT:
803
+ raise RuntimeError(
804
+ "Found state_dict_type LOCAL_STATE_DICT. "
805
+ "DeviceMesh is not compatible with LOCAL_STATE_DICT. "
806
+ "Please set state_dict_type to SHARDED_STATE_DICT to get DTensor state_dict."
807
+ )
808
+ else:
809
+ fsdp_state._state_dict_config._use_dtensor = True
810
+
811
+
812
+ @no_type_check
813
+ @torch.no_grad()
814
+ def _pre_load_state_dict_hook(
815
+ module: nn.Module,
816
+ state_dict: dict[str, Any],
817
+ prefix: str,
818
+ *args: Any,
819
+ ) -> None:
820
+ """
821
+ This is called before ``module._load_from_state_dict()``.
822
+ ``fsdp_state._state_dict_type`` is used to decide what preprocessing will
823
+ be done.
824
+ """
825
+ fsdp_state = _get_module_fsdp_state_if_fully_sharded_module(module)
826
+ if fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD:
827
+ context = _replace_with_full_state_dict_type(fsdp_state)
828
+ warnings.warn(
829
+ "When using ``NO_SHARD`` for ``ShardingStrategy``, full_state_dict will"
830
+ "be returned.",
831
+ stacklevel=2,
832
+ )
833
+ else:
834
+ _set_use_dtensor(fsdp_state)
835
+ context = contextlib.nullcontext()
836
+
837
+ _lazy_init(fsdp_state, module)
838
+ if fsdp_state._is_root:
839
+ SimpleProfiler.reset()
840
+
841
+ with context:
842
+ _pre_load_state_dict_hook_fn = {
843
+ StateDictType.FULL_STATE_DICT: _full_pre_load_state_dict_hook,
844
+ StateDictType.LOCAL_STATE_DICT: _local_pre_load_state_dict_hook,
845
+ StateDictType.SHARDED_STATE_DICT: _sharded_pre_load_state_dict_hook,
846
+ }
847
+ # Code that is common for all state_dict impls
848
+ if fsdp_state._device_handle.is_available():
849
+ fsdp_state._device_handle.synchronize()
850
+ # Dispatch into state_dict specific implementation of pre-hook.
851
+ _pre_load_state_dict_hook_fn[fsdp_state._state_dict_type](
852
+ module, fsdp_state, state_dict, prefix
853
+ )
854
+
855
+
856
+ @no_type_check
857
+ @torch.no_grad()
858
+ def _post_load_state_dict_hook(
859
+ module: nn.Module,
860
+ incompatible_keys: tuple[list[str], list[str]],
861
+ *args: Any,
862
+ ) -> None:
863
+ fsdp_state = _get_module_fsdp_state_if_fully_sharded_module(module)
864
+ if fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD:
865
+ context = _replace_with_full_state_dict_type(fsdp_state)
866
+ warnings.warn(
867
+ "When using ``NO_SHARD`` for ``ShardingStrategy``, full_state_dict will"
868
+ "be returned.",
869
+ stacklevel=2,
870
+ )
871
+ else:
872
+ context = contextlib.nullcontext()
873
+
874
+ with context:
875
+ _post_load_state_dict_hook_fn = {
876
+ StateDictType.FULL_STATE_DICT: _full_post_load_state_dict_hook,
877
+ StateDictType.LOCAL_STATE_DICT: _local_post_load_state_dict_hook,
878
+ StateDictType.SHARDED_STATE_DICT: _sharded_post_load_state_dict_hook,
879
+ }
880
+ # Code that is common for all state_dict impls
881
+ # Dispatch into state_dict type specific implementation of post-hook for
882
+ # loading state_dict.
883
+ _post_load_state_dict_hook_fn[fsdp_state._state_dict_type](module, fsdp_state)
884
+
885
+ # When reporting incompatible keys, trim FSDP prefixes.
886
+ missing_keys = incompatible_keys[0]
887
+ unexpected_keys = incompatible_keys[1]
888
+ for i in range(len(missing_keys)):
889
+ missing_keys[i] = clean_tensor_name(missing_keys[i])
890
+
891
+ for i in range(len(unexpected_keys)):
892
+ unexpected_keys[i] = clean_tensor_name(unexpected_keys[i])
893
+
894
+ if fsdp_state._is_root:
895
+ SimpleProfiler.dump_and_reset("FSDP model load_state_dict profiling: ")
896
+
897
+
898
+ def _register_all_state_dict_hooks(state: _FSDPState):
899
+ """
900
+ Registers pre-save, post-save, pre-load, and post-load state dict hooks.
901
+ """
902
+ for hook_registration_fn_str, hook, hook_registration_fn_kwargs in (
903
+ ("register_state_dict_pre_hook", _pre_state_dict_hook, {}),
904
+ ("_register_state_dict_hook", _post_state_dict_hook, {}),
905
+ (
906
+ "_register_load_state_dict_pre_hook",
907
+ _pre_load_state_dict_hook,
908
+ {"with_module": True},
909
+ ),
910
+ ("register_load_state_dict_post_hook", _post_load_state_dict_hook, {}),
911
+ ):
912
+ _register_state_dict_hooks_base(
913
+ state, hook_registration_fn_str, hook, hook_registration_fn_kwargs
914
+ )
915
+
916
+
917
+ @no_type_check
918
+ def _register_state_dict_hooks_base(
919
+ state: _FSDPState,
920
+ hook_registration_fn_name: str,
921
+ hook: Callable,
922
+ hook_registration_fn_kwargs: dict[str, Any],
923
+ ) -> None:
924
+ """Registers ``hook`` using ``hook_registration_fn``."""
925
+ if not _is_composable(state):
926
+ getattr(state, hook_registration_fn_name)(hook, **hook_registration_fn_kwargs)
927
+ else:
928
+ handle = state._handle
929
+ if handle:
930
+ getattr(handle._fully_sharded_module, hook_registration_fn_name)(
931
+ hook, **hook_registration_fn_kwargs
932
+ )
venv/lib/python3.14/site-packages/torch/distributed/fsdp/_trace_utils.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import functools
3
+ from collections.abc import Callable
4
+ from contextlib import contextmanager
5
+ from dataclasses import dataclass, field
6
+ from typing import Any, NamedTuple
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+
11
+
12
+ @dataclass
13
+ class TracingConfig:
14
+ """
15
+ This represents a symbolic tracing configuration.
16
+
17
+ Args:
18
+ tracer (torch.fx.Tracer): An instance of :class:`torch.fx.Tracer` to
19
+ use for symbolic tracing. The default value is the native
20
+ :class:`torch.fx.Tracer` constructed with default arguments.
21
+ However, the user may want to pass a different value such as the
22
+ ``HFTracer`` for models in the HuggingFace Transformers_ library.
23
+ .. _Transformers: https://huggingface.co/docs/transformers/index
24
+ concrete_args (Optional[Dict[str, Any]]): Concrete arguments that
25
+ should not be treated as ``torch.fx.Proxy`` when tracing the
26
+ module ``forward()``. Passing ``concrete_args`` allows partially
27
+ specializing the forward, e.g. to remove control flow or data
28
+ structures. This ``concrete_args`` here is the same argument used
29
+ in :meth:`~torch.fx.Tracer.trace`.
30
+ """
31
+
32
+ tracer: torch.fx.Tracer = field(default_factory=torch.fx.Tracer)
33
+ concrete_args: dict[str, Any] | None = None
34
+
35
+
36
+ class _ParamUsageInfo(NamedTuple):
37
+ """
38
+ This is used for ``_ExecutionInfo.module_to_param_usage_infos`` to record
39
+ execution information. The ``dict`` maps modules to a list of these
40
+ ``_ParamUsageInfo`` instances, where each instance represents a group of
41
+ parameters used together.
42
+
43
+ Specifically, for each module key in the ``dict``, each instance of this
44
+ class represents either:
45
+ (1) the module and some sublist of its ``named_parameters()`` used
46
+ together in execution (see ``_patched_create_proxy()``), or
47
+ (2) a submodule and all of ``submodule.named_parameters()`` (see
48
+ ``_patched_call_module()``).
49
+
50
+ Type (1) corresponds to directly using parameters in ops without calling
51
+ ``forward()``, and type (2) corresponds to calling ``forward()``. The
52
+ mapped-to lists in the ``dict`` follow the execution order.
53
+ """
54
+
55
+ module: nn.Module
56
+ named_params: list[tuple[str, nn.Parameter]]
57
+
58
+
59
+ class _ExecutionInfo:
60
+ """
61
+ This represents the execution order information from the forward pass.
62
+
63
+ Attributes:
64
+ curr_module (nn.Module): Current module being traced.
65
+ module_forward_order (List[nn.Module]): The modules in (pre-)forward
66
+ order, i.e. the order in which their ``forward()`` methods are
67
+ called. Each call to a module's ``forward()`` corresponds to one
68
+ element in the list.
69
+ module_to_param_usage_infos (Dict[nn.Module, List[_ParamUsageInfo]]):
70
+ Maps a module to a list of module execution infos. See
71
+ :class:`_ParamUsageInfo` for details.
72
+ param_forward_order (List[nn.Parameter]): The parameters in forward
73
+ execution order, where only a parameter's first participation is
74
+ included.
75
+ visited_params (Set[nn.Parameter]): The parameters visited so far
76
+ during the trace. This is only used during tracing for fast
77
+ membership check. Invariant: The parameters in
78
+ ``param_forward_order`` are exactly those in ``visited_params``.
79
+ """
80
+
81
+ def __init__(self, root_module: nn.Module) -> None:
82
+ self.curr_module: nn.Module = root_module
83
+ self.module_forward_order: list[nn.Module] = [root_module]
84
+ self.module_to_param_usage_infos: dict[nn.Module, list[_ParamUsageInfo]] = {
85
+ root_module: []
86
+ }
87
+ self.param_forward_order: list[nn.Parameter] = []
88
+ self.visited_params: set[nn.Parameter] = set()
89
+
90
+
91
+ class _ExecOrderTracer:
92
+ def __init__(self) -> None:
93
+ self.exec_info: _ExecutionInfo | None = None
94
+
95
+ @contextmanager
96
+ def patch_tracer(self, tracer: torch.fx.Tracer, root_module: nn.Module):
97
+ self.exec_info = _ExecutionInfo(root_module)
98
+ orig_call_module = tracer.call_module
99
+ orig_create_proxy = tracer.create_proxy
100
+ tracer.call_module = functools.partial( # type: ignore[method-assign]
101
+ self._patched_call_module, orig_call_module, self.exec_info
102
+ )
103
+ fqn_to_param = dict(root_module.named_parameters())
104
+ tracer.create_proxy = functools.partial( # type: ignore[method-assign]
105
+ self._patched_create_proxy,
106
+ orig_create_proxy,
107
+ self.exec_info,
108
+ fqn_to_param,
109
+ )
110
+ try:
111
+ yield
112
+ finally:
113
+ tracer.call_module = orig_call_module # type: ignore[method-assign]
114
+ tracer.create_proxy = orig_create_proxy # type: ignore[method-assign]
115
+
116
+ def _patched_call_module(
117
+ self,
118
+ call_module: Callable,
119
+ exec_info: _ExecutionInfo,
120
+ # Below are the expected arguments to `call_module()`
121
+ module: nn.Module,
122
+ forward: Callable,
123
+ args: tuple[Any, ...],
124
+ kwargs: dict[str, Any],
125
+ ) -> Any:
126
+ """
127
+ Overrides ``call_module`` to save execution information to
128
+ ``exec_info``. Note that ``call_module`` is called during symbolic
129
+ tracing for each non-root module.
130
+
131
+ Args:
132
+ call_module (Callable): Original ``call_module`` to override.
133
+ exec_info (_ExecutionInfo): Used to record execution information.
134
+ module (nn.Module): Module corresponding to this ``call_module``.
135
+ forward (Callable): ``forward()`` method of ``module`` to be called
136
+ for this ``call_module``.
137
+ args (Tuple[Any, ...]): Positional arguments for ``forward``.
138
+ kwargs (Dict[str, Any]): Keyword arguments for ``forward``.
139
+
140
+ Returns:
141
+ Same return value as ``call_module``.
142
+ """
143
+ exec_info.module_forward_order.append(module)
144
+ named_params = list(module.named_parameters())
145
+ curr_module = exec_info.curr_module
146
+ if named_params:
147
+ if curr_module not in exec_info.module_to_param_usage_infos:
148
+ raise AssertionError(
149
+ "The current module should have already been processed by a patched `call_module`"
150
+ )
151
+ exec_info.module_to_param_usage_infos[exec_info.curr_module].append(
152
+ _ParamUsageInfo(module, named_params)
153
+ )
154
+ prev_curr_module = curr_module
155
+ exec_info.curr_module = module
156
+ exec_info.module_to_param_usage_infos[module] = []
157
+ output = call_module(module, forward, args, kwargs)
158
+ exec_info.curr_module = prev_curr_module
159
+ return output
160
+
161
+ def _patched_create_proxy(
162
+ self,
163
+ create_proxy: Callable,
164
+ exec_info: _ExecutionInfo,
165
+ fqn_to_param: dict[str, nn.Parameter],
166
+ # Below are the expected arguments to `create_proxy()`
167
+ kind: str,
168
+ target: torch.fx.node.Target,
169
+ args: tuple[Any, ...],
170
+ kwargs: dict[str, Any],
171
+ name: str | None = None,
172
+ type_expr: Any | None = None,
173
+ proxy_factory_fn: Callable[[torch.fx.Node], torch.fx.Proxy] | None = None,
174
+ ) -> torch.fx.Proxy:
175
+ """
176
+ Overrides ``create_proxy`` to save execution information to
177
+ ``exec_info``. Note that ``create_proxy`` is called during symbolic
178
+ tracing for each leaf function/method/module.
179
+
180
+ Args:
181
+ create_proxy (Callable): Original ``create_proxy`` to override.
182
+ exec_info (_ExecutionInfo): Used to record execution information.
183
+ fqn_to_param (Dict[str, nn.Parameter]): ``dict`` version of the
184
+ root module's ``named_parameters()`` with FQN as key and
185
+ parameter as value.
186
+ kind (str): Kind of the target method ('call_function',
187
+ 'call_method', 'get_attr', 'call_module', 'placeholder', or
188
+ 'output'). See :class:`torch.fx.Graph` for details. This is
189
+ passed to ``create_proxy``.
190
+ target (torch.fx.node.Target): Contains the string name of the
191
+ function/method/module. This is passed to ``create_proxy``.
192
+ args (Tuple[Any, ...]): Positional arguments for the function/
193
+ method/module. This is passed to ``create_proxy``.
194
+ kwargs (Dict[str, Any]): Keyword arguments for the function/method/
195
+ module. This is passed to ``create_proxy``
196
+ name (Optional[str]): An optional string name for the ``Node``
197
+ created in ``create_proxy``. This is passed to
198
+ ``create_proxy``.
199
+ type_expr (Optional[Any]): An optional type annotation representing
200
+ the Python type that the output of the node has. This is passed
201
+ to ``create_proxy``.
202
+ proxy_factory_fn (Callable[[torch.fx.Node], torch.fx.Proxy]):
203
+ An alternative proxy constructor used in ``create_proxy``. This
204
+ is passed to ``create_proxy``.
205
+
206
+ Returns:
207
+ torch.fx.Proxy: Created ``Node`` wrapped in a ``Proxy`` object.
208
+ """
209
+ proxy = create_proxy(
210
+ kind, target, args, kwargs, name, type_expr, proxy_factory_fn
211
+ )
212
+ curr_module = exec_info.curr_module
213
+ if kind in ("call_function", "call_method"):
214
+ if args is not None:
215
+ named_params: list[tuple[str, nn.Parameter]] = []
216
+ for arg in args:
217
+ if (
218
+ isinstance(arg, torch.fx.Proxy)
219
+ and arg.node.target in fqn_to_param
220
+ ):
221
+ param = fqn_to_param[arg.node.target] # type: ignore[index]
222
+ named_params.append((arg.node.target, param)) # type: ignore[arg-type]
223
+ if param not in exec_info.visited_params:
224
+ exec_info.visited_params.add(param)
225
+ exec_info.param_forward_order.append(param)
226
+ if named_params:
227
+ exec_info.module_to_param_usage_infos[curr_module].append(
228
+ _ParamUsageInfo(curr_module, named_params)
229
+ )
230
+ elif kind == "call_module":
231
+ named_params = list(curr_module.named_parameters())
232
+ if named_params:
233
+ exec_info.module_to_param_usage_infos[curr_module].append(
234
+ _ParamUsageInfo(curr_module, named_params)
235
+ )
236
+ for _, param in named_params:
237
+ if param not in exec_info.visited_params:
238
+ exec_info.visited_params.add(param)
239
+ exec_info.param_forward_order.append(param)
240
+ return proxy
venv/lib/python3.14/site-packages/torch/distributed/fsdp/_traversal_utils.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ NOTE: This file must be imported like
3
+ ``import torch.distributed.fsdp._traversal_utils`` and not like
4
+ ``from torch.distributed.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
+
10
+ import torch.nn as nn
11
+ from torch.distributed._composable.contract import _get_registry
12
+ from torch.distributed.fsdp._common_utils import _FSDPState, _get_module_fsdp_state
13
+
14
+
15
+ """
16
+ [Note: FSDP State Traversal]
17
+ For the wrapper code path, ``_FSDPState`` is the ``FullyShardedDataParallel``
18
+ module wrapping a fully sharded module, and for the non-wrapper code path,
19
+ ``_FSDPState`` is an object that gets embedded on a fully sharded module.
20
+ See [Note: Fully Sharded Module] for the definition.
21
+
22
+ There are three common traversal idioms: Given a root module,
23
+ - ``_get_fsdp_states()`` returns all ``_FSDPState`` s in the tree.
24
+ - ``get_fsdp_root_states()`` returns all local root ``_FSDPState`` s in the
25
+ tree (i.e. those with ``_is_root == True``).
26
+ - ``_get_fsdp_handles()``returns all ``FlatParamHandle`` s in the tree.
27
+
28
+ All of these methods must take in the root module (i.e. an ``nn.Module``) and
29
+ not a general ``_FSDPState`` because ``_FSDPState`` does not support a graph
30
+ traversal, whereas ``nn.Module`` has ``nn.Module.modules()`` for traversal.
31
+ """
32
+
33
+
34
+ def _composable(module: nn.Module) -> bool:
35
+ """
36
+ Returns if ``module`` can compose with ``fully_shard``.
37
+ """
38
+ # TODO: Add any other composable APIs that are mutually exclusive.
39
+ registry = _get_registry(module)
40
+ if registry is None:
41
+ return True
42
+ return "replicate" not in registry
43
+
44
+
45
+ # TODO (awgu): We may be able to remove this function if we retired the
46
+ # `use_orig_params=False` code path since so far we only need the module for
47
+ # `FlatParameter` registration, which is not needed for `use_orig_params=True`.
48
+ def _get_fsdp_states_with_modules(
49
+ module: nn.Module,
50
+ ) -> tuple[list[_FSDPState], list[nn.Module]]:
51
+ """
52
+ Returns a tuple containing:
53
+ 1. A list of the ``_FSDPState`` instances in the module tree rooted at
54
+ ``module`` without any duplicates and following the ``module.modules()``
55
+ traversal order (which is assumed to be depth-first).
56
+ 2. A corresponding list of the modules owning the states in the first list.
57
+
58
+ For the wrapper code path, both returned lists are the same, each
59
+ containing all ``FullyShardedDataParallel`` instances. For the composable
60
+ code path, this returns a list of all composable state instances and a list
61
+ of the corresponding fully sharded modules. See [Note: Fully Sharded
62
+ Module].
63
+
64
+ NOTE: The traversal does not proceed into any module annotated by an
65
+ incompatible API (e.g. ``replicate``).
66
+ """
67
+ fsdp_states: list[_FSDPState] = []
68
+ fsdp_modules: list[nn.Module] = []
69
+ # Track the visited FSDP states since multiple modules may share the same
70
+ # one and we want to return a de-duplicated list
71
+ visited_fsdp_states: set[_FSDPState] = set()
72
+ # Track the visited modules in case of shared modules, which implies the
73
+ # module graph is no longer a tree
74
+ visited_modules: set[nn.Module] = set()
75
+
76
+ # Perform depth-first search from `module` to ensure that we do not
77
+ # traverse into an incompatible API's subtree (use DFS instead of BFS to
78
+ # match `.modules()` order)
79
+ deque: collections.deque[nn.Module] = collections.deque([module])
80
+ while deque:
81
+ submodule = deque.popleft()
82
+ visited_modules.add(submodule)
83
+ if not _composable(submodule):
84
+ continue
85
+ for child_module in reversed(list(submodule.children())):
86
+ if child_module not in visited_modules:
87
+ deque.appendleft(child_module)
88
+ optional_state = _get_module_fsdp_state(submodule)
89
+ if optional_state is not None and optional_state not in visited_fsdp_states:
90
+ visited_fsdp_states.add(optional_state)
91
+ fsdp_states.append(optional_state)
92
+ fsdp_modules.append(submodule)
93
+ return fsdp_states, fsdp_modules
94
+
95
+
96
+ def _get_fsdp_states(module: nn.Module) -> list[_FSDPState]:
97
+ """See :func:`_get_fsdp_states_with_modules`."""
98
+ fsdp_states, _ = _get_fsdp_states_with_modules(module)
99
+ return fsdp_states
100
+
101
+
102
+ def _get_fsdp_handles(module: nn.Module) -> list:
103
+ """
104
+ Returns all ``FlatParamHandle`` s in the module tree rooted at ``module``
105
+ following the rules in :func:`_get_fsdp_state`.
106
+ """
107
+ handles = [
108
+ fsdp_state._handle
109
+ for fsdp_state in _get_fsdp_states(module)
110
+ if fsdp_state._handle is not None
111
+ ]
112
+ return handles
venv/lib/python3.14/site-packages/torch/distributed/fsdp/_unshard_param_utils.py ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import contextlib
3
+ import warnings
4
+ from collections.abc import Generator
5
+ from typing import cast
6
+
7
+ import torch
8
+ import torch.distributed.fsdp._traversal_utils as traversal_utils
9
+ import torch.nn as nn
10
+ from torch.distributed.fsdp._common_utils import (
11
+ _FSDPState,
12
+ _get_module_fsdp_state,
13
+ _has_fsdp_params,
14
+ _module_handle,
15
+ HandleTrainingState,
16
+ TrainingState,
17
+ )
18
+ from torch.distributed.fsdp._runtime_utils import (
19
+ _lazy_init,
20
+ _reset_flat_param_grad_info_if_needed,
21
+ _reshard,
22
+ _reshard_grads,
23
+ _unshard,
24
+ _unshard_grads,
25
+ )
26
+ from torch.distributed.utils import _p_assert
27
+
28
+ from ._flat_param import FlatParamHandle
29
+
30
+
31
+ FLAT_PARAM = "_flat_param"
32
+
33
+
34
+ @torch.no_grad()
35
+ def _writeback_to_local_shard(
36
+ handle: FlatParamHandle,
37
+ writeback_grad: bool,
38
+ ):
39
+ """
40
+ For the handle, writes back the this rank's shard of the unsharded
41
+ flattened parameter to the sharded flattened parameter. If
42
+ ``writeback_grad=True``, then writes back to the sharded gradient as
43
+ well.
44
+
45
+ Precondition: The handle's ``FlatParameter`` 's data points to the
46
+ padded unsharded flattened parameter.
47
+ """
48
+
49
+ def _get_shard(flat_param_or_grad: torch.Tensor) -> torch.Tensor:
50
+ if handle.uses_sharded_strategy:
51
+ # For sharded strategies, get the *unpadded* shard instead of
52
+ # the *padded* shard to persist user changes to the padding
53
+ # (though FSDP does not explicitly support this)
54
+ shard, _ = FlatParamHandle._get_unpadded_shard(
55
+ flat_param_or_grad,
56
+ handle.rank,
57
+ handle.world_size,
58
+ )
59
+ return shard
60
+ # For `NO_SHARD`, the `flat_param` or its gradient may be modified,
61
+ # so we write it back directly
62
+ return flat_param_or_grad
63
+
64
+ param_shard = _get_shard(handle.flat_param)
65
+ handle.flat_param._local_shard[: param_shard.numel()].copy_(param_shard) # type: ignore[attr-defined]
66
+ if writeback_grad:
67
+ existing_grad = handle.sharded_grad
68
+ if existing_grad is not None:
69
+ if handle.flat_param.grad is None:
70
+ raise AssertionError("Expected handle.flat_param.grad to not be None")
71
+ grad_shard = _get_shard(handle.flat_param.grad)
72
+ existing_grad[: grad_shard.numel()].copy_(grad_shard)
73
+
74
+
75
+ def _deregister_flat_param(state: _FSDPState, module: nn.Module) -> None:
76
+ """
77
+ De-registers the flattened parameter from the wrapped module, hiding it
78
+ from ``nn.Module`` methods.
79
+
80
+ We do not use ``del`` because we want ``FLAT_PARAM`` to always be an
81
+ attribute but dynamically change whether it is visible to ``nn.Module``
82
+ methods.
83
+ """
84
+ if _has_fsdp_params(state, module):
85
+ # TODO: figure out the case for the composable APIs.
86
+ cast(nn.Module, module.module)._parameters.pop(FLAT_PARAM, None)
87
+
88
+
89
+ def _register_flat_param(state: _FSDPState, module: nn.Module) -> None:
90
+ """
91
+ Registers the flattened parameter to the wrapped module, making it
92
+ visible to ``nn.Module`` methods.
93
+
94
+ We do not use :meth:`nn.Module.register_parameter` because we want
95
+ ``FLAT_PARAM`` to always be an attribute but dynamically change whether
96
+ it is visible to ``nn.Module`` methods.
97
+ """
98
+ handle = _module_handle(state, module)
99
+ if _has_fsdp_params(state, module):
100
+ # TODO: figure out the case for the composable APIs.
101
+ cast(nn.Module, module.module)._parameters[FLAT_PARAM] = handle.flat_param
102
+
103
+
104
+ @contextlib.contextmanager
105
+ def _unflatten_as_params(state: _FSDPState, module: nn.Module) -> Generator:
106
+ """
107
+ Assumes that the flattened parameter is unsharded. When in the context,
108
+ de-registers the flattened parameter and unflattens the original
109
+ parameters as ``nn.Parameter`` views into the flattened parameter.
110
+ After the context, re-registers the flattened parameter and restores
111
+ the original parameters as ``Tensor`` views into the flattened
112
+ parameter.
113
+ """
114
+ handle = _module_handle(state, module)
115
+ if not handle:
116
+ yield
117
+ else:
118
+ _deregister_flat_param(state, module)
119
+ try:
120
+ with handle.unflatten_as_params():
121
+ yield
122
+ finally:
123
+ if not handle._use_orig_params:
124
+ _register_flat_param(state, module)
125
+
126
+
127
+ def _validate_unshard_params_args(
128
+ state: _FSDPState,
129
+ writeback: bool,
130
+ rank0_only: bool,
131
+ offload_to_cpu: bool,
132
+ with_grads: bool,
133
+ ) -> None:
134
+ if with_grads and (offload_to_cpu or not state._use_orig_params):
135
+ raise NotImplementedError(
136
+ f"with_grads={with_grads}, "
137
+ f"use_orig_params={state._use_orig_params}, "
138
+ f"offload_to_cpu={offload_to_cpu} "
139
+ f"is not supported yet"
140
+ )
141
+ if offload_to_cpu and state._handle and (not state._handle.uses_sharded_strategy):
142
+ raise NotImplementedError(
143
+ "offload_to_cpu=True and NO_SHARD is not supported yet"
144
+ )
145
+ if writeback and rank0_only:
146
+ # TODO: Rank 0 can broadcast the `FlatParameter` to allow all ranks to
147
+ # persist the changes.
148
+ raise NotImplementedError(
149
+ "writeback=True and rank0_only=True is not supported yet"
150
+ )
151
+ if offload_to_cpu and not rank0_only:
152
+ warnings.warn(
153
+ "offload_to_cpu=True and rank0_only=False may result in the"
154
+ "unsharded parameters being redundantly copied to CPU memory for "
155
+ "GPUs sharing the same CPU memory, which risks CPU OOM. We "
156
+ "recommend using offload_to_cpu=True with rank0_only=True.",
157
+ stacklevel=2,
158
+ )
159
+
160
+
161
+ @contextlib.contextmanager
162
+ def _unshard_fsdp_state_params(
163
+ module: nn.Module,
164
+ state: _FSDPState,
165
+ writeback: bool,
166
+ rank0_only: bool,
167
+ offload_to_cpu: bool,
168
+ with_grads: bool,
169
+ ):
170
+ """
171
+ This unshards the parameters for a single FSDP state ``state`` that
172
+ corresponds to ``module``.
173
+ """
174
+ _validate_unshard_params_args(
175
+ state, writeback, rank0_only, offload_to_cpu, with_grads
176
+ )
177
+ state._device_handle.synchronize()
178
+ # If handles are shared by other module(s), the handle may be already unsharded.
179
+ maybe_handle = _module_handle(state, module)
180
+ handle = None
181
+ if (
182
+ maybe_handle
183
+ and maybe_handle._training_state != HandleTrainingState.SUMMON_FULL_PARAMS
184
+ ):
185
+ handle = maybe_handle
186
+ if not handle:
187
+ yield
188
+ return
189
+
190
+ if handle._training_state != HandleTrainingState.IDLE:
191
+ raise AssertionError(
192
+ f"Expects the handle training to be IDLE but got {handle._training_state}"
193
+ )
194
+
195
+ handle._training_state = HandleTrainingState.SUMMON_FULL_PARAMS
196
+
197
+ _reset_flat_param_grad_info_if_needed(handle)
198
+ free_unsharded_flat_param = handle.needs_unshard()
199
+ # No need to call `wait_stream()` since we unshard in the computation
200
+ # stream directly
201
+ computation_stream = state._device_handle.current_stream()
202
+ _unshard(state, handle, computation_stream, computation_stream)
203
+ if with_grads:
204
+ _unshard_grads(handle)
205
+
206
+ if rank0_only and state.rank != 0:
207
+ # Free the unsharded flattened parameter early
208
+ _reshard(state, handle, free_unsharded_flat_param)
209
+ if with_grads:
210
+ _reshard_grads(handle)
211
+ try:
212
+ yield
213
+ finally:
214
+ handle._training_state = HandleTrainingState.IDLE
215
+ else:
216
+ # Unflatten the unsharded flattened parameters
217
+ with contextlib.ExitStack() as stack:
218
+ # Invariant: rank == 0 or !rank0_only
219
+ if offload_to_cpu and handle.uses_sharded_strategy:
220
+ stack.enter_context(handle.to_cpu())
221
+ # NOTE: Since PyTorch enforces that a parameter and its
222
+ # gradients need to match metadata (e.g. device), we must
223
+ # move gradients to CPU *after* we move parameters.
224
+ # NOTE: This assumes 1 `FlatParameter`
225
+ if not state._use_orig_params:
226
+ stack.enter_context(_unflatten_as_params(state, module))
227
+ try:
228
+ yield
229
+ finally:
230
+ stack.close()
231
+ if writeback:
232
+ _writeback_to_local_shard(handle, with_grads)
233
+ _reshard(state, handle, free_unsharded_flat_param)
234
+ if with_grads:
235
+ _reshard_grads(handle)
236
+ handle._training_state = HandleTrainingState.IDLE
237
+
238
+
239
+ @contextlib.contextmanager
240
+ def _unshard_params_for_summon(
241
+ module: nn.Module,
242
+ state: _FSDPState,
243
+ writeback: bool,
244
+ rank0_only: bool,
245
+ offload_to_cpu: bool,
246
+ with_grads: bool,
247
+ ):
248
+ _validate_unshard_params_args(
249
+ state, writeback, rank0_only, offload_to_cpu, with_grads
250
+ )
251
+ _lazy_init(state, module)
252
+ if state.training_state == TrainingState.FORWARD_BACKWARD:
253
+ raise AssertionError(
254
+ "Cannot manually unshard parameters during forward/backward"
255
+ )
256
+ elif state.training_state == TrainingState.SUMMON_FULL_PARAMS:
257
+ raise AssertionError(
258
+ "Cannot manually unshard parameters when already unsharding parameters"
259
+ )
260
+ with _unshard_fsdp_state_params(
261
+ module=module,
262
+ state=state,
263
+ writeback=writeback,
264
+ rank0_only=rank0_only,
265
+ offload_to_cpu=offload_to_cpu,
266
+ with_grads=with_grads,
267
+ ):
268
+ try:
269
+ state.training_state = TrainingState.SUMMON_FULL_PARAMS
270
+ yield
271
+ finally:
272
+ state.training_state = TrainingState.IDLE
273
+
274
+
275
+ @contextlib.contextmanager
276
+ def _unshard_params(
277
+ module: nn.Module,
278
+ recurse: bool,
279
+ writeback: bool,
280
+ rank0_only: bool,
281
+ offload_to_cpu: bool,
282
+ with_grads: bool,
283
+ ):
284
+ """
285
+ This unshards FSDP-managed parameters for all modules with FSDP applied in
286
+ the module tree rooted at ``module``.
287
+ """
288
+ if not recurse:
289
+ optional_state = _get_module_fsdp_state(module)
290
+ if optional_state is None:
291
+ with contextlib.nullcontext():
292
+ yield
293
+ return
294
+ states_and_modules = ([optional_state], [module])
295
+ else:
296
+ states_and_modules = traversal_utils._get_fsdp_states_with_modules(module)
297
+ with contextlib.ExitStack() as stack:
298
+ for state, module in zip(*states_and_modules):
299
+ stack.enter_context(
300
+ _unshard_params_for_summon(
301
+ module=module,
302
+ state=state,
303
+ writeback=writeback,
304
+ rank0_only=rank0_only,
305
+ offload_to_cpu=offload_to_cpu,
306
+ with_grads=with_grads,
307
+ )
308
+ )
309
+ yield
310
+
311
+
312
+ def _deregister_orig_params(state: _FSDPState, module: nn.Module) -> None:
313
+ """
314
+ Deregisters the original parameters; registers the ``FlatParameter``.
315
+ """
316
+ handle = _module_handle(state, module)
317
+ if not handle:
318
+ return
319
+ _p_assert(
320
+ handle._use_orig_params,
321
+ f"Inconsistent `_use_orig_params` -- FSDP: {state._use_orig_params} "
322
+ f"handle: {handle._use_orig_params}",
323
+ )
324
+ handle._deregister_orig_params()
325
+ _register_flat_param(state, module)
326
+
327
+
328
+ def _register_orig_params(state: _FSDPState, module: nn.Module) -> None:
329
+ """
330
+ Deregisters the ``FlatParameter``; registers the original parameters.
331
+ """
332
+ handle = _module_handle(state, module)
333
+ if not handle:
334
+ return
335
+ _deregister_flat_param(state, module)
336
+ if handle.is_sharded(handle.flat_param):
337
+ handle._use_sharded_views()
338
+ handle._use_sharded_grad_views()
339
+ else:
340
+ handle._use_unsharded_views(as_params=True)
venv/lib/python3.14/site-packages/torch/distributed/fsdp/_wrap_utils.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import collections
3
+ import functools
4
+ import inspect
5
+ import warnings
6
+ from collections.abc import Callable
7
+ from functools import partial
8
+ from typing import Any
9
+
10
+ import torch.nn as nn
11
+ from torch.distributed.fsdp._common_utils import (
12
+ _get_module_fsdp_state,
13
+ _override_module_mixed_precision,
14
+ )
15
+ from torch.distributed.fsdp.wrap import (
16
+ _construct_wrap_fn,
17
+ _or_policy,
18
+ _Policy,
19
+ _post_order_apply,
20
+ _recursive_wrap,
21
+ _run_mixed_precision_override_policy,
22
+ _wrap_module_cls_individually,
23
+ )
24
+
25
+
26
+ def _auto_wrap(
27
+ root_module: nn.Module,
28
+ policy: Callable | _Policy,
29
+ ignored_modules: set[nn.Module],
30
+ ignored_params: set[nn.Parameter],
31
+ root_kwargs: dict[str, Any],
32
+ fsdp_fn: Callable, # e.g. `FullyShardedDataParallel` or `fully_shard`
33
+ ):
34
+ """
35
+ Auto wraps modules in ``root_module`` 's tree according to ``policy``
36
+ following a post-order traversal.
37
+
38
+ Precondition: ``root_kwargs`` should contain all arguments except
39
+ ``module``. This function accepts the kwargs dict directly since it gets
40
+ forwarded into the post-order traversal function.
41
+ """
42
+ mixed_precision = root_kwargs["mixed_precision"]
43
+ is_wrapper = inspect.isclass(fsdp_fn)
44
+ # TODO: We may relax this no-nested-wrapping constraint to support manual
45
+ # wrapping followed by auto wrapping.
46
+ _check_nested_wrapping(root_module)
47
+
48
+ if isinstance(policy, _Policy):
49
+ root_kwargs["auto_wrap_policy" if is_wrapper else "policy"] = None
50
+ target_module_to_kwargs = policy._run_policy(
51
+ root_module, ignored_modules, root_kwargs
52
+ )
53
+ if mixed_precision is not None:
54
+ target_module_to_kwargs = _run_mixed_precision_override_policy(
55
+ root_module,
56
+ mixed_precision._module_classes_to_ignore,
57
+ ignored_modules,
58
+ root_kwargs,
59
+ target_module_to_kwargs,
60
+ )
61
+ overridden_module_classes = _override_module_mixed_precision(
62
+ root_module, mixed_precision._module_classes_to_ignore
63
+ )
64
+ _warn_on_overridden_mixed_precision(overridden_module_classes)
65
+ use_orig_params = root_kwargs.get("use_orig_params", False)
66
+ _validate_frozen_params(
67
+ root_module,
68
+ set(target_module_to_kwargs.keys()),
69
+ ignored_params,
70
+ use_orig_params,
71
+ )
72
+ wrap_fn = _construct_wrap_fn(root_module, target_module_to_kwargs, fsdp_fn)
73
+ _post_order_apply(root_module, wrap_fn)
74
+ return
75
+
76
+ recursive_wrap_kwargs = {
77
+ "module": root_module,
78
+ "auto_wrap_policy": policy,
79
+ "wrapper_cls": fsdp_fn,
80
+ "ignored_modules": ignored_modules,
81
+ "ignored_params": ignored_params,
82
+ "only_wrap_children": True,
83
+ }
84
+ if mixed_precision is not None:
85
+ # Wrap modules of the ignored types separately and register forward
86
+ # hooks to cast to fp32 and back to the original dtype, respectively
87
+ overridden_module_classes = _override_module_mixed_precision(
88
+ root_module, mixed_precision._module_classes_to_ignore
89
+ )
90
+ policy = functools.partial(
91
+ _or_policy,
92
+ policies=[
93
+ policy,
94
+ partial(
95
+ _wrap_module_cls_individually,
96
+ module_classes=mixed_precision._module_classes_to_ignore,
97
+ ),
98
+ ],
99
+ )
100
+ recursive_wrap_kwargs["auto_wrap_policy"] = policy
101
+ _warn_on_overridden_mixed_precision(overridden_module_classes)
102
+ _recursive_wrap(**recursive_wrap_kwargs, **root_kwargs) # type: ignore[arg-type]
103
+
104
+
105
+ def _check_nested_wrapping(root_module: nn.Module):
106
+ for module_name, module in root_module.named_modules():
107
+ if _get_module_fsdp_state(module) is not None:
108
+ raise ValueError(
109
+ "FSDP auto wrapping requires modules to not already have "
110
+ f"FSDP applied but found {module_name} in\n{root_module}"
111
+ )
112
+
113
+
114
+ def _warn_on_overridden_mixed_precision(
115
+ overridden_module_classes: set[type[nn.Module]],
116
+ ):
117
+ if len(overridden_module_classes) == 0:
118
+ return
119
+ warnings.warn(
120
+ "Both mixed precision and an auto_wrap_policy were specified to FSDP, "
121
+ f"where the wrapped module has submodules of type:\n{overridden_module_classes}\n"
122
+ "These modules will be wrapped as separate FSDP instacnes with mixed "
123
+ "precision disabled.",
124
+ stacklevel=2,
125
+ )
126
+
127
+
128
+ def _validate_frozen_params(
129
+ root_module: nn.Module,
130
+ modules_to_wrap: set[nn.Module],
131
+ ignored_params: set[nn.Parameter],
132
+ use_orig_params: bool,
133
+ ):
134
+ """
135
+ This checks that, given ``modules_to_wrap``, each module would manage
136
+ parameters that are uniformly frozen or non-frozen. This uniformity
137
+ requirement is strict for ``use_orig_params=False`` (hard error) and highly
138
+ recommended for ``use_orig_params=True`` (user warning).
139
+ """
140
+ post_order_named_modules = _get_post_order_named_modules(root_module)
141
+ visited_modules: set[nn.Module] = set()
142
+ for module_name, module in post_order_named_modules:
143
+ if module in modules_to_wrap:
144
+ param_to_fqn = _get_managed_param_to_fqn(
145
+ module, ignored_params, visited_modules, module_name
146
+ )
147
+ frozen_param_fqns: list[str] = []
148
+ frozen_param_numel = 0
149
+ nonfrozen_param_fqns: list[str] = []
150
+ nonfrozen_param_numel = 0
151
+ for param, fqn in param_to_fqn.items():
152
+ if param.requires_grad:
153
+ nonfrozen_param_fqns.append(fqn)
154
+ nonfrozen_param_numel += param.numel()
155
+ else:
156
+ frozen_param_fqns.append(fqn)
157
+ frozen_param_numel += param.numel()
158
+ if len(frozen_param_fqns) > 0 and len(nonfrozen_param_fqns) > 0:
159
+ msg = f"{module_name} has both parameters with requires_grad=True and False."
160
+ if use_orig_params:
161
+ total_param_numel = frozen_param_numel + nonfrozen_param_numel
162
+ msg += (
163
+ " We do not recommend wrapping such modules since "
164
+ "the gradient memory usage will be higher than expected "
165
+ f"({total_param_numel} numel instead of {nonfrozen_param_numel} numel "
166
+ "before sharding via reduce-scatter). "
167
+ )
168
+ else:
169
+ msg += " FSDP does not support wrapping such modules when use_orig_params=False. "
170
+ msg += "If possible, wrap the frozen parameters with FSDP separately.\n"
171
+ msg += (
172
+ f"The following parameters have requires_grad=True:\n{nonfrozen_param_fqns}\n"
173
+ f"The following parameters have requires_grad=False:\n{frozen_param_fqns}"
174
+ )
175
+ if use_orig_params:
176
+ warnings.warn(msg, stacklevel=2)
177
+ else:
178
+ raise ValueError(msg)
179
+
180
+
181
+ def _get_post_order_named_modules(
182
+ root_module: nn.Module,
183
+ ) -> list[tuple[str, nn.Module]]:
184
+ """
185
+ This returns the named modules following a post-order traversal, which is a
186
+ valid reverse topological sort. We achieve this using the reverse of a
187
+ stack-based DFS order instead of reversing ``root_module.named_modules()``
188
+ since the former gives the modules in registration order at each level in
189
+ the module tree (as opposed to the reverse), which allows us to error/warn
190
+ on the first registered module that violates the condition.
191
+
192
+ For example, consider the following module structure:
193
+ M(
194
+ S1(),
195
+ S2(
196
+ SS1(),
197
+ SS2(),
198
+ ),
199
+ S3(),
200
+ )
201
+ The reverse DFS order is [S1, SS1, SS2, S2, S3, M], while the reverse
202
+ ``named_modules()`` order is [S3, SS2, SS1, S2, S1, M].
203
+ """
204
+ visited_modules = {root_module}
205
+ stack = [("", root_module)]
206
+ # Append and reverse at the end for linear-time algorithm
207
+ reverse_post_order_named_modules: list[tuple[str, nn.Module]] = []
208
+ while stack:
209
+ module_name, module = stack.pop()
210
+ reverse_post_order_named_modules.append((module_name, module))
211
+ for child_module_name, child_module in module.named_children():
212
+ if child_module is None: # only for overrides of `named_children()`
213
+ continue
214
+ if child_module not in visited_modules:
215
+ visited_modules.add(child_module)
216
+ if module_name != "":
217
+ child_module_name = module_name + "." + child_module_name
218
+ stack.append((child_module_name, child_module))
219
+ post_order_named_modules = list(reversed(reverse_post_order_named_modules))
220
+ return post_order_named_modules
221
+
222
+
223
+ def _get_managed_param_to_fqn(
224
+ module_to_wrap: nn.Module,
225
+ ignored_params: set[nn.Parameter],
226
+ visited_modules: set[nn.Module],
227
+ root_prefix: str,
228
+ ) -> dict[nn.Parameter, str]:
229
+ """
230
+ This returns a dict that maps managed parameter to its FQN for the given
231
+ ``module_to_wrap``. The dict's keys are exactly the parameters that would
232
+ be managed by the module, where this is achieved by calling this function
233
+ on the modules to wrap in reverse topological order, destructively updating
234
+ ``visited_modules``, and not traversing into those modules. The FQNs are
235
+ prefixed from the root (via ``root_prefix``) to be more informative.
236
+
237
+ NOTE: This function is meant to be called pre-wrapping and iteratively in
238
+ reverse topological order to cover the full module tree. This differs from
239
+ the ``_get_param_to_fqn()`` function meant to be called post-wrapping and
240
+ on the full module tree in one shot. Given those differences, we do not try
241
+ to unify the two.
242
+ """
243
+ param_to_fqn: dict[nn.Parameter, str] = {}
244
+ # Run BFS (or any tree traversal works)
245
+ queue = collections.deque([(module_to_wrap, root_prefix)])
246
+ visited_modules.add(module_to_wrap)
247
+ while queue:
248
+ module, prefix = queue.popleft()
249
+ for param_name, param in module.named_parameters(recurse=False):
250
+ if param not in ignored_params:
251
+ fqn = param_name if prefix == "" else prefix + "." + param_name
252
+ param_to_fqn[param] = fqn
253
+ for child_module_name, child_module in module.named_children():
254
+ if child_module is None: # only for overrides of `named_children()`
255
+ continue
256
+ if child_module not in visited_modules:
257
+ visited_modules.add(child_module)
258
+ child_prefix = (
259
+ child_module_name
260
+ if prefix == ""
261
+ else prefix + "." + child_module_name
262
+ )
263
+ queue.append((child_module, child_prefix))
264
+ return param_to_fqn
venv/lib/python3.14/site-packages/torch/distributed/fsdp/api.py ADDED
@@ -0,0 +1,416 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This file includes public APIs for FSDP such as the classes used for the
3
+ constructor arguments.
4
+ """
5
+
6
+ from collections.abc import Sequence
7
+ from dataclasses import dataclass
8
+ from enum import auto, Enum
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: torch.dtype | None = None
221
+ reduce_dtype: torch.dtype | None = None
222
+ buffer_dtype: torch.dtype | None = 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
+
250
+ .. note::
251
+ FSDP currently supports three types of ``state_dict``:
252
+ 1. ``state_dict/load_state_dict`: this pair of APIs return and load
253
+ the non-sharded, unflattened parameters. The semantics is the
254
+ same as using DDP.
255
+ 2. ``_local_state_dict/_load_local_state_dict``: this pair of APIs return
256
+ and load local sharded, flattened parameters. The values returned
257
+ by ``_local_state_dict`` can be directly used by FSDP and is only
258
+ meaningful to FSDP (because parameters are flattened). Note that
259
+ these APIs are meant for use via the :func:`state_dict_type`
260
+ context manager as follows:
261
+ >>> # xdoctest: +SKIP("undefined variables")
262
+ >>> with fsdp.state_dict_type(StateDictType.LOCAL_STATE_DICT):
263
+ ... state = fsdp.state_dict() # loads local state dict
264
+ 3. ``_sharded_state_dict/_load_sharded_state_dict``: this pair of APIs
265
+ return and load sharded, unflattened parameters. The ``state_dict``
266
+ return by ``sharded_state_dict`` can be used by all other parallel
267
+ schemes (resharding may be required).
268
+ """
269
+
270
+ FULL_STATE_DICT = auto()
271
+ LOCAL_STATE_DICT = auto()
272
+ SHARDED_STATE_DICT = auto()
273
+
274
+
275
+ @dataclass
276
+ class StateDictConfig:
277
+ """
278
+ ``StateDictConfig`` is the base class for all ``state_dict`` configuration
279
+ classes. Users should instantiate a child class (e.g.
280
+ ``FullStateDictConfig``) in order to configure settings for the
281
+ corresponding ``state_dict`` type supported by FSDP.
282
+
283
+ Attributes:
284
+ offload_to_cpu (bool): If ``True``, then FSDP offloads the state dict
285
+ values to CPU, and if ``False``, then FSDP keeps them on GPU.
286
+ (Default: ``False``)
287
+ """
288
+
289
+ offload_to_cpu: bool = False
290
+
291
+
292
+ @dataclass
293
+ class FullStateDictConfig(StateDictConfig):
294
+ """
295
+ ``FullStateDictConfig`` is a config class meant to be used with
296
+ ``StateDictType.FULL_STATE_DICT``. We recommend enabling both
297
+ ``offload_to_cpu=True`` and ``rank0_only=True`` when saving full state
298
+ dicts to save GPU memory and CPU memory, respectively. This config class
299
+ is meant to be used via the :func:`state_dict_type` context manager as
300
+ follows:
301
+
302
+ >>> # xdoctest: +SKIP("undefined variables")
303
+ >>> from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
304
+ >>> fsdp = FSDP(model, auto_wrap_policy=...)
305
+ >>> cfg = FullStateDictConfig(offload_to_cpu=True, rank0_only=True)
306
+ >>> with FSDP.state_dict_type(fsdp, StateDictType.FULL_STATE_DICT, cfg):
307
+ >>> state = fsdp.state_dict()
308
+ >>> # `state` will be empty on non rank 0 and contain CPU tensors on rank 0.
309
+ >>> # To reload checkpoint for inference, finetuning, transfer learning, etc:
310
+ >>> model = model_fn() # Initialize model in preparation for wrapping with FSDP
311
+ >>> if dist.get_rank() == 0:
312
+ >>> # Load checkpoint only on rank 0 to avoid memory redundancy
313
+ >>> state_dict = torch.load("my_checkpoint.pt")
314
+ >>> model.load_state_dict(state_dict)
315
+ >>> # All ranks initialize FSDP module as usual. `sync_module_states` argument
316
+ >>> # communicates loaded checkpoint states from rank 0 to rest of the world.
317
+ >>> fsdp = FSDP(
318
+ ... model,
319
+ ... device_id=torch.cuda.current_device(),
320
+ ... auto_wrap_policy=...,
321
+ ... sync_module_states=True,
322
+ ... )
323
+ >>> # After this point, all ranks have FSDP model with loaded checkpoint.
324
+
325
+ Attributes:
326
+ rank0_only (bool): If ``True``, then only rank 0 saves the full state
327
+ dict, and nonzero ranks save an empty dict. If ``False``, then all
328
+ ranks save the full state dict. (Default: ``False``)
329
+ """
330
+
331
+ rank0_only: bool = False
332
+
333
+
334
+ @dataclass
335
+ class LocalStateDictConfig(StateDictConfig):
336
+ pass
337
+
338
+
339
+ @dataclass
340
+ class ShardedStateDictConfig(StateDictConfig):
341
+ """
342
+ ``ShardedStateDictConfig`` is a config class meant to be used with
343
+ ``StateDictType.SHARDED_STATE_DICT``.
344
+
345
+ Attributes:
346
+ _use_dtensor (bool): If ``True``, then FSDP saves the state dict values
347
+ as ``DTensor``, and if ``False``, then FSDP saves them as
348
+ ``ShardedTensor``. (Default: ``False``)
349
+
350
+ .. warning:: ``_use_dtensor`` is a private field of :class:`ShardedStateDictConfig`
351
+ and it is used by FSDP to determine the type of state dict values. Users should not
352
+ manually modify ``_use_dtensor``.
353
+ """
354
+
355
+ _use_dtensor: bool = False
356
+
357
+
358
+ @dataclass
359
+ class OptimStateDictConfig:
360
+ """
361
+ ``OptimStateDictConfig`` is the base class for all ``optim_state_dict``
362
+ configuration classes. Users should instantiate a child class (e.g.
363
+ ``FullOptimStateDictConfig``) in order to configure settings for the
364
+ corresponding ``optim_state_dict`` type supported by FSDP.
365
+
366
+ Attributes:
367
+ offload_to_cpu (bool): If ``True``, then FSDP offloads the state dict's
368
+ tensor values to CPU, and if ``False``, then FSDP keeps them on the
369
+ original device (which is GPU unless parameter CPU offloading is
370
+ enabled). (Default: ``True``)
371
+ """
372
+
373
+ offload_to_cpu: bool = True
374
+
375
+
376
+ @dataclass
377
+ class FullOptimStateDictConfig(OptimStateDictConfig):
378
+ """
379
+ Attributes:
380
+ rank0_only (bool): If ``True``, then only rank 0 saves the full state
381
+ dict, and nonzero ranks save an empty dict. If ``False``, then all
382
+ ranks save the full state dict. (Default: ``False``)
383
+ """
384
+
385
+ rank0_only: bool = False
386
+
387
+
388
+ @dataclass
389
+ class LocalOptimStateDictConfig(OptimStateDictConfig):
390
+ offload_to_cpu: bool = False
391
+
392
+
393
+ @dataclass
394
+ class ShardedOptimStateDictConfig(OptimStateDictConfig):
395
+ """
396
+ ``ShardedOptimStateDictConfig`` is a config class meant to be used with
397
+ ``StateDictType.SHARDED_STATE_DICT``.
398
+
399
+ Attributes:
400
+ _use_dtensor (bool): If ``True``, then FSDP saves the state dict values
401
+ as ``DTensor``, and if ``False``, then FSDP saves them as
402
+ ``ShardedTensor``. (Default: ``False``)
403
+
404
+ .. warning:: ``_use_dtensor`` is a private field of :class:`ShardedOptimStateDictConfig`
405
+ and it is used by FSDP to determine the type of state dict values. Users should not
406
+ manually modify ``_use_dtensor``.
407
+ """
408
+
409
+ _use_dtensor: bool = False
410
+
411
+
412
+ @dataclass
413
+ class StateDictSettings:
414
+ state_dict_type: StateDictType
415
+ state_dict_config: StateDictConfig
416
+ optim_state_dict_config: OptimStateDictConfig
venv/lib/python3.14/site-packages/torch/distributed/fsdp/fully_sharded_data_parallel.py ADDED
The diff for this file is too large to render. See raw diff
 
venv/lib/python3.14/site-packages/torch/distributed/fsdp/sharded_grad_scaler.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import logging
3
+ from collections import abc, defaultdict
4
+ from collections.abc import Iterable
5
+ from typing import Any, overload
6
+
7
+ import torch
8
+ import torch.distributed as dist
9
+ from torch.amp.grad_scaler import _MultiDeviceReplicator, GradScaler, OptState
10
+ from torch.distributed.distributed_c10d import ProcessGroup
11
+
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ def _refresh_per_optimizer_state() -> dict[str, Any]:
17
+ return {"stage": OptState.READY, "found_inf_per_device": {}}
18
+
19
+
20
+ def _is_supported_device(tensor: torch.Tensor) -> bool:
21
+ return tensor.is_cuda or tensor.device.type in (
22
+ "xla",
23
+ "cpu",
24
+ "hpu",
25
+ "mtia",
26
+ "xpu",
27
+ torch._C._get_privateuse1_backend_name(),
28
+ )
29
+
30
+
31
+ class _GeneralMultiDeviceReplicator(_MultiDeviceReplicator):
32
+ """
33
+ Lazily serves tensor to request device. This class extends
34
+ _MultiDeviceReplicator to allow support for "cpu" as a device.
35
+ """
36
+
37
+ def __init__(self, master_tensor: torch.Tensor) -> None:
38
+ if not _is_supported_device(master_tensor):
39
+ raise AssertionError(
40
+ f"Expected supported device, got {master_tensor.device}"
41
+ )
42
+ self.master = master_tensor
43
+ self._per_device_tensors: dict[torch.device, torch.Tensor] = {}
44
+
45
+
46
+ class ShardedGradScaler(GradScaler):
47
+ """
48
+ ShardedGradScaler helps perform gradient scaling in a shard aware manner. It extends
49
+ functionality from GradScaler:
50
+ * Supports Pytorch DDP and FSDP implementations
51
+ * Support CPU offloaded tensors (as used in fully sharded data parallel[FSDP])
52
+ * Supports the custom Mixed Precision loss dtype (fp16, bf16) that FSDP returns
53
+ * Sync inf/nan for scaled gradient tensors on any torch.device (where tensors are placed) across
54
+ nodes
55
+
56
+ Example::
57
+
58
+ # Creates a ShardedGradScaler once at the beginning of training.
59
+ scaler = ShardedGradScaler()
60
+
61
+ for epoch in epochs:
62
+ for input, target in data:
63
+ optimizer.zero_grad()
64
+ output = model(input)
65
+ loss = loss_fn(output, target)
66
+
67
+ # Scales loss. Calls backward() on scaled loss to create scaled gradients.
68
+ scaler.scale(loss).backward()
69
+
70
+ # scaler.step() first unscales gradients of the optimizer's params.
71
+ # If gradients don't contain infs/NaNs, optimizer.step() is then called,
72
+ # otherwise, optimizer.step() is skipped.
73
+ scaler.step(optimizer)
74
+
75
+ # Updates the scale for next iteration.
76
+ scaler.update()
77
+
78
+ See :class:`GradScaler` for explanation of scaling/unscaling and more use cases.
79
+
80
+ Args:
81
+ init_scale (float, optional, default=2.**16): Initial scale factor.
82
+ growth_factor (float, optional, default=2.0): Factor by which the scale is multiplied during
83
+ :meth:`update` if no inf/NaN gradients occur for ``growth_interval`` consecutive iterations.
84
+ backoff_factor (float, optional, default=0.5): Factor by which the scale is multiplied during
85
+ :meth:`update` if inf/NaN gradients occur in an iteration.
86
+ growth_interval (int, optional, default=2000): Number of consecutive iterations without inf/NaN gradients
87
+ that must occur for the scale to be multiplied by ``growth_factor``.
88
+ enabled (bool, optional): If ``False``, disables gradient scaling. :meth:`step` simply
89
+ invokes the underlying ``optimizer.step()``, and other methods become no-ops.
90
+ Default: ``True``
91
+ process_group (ProcessGroup, optional, default=torch.distributed.group.WORLD):
92
+ process group for sharding
93
+ """
94
+
95
+ def __init__(
96
+ self,
97
+ device: str = "cuda",
98
+ init_scale: float = 2.0**16,
99
+ backoff_factor: float = 0.5,
100
+ growth_factor: float = 2.0,
101
+ growth_interval: int = 2000,
102
+ enabled: bool = True,
103
+ process_group: ProcessGroup | None = dist.group.WORLD,
104
+ ) -> None:
105
+ super().__init__(
106
+ device,
107
+ init_scale=init_scale,
108
+ backoff_factor=backoff_factor,
109
+ growth_factor=growth_factor,
110
+ growth_interval=growth_interval,
111
+ enabled=enabled,
112
+ )
113
+ if self._enabled:
114
+ self.process_group = process_group
115
+ self._per_optimizer_states = defaultdict(_refresh_per_optimizer_state)
116
+
117
+ @overload
118
+ def scale(self, outputs: torch.Tensor) -> torch.Tensor: ...
119
+
120
+ @overload
121
+ def scale(self, outputs: list[torch.Tensor]) -> list[torch.Tensor]: ...
122
+
123
+ @overload
124
+ def scale(self, outputs: tuple[torch.Tensor, ...]) -> tuple[torch.Tensor, ...]: ...
125
+
126
+ @overload
127
+ def scale(self, outputs: Iterable[torch.Tensor]) -> Iterable[torch.Tensor]: ...
128
+
129
+ def scale(
130
+ self, outputs: torch.Tensor | Iterable[torch.Tensor]
131
+ ) -> torch.Tensor | Iterable[torch.Tensor]:
132
+ if not self._enabled:
133
+ return outputs
134
+
135
+ if isinstance(outputs, torch.Tensor):
136
+ if not _is_supported_device(outputs):
137
+ raise AssertionError(f"Expected supported device, got {outputs.device}")
138
+ if self._scale is None:
139
+ self._lazy_init_scale_growth_tracker(outputs.device)
140
+ if self._scale is None:
141
+ raise AssertionError("Expected _scale to be initialized, got None")
142
+ scaled_output = outputs * self._scale.to(
143
+ device=outputs.device, non_blocking=True
144
+ )
145
+ # Here we ensure the return dtype is the same as the outputs dtype.
146
+ # For the FSDP + Mixed Precision use case, the loss output is in the Mixed Precision
147
+ # format (fp16, bf16) and so the scaled loss should be of the same dtype.
148
+ return scaled_output.type(outputs.dtype)
149
+
150
+ stash: list[_GeneralMultiDeviceReplicator] = []
151
+
152
+ def apply_scale(val: torch.Tensor | Iterable[torch.Tensor]):
153
+ if isinstance(val, torch.Tensor):
154
+ if not _is_supported_device(val):
155
+ raise AssertionError(f"Expected supported device, got {val.device}")
156
+ if len(stash) == 0:
157
+ if self._scale is None:
158
+ self._lazy_init_scale_growth_tracker(val.device)
159
+ if self._scale is None:
160
+ raise AssertionError(
161
+ "Expected _scale to be initialized, got None"
162
+ )
163
+ stash.append(_GeneralMultiDeviceReplicator(self._scale))
164
+ scaled_val = val * stash[0].get(val.device)
165
+ # Here we ensure the return dtype is the same as the outputs dtype.
166
+ # For the FSDP + Mixed Precision use case, the loss output is in the Mixed Precision
167
+ # format (fp16, bf16) and so the scaled loss should be of the same dtype.
168
+ return scaled_val.type(val.dtype)
169
+ if isinstance(val, abc.Iterable):
170
+ iterator = map(apply_scale, val)
171
+ if isinstance(val, (list, tuple)):
172
+ return type(val)(iterator)
173
+ return iterator
174
+ raise ValueError("outputs must be a Tensor or an iterable of Tensors")
175
+
176
+ return apply_scale(outputs)
177
+
178
+ def _unscale_grads_(
179
+ self,
180
+ optimizer: torch.optim.Optimizer,
181
+ inv_scale: torch.Tensor,
182
+ found_inf: torch.Tensor,
183
+ allow_fp16: bool = True,
184
+ ) -> dict[torch.device, torch.Tensor]:
185
+ per_device_inv_scale = _GeneralMultiDeviceReplicator(inv_scale)
186
+ per_device_found_inf = _GeneralMultiDeviceReplicator(found_inf)
187
+
188
+ # To set up _amp_foreach_non_finite_check_and_unscale_, split grads by device and dtype.
189
+ # There could be thousands of grads, so we'd like to iterate through them just once.
190
+ # However, we don't know their devices or dtypes in advance.
191
+
192
+ # https://stackoverflow.com/questions/5029934/defaultdict-of-defaultdict
193
+ # Google says mypy struggles with defaultdicts type annotations.
194
+ per_device_and_dtype_grads = defaultdict(lambda: defaultdict(list)) # type: ignore[var-annotated]
195
+ with torch.no_grad():
196
+ for group in optimizer.param_groups:
197
+ for param in group["params"]:
198
+ if param.grad is None:
199
+ continue
200
+ if (not allow_fp16) and param.grad.dtype == torch.float16:
201
+ raise ValueError("Attempting to unscale FP16 gradients.")
202
+ if param.grad.is_sparse:
203
+ # is_coalesced() == False means the sparse grad has values with duplicate indices.
204
+ # coalesce() deduplicates indices and adds all values that have the same index.
205
+ # For scaled fp16 values, there's a good chance coalescing will cause overflow,
206
+ # so we should check the coalesced _values().
207
+ if param.grad.dtype is torch.float16:
208
+ # coalesce is not supported in torch.float16
209
+ param_grad_fp32 = param.grad.type(torch.float32).coalesce()
210
+ param.grad = param_grad_fp32.type(torch.float16)
211
+ to_unscale = param.grad._values()
212
+ else:
213
+ to_unscale = param.grad
214
+
215
+ per_device_and_dtype_grads[to_unscale.device][
216
+ to_unscale.dtype
217
+ ].append(to_unscale)
218
+
219
+ for device, per_dtype_grads in per_device_and_dtype_grads.items():
220
+ for grads in per_dtype_grads.values():
221
+ torch._amp_foreach_non_finite_check_and_unscale_(
222
+ grads,
223
+ per_device_found_inf.get(device),
224
+ per_device_inv_scale.get(device),
225
+ )
226
+ # There exist contexts (e.g. w/ `use_orig_params=True`) wherein some
227
+ # ranks may have no (non-zero sized) parameter shards, necessitating the
228
+ # initialization of `per_device_found_inf._per_device_tensors` here
229
+ if not per_device_found_inf._per_device_tensors:
230
+ if self._scale is None:
231
+ raise AssertionError("Expected _scale to be initialized, got None")
232
+ per_device_found_inf.get(self._scale.device)
233
+ return per_device_found_inf._per_device_tensors
234
+
235
+ def unscale_(self, optimizer: torch.optim.Optimizer) -> None:
236
+ if not self._enabled:
237
+ return
238
+
239
+ self._check_scale_growth_tracker("unscale_")
240
+
241
+ optimizer_state = self._per_optimizer_states[id(optimizer)]
242
+
243
+ if optimizer_state["stage"] is OptState.UNSCALED:
244
+ raise RuntimeError(
245
+ "unscale_() has already been called on this optimizer since the last update()."
246
+ )
247
+ elif optimizer_state["stage"] is OptState.STEPPED:
248
+ raise RuntimeError("unscale_() is being called after step().")
249
+
250
+ # FP32 division can be imprecise for certain compile options, so we carry out the reciprocal in FP64.
251
+ if self._scale is None:
252
+ raise AssertionError("Expected _scale to be initialized, got None")
253
+ inv_scale = self._scale.double().reciprocal().float()
254
+ found_inf = torch.full(
255
+ (1,), 0.0, dtype=torch.float32, device=self._scale.device
256
+ )
257
+
258
+ optimizer_state["found_inf_per_device"] = self._unscale_grads_(
259
+ optimizer, inv_scale, found_inf, True
260
+ )
261
+ optimizer_state["stage"] = OptState.UNSCALED
262
+
263
+ # Synchronize the detected inf across the ranks
264
+ optimizer_state = self._per_optimizer_states[id(optimizer)]
265
+ works = []
266
+ found_inf_on_cpus = []
267
+ found_inf_on_devices = []
268
+
269
+ for found_inf in optimizer_state["found_inf_per_device"].values():
270
+ if self._device != "cpu" and found_inf.device.type == "cpu":
271
+ found_inf_on_cpus.append(found_inf)
272
+ found_inf_on_device = found_inf.to(self._device)
273
+ found_inf_on_devices.append(found_inf_on_device)
274
+ works.append(
275
+ dist.all_reduce(
276
+ found_inf_on_device, async_op=True, group=self.process_group
277
+ )
278
+ )
279
+ else:
280
+ works.append(
281
+ dist.all_reduce(found_inf, async_op=True, group=self.process_group)
282
+ )
283
+ for work in works:
284
+ work.wait()
285
+ if found_inf_on_cpus:
286
+ torch._foreach_copy_(found_inf_on_cpus, found_inf_on_devices)
287
+
288
+ def _amp_update_scale_cpu_(self, found_inf: torch.Tensor) -> None:
289
+ """
290
+ If found_inf is 1.0 (True), then scale is multiplied by backoff_factor and growth_tracker is set to zero.
291
+ Otherwise, scale is multiplied by the growth factor when the growth interval is reached.
292
+ """
293
+ if self._scale is None or self._growth_tracker is None:
294
+ raise AssertionError(
295
+ "Expected _scale and _growth_tracker to be initialized, got None"
296
+ )
297
+
298
+ if found_inf.item() >= 1.0:
299
+ self._scale *= self._backoff_factor
300
+ self._growth_tracker.fill_(0)
301
+ else:
302
+ successful = self._growth_tracker + 1
303
+ if successful == self._growth_interval:
304
+ self._scale *= self._growth_factor
305
+ self._growth_tracker.fill_(0)
306
+ else:
307
+ self._growth_tracker = successful
308
+
309
+ def update(self, new_scale: float | torch.Tensor | None = None) -> None:
310
+ """
311
+ Updates the scale factor.
312
+ If any optimizer steps were skipped the scale is multiplied by ``backoff_factor``
313
+ to reduce it. If ``growth_interval`` unskipped iterations occurred consecutively,
314
+ the scale is multiplied by ``growth_factor`` to increase it.
315
+ Passing ``new_scale`` sets the new scale value manually. (``new_scale`` is not
316
+ used directly, it's used to fill GradScaler's internal scale tensor. So if
317
+ ``new_scale`` was a tensor, later in-place changes to that tensor will not further
318
+ affect the scale GradScaler uses internally.)
319
+ Args:
320
+ new_scale (float or :class:`torch.Tensor`, optional, default=None): New scale factor.
321
+ .. warning::
322
+ :meth:`update` should only be called at the end of the iteration, after ``scaler.step(optimizer)`` has
323
+ been invoked for all optimizers used this iteration.
324
+ """
325
+
326
+ if not self._enabled:
327
+ return
328
+
329
+ _scale, _growth_tracker = self._check_scale_growth_tracker("update") # type: ignore[var-annotated]
330
+
331
+ if new_scale is not None:
332
+ # Accept a new user-defined scale.
333
+ if isinstance(new_scale, float):
334
+ self._scale.fill_(new_scale) # type: ignore[union-attr]
335
+ else:
336
+ reason = (
337
+ "new_scale should be a float or a 1-element torch.cuda.FloatTensor or "
338
+ "torch.FloatTensor with requires_grad=False."
339
+ )
340
+ if new_scale.device.type != self._device:
341
+ raise AssertionError(reason)
342
+ if new_scale.numel() != 1:
343
+ raise AssertionError(reason)
344
+ if new_scale.requires_grad is not False:
345
+ raise AssertionError(reason)
346
+ self._scale.copy_(new_scale) # type: ignore[union-attr]
347
+ else:
348
+ # Consume shared inf/nan data collected from optimizers to update the scale.
349
+ # If all found_inf tensors are on the same device as self._scale, this operation is asynchronous.
350
+ found_infs = [
351
+ found_inf.to(device=_scale.device, non_blocking=True)
352
+ for state in self._per_optimizer_states.values()
353
+ for found_inf in state["found_inf_per_device"].values()
354
+ ]
355
+
356
+ if len(found_infs) == 0:
357
+ raise AssertionError("No inf checks were recorded prior to update.")
358
+
359
+ found_inf_combined = found_infs[0]
360
+ if len(found_infs) > 1:
361
+ for i in range(1, len(found_infs)):
362
+ found_inf_combined += found_infs[i]
363
+
364
+ if _scale.device.type == "cpu":
365
+ self._amp_update_scale_cpu_(found_inf_combined)
366
+ else:
367
+ torch._amp_update_scale_(
368
+ self._scale, # type: ignore[arg-type]
369
+ self._growth_tracker, # type: ignore[arg-type]
370
+ found_inf_combined,
371
+ self._growth_factor, # type: ignore[arg-type]
372
+ self._backoff_factor, # type: ignore[arg-type]
373
+ self._growth_interval, # type: ignore[arg-type]
374
+ )
375
+
376
+ # To prepare for next iteration, clear the data collected from optimizers this iteration.
377
+ self._per_optimizer_states = defaultdict(_refresh_per_optimizer_state)
venv/lib/python3.14/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 collections.abc import Callable, Generator, Iterable, Sequence
11
+ from typing import Any, cast
12
+
13
+ import torch.nn as nn
14
+
15
+
16
+ __all__ = [
17
+ "always_wrap_policy",
18
+ "lambda_auto_wrap_policy",
19
+ "transformer_auto_wrap_policy",
20
+ "size_based_auto_wrap_policy",
21
+ "enable_wrap",
22
+ "wrap",
23
+ "CustomPolicy",
24
+ "ModuleWrapPolicy",
25
+ ]
26
+
27
+
28
+ # NOTE: We intentionally keep this function simple and isolate the complexity
29
+ # to `fn` to enable using this function generically. We may move this to a
30
+ # non-FSDP-specific folder and/or make it public in the future.
31
+ def _post_order_apply(
32
+ root_module: nn.Module,
33
+ fn: Callable[[nn.Module], nn.Module | None],
34
+ ):
35
+ """
36
+ This applies ``fn`` to every module in the module tree of ``root_module``
37
+ following a post-order traversal. If ``fn`` returns an :class:`nn.Module`,
38
+ then this replaces the original module with the newly returned one in the
39
+ tree. Otherwise, ``fn`` should return ``None``, in which case the module is
40
+ not changed.
41
+ """
42
+ # Track visited modules to avoid visiting shared modules multiple times
43
+ visited_modules: set[nn.Module] = {root_module}
44
+
45
+ def _post_order_apply_inner(
46
+ module: nn.Module,
47
+ module_name: str,
48
+ parent_module: nn.Module | None,
49
+ ):
50
+ for child_module_name, child_module in module.named_children():
51
+ if child_module not in visited_modules:
52
+ visited_modules.add(child_module)
53
+ _post_order_apply_inner(child_module, child_module_name, module)
54
+ optional_module = fn(module)
55
+ if optional_module is not None:
56
+ if not isinstance(parent_module, nn.Module):
57
+ raise AssertionError(
58
+ "Non-root modules should have their parent module set but got "
59
+ f"{parent_module} for {module}"
60
+ )
61
+ if not module_name:
62
+ raise AssertionError(
63
+ "Non-root modules should have their module name set but got "
64
+ f"an empty module name for {module}"
65
+ )
66
+ if not isinstance(optional_module, nn.Module):
67
+ raise AssertionError(
68
+ f"fn should return None or an nn.Module but got {optional_module}"
69
+ )
70
+ setattr(parent_module, module_name, optional_module)
71
+
72
+ _post_order_apply_inner(root_module, "", None)
73
+
74
+
75
+ def _construct_wrap_fn(
76
+ root_module: nn.Module,
77
+ target_module_to_kwargs: dict[nn.Module, dict[str, Any]],
78
+ fsdp_fn: Callable,
79
+ ) -> Callable[[nn.Module], nn.Module | None]:
80
+ """
81
+ This constructs the "wrap" function to pass to :func:`_post_order_apply`
82
+ based on ``target_module_to_kwargs``, which should be constructed from the
83
+ wrapping policy.
84
+ """
85
+
86
+ def fn(module: nn.Module) -> nn.Module | None:
87
+ # Explicitly avoid wrapping the root module since for FSDP, it is
88
+ # handled by the caller
89
+ if module in target_module_to_kwargs and module is not root_module:
90
+ kwargs = target_module_to_kwargs[module]
91
+ return fsdp_fn(module, **kwargs)
92
+ return None
93
+
94
+ return fn
95
+
96
+
97
+ def _run_mixed_precision_override_policy(
98
+ root_module: nn.Module,
99
+ module_classes: Iterable[type[nn.Module]],
100
+ ignored_modules: set[nn.Module],
101
+ root_kwargs: dict[str, Any],
102
+ target_module_to_kwargs: dict[nn.Module, dict[str, Any]],
103
+ ):
104
+ module_classes_tuple = tuple(set(module_classes))
105
+ for module in root_module.modules():
106
+ if module in ignored_modules:
107
+ continue
108
+ elif isinstance(module, module_classes_tuple):
109
+ # This policy overrides any existing policy
110
+ if module not in target_module_to_kwargs:
111
+ # Only inherit from the root kwargs if not already specified
112
+ target_module_to_kwargs[module] = root_kwargs
113
+ target_module_to_kwargs[module]["mixed_precision"] = None
114
+ return target_module_to_kwargs
115
+
116
+
117
+ def always_wrap_policy(*args, **kwargs) -> bool:
118
+ """
119
+ A simple recursive wrap policy that always returns ``True``. This means
120
+ that every submodule is wrapped by the wrapper class in
121
+ :func:`_recursive_wrap`.
122
+ """
123
+ return True
124
+
125
+
126
+ class _Policy(ABC):
127
+ """
128
+ This defines an abstract base class that represents a policy for applying
129
+ a module-level API.
130
+ """
131
+
132
+ @abstractmethod
133
+ def _run_policy(
134
+ self,
135
+ root_module: nn.Module,
136
+ ignored_modules: set[nn.Module],
137
+ root_kwargs: dict[str, Any],
138
+ ) -> dict[nn.Module, dict[str, Any]]:
139
+ """
140
+ This should return a dict ``target_module_to_kwargs`` that maps from
141
+ each target module to wrap to its kwargs.
142
+ """
143
+ ...
144
+
145
+
146
+ def _module_wrap_policy(
147
+ module: nn.Module,
148
+ recurse: bool,
149
+ nonwrapped_numel: int,
150
+ module_classes: set[type[nn.Module]],
151
+ ) -> bool:
152
+ """
153
+ This auto wrap policy wraps every module that is an instance of any type in
154
+ ``module_classes`` as its own FSDP instance. The root module given by
155
+ ``module`` is always wrapped as an FSDP instance regardless. Since the
156
+ wrapping proceeds bottom up, each FSDP instance manages the parameters in
157
+ its subtree excluding any already managed by a child FSDP instance.
158
+
159
+ Args:
160
+ module (nn.Module): Current module being considered.
161
+ recurse (bool): If ``False``, then this function must decide whether
162
+ ``module`` should be wrapped as an FSDP instance or not. If
163
+ ``True``, then the function is still recursing down the module
164
+ tree as a part of the DFS.
165
+ nonwrapped_numel (int): Parameter numel not yet wrapped.
166
+ module_classes (Set[Type[nn.Module]]): Set of module classes that are
167
+ wrapped as FSDP instances.
168
+
169
+ Returns:
170
+ ``True`` if ``recurse=True``, and whether ``module`` should be wrapped
171
+ if ``recurse=False``.
172
+ """
173
+ if recurse:
174
+ return True # always recurse
175
+ return isinstance(module, tuple(module_classes))
176
+
177
+
178
+ class ModuleWrapPolicy(_Policy):
179
+ """
180
+ This policy applies to every module of the specified module classes,
181
+ passing in the kwargs given to the root.
182
+ """
183
+
184
+ def __init__(self, module_classes: Iterable[type[nn.Module]]):
185
+ module_classes_set = set(module_classes)
186
+ self._module_classes = module_classes_set
187
+ self._module_classes_str = str(module_classes_set)
188
+
189
+ def _run_policy(
190
+ self,
191
+ root_module: nn.Module,
192
+ ignored_modules: set[nn.Module],
193
+ root_kwargs: dict[str, Any],
194
+ ) -> dict[nn.Module, dict[str, Any]]:
195
+ module_classes = tuple(self._module_classes)
196
+ target_module_to_kwargs: dict[nn.Module, dict[str, Any]] = {}
197
+ for module in root_module.modules():
198
+ if module in ignored_modules:
199
+ continue
200
+ elif isinstance(module, module_classes):
201
+ # Shallow copy to avoid coupling changes across modules
202
+ target_module_to_kwargs[module] = copy.copy(root_kwargs)
203
+ return target_module_to_kwargs
204
+
205
+ def __call__(self, module, recurse, *args, **kwargs):
206
+ # nonwrapped_numel is not used.
207
+ return _module_wrap_policy(
208
+ module, recurse, nonwrapped_numel=-1, module_classes=self._module_classes
209
+ )
210
+
211
+ def __repr__(self) -> str:
212
+ return super().__repr__() + f"({self._module_classes_str})"
213
+
214
+
215
+ class CustomPolicy(_Policy):
216
+ """
217
+ This policy takes in a lambda function that maps a given ``nn.Module`` to
218
+ either ``False``, ``True``, or a kwarg dictionary.
219
+ - If the function returns ``False`` or an empty dictionary, then the module
220
+ does not have the API applied.
221
+ - If the function returns ``True``, then the module has the API applied
222
+ with the root's kwargs.
223
+ - If the function returns a non-empty dictionary, then the module has the
224
+ API applied, and the dictionary overrides the root's kwargs.
225
+
226
+ Example::
227
+
228
+ >>> # xdoctest: +SKIP("undefined variables")
229
+ >>> model = init_transformer_model(...)
230
+ >>> def lambda_fn(module: nn.Module):
231
+ >>> if module is model.lm_head:
232
+ >>> return {"sharding_strategy": ShardingStrategy.SHARD_GRAD_OP}
233
+ >>> elif isinstance(module, TransformerBlock):
234
+ >>> return True
235
+ >>> return False
236
+ >>> policy = CustomPolicy(lambda_fn)
237
+ >>> fsdp_model = FSDP(model, auto_wrap_policy=policy)
238
+ """
239
+
240
+ def __init__(self, lambda_fn: Callable[[nn.Module], bool | dict[str, Any]]):
241
+ self._lambda_fn = lambda_fn
242
+
243
+ def _run_policy(
244
+ self,
245
+ root_module: nn.Module,
246
+ ignored_modules: set[nn.Module],
247
+ root_kwargs: dict[str, Any],
248
+ ) -> dict[nn.Module, dict[str, Any]]:
249
+ target_module_to_kwargs: dict[nn.Module, dict[str, Any]] = {}
250
+ for module in root_module.modules():
251
+ if module in ignored_modules:
252
+ continue
253
+ res = self._lambda_fn(module)
254
+ if not isinstance(res, (dict, bool)):
255
+ raise ValueError(
256
+ "The lambda_fn passed to CustomPolicy should return "
257
+ f"False/True or a kwarg dict, but it returned {res}"
258
+ )
259
+ if not res:
260
+ continue
261
+ kwargs = copy.copy(root_kwargs)
262
+ if isinstance(res, dict):
263
+ # Override the root kwargs with the ones specified by the
264
+ # lambda function
265
+ kwargs.update(res)
266
+ target_module_to_kwargs[module] = kwargs
267
+ return target_module_to_kwargs
268
+
269
+
270
+ def lambda_auto_wrap_policy(
271
+ module: nn.Module, recurse: bool, nonwrapped_numel: int, lambda_fn: Callable
272
+ ) -> bool:
273
+ """
274
+ A convenient auto wrap policy to wrap submodules based on an arbitrary user
275
+ function. If `lambda_fn(submodule) == True``, the submodule will be wrapped as
276
+ a `wrapper_cls` unit.
277
+
278
+ Return if a module should be wrapped during auto wrapping.
279
+
280
+ The first three parameters are required by :func:`_recursive_wrap`.
281
+
282
+ Args:
283
+ module (nn.Module): Current module being considered.
284
+ recurse (bool): If ``False``, then this function must decide whether
285
+ ``module`` should be wrapped as an FSDP instance or not. If
286
+ ``True``, then the function is still recursing down the module
287
+ tree as a part of the DFS.
288
+ nonwrapped_numel (int): Parameter numel not yet wrapped.
289
+
290
+ lambda_fn (Callable[[nn.Module], bool]): If this returns ``True``, then
291
+ this module will be wrapped.
292
+ """
293
+ if recurse:
294
+ return True # always recurse
295
+ return lambda_fn(module)
296
+
297
+
298
+ def transformer_auto_wrap_policy(
299
+ module: nn.Module,
300
+ recurse: bool,
301
+ nonwrapped_numel: int,
302
+ transformer_layer_cls: set[type[nn.Module]],
303
+ ) -> bool:
304
+ """
305
+ See :func:`_module_wrap_policy`, where ``transformer_layer_cls`` is the
306
+ same as ``module_classes``. Note that shared parameters must be wrapped in
307
+ the same FSDP instance, so this auto wrap policy can help wrap shared
308
+ embeddings into the same FSDP instance for transformer models.
309
+ """
310
+ return _module_wrap_policy(module, recurse, nonwrapped_numel, transformer_layer_cls)
311
+
312
+
313
+ def _wrap_module_cls_individually(
314
+ module: nn.Module, module_classes: Sequence[type], recurse: bool, *args, **kwargs
315
+ ):
316
+ if recurse:
317
+ # always recurse
318
+ return True
319
+ else:
320
+ # if not recursing, decide whether we should wrap based on whether the type of module
321
+ # is in `module_classes`.
322
+ return isinstance(module, tuple(module_classes))
323
+
324
+
325
+ def _or_policy(
326
+ module: nn.Module,
327
+ recurse: bool,
328
+ nonwrapped_numel: int,
329
+ policies,
330
+ ) -> bool:
331
+ """
332
+ A policy that wraps ``module`` if any policy in the passed in iterable of
333
+ ``policies`` returns ``True``.
334
+ """
335
+ return any(
336
+ policy(module=module, recurse=recurse, nonwrapped_numel=nonwrapped_numel)
337
+ for policy in policies
338
+ )
339
+
340
+
341
+ def size_based_auto_wrap_policy(
342
+ module: nn.Module,
343
+ recurse: bool,
344
+ nonwrapped_numel: int,
345
+ # Additional custom arguments
346
+ min_num_params: int = int(1e8),
347
+ force_leaf_modules: set[type[nn.Module]] | None = None,
348
+ exclude_wrap_modules: set[type[nn.Module]] | None = None,
349
+ ) -> bool:
350
+ """
351
+ A size-based auto wrap policy.
352
+
353
+ Args:
354
+ module (nn.Module): Current module being considered.
355
+ recurse (bool): If ``False``, then this function must decide whether
356
+ ``module`` should be wrapped as an FSDP instance or not. If
357
+ ``True``, then the function is still recursing down the module
358
+ tree as a part of the DFS.
359
+ nonwrapped_numel (int): Parameter numel not yet wrapped.
360
+
361
+ min_num_params (int): Customizable policy input that controls the size
362
+ threshold over which a module is ready to be wrapped. This is in
363
+ units of numel.
364
+ force_leaf_modules (Optional[set[type[nn.Module]]]): Set of module types to keep
365
+ as leaves, i.e. their children will never be wrapped.
366
+ exclude_wrap_modules (Optional[set[type[nn.Module]]]): Set of module types to be
367
+ excluded in wrapping.
368
+
369
+ Returns:
370
+ Whether ``module`` should be wrapped.
371
+ """
372
+ force_leaf_modules = (
373
+ size_based_auto_wrap_policy.FORCE_LEAF_MODULES # type: ignore[attr-defined]
374
+ if force_leaf_modules is None
375
+ else force_leaf_modules
376
+ )
377
+ exclude_wrap_modules = (
378
+ size_based_auto_wrap_policy.EXCLUDE_WRAP_MODULES # type: ignore[attr-defined]
379
+ if exclude_wrap_modules is None
380
+ else exclude_wrap_modules
381
+ )
382
+
383
+ # Keep the argument `min_num_params` for BC for now, but it represents the
384
+ # minimum non-wrapped *numel* before triggering a wrapping
385
+ min_nonwrapped_numel = min_num_params
386
+ is_large = nonwrapped_numel >= min_nonwrapped_numel
387
+ if recurse:
388
+ # We should recurse if the module is big enough but not in force_leaf_modules list.
389
+ return is_large and not isinstance(module, tuple(force_leaf_modules))
390
+ else:
391
+ # If we are not recursing, determine if we should wrap.
392
+ return is_large and not isinstance(module, tuple(exclude_wrap_modules))
393
+
394
+
395
+ # Set those defaults to the size_based_auto_wrap_policy function. Make them easy to be imported.
396
+ size_based_auto_wrap_policy.EXCLUDE_WRAP_MODULES = {nn.ModuleList, nn.ModuleDict} # type: ignore[attr-defined]
397
+ size_based_auto_wrap_policy.FORCE_LEAF_MODULES = {nn.MultiheadAttention} # type: ignore[attr-defined]
398
+
399
+
400
+ @contextlib.contextmanager
401
+ def enable_wrap(
402
+ *, wrapper_cls: Any, **wrapper_kwargs: Any
403
+ ) -> Generator[None, None, None]:
404
+ """
405
+ Context manager to wrap modules using a wrapper.
406
+
407
+ Useful for when you'd like to apply the same configuration arguments to all
408
+ child modules that you wrap. A particularly important use case is wrapping
409
+ large layers so that they get sharded (in-place) during initialization, to
410
+ avoid running out of system memory. Large layers can indicate that they
411
+ should be sharded via the ``wrap`` annotation and this context manager can
412
+ provide the exact configuration for these nested instances.
413
+
414
+ Usage::
415
+
416
+ with enable_wrap(wrapper_cls, **params):
417
+ # Wraps layer in FSDP by default if within context
418
+ self.l1 = wrap(torch.nn.Linear(5, 5))
419
+
420
+ Args:
421
+ wrapper_cls:
422
+ Class that `wrap` annotation will `wrap` modules with, such as
423
+ `FullyShardedDataParallel`.
424
+ **wrapper_kwargs:
425
+ Configuration settings that will be passed to all ``wrap``
426
+ instances inside the context
427
+ """
428
+ kwargs = {
429
+ "wrapper_cls": wrapper_cls,
430
+ **wrapper_kwargs,
431
+ }
432
+ with _ConfigAutoWrap(**kwargs):
433
+ yield
434
+
435
+
436
+ def wrap(module: nn.Module, **wrap_overrides: Any) -> nn.Module:
437
+ """
438
+ Annotate that a module should be wrapped. Annotated modules will only be
439
+ wrapped if inside of an :func:`enable_wrap` context manager. This allows
440
+ a module to be initialized both with and without a wrapper without code
441
+ change.
442
+
443
+ The class that this function wraps the passed in ``nn.Module`` with is the
444
+ passed in ``wrapper_cls`` argument into ``enable_wrap``. Both
445
+ ``enable_wrap`` and ``wrap`` can take in kwargs specifying how to construct
446
+ the ``wrapper_cls`` instance. In the case of duplicate kwargs in
447
+ ``enable_wrap`` and ``wrap``, the argument passed into ``wrap`` will be
448
+ respected.
449
+
450
+ Usage::
451
+
452
+ with enable_wrap(wrapper_cls=FSDP, **fsdp_config):
453
+ # Wraps layer in FSDP by default if within context
454
+ self.l1 = wrap(torch.nn.Linear(5, 5))
455
+
456
+ Args:
457
+ module (nn.Module): module to wrap (if in :func:`enable_wrap` context)
458
+ **wrap_overrides: configuration overrides that will take priority over
459
+ the values provided by the :func:`enable_wrap` context
460
+ """
461
+ if _ConfigAutoWrap.in_autowrap_context:
462
+ if _ConfigAutoWrap.wrapper_cls is None:
463
+ raise AssertionError("Expected _ConfigAutoWrap.wrapper_cls to be set")
464
+
465
+ wrap_overrides = {**_ConfigAutoWrap.kwargs, **wrap_overrides}
466
+ return _wrap(
467
+ module,
468
+ _ConfigAutoWrap.wrapper_cls,
469
+ **wrap_overrides,
470
+ )
471
+ return module
472
+
473
+
474
+ def _wrap(module: nn.Module, wrapper_cls: Callable, **kwargs) -> nn.Module:
475
+ if wrapper_cls is None:
476
+ raise AssertionError("Expected wrapper_cls to be set")
477
+ if hasattr(module, "_wrap_overrides"):
478
+ # If module has a _wrap_overrides attribute, we force overriding the
479
+ # FSDP config with these attributes for this module. Currently this
480
+ # is only used to disable mixed precision for BatchNorm when
481
+ # auto_wrapping.
482
+ overrides = {**kwargs, **module._wrap_overrides} # type: ignore[arg-type, dict-item]
483
+ return wrapper_cls(module, **overrides)
484
+
485
+ return wrapper_cls(module, **kwargs)
486
+
487
+
488
+ def _recursive_wrap(
489
+ module: nn.Module,
490
+ auto_wrap_policy: Callable,
491
+ wrapper_cls: Callable,
492
+ ignored_modules: set[nn.Module],
493
+ ignored_params: set[nn.Parameter],
494
+ only_wrap_children: bool = False,
495
+ **kwargs: Any,
496
+ ) -> tuple[nn.Module, int]:
497
+ """
498
+ Wraps submodules of ``module`` for which ``auto_wrap_policy`` returns
499
+ ``True`` with ``wrapper_cls``.
500
+
501
+ Args:
502
+ module (nn.Module): Module to recursively wrap.
503
+ auto_wrap_policy (Callable): A callable representing a policy that
504
+ determines which modules to recursively wrap with ``wrapper_cls``.
505
+ ignored_modules (set[torch.nn.Module]): Modules to ignore when
506
+ wrapping.
507
+ ignored_params (set[torch.nn.Parameter]): Parameters to ignore when
508
+ wrapping; these should be the parameters contained in the modules
509
+ in ``ignored_modules``.
510
+ Returns:
511
+ (nn.Module, int):
512
+ ``module`` after wrapping and the numel recursively wrapped.
513
+ """
514
+ if auto_wrap_policy is None:
515
+ raise AssertionError("Must specify auto_wrap_policy.")
516
+ if wrapper_cls is None:
517
+ raise AssertionError("Must specify wrapper_cls")
518
+ # Make sure no child is already wrapped.
519
+ for _, child in module.named_modules():
520
+ if child in ignored_modules:
521
+ continue
522
+ try:
523
+ if isinstance(child, cast(type, wrapper_cls)):
524
+ raise AssertionError(
525
+ f"Child module {child} is already wrapped by {wrapper_cls}"
526
+ )
527
+ except TypeError:
528
+ # wrapper_cls is a function as opposed to a class type, just bypass above check.
529
+ pass
530
+
531
+ # We count all params, assuming none of them are already wrapped.
532
+ nonwrapped_numel = sum(
533
+ p.numel() for p in module.parameters() if p not in ignored_params
534
+ )
535
+
536
+ if auto_wrap_policy is None:
537
+ raise AssertionError("Expected auto_wrap_policy to be set")
538
+ if auto_wrap_policy(module=module, recurse=True, nonwrapped_numel=nonwrapped_numel):
539
+ total_wrapped_numel = 0
540
+ # Iterate through the children, recursively wrap if necessary
541
+ for name, child in module.named_children():
542
+ if child in ignored_modules:
543
+ continue
544
+ wrapped_child, num_wrapped_params = _recursive_wrap(
545
+ module=child,
546
+ auto_wrap_policy=auto_wrap_policy,
547
+ wrapper_cls=wrapper_cls,
548
+ ignored_modules=ignored_modules,
549
+ ignored_params=ignored_params,
550
+ **kwargs,
551
+ )
552
+ setattr(module, name, wrapped_child)
553
+ # Keep track of how many parameters have been wrapped
554
+ total_wrapped_numel += num_wrapped_params
555
+ # decide if we need to wrap the current module,
556
+ # since the left over parameters exceed the number of params to wrap
557
+ remainder = nonwrapped_numel - total_wrapped_numel
558
+ if not only_wrap_children and auto_wrap_policy(
559
+ module=module, recurse=False, nonwrapped_numel=remainder
560
+ ):
561
+ # Leaf node or final wrapping of the remainder both happen here.
562
+ return _wrap(module, wrapper_cls, **kwargs), nonwrapped_numel
563
+ else:
564
+ return module, total_wrapped_numel
565
+ return module, 0
566
+
567
+
568
+ class _ConfigAutoWrap:
569
+ """
570
+ Helper class to wrap modules based on default config args via a context manager.
571
+ See :func:`enable_wrap` for more information.
572
+ """
573
+
574
+ in_autowrap_context: bool = False # Context flag
575
+ wrapper_cls: Callable | None = None # The wrapper class
576
+ kwargs: dict[str, Any] = {} # Wrapper's args
577
+
578
+ def __init__(self, **kwargs: dict[str, Any]):
579
+ self.kwargs = kwargs
580
+
581
+ @staticmethod
582
+ def enable_autowrap_context(kwargs: Any) -> None:
583
+ if _ConfigAutoWrap.in_autowrap_context:
584
+ raise NotImplementedError(
585
+ "You are already within an autowrap context and we currently do not supported nested autowrap."
586
+ )
587
+ _ConfigAutoWrap.in_autowrap_context = True
588
+ # Get and save the wrapper cls for the context.
589
+ if "wrapper_cls" not in kwargs:
590
+ raise AssertionError(
591
+ "Expected to pass in wrapper_cls arg into _ConfigAutoWrap."
592
+ )
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()
venv/lib/python3.14/site-packages/torch/distributed/launch.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ r"""
3
+ Module ``torch.distributed.launch``.
4
+
5
+ ``torch.distributed.launch`` is a module that spawns up multiple distributed
6
+ training processes on each of the training nodes.
7
+
8
+ .. warning::
9
+
10
+ This module is going to be deprecated in favor of :ref:`torchrun <launcher-api>`.
11
+
12
+ The utility can be used for single-node distributed training, in which one or
13
+ more processes per node will be spawned. The utility can be used for either
14
+ CPU training or GPU training. If the utility is used for GPU training,
15
+ each distributed process will be operating on a single GPU. This can achieve
16
+ well-improved single-node training performance. It can also be used in
17
+ multi-node distributed training, by spawning up multiple processes on each node
18
+ for well-improved multi-node distributed training performance as well.
19
+ This will especially be beneficial for systems with multiple Infiniband
20
+ interfaces that have direct-GPU support, since all of them can be utilized for
21
+ aggregated communication bandwidth.
22
+
23
+ In both cases of single-node distributed training or multi-node distributed
24
+ training, this utility will launch the given number of processes per node
25
+ (``--nproc-per-node``). If used for GPU training, this number needs to be less
26
+ or equal to the number of GPUs on the current system (``nproc_per_node``),
27
+ and each process will be operating on a single GPU from *GPU 0 to
28
+ GPU (nproc_per_node - 1)*.
29
+
30
+ **How to use this module:**
31
+
32
+ 1. Single-Node multi-process distributed training
33
+
34
+ ::
35
+
36
+ python -m torch.distributed.launch --nproc-per-node=NUM_GPUS_YOU_HAVE
37
+ YOUR_TRAINING_SCRIPT.py (--arg1 --arg2 --arg3 and all other
38
+ arguments of your training script)
39
+
40
+ 2. Multi-Node multi-process distributed training: (e.g. two nodes)
41
+
42
+
43
+ Node 1: *(IP: 192.168.1.1, and has a free port: 1234)*
44
+
45
+ ::
46
+
47
+ python -m torch.distributed.launch --nproc-per-node=NUM_GPUS_YOU_HAVE
48
+ --nnodes=2 --node-rank=0 --master-addr="192.168.1.1"
49
+ --master-port=1234 YOUR_TRAINING_SCRIPT.py (--arg1 --arg2 --arg3
50
+ and all other arguments of your training script)
51
+
52
+ Node 2:
53
+
54
+ ::
55
+
56
+ python -m torch.distributed.launch --nproc-per-node=NUM_GPUS_YOU_HAVE
57
+ --nnodes=2 --node-rank=1 --master-addr="192.168.1.1"
58
+ --master-port=1234 YOUR_TRAINING_SCRIPT.py (--arg1 --arg2 --arg3
59
+ and all other arguments of your training script)
60
+
61
+ 3. To look up what optional arguments this module offers:
62
+
63
+ ::
64
+
65
+ python -m torch.distributed.launch --help
66
+
67
+
68
+ **Important Notices:**
69
+
70
+ 1. This utility and multi-process distributed (single-node or
71
+ multi-node) GPU training currently only achieves the best performance using
72
+ the NCCL distributed backend. Thus NCCL backend is the recommended backend to
73
+ use for GPU training.
74
+
75
+ 2. In your training program, you must parse the command-line argument:
76
+ ``--local-rank=LOCAL_PROCESS_RANK``, which will be provided by this module.
77
+ If your training program uses GPUs, you should ensure that your code only
78
+ runs on the GPU device of LOCAL_PROCESS_RANK. This can be done by:
79
+
80
+ Parsing the local_rank argument
81
+
82
+ ::
83
+
84
+ >>> # xdoctest: +SKIP
85
+ >>> import argparse
86
+ >>> parser = argparse.ArgumentParser()
87
+ >>> parser.add_argument("--local-rank", "--local_rank", type=int)
88
+ >>> args = parser.parse_args()
89
+
90
+ Set your device to local rank using either
91
+
92
+ ::
93
+
94
+ >>> torch.cuda.set_device(args.local_rank) # before your code runs
95
+
96
+ or
97
+
98
+ ::
99
+
100
+ >>> with torch.cuda.device(args.local_rank):
101
+ >>> # your code to run
102
+ >>> ...
103
+
104
+ .. versionchanged:: 2.0.0
105
+
106
+ The launcher will passes the ``--local-rank=<rank>`` argument to your script.
107
+ From PyTorch 2.0.0 onwards, the dashed ``--local-rank`` is preferred over the
108
+ previously used underscored ``--local_rank``.
109
+
110
+ For backward compatibility, it may be necessary for users to handle both
111
+ cases in their argument parsing code. This means including both ``"--local-rank"``
112
+ and ``"--local_rank"`` in the argument parser. If only ``"--local_rank"`` is
113
+ provided, the launcher will trigger an error: "error: unrecognized arguments:
114
+ --local-rank=<rank>". For training code that only supports PyTorch 2.0.0+,
115
+ including ``"--local-rank"`` should be sufficient.
116
+
117
+ 3. In your training program, you are supposed to call the following function
118
+ at the beginning to start the distributed backend. It is strongly recommended
119
+ that ``init_method=env://``. Other init methods (e.g. ``tcp://``) may work,
120
+ but ``env://`` is the one that is officially supported by this module.
121
+
122
+ ::
123
+
124
+ >>> torch.distributed.init_process_group(backend='YOUR BACKEND',
125
+ >>> init_method='env://')
126
+
127
+ 4. In your training program, you can either use regular distributed functions
128
+ or use :func:`torch.nn.parallel.DistributedDataParallel` module. If your
129
+ training program uses GPUs for training and you would like to use
130
+ :func:`torch.nn.parallel.DistributedDataParallel` module,
131
+ here is how to configure it.
132
+
133
+ ::
134
+
135
+ >>> model = torch.nn.parallel.DistributedDataParallel(model,
136
+ >>> device_ids=[args.local_rank],
137
+ >>> output_device=args.local_rank)
138
+
139
+ Please ensure that ``device_ids`` argument is set to be the only GPU device id
140
+ that your code will be operating on. This is generally the local rank of the
141
+ process. In other words, the ``device_ids`` needs to be ``[args.local_rank]``,
142
+ and ``output_device`` needs to be ``args.local_rank`` in order to use this
143
+ utility
144
+
145
+ 5. Another way to pass ``local_rank`` to the subprocesses via environment variable
146
+ ``LOCAL_RANK``. This behavior is enabled when you launch the script with
147
+ ``--use-env=True``. You must adjust the subprocess example above to replace
148
+ ``args.local_rank`` with ``os.environ['LOCAL_RANK']``; the launcher
149
+ will not pass ``--local-rank`` when you specify this flag.
150
+
151
+ .. warning::
152
+
153
+ ``local_rank`` is NOT globally unique: it is only unique per process
154
+ on a machine. Thus, don't use it to decide if you should, e.g.,
155
+ write to a networked filesystem. See
156
+ https://github.com/pytorch/pytorch/issues/12042 for an example of
157
+ how things can go wrong if you don't do this correctly.
158
+
159
+
160
+
161
+ """
162
+
163
+ from typing_extensions import deprecated as _deprecated
164
+
165
+ from torch.distributed.run import get_args_parser, run
166
+
167
+
168
+ def parse_args(args):
169
+ parser = get_args_parser()
170
+ parser.add_argument(
171
+ "--use-env",
172
+ "--use_env",
173
+ default=False,
174
+ action="store_true",
175
+ help="Use environment variable to pass "
176
+ "'local rank'. For legacy reasons, the default value is False. "
177
+ "If set to True, the script will not pass "
178
+ "--local-rank as argument, and will instead set LOCAL_RANK.",
179
+ )
180
+ return parser.parse_args(args)
181
+
182
+
183
+ def launch(args):
184
+ if args.no_python and not args.use_env:
185
+ raise ValueError(
186
+ "When using the '--no-python' flag, you must also set the '--use-env' flag."
187
+ )
188
+ run(args)
189
+
190
+
191
+ @_deprecated(
192
+ "The module torch.distributed.launch is deprecated\n"
193
+ "and will be removed in future. Use torchrun.\n"
194
+ "Note that --use-env is set by default in torchrun.\n"
195
+ "If your script expects `--local-rank` argument to be set, please\n"
196
+ "change it to read from `os.environ['LOCAL_RANK']` instead. See \n"
197
+ "https://pytorch.org/docs/stable/distributed.html#launch-utility for \n"
198
+ "further instructions\n",
199
+ category=FutureWarning,
200
+ )
201
+ def main(args=None):
202
+ args = parse_args(args)
203
+ launch(args)
204
+
205
+
206
+ if __name__ == "__main__":
207
+ main()
venv/lib/python3.14/site-packages/torch/distributed/launcher/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env/python3
2
+
3
+ # Copyright (c) Facebook, Inc. and its affiliates.
4
+ # All rights reserved.
5
+ #
6
+ # This source code is licensed under the BSD-style license found in the
7
+ # LICENSE file in the root directory of this source tree.
8
+
9
+
10
+ from torch.distributed.launcher.api import ( # noqa: F401
11
+ elastic_launch,
12
+ launch_agent,
13
+ LaunchConfig,
14
+ )
venv/lib/python3.14/site-packages/torch/distributed/launcher/api.py ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # mypy: allow-untyped-defs
3
+
4
+ # Copyright (c) Facebook, Inc. and its affiliates.
5
+ # All rights reserved.
6
+ #
7
+ # This source code is licensed under the BSD-style license found in the
8
+ # LICENSE file in the root directory of this source tree.
9
+ import os
10
+ import sys
11
+ import uuid
12
+ from collections.abc import Callable
13
+ from dataclasses import dataclass, field
14
+ from typing import Any
15
+
16
+ import torch
17
+ import torch.distributed.elastic.rendezvous.registry as rdzv_registry
18
+ from torch._utils_internal import get_default_numa_options, justknobs_check
19
+ from torch.distributed.elastic import events, metrics
20
+ from torch.distributed.elastic.agent.server.api import WorkerSpec
21
+ from torch.distributed.elastic.agent.server.health_check_server import (
22
+ create_healthcheck_server,
23
+ )
24
+ from torch.distributed.elastic.agent.server.local_elastic_agent import (
25
+ _AliveCallbackProxy,
26
+ LocalElasticAgent,
27
+ TORCHELASTIC_HEALTH_CHECK_PORT,
28
+ )
29
+ from torch.distributed.elastic.multiprocessing import (
30
+ DefaultLogsSpecs,
31
+ LogsSpecs,
32
+ SignalException,
33
+ )
34
+ from torch.distributed.elastic.multiprocessing.errors import ChildFailedError
35
+ from torch.distributed.elastic.rendezvous import RendezvousParameters
36
+ from torch.distributed.elastic.rendezvous.utils import parse_rendezvous_endpoint
37
+ from torch.distributed.elastic.utils.logging import get_logger
38
+ from torch.numa.binding import NumaOptions
39
+
40
+
41
+ __all__ = ["LaunchConfig", "elastic_launch", "launch_agent"]
42
+
43
+ logger = get_logger(__name__)
44
+
45
+
46
+ @dataclass
47
+ class LaunchConfig:
48
+ """
49
+ Creates a rendezvous config.
50
+
51
+ Args:
52
+ min_nodes: Minimum amount of nodes that the user function will
53
+ be launched on. Elastic agent ensures that the user
54
+ function start only when the min_nodes amount enters
55
+ the rendezvous.
56
+ max_nodes: Maximum amount of nodes that the user function
57
+ will be launched on.
58
+ nproc_per_node: On each node the elastic agent will launch
59
+ this amount of workers that will execute user
60
+ defined function.
61
+ rdzv_backend: rdzv_backend to use in the rendezvous (zeus-adapter, etcd).
62
+ rdzv_endpoint: The endpoint of the rdzv sync. storage.
63
+ rdzv_configs: Key, value pair that specifies rendezvous specific configuration.
64
+ rdzv_timeout: Legacy argument that specifies timeout for the rendezvous. It is going
65
+ to be removed in future versions, see the note below. The default timeout is 900 seconds.
66
+ run_id: The unique run id of the job (if not passed a unique one will be
67
+ deduced from run environment - flow workflow id in flow - or auto generated).
68
+ role: User defined role of the worker (defaults to "trainer").
69
+ max_restarts: The maximum amount of restarts that elastic agent will conduct
70
+ on workers before failure.
71
+ monitor_interval: The interval in seconds that is used by the elastic_agent
72
+ as a period of monitoring workers.
73
+ start_method: The method is used by the elastic agent to start the
74
+ workers (spawn, fork, forkserver).
75
+ metrics_cfg: configuration to initialize metrics.
76
+ local_addr: address of the local node if any. If not set, a lookup on the local
77
+ machine's FQDN will be performed.
78
+ local_ranks_filter: ranks for which to show logs in console. If not set, show from all.
79
+ event_log_handler: name of the event logging handler as registered in
80
+ `elastic/events/handlers.py <https://docs.pytorch.org/docs/stable/elastic/events.html>`_.
81
+ duplicate_stdout_filters: If non-empty, duplicates stdout to a file containing only lines
82
+ that match _any_ of the filter strings.
83
+ duplicate_stderr_filters: If non-empty, duplicates stderr to a file containing only lines
84
+ that match _any_ of the filter strings.
85
+ virtual_local_rank: Enable virtual local rank mode for workers (defaults to False).
86
+ When enabled, LOCAL_RANK is set to 0 for all workers and
87
+ CUDA_VISIBLE_DEVICES is adjusted so each worker accesses its
88
+ assigned GPU at device index 0.
89
+ shutdown_timeout: Time in seconds to wait for graceful shutdown of workers before
90
+ sending SIGKILL. Can also be set via TORCH_ELASTIC_SHUTDOWN_TIMEOUT
91
+ environment variable. Defaults to 30 seconds.
92
+
93
+
94
+ .. note::
95
+ `rdzv_timeout` is a legacy argument that will be removed in future.
96
+ Set the timeout via `rdzv_configs['timeout']`
97
+
98
+ """
99
+
100
+ min_nodes: int
101
+ max_nodes: int
102
+ nproc_per_node: int
103
+ logs_specs: LogsSpecs | None = None
104
+ run_id: str = ""
105
+ role: str = "default_role"
106
+ rdzv_endpoint: str = ""
107
+ rdzv_backend: str = "etcd"
108
+ rdzv_configs: dict[str, Any] = field(default_factory=dict)
109
+ rdzv_timeout: int = -1
110
+ max_restarts: int = 3
111
+ monitor_interval: float = 0.1
112
+ start_method: str = "spawn"
113
+ log_line_prefix_template: str | None = None
114
+ metrics_cfg: dict[str, str] = field(default_factory=dict)
115
+ local_addr: str | None = None
116
+ event_log_handler: str = "null"
117
+ numa_options: NumaOptions | None = None
118
+ signals_to_handle: str = "SIGTERM,SIGINT,SIGHUP,SIGQUIT"
119
+ duplicate_stdout_filters: list[str] | None = None
120
+ duplicate_stderr_filters: list[str] | None = None
121
+ virtual_local_rank: bool = False
122
+ shutdown_timeout: int | None = None
123
+
124
+ def __post_init__(self):
125
+ default_timeout = 900
126
+ if self.rdzv_timeout != -1:
127
+ self.rdzv_configs["timeout"] = self.rdzv_timeout
128
+ elif "timeout" not in self.rdzv_configs:
129
+ self.rdzv_configs["timeout"] = default_timeout
130
+
131
+ # Post-processing to enable refactoring to introduce logs_specs due to non-torchrun API usage
132
+ if self.logs_specs is None:
133
+ self.logs_specs = DefaultLogsSpecs()
134
+
135
+ if (
136
+ self.numa_options is None
137
+ and torch.cuda.is_available()
138
+ # We assume local_rank n uses cuda device n.
139
+ and torch.cuda.device_count() == self.nproc_per_node
140
+ ):
141
+ self.numa_options = get_default_numa_options()
142
+ logger.info("Using default numa options = %r", self.numa_options)
143
+
144
+ # Set shutdown_timeout from environment variable if not explicitly set
145
+ if self.shutdown_timeout is None:
146
+ self.shutdown_timeout = int(
147
+ os.environ.get("TORCH_ELASTIC_SHUTDOWN_TIMEOUT", "30")
148
+ )
149
+ elif self.shutdown_timeout < 0:
150
+ raise ValueError(
151
+ f"shutdown_timeout must be non-negative, got {self.shutdown_timeout}"
152
+ )
153
+
154
+
155
+ class elastic_launch:
156
+ """
157
+ Launches an torchelastic agent on the container that invoked the entrypoint.
158
+
159
+ 1. Pass the ``entrypoint`` arguments as non ``kwargs`` (e.g. no named parameters)/
160
+ ``entrypoint`` can be a function or a command.
161
+ 2. The return value is a map of each worker's output mapped
162
+ by their respective global rank.
163
+
164
+ Usage
165
+
166
+ ::
167
+
168
+ def worker_fn(foo):
169
+ # ...
170
+
171
+ def main():
172
+ # entrypoint is a function.
173
+ outputs = elastic_launch(LaunchConfig, worker_fn)(foo)
174
+ # return rank 0's output
175
+ return outputs[0]
176
+
177
+ # entrypoint is a command and ``script.py`` is the python module.
178
+ outputs = elastic_launch(LaunchConfig, "script.py")(args)
179
+ outputs = elastic_launch(LaunchConfig, "python")("script.py")
180
+ """
181
+
182
+ def __init__(
183
+ self,
184
+ config: LaunchConfig,
185
+ entrypoint: Callable | str | None,
186
+ ):
187
+ self._config = config
188
+ self._entrypoint = entrypoint
189
+
190
+ def __call__(self, *args):
191
+ return launch_agent(self._config, self._entrypoint, list(args))
192
+
193
+
194
+ def _get_entrypoint_name(entrypoint: Callable | str | None, args: list[Any]) -> str:
195
+ """Retrieve entrypoint name with the rule:
196
+ 1. If entrypoint is a function, use ``entrypoint.__qualname__``.
197
+ 2. If entrypoint is a string, check its value:
198
+ 2.1 if entrypoint equals to ``sys.executable`` (like "python"), use the first element from ``args``
199
+ which does not start with hifen letter (for example, "-u" will be skipped).
200
+ 2.2 otherwise, use ``entrypoint`` value.
201
+ 3. Otherwise, return empty string.
202
+ """
203
+ if isinstance(entrypoint, Callable): # type: ignore[arg-type]
204
+ return entrypoint.__name__ # type: ignore[union-attr]
205
+ elif isinstance(entrypoint, str):
206
+ if entrypoint == sys.executable:
207
+ return next((arg for arg in args if arg[0] != "-"), "")
208
+ else:
209
+ return entrypoint
210
+ else:
211
+ return ""
212
+
213
+
214
+ def _get_addr_and_port(
215
+ rdzv_parameters: RendezvousParameters,
216
+ ) -> tuple[str | None, int | None]:
217
+ if rdzv_parameters.backend != "static":
218
+ return (None, None)
219
+ endpoint = rdzv_parameters.endpoint
220
+ endpoint = endpoint.strip()
221
+ if not endpoint:
222
+ raise ValueError(
223
+ "Endpoint is missing in endpoint. Try to add --master-addr and --master-port"
224
+ )
225
+ master_addr, master_port = parse_rendezvous_endpoint(endpoint, default_port=-1)
226
+ if master_port == -1:
227
+ raise ValueError(
228
+ f"port is missing in endpoint: {endpoint}. Try to specify --master-port"
229
+ )
230
+ return (master_addr, master_port)
231
+
232
+
233
+ def launch_agent(
234
+ config: LaunchConfig,
235
+ entrypoint: Callable | str | None,
236
+ args: list[Any],
237
+ ) -> dict[int, Any]:
238
+ if not config.run_id:
239
+ run_id = str(uuid.uuid4().int)
240
+ logger.warning("config has no run_id, generated a random run_id: %s", run_id)
241
+ config.run_id = run_id
242
+
243
+ entrypoint_name = _get_entrypoint_name(entrypoint, args)
244
+
245
+ logger.info(
246
+ "Starting elastic_operator with launch configs:\n"
247
+ " entrypoint : %(entrypoint)s\n"
248
+ " min_nodes : %(min_nodes)s\n"
249
+ " max_nodes : %(max_nodes)s\n"
250
+ " nproc_per_node : %(nproc_per_node)s\n"
251
+ " run_id : %(run_id)s\n"
252
+ " rdzv_backend : %(rdzv_backend)s\n"
253
+ " rdzv_endpoint : %(rdzv_endpoint)s\n"
254
+ " rdzv_configs : %(rdzv_configs)s\n"
255
+ " max_restarts : %(max_restarts)s\n"
256
+ " monitor_interval : %(monitor_interval)s\n"
257
+ " log_dir : %(log_dir)s\n"
258
+ " metrics_cfg : %(metrics_cfg)s\n"
259
+ " event_log_handler : %(event_log_handler)s\n"
260
+ " numa_options : %(numa_options)s\n"
261
+ " signals_to_handle : %(signals_to_handle)s\n"
262
+ " duplicate_stdout_filters : %(duplicate_stdout_filters)s\n"
263
+ " duplicate_stderr_filters : %(duplicate_stderr_filters)s\n",
264
+ {
265
+ "entrypoint": entrypoint_name,
266
+ "min_nodes": config.min_nodes,
267
+ "max_nodes": config.max_nodes,
268
+ "nproc_per_node": config.nproc_per_node,
269
+ "run_id": config.run_id,
270
+ "rdzv_backend": config.rdzv_backend,
271
+ "rdzv_endpoint": config.rdzv_endpoint,
272
+ "rdzv_configs": config.rdzv_configs,
273
+ "max_restarts": config.max_restarts,
274
+ "monitor_interval": config.monitor_interval,
275
+ "log_dir": config.logs_specs.root_log_dir, # type: ignore[union-attr]
276
+ "metrics_cfg": config.metrics_cfg,
277
+ "event_log_handler": config.event_log_handler,
278
+ "numa_options": config.numa_options,
279
+ "signals_to_handle": config.signals_to_handle,
280
+ "duplicate_stdout_filters": config.duplicate_stdout_filters,
281
+ "duplicate_stderr_filters": config.duplicate_stderr_filters,
282
+ },
283
+ )
284
+
285
+ rdzv_parameters = RendezvousParameters(
286
+ backend=config.rdzv_backend,
287
+ endpoint=config.rdzv_endpoint,
288
+ run_id=config.run_id,
289
+ min_nodes=config.min_nodes,
290
+ max_nodes=config.max_nodes,
291
+ local_addr=config.local_addr,
292
+ **config.rdzv_configs,
293
+ )
294
+
295
+ master_addr, master_port = _get_addr_and_port(rdzv_parameters)
296
+
297
+ # Set the signals to handle in the environment variable
298
+ os.environ["TORCHELASTIC_SIGNALS_TO_HANDLE"] = config.signals_to_handle
299
+
300
+ # Start health check server before rendezvous so TW sees a healthy
301
+ # thrift port during the potentially long MAST rendezvous store barrier
302
+ # (10-22+ min for large jobs). The _AliveCallbackProxy returns
303
+ # time.time() until wired to the agent after construction.
304
+ health_check_server = None
305
+ alive_callback_proxy = None
306
+ healthcheck_port = os.getenv(TORCHELASTIC_HEALTH_CHECK_PORT)
307
+ if healthcheck_port is not None and justknobs_check(
308
+ "ai_infra/pytorch_distributed:torchelastic_enable_healthcheck_before_rendezvous",
309
+ default=False,
310
+ ):
311
+ try:
312
+ alive_callback_proxy = _AliveCallbackProxy()
313
+ health_check_server = create_healthcheck_server(
314
+ alive_callback=alive_callback_proxy,
315
+ port=int(healthcheck_port),
316
+ timeout=60,
317
+ )
318
+ health_check_server.start()
319
+ logger.info(
320
+ "Started early health check server on port %s before rendezvous",
321
+ healthcheck_port,
322
+ )
323
+ except Exception:
324
+ logger.warning("Failed to start early health check server", exc_info=True)
325
+ health_check_server = None
326
+ alive_callback_proxy = None
327
+
328
+ spec = WorkerSpec(
329
+ role=config.role,
330
+ local_world_size=config.nproc_per_node,
331
+ entrypoint=entrypoint,
332
+ args=tuple(args),
333
+ rdzv_handler=rdzv_registry.get_rendezvous_handler(rdzv_parameters),
334
+ max_restarts=config.max_restarts,
335
+ monitor_interval=config.monitor_interval,
336
+ master_addr=master_addr,
337
+ master_port=master_port,
338
+ local_addr=config.local_addr,
339
+ event_log_handler=config.event_log_handler,
340
+ numa_options=config.numa_options,
341
+ duplicate_stdout_filters=config.duplicate_stdout_filters,
342
+ duplicate_stderr_filters=config.duplicate_stderr_filters,
343
+ virtual_local_rank=config.virtual_local_rank,
344
+ )
345
+
346
+ agent = LocalElasticAgent(
347
+ spec=spec,
348
+ logs_specs=config.logs_specs, # type: ignore[arg-type]
349
+ start_method=config.start_method,
350
+ log_line_prefix_template=config.log_line_prefix_template,
351
+ shutdown_timeout=config.shutdown_timeout, # type: ignore[arg-type]
352
+ health_check_server=health_check_server,
353
+ )
354
+
355
+ if alive_callback_proxy is not None:
356
+ alive_callback_proxy.set_delegate(agent._get_alive_time)
357
+
358
+ shutdown_rdzv = True
359
+ try:
360
+ metrics.initialize_metrics(metrics.MetricsConfig(config.metrics_cfg))
361
+
362
+ result = agent.run()
363
+ # records that agent.run() has succeeded NOT that workers have succeeded
364
+ events.record(agent.get_event_succeeded(), config.event_log_handler)
365
+
366
+ if result.is_failed():
367
+ # ChildFailedError is treated specially by @record
368
+ # if the error files for the failed children exist
369
+ # @record will copy the first error (root cause)
370
+ # to the error file of the launcher process.
371
+ raise ChildFailedError(
372
+ name=entrypoint_name,
373
+ failures=result.failures,
374
+ )
375
+
376
+ return result.return_values
377
+ except ChildFailedError:
378
+ raise
379
+ except SignalException:
380
+ # when the agent dies with a signal do NOT shutdown the rdzv_handler
381
+ # since this closes the rendezvous on this rdzv_id permanently and
382
+ # prevents any additional scaling events
383
+ shutdown_rdzv = False
384
+ events.record(agent.get_event_failed(), config.event_log_handler)
385
+ raise
386
+ except Exception:
387
+ events.record(agent.get_event_failed(), config.event_log_handler)
388
+ raise
389
+ finally:
390
+ if shutdown_rdzv:
391
+ spec.rdzv_handler.shutdown()
venv/lib/python3.14/site-packages/torch/distributed/logging_handlers.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ # Copyright (c) Facebook, Inc. and its affiliates.
4
+ # All rights reserved.
5
+ #
6
+ # This source code is licensed under the BSD-style license found in the
7
+ # LICENSE file in the root directory of this source tree.
8
+
9
+ import logging
10
+
11
+
12
+ __all__: list[str] = []
13
+
14
+ _log_handlers: dict[str, logging.Handler] = {
15
+ "default": logging.NullHandler(),
16
+ }
venv/lib/python3.14/site-packages/torch/distributed/nn/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ from .functional import * # noqa: F403
4
+
5
+
6
+ if torch.distributed.rpc.is_available():
7
+ from .api.remote_module import RemoteModule
venv/lib/python3.14/site-packages/torch/distributed/nn/api/__init__.py ADDED
File without changes
venv/lib/python3.14/site-packages/torch/distributed/nn/api/remote_module.py ADDED
@@ -0,0 +1,762 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ # mypy: allow-untyped-defs
3
+ import collections
4
+ import io
5
+ import sys
6
+ import types
7
+ from collections.abc import Callable, Iterator, Mapping
8
+ from typing import Any, TypeVar
9
+ from typing_extensions import Self
10
+
11
+ import torch
12
+ import torch.distributed.rpc as rpc
13
+ from torch import device, dtype, nn, Tensor
14
+ from torch.distributed import _remote_device
15
+ from torch.distributed.nn.jit import instantiator
16
+ from torch.distributed.rpc.internal import _internal_rpc_pickler
17
+ from torch.nn import Module
18
+ from torch.nn.parameter import Parameter
19
+ from torch.utils.hooks import RemovableHandle
20
+
21
+
22
+ __all__ = ["RemoteModule"]
23
+
24
+ _grad_t = tuple[Tensor, ...] | Tensor
25
+ # See https://mypy.readthedocs.io/en/latest/generics.html#generic-methods-and-generic-self for the use
26
+ # of `T` to annotate `self`. Many methods of `Module` return `self` and we want those return values to be
27
+ # the type of the subclass, not the looser type of `Module`.
28
+ T = TypeVar("T", bound="Module")
29
+
30
+ _NON_SCRIPTABLE_REMOTE_MODULE_MODULE = (
31
+ instantiator.instantiate_non_scriptable_remote_module_template()
32
+ )
33
+
34
+ _REMOTE_MODULE_PICKLED_ATTRIBUTES = (
35
+ "on",
36
+ "device",
37
+ "is_device_map_set",
38
+ "is_scriptable",
39
+ "generated_methods",
40
+ "module_rref",
41
+ )
42
+
43
+ _SerializedRemoteModule = collections.namedtuple( # type: ignore[misc]
44
+ "_SerializedRemoteModule",
45
+ _REMOTE_MODULE_PICKLED_ATTRIBUTES,
46
+ )
47
+
48
+ # These attributes are mostly from RemoteModule's parent class and are intentionally not pickled.
49
+ # A new attribute of RemoteModule should be either in _REMOTE_MODULE_PICKLED_ATTRIBUTES
50
+ # or _REMOTE_MODULE_ATTRIBUTES_IGNORE_FOR_PICKLING.
51
+ # Otherwise, it will not be pickled.
52
+ _REMOTE_MODULE_ATTRIBUTES_IGNORE_FOR_PICKLING = (
53
+ "training",
54
+ "_parameters",
55
+ "_buffers",
56
+ "_non_persistent_buffers_set",
57
+ "_backward_hooks",
58
+ "_backward_pre_hooks",
59
+ "_is_full_backward_hook",
60
+ "_forward_hooks",
61
+ "_forward_hooks_with_kwargs",
62
+ "_forward_hooks_always_called",
63
+ "_forward_pre_hooks",
64
+ "_forward_pre_hooks_with_kwargs",
65
+ "_state_dict_hooks",
66
+ "_state_dict_pre_hooks",
67
+ "_load_state_dict_pre_hooks",
68
+ "_load_state_dict_post_hooks",
69
+ "_state_dict_pre_hooks",
70
+ "_modules",
71
+ # The two attributes below are generated methods, not available at pickling time.
72
+ "forward_async",
73
+ "forward",
74
+ )
75
+
76
+
77
+ # RPC handler.
78
+ def _instantiate_template(module_interface_cls, enable_moving_cpu_tensors_to_cuda):
79
+ instantiator.instantiate_scriptable_remote_module_template(
80
+ module_interface_cls, enable_moving_cpu_tensors_to_cuda
81
+ )
82
+
83
+
84
+ def _create_module(module_cls, args, kwargs, device):
85
+ module = module_cls(*args, **kwargs)
86
+ if not isinstance(module, nn.Module):
87
+ raise ValueError(
88
+ "Expect `module_cls(*args, **kwargs)` returns an instance of <class nn.Module>, "
89
+ f"but it returns an instance of {type(module)}."
90
+ )
91
+ module.to(device)
92
+ return module
93
+
94
+
95
+ def _create_module_with_interface(
96
+ module_cls, args, kwargs, device, module_interface_cls
97
+ ):
98
+ module = _create_module(module_cls, args, kwargs, device)
99
+ if module_interface_cls is not None:
100
+ module = torch.jit.script(module)
101
+ return rpc.RRef(module, module_interface_cls)
102
+
103
+
104
+ def _param_rrefs(module_rref, recurse) -> list[rpc.RRef[Parameter]]:
105
+ ret: list[rpc.RRef[Parameter]] = [
106
+ rpc.RRef(param) for param in module_rref.local_value().parameters(recurse)
107
+ ]
108
+ return ret
109
+
110
+
111
+ def _raise_not_supported(name: str) -> None:
112
+ raise ValueError(f"Method ``{name}`` not supported for RemoteModule")
113
+
114
+
115
+ class _RemoteModule(nn.Module):
116
+ def __new__(cls, *args, **kwargs):
117
+ # Use __new__ for logging purposes.
118
+ torch._C._log_api_usage_once("torch.distributed.nn.api.remote_module")
119
+ return super().__new__(cls)
120
+
121
+ def __init__(
122
+ self,
123
+ remote_device: str,
124
+ module_cls: type[nn.Module],
125
+ args: tuple | None = None,
126
+ kwargs: dict[str, Any] | None = None,
127
+ _module_interface_cls: Any = None,
128
+ ):
129
+ """
130
+ RemoteModule instance can only be created after RPC initialization.
131
+
132
+ It creates a user-specified module on a specified remote node.
133
+ It behaves like a regular ``nn.Module`` except that the ``forward`` method is
134
+ executed on the remote node.
135
+ It takes care of autograd recording to ensure the backward pass propagates
136
+ gradients back to the corresponding remote module.
137
+ It can be shared across processors using `RPC framework <https://pytorch.org/docs/stable/rpc.html>`__,
138
+ without incurring any overheads of copying the actual module,
139
+ which is equivalent to an :class:`~torch.distributed.rpc.RRef`
140
+ pointing to the remote module.
141
+
142
+ The arguments of ``forward_async`` and ``forward`` are the same as
143
+ the ``forward`` method of the module returned by the ``module_cls``.
144
+
145
+ Apart from ``forward_async`` and ``forward``, no other methods are supported from nn.Module for now.
146
+
147
+ Particularly, to create a hybrid model, typically the local modules should be
148
+ created outside of remote modules, rather than as submodules of any remote module (by calling ``add_module``).
149
+ Hybrid Example:
150
+ >>> class HybridModel(nn.Module):
151
+ >>> def __init__(self) -> None:
152
+ >>> nn.Module.__init__(self)
153
+ >>> self.remote_embedding = RemoteModule(...)
154
+ >>> self.local_linear = nn.Linear(...)
155
+
156
+ For example, if ``module_cls`` returns an instance of ``nn.Linear``,
157
+ that has ``forward`` method signature, ``def forward(input: Tensor) -> Tensor:``,
158
+ the generated ``RemoteModule`` will have 2 methods in signature of
159
+ ``def forward(input: Tensor) -> Tensor:`` and
160
+ ``def forward_async(input: Tensor) -> Future[Tensor]:``.
161
+
162
+ .. note::
163
+ If the remote module is placed on a cuda device,
164
+ any input CPU tensors will be automatically moved to the same cuda device,
165
+ and GPU tensors are returned over the wire according to the device map of the remote worker on TensorPipe RPC backend.
166
+
167
+ Args:
168
+ remote_device (str): Device on the destination worker where we'd like to place this module.
169
+ The device can be a local device or a remote device specified by one of the following remote
170
+ formats:
171
+
172
+ 1. "rank:<rank>/<device>" (ex: "rank:0/cuda:0").
173
+ 2. "<worker_name>/<device>" (ex: "trainer0/cuda:0").
174
+
175
+ In addition, the device field can be optional and the default value is "cpu".
176
+ module_cls (nn.Module): For example,
177
+ >>> class MyModule(nn.Module):
178
+ >>> def forward(input):
179
+ >>> return input + 1
180
+ >>>
181
+ >>> module_cls = MyModule
182
+ args (Sequence, optional): args to be passed to ``module_cls``.
183
+ kwargs (Dict, optional): kwargs to be passed to ``module_cls``.
184
+ _module_interface_cls (type, optional): The TorchScript interface type for the module
185
+ to be created. The type object should be decorated by @torch.jit.interface.
186
+ If not provided, the generated RemoteModule is not torchscript-able.
187
+ Warning, this is an experimental API and susceptible to frequent changes.
188
+
189
+ Returns:
190
+ A remote module instance which wraps the :class:`~nn.Module` created by the
191
+ user-provided ``module_cls``, it has a blocking ``forward`` method and an
192
+ asynchronous ``forward_async`` method that returns a future of the ``forward`` call
193
+ on the user-provided module on the remote side.
194
+
195
+ Example::
196
+ Run the following code in two different processes:
197
+
198
+ >>> # xdoctest: +SKIP("distributed")
199
+ >>> # On worker 0:
200
+ >>> import torch
201
+ >>> import torch.distributed.rpc as rpc
202
+ >>> from torch import nn, Tensor
203
+ >>> from torch.distributed.nn.api.remote_module import RemoteModule
204
+ >>>
205
+ >>> rpc.init_rpc("worker0", rank=0, world_size=2)
206
+ >>> remote_linear_module = RemoteModule(
207
+ >>> "worker1/cpu", nn.Linear, args=(20, 30),
208
+ >>> )
209
+ >>> input = torch.randn(128, 20)
210
+ >>> ret_fut = remote_linear_module.forward_async(input)
211
+ >>> ret = ret_fut.wait()
212
+ >>> rpc.shutdown()
213
+
214
+ >>> # On worker 1:
215
+ >>> import torch
216
+ >>> import torch.distributed.rpc as rpc
217
+ >>>
218
+ >>> rpc.init_rpc("worker1", rank=1, world_size=2)
219
+ >>> rpc.shutdown()
220
+ """
221
+ super().__init__()
222
+
223
+ enable_moving_cpu_tensors_to_cuda = self._prepare_init(remote_device)
224
+
225
+ # Default arguments preparation.
226
+ args = args if args is not None else ()
227
+ kwargs = kwargs if kwargs is not None else {}
228
+
229
+ if _module_interface_cls is not None:
230
+ # Users reply on this field to know if this generated RemoteModule is TorchScript-able.
231
+ self.is_scriptable = True
232
+
233
+ # Instantiate template on remote side.
234
+ fut = rpc.rpc_async(
235
+ self.on,
236
+ _instantiate_template,
237
+ (_module_interface_cls, enable_moving_cpu_tensors_to_cuda),
238
+ )
239
+
240
+ self._init_template(
241
+ _module_interface_cls, enable_moving_cpu_tensors_to_cuda
242
+ )
243
+
244
+ # Instantiate template on remote side.
245
+ fut = rpc.rpc_async(
246
+ self.on,
247
+ _instantiate_template,
248
+ (_module_interface_cls, enable_moving_cpu_tensors_to_cuda),
249
+ )
250
+
251
+ # Create the module on the remote side.
252
+ fut.wait() # Ensure remote_module_cls is available on remote side.
253
+
254
+ # TODO: We need to change this to rpc.remote, and make it async (see the else branch below).
255
+ # For that we need to be able to apply _module_interface_cls to the RRef returned by rpc.remote
256
+ # See https://github.com/pytorch/pytorch/issues/58098 for more context.
257
+ self.module_rref = rpc.rpc_sync(
258
+ self.on,
259
+ _create_module_with_interface,
260
+ (module_cls, args, kwargs, self.device, _module_interface_cls),
261
+ )
262
+ else:
263
+ self.is_scriptable = False
264
+ self.generated_methods = (
265
+ _NON_SCRIPTABLE_REMOTE_MODULE_MODULE._generated_methods
266
+ )
267
+ # Create the module on the remote side.
268
+ self.module_rref = rpc.remote(
269
+ self.on,
270
+ _create_module,
271
+ (module_cls, args, kwargs, self.device),
272
+ )
273
+
274
+ self._install_generated_methods()
275
+ self._check_attribute_picklability()
276
+
277
+ def remote_parameters(self, recurse: bool = True) -> list[rpc.RRef[Parameter]]:
278
+ """
279
+ Return a list of :class:`~torch.distributed.rpc.RRef` pointing to the remote module's parameters.
280
+
281
+ This can typically be used in conjunction
282
+ with :class:`~torch.distributed.optim.DistributedOptimizer`.
283
+
284
+ Args:
285
+ recurse (bool): if True, then returns parameters of the remote
286
+ module and all submodules of the remote module. Otherwise,
287
+ returns only parameters that are direct members of the
288
+ remote module.
289
+
290
+ Returns:
291
+ A list of :class:`~torch.distributed.rpc.RRef` (``List[RRef[nn.Parameter]]``)
292
+ to remote module's parameters.
293
+ """
294
+ return rpc.rpc_sync(self.on, _param_rrefs, args=(self.module_rref, recurse))
295
+
296
+ def get_module_rref(self) -> rpc.RRef[nn.Module]:
297
+ """Return an :class:`~torch.distributed.rpc.RRef` (``RRef[nn.Module]``) pointing to the remote module."""
298
+ return self.module_rref
299
+
300
+ @torch.jit.export
301
+ def __getstate__(self):
302
+ raise RuntimeError(
303
+ "Cannot pickle RemoteModule in python pickler. RemoteModule can only be pickled when using RPC"
304
+ )
305
+
306
+ @torch.jit.export
307
+ def __setstate__(self, state):
308
+ raise RuntimeError(
309
+ "Cannot unpickle RemoteModule in python pickler. RemoteModule can only be unpickled when using RPC"
310
+ )
311
+
312
+ def register_buffer(
313
+ self, name: str, tensor: Tensor | None, persistent: bool = True
314
+ ) -> None:
315
+ _raise_not_supported(self.register_buffer.__name__)
316
+
317
+ def register_parameter(self, name: str, param: Parameter | None) -> None:
318
+ _raise_not_supported(self.register_parameter.__name__)
319
+
320
+ def add_module(self, name: str, module: Module | None) -> None:
321
+ _raise_not_supported(self.add_module.__name__)
322
+
323
+ def apply(self, fn: Callable[[Module], None]) -> Self: # type: ignore[return]
324
+ _raise_not_supported(self.apply.__name__)
325
+
326
+ def cuda(self, device: int | device | None = None) -> Self: # type: ignore[return]
327
+ _raise_not_supported(self.cuda.__name__)
328
+
329
+ def ipu(self, device: int | device | None = None) -> Self: # type: ignore[return]
330
+ _raise_not_supported(self.ipu.__name__)
331
+
332
+ def xpu(self, device: int | device | None = None) -> Self: # type: ignore[return]
333
+ _raise_not_supported(self.xpu.__name__)
334
+
335
+ def cpu(self) -> Self: # type: ignore[return]
336
+ _raise_not_supported(self.cpu.__name__)
337
+
338
+ def type(self, dst_type: dtype | str) -> Self: # type: ignore[return]
339
+ _raise_not_supported(self.type.__name__)
340
+
341
+ def float(self) -> Self: # type: ignore[return]
342
+ _raise_not_supported(self.float.__name__)
343
+
344
+ def double(self) -> Self: # type: ignore[return]
345
+ _raise_not_supported(self.double.__name__)
346
+
347
+ def half(self) -> Self: # type: ignore[return]
348
+ _raise_not_supported(self.half.__name__)
349
+
350
+ def bfloat16(self) -> Self: # type: ignore[return]
351
+ _raise_not_supported(self.bfloat16.__name__)
352
+
353
+ def to(self, *args, **kwargs) -> T: # type: ignore[misc, return, type-var]
354
+ _raise_not_supported(self.to.__name__)
355
+
356
+ def register_backward_hook( # type: ignore[return]
357
+ self,
358
+ hook: Callable[[Module, _grad_t, _grad_t], _grad_t | None],
359
+ # pyrefly: ignore [bad-return]
360
+ ) -> RemovableHandle:
361
+ _raise_not_supported(self.register_backward_hook.__name__)
362
+
363
+ def register_forward_pre_hook( # type: ignore[return]
364
+ self,
365
+ hook: Callable[[T, tuple[Any, ...]], Any | None]
366
+ | Callable[
367
+ [T, tuple[Any, ...], dict[str, Any]], tuple[Any, dict[str, Any]] | None
368
+ ],
369
+ prepend: bool = False,
370
+ with_kwargs: bool = False,
371
+ # pyrefly: ignore [bad-return]
372
+ ) -> RemovableHandle:
373
+ _raise_not_supported(self.register_forward_pre_hook.__name__)
374
+
375
+ def register_forward_hook( # type: ignore[return, override]
376
+ self,
377
+ hook: Callable[[T, tuple[Any, ...], Any], Any | None]
378
+ | Callable[[T, tuple[Any, ...], dict[str, Any], Any], Any | None],
379
+ prepend: bool = False,
380
+ with_kwargs: bool = False,
381
+ # pyrefly: ignore [bad-return]
382
+ ) -> RemovableHandle:
383
+ _raise_not_supported(self.register_forward_hook.__name__)
384
+
385
+ def state_dict(self, *args, **kwargs):
386
+ _raise_not_supported(self.state_dict.__name__)
387
+
388
+ def load_state_dict(
389
+ self,
390
+ state_dict: Mapping[str, Any],
391
+ strict: bool = True,
392
+ assign: bool = False,
393
+ ):
394
+ _raise_not_supported(self.load_state_dict.__name__)
395
+
396
+ def parameters(self, recurse: bool = True) -> Iterator[Parameter]:
397
+ raise ValueError(
398
+ "Method ``parameters`` not supported for RemoteModule. Please use ``remote_parameters`` instead."
399
+ )
400
+
401
+ def named_parameters( # type: ignore[return]
402
+ self,
403
+ prefix: str = "",
404
+ recurse: bool = True,
405
+ remove_duplicate: bool = True,
406
+ # pyrefly: ignore [bad-return]
407
+ ) -> Iterator[tuple[str, Parameter]]:
408
+ _raise_not_supported(self.named_parameters.__name__)
409
+
410
+ def buffers(self, recurse: bool = True) -> Iterator[Tensor]: # type: ignore[return]
411
+ _raise_not_supported(self.buffers.__name__)
412
+
413
+ def named_buffers( # type: ignore[return]
414
+ self,
415
+ prefix: str = "",
416
+ recurse: bool = True,
417
+ remove_duplicate: bool = True,
418
+ # pyrefly: ignore [bad-return]
419
+ ) -> Iterator[tuple[str, Tensor]]:
420
+ _raise_not_supported(self.named_buffers.__name__)
421
+
422
+ def children(self) -> Iterator[Module]: # type: ignore[return]
423
+ _raise_not_supported(self.children.__name__)
424
+
425
+ def named_children(self) -> Iterator[tuple[str, Module]]: # type: ignore[return]
426
+ _raise_not_supported(self.named_children.__name__)
427
+
428
+ def modules(self) -> Iterator[Module]: # type: ignore[return]
429
+ _raise_not_supported(self.modules.__name__)
430
+
431
+ def named_modules(
432
+ self,
433
+ memo: set[Module] | None = None,
434
+ prefix: str = "",
435
+ remove_duplicate: bool = True,
436
+ ):
437
+ _raise_not_supported(self.named_modules.__name__)
438
+
439
+ def train(self, mode: bool = True) -> Self:
440
+ return self.module_rref.rpc_sync().train() # type: ignore[operator, union-attr]
441
+
442
+ def eval(self) -> Self:
443
+ return self.module_rref.rpc_sync().eval() # type: ignore[operator, union-attr]
444
+
445
+ def requires_grad_(self, requires_grad: bool = True) -> Self: # type: ignore[return]
446
+ _raise_not_supported(self.requires_grad_.__name__)
447
+
448
+ def zero_grad(self, set_to_none: bool = True) -> None:
449
+ _raise_not_supported(self.zero_grad.__name__)
450
+
451
+ def share_memory(self) -> Self: # type: ignore[return]
452
+ _raise_not_supported(self.share_memory.__name__)
453
+
454
+ def extra_repr(self) -> str: # type: ignore[return]
455
+ _raise_not_supported(self.extra_repr.__name__)
456
+
457
+ def _prepare_init(self, remote_device_str: str) -> bool:
458
+ """Prepare the initialization and returns whether to enable automatically moving CPU tensors to CUDA devices."""
459
+ # Sanity check.
460
+ if not rpc._is_current_rpc_agent_set():
461
+ raise AssertionError("RemoteModule only works in RPC.")
462
+
463
+ remote_device = _remote_device(remote_device_str)
464
+ self.on = (
465
+ remote_device.worker_name()
466
+ if remote_device.worker_name() is not None
467
+ else remote_device.rank()
468
+ )
469
+ self.device = str(remote_device.device())
470
+ agent = rpc._get_current_rpc_agent()
471
+ # If the device map of the remote worker is set,
472
+ # then enable moving any input CPU tensors to the same cuda device.
473
+ self.is_device_map_set = bool(
474
+ agent._get_device_map(agent.get_worker_info(self.on)) # type: ignore[arg-type]
475
+ )
476
+ # ``enable_moving_cpu_tensors_to_cuda`` is less strict than ``is_device_map_set``:
477
+ # If ``enable_moving_cpu_tensors_to_cuda`` is true, but the device map is not set,
478
+ # then any CPU tensors can still be moved to a cuda device to run forward,
479
+ # but the output must be moved back to CPU before being sent over the wire.
480
+ enable_moving_cpu_tensors_to_cuda = torch.device(self.device).type == "cuda"
481
+ return enable_moving_cpu_tensors_to_cuda
482
+
483
+ def _init_template(self, module_interface_cls, enable_moving_cpu_tensors_to_cuda):
484
+ """Instantiate template on local side."""
485
+ generated_module = instantiator.instantiate_scriptable_remote_module_template(
486
+ module_interface_cls, enable_moving_cpu_tensors_to_cuda
487
+ )
488
+ self.generated_methods = generated_module._generated_methods
489
+
490
+ def _check_attribute_picklability(self):
491
+ """Check if all the attribute has explicitly defined whether to be pickled (i.e., picklability)."""
492
+ for k in self.__dict__:
493
+ if (
494
+ k not in _REMOTE_MODULE_PICKLED_ATTRIBUTES
495
+ and k not in _REMOTE_MODULE_ATTRIBUTES_IGNORE_FOR_PICKLING
496
+ ):
497
+ raise AttributeError(
498
+ f"Attribute {k} must be either in ``_REMOTE_MODULE_PICKLED_ATTRIBUTES`` or "
499
+ "``_REMOTE_MODULE_ATTRIBUTES_IGNORE_FOR_PICKLING``."
500
+ )
501
+
502
+ def _install_generated_methods(self):
503
+ for method in self.generated_methods:
504
+ method_name = method.__name__
505
+ method = torch.jit.export(method)
506
+ setattr(self, method_name, types.MethodType(method, self))
507
+
508
+ @staticmethod
509
+ def init_from_module_rref(
510
+ remote_device: str,
511
+ module_rref: rpc.RRef[nn.Module],
512
+ _module_interface_cls: Any = None,
513
+ ):
514
+ """
515
+ Besides the constructor, a RemoteModule instance can also be initialized given a module RRef.
516
+
517
+ This alternate initialization method can be particularly useful if we want to create multiple
518
+ RemoteModule instances that share the same underlying module and reduce memory consumption.
519
+
520
+ Moreover, this also provides a workaround for passing script RemoteModule over RPC,
521
+ which is not supported. The recommended way is as follows:
522
+
523
+ 1. the sender creates a RemoteModule;
524
+ 2. the sender sends its ``module_rref`` over RPC;
525
+ 3. the receiver calls this method to initialize another RemoteModule using the same ``module_rref``.
526
+
527
+ Example::
528
+ Run the following code in two different processes:
529
+
530
+ >>> # xdoctest: +SKIP("distributed")
531
+ >>> # On worker 0:
532
+ >>> import torch
533
+ >>> import torch.distributed.rpc as rpc
534
+ >>> from torch import nn, Tensor
535
+ >>> from torch.distributed.nn.api.remote_module import RemoteModule
536
+ >>>
537
+ >>> rpc.init_rpc("worker0", rank=0, world_size=2)
538
+ >>> remote_module = RemoteModule(
539
+ >>> "worker1/cpu", nn.Linear, args=(20, 30),
540
+ >>> )
541
+ >>>
542
+ >>> remote_module1 = rpc.rpc_sync(
543
+ >>> "worker1/cpu",
544
+ >>> RemoteModule.init_from_module_rref,
545
+ >>> ("worker1/cpu", remote_module1.get_module_rref()),
546
+ >>> )
547
+ >>> rpc.shutdown()
548
+
549
+ >>> # On worker 1:
550
+ >>> import torch
551
+ >>> import torch.distributed.rpc as rpc
552
+ >>>
553
+ >>> rpc.init_rpc("worker1", rank=1, world_size=2)
554
+ >>> rpc.shutdown()
555
+
556
+ Args:
557
+ remote_device (str): Device on the destination worker where we'd like to place this module.
558
+ The device can be a local device or a remote device specified by one of the following remote
559
+ formats:
560
+
561
+ 1. "rank:<rank>/<device>" (ex: "rank:0/cuda:0").
562
+ 2. "<worker_name>/<device>" (ex: "trainer0/cuda:0").
563
+
564
+ In addition, the device field can be optional and the default value is "cpu".
565
+ module_rref (RRef[nn.Module]): The module reference shared by both the caller and
566
+ the created remote module.
567
+ _module_interface_cls (type, optional): The TorchScript interface type for the module
568
+ to be created. The type object should be decorated by @torch.jit.interface.
569
+ If not provided, the generated RemoteModule is not torchscript-able.
570
+ Warning, this is an experimental API and susceptible to frequent changes.
571
+
572
+ Returns:
573
+ A remote module instance which wraps the :class:`~nn.Module` created by the
574
+ user-provided ``module_rref``, it has a blocking ``forward`` method and an
575
+ asynchronous ``forward_async`` method that returns a future of the ``forward`` call
576
+ on the user-provided module on the remote side.
577
+ """
578
+ # NOTE: if a new attribute is added to this class, also need to add it
579
+ # to ``_REMOTE_MODULE_PICKLED_ATTRIBUTES`` for pickling/unpickling.
580
+
581
+ remote_module = object.__new__(RemoteModule)
582
+
583
+ enable_moving_cpu_tensors_to_cuda = remote_module._prepare_init(remote_device)
584
+
585
+ if _module_interface_cls is not None:
586
+ # Users reply on this field to know if this generated RemoteModule is TorchScript-able.
587
+ remote_module.is_scriptable = True
588
+
589
+ remote_module._init_template(
590
+ _module_interface_cls, enable_moving_cpu_tensors_to_cuda
591
+ )
592
+ else:
593
+ remote_module.is_scriptable = False
594
+ remote_module.generated_methods = (
595
+ _NON_SCRIPTABLE_REMOTE_MODULE_MODULE._generated_methods
596
+ )
597
+ remote_module.module_rref = module_rref
598
+
599
+ remote_module._install_generated_methods()
600
+ remote_module._check_attribute_picklability()
601
+
602
+ return remote_module
603
+
604
+
605
+ class RemoteModule(_RemoteModule):
606
+ """
607
+ A RemoteModule instance can only be created after RPC initialization.
608
+
609
+ It creates a user-specified module on a specified remote node.
610
+ It behaves like a regular ``nn.Module`` except that the ``forward`` method is
611
+ executed on the remote node.
612
+ It takes care of autograd recording to ensure the backward pass propagates
613
+ gradients back to the corresponding remote module.
614
+
615
+ It generates two methods ``forward_async`` and ``forward`` based on the
616
+ signature of the ``forward`` method of ``module_cls``. ``forward_async``
617
+ runs asynchronously and returns a Future. The arguments of ``forward_async``
618
+ and ``forward`` are the same as the ``forward`` method of the module
619
+ returned by the ``module_cls``.
620
+
621
+ For example, if ``module_cls`` returns an instance of ``nn.Linear``,
622
+ that has ``forward`` method signature: ``def forward(input: Tensor) -> Tensor:``,
623
+ the generated ``RemoteModule`` will have 2 methods with the signatures:
624
+
625
+ | ``def forward(input: Tensor) -> Tensor:``
626
+ | ``def forward_async(input: Tensor) -> Future[Tensor]:``
627
+
628
+ Args:
629
+ remote_device (str): Device on the destination worker where we'd like to place this module.
630
+ The format should be "<workername>/<device>", where the device field can be parsed as torch.device type.
631
+ E.g., "trainer0/cpu", "trainer0", "ps0/cuda:0".
632
+ In addition, the device field can be optional and the default value is "cpu".
633
+ module_cls (nn.Module): Class for the module to be created remotely. For example,
634
+
635
+ >>> class MyModule(nn.Module):
636
+ >>> def forward(input):
637
+ >>> return input + 1
638
+ >>>
639
+ >>> module_cls = MyModule
640
+
641
+ args (Sequence, optional): args to be passed to ``module_cls``.
642
+ kwargs (Dict, optional): kwargs to be passed to ``module_cls``.
643
+
644
+ Returns:
645
+ A remote module instance which wraps the :class:`~nn.Module` created by the
646
+ user-provided ``module_cls``, it has a blocking ``forward`` method and an
647
+ asynchronous ``forward_async`` method that returns a future of the ``forward`` call
648
+ on the user-provided module on the remote side.
649
+
650
+ Example::
651
+ Run the following code in two different processes:
652
+
653
+ >>> # xdoctest: +SKIP("distributed")
654
+ >>> # On worker 0:
655
+ >>> import torch
656
+ >>> import torch.distributed.rpc as rpc
657
+ >>> from torch import nn, Tensor
658
+ >>> from torch.distributed.nn.api.remote_module import RemoteModule
659
+ >>>
660
+ >>> rpc.init_rpc("worker0", rank=0, world_size=2)
661
+ >>> remote_linear_module = RemoteModule(
662
+ >>> "worker1/cpu", nn.Linear, args=(20, 30),
663
+ >>> )
664
+ >>> input = torch.randn(128, 20)
665
+ >>> ret_fut = remote_linear_module.forward_async(input)
666
+ >>> ret = ret_fut.wait()
667
+ >>> rpc.shutdown()
668
+
669
+ >>> # On worker 1:
670
+ >>> import torch
671
+ >>> import torch.distributed.rpc as rpc
672
+ >>>
673
+ >>> rpc.init_rpc("worker1", rank=1, world_size=2)
674
+ >>> rpc.shutdown()
675
+
676
+ Furthermore, a more practical example that is combined with
677
+ `DistributedDataParallel <https://pytorch.org/docs/stable/nn.html#torch.nn.parallel.DistributedDataParallel>`__ (DDP)
678
+ can be found in this `tutorial <https://pytorch.org/tutorials/advanced/rpc_ddp_tutorial.html>`__.
679
+ """
680
+
681
+ def __init__(
682
+ self,
683
+ remote_device: str,
684
+ module_cls: type[nn.Module],
685
+ args: tuple | None = None,
686
+ kwargs: dict[str, Any] | None = None,
687
+ ):
688
+ super().__init__(remote_device, module_cls, args, kwargs)
689
+
690
+
691
+ def _remote_module_receiver(
692
+ *remote_module_pickled_attrs,
693
+ ):
694
+ """Deserializes a RemoteModule."""
695
+ serialized_remote_module = _SerializedRemoteModule._make(
696
+ remote_module_pickled_attrs
697
+ )
698
+ m = object.__new__(RemoteModule)
699
+ m.__dict__.update(serialized_remote_module._asdict())
700
+
701
+ # Unpickling the attribute `module_rref` must invoke RRef's `_deserialize()` method.
702
+ m.module_rref = rpc.PyRRef._deserialize(m.module_rref)
703
+
704
+ # Install generated methods when unpickled.
705
+ for method in m.generated_methods:
706
+ method_name = method.__name__
707
+ method = torch.jit.export(method)
708
+ setattr(m, method_name, types.MethodType(method, m))
709
+
710
+ return m
711
+
712
+
713
+ def _remote_module_reducer(remote_module):
714
+ """Serialize a RemoteModule."""
715
+ pickled_attrs = {}
716
+ for k, v in remote_module.__dict__.items():
717
+ # Pickling the attribute `module_rref` must invoke RRef's `_serialize()` method.
718
+ if k == "module_rref":
719
+ pickled_attrs[k] = v._serialize()
720
+ elif k in _REMOTE_MODULE_PICKLED_ATTRIBUTES:
721
+ pickled_attrs[k] = v
722
+ # Check if unpickled attributes are all in _REMOTE_MODULE_ATTRIBUTES_IGNORE_FOR_PICKLING.
723
+ elif k not in _REMOTE_MODULE_ATTRIBUTES_IGNORE_FOR_PICKLING:
724
+ print(
725
+ f"The new attribute ``{k}`` of RemoteModule is ignored during RPC pickling. "
726
+ "To pickle this attribute, please add it to ``_REMOTE_MODULE_PICKLED_ATTRIBUTES``. "
727
+ "Otherwise, please explicitly add it to ``_REMOTE_MODULE_ATTRIBUTES_IGNORE_FOR_PICKLING``.",
728
+ file=sys.stderr,
729
+ )
730
+
731
+ return (
732
+ _remote_module_receiver,
733
+ tuple(pickled_attrs.values()),
734
+ )
735
+
736
+
737
+ def _recursive_script_module_receiver(
738
+ recursive_script_module_serialized,
739
+ ):
740
+ """Deserializes a RecursiveScriptModule that does not contain a script RemoteModule."""
741
+ f = io.BytesIO(recursive_script_module_serialized)
742
+ m = torch.jit.load(f)
743
+ return m
744
+
745
+
746
+ def _recursive_script_module_reducer(recursive_script_module):
747
+ """Serialize a RecursiveScriptModule that does not contain a script RemoteModule, and raises an error otherwise."""
748
+ if hasattr(recursive_script_module._c, "module_rref"):
749
+ raise RuntimeError(
750
+ "Passing a script RemoteModule over RPC is not supported. Please create a RemoteModule in the sender, "
751
+ "send the `module_rref` to the receiver, and create a new instance on the receiver end by passing this `module_rref`."
752
+ )
753
+
754
+ f = io.BytesIO()
755
+ torch.jit.save(recursive_script_module, f)
756
+ return (_recursive_script_module_receiver, (f.getvalue(),))
757
+
758
+
759
+ _internal_rpc_pickler._register_reducer(RemoteModule, _remote_module_reducer)
760
+ _internal_rpc_pickler._register_reducer(
761
+ torch.jit.RecursiveScriptModule, _recursive_script_module_reducer
762
+ )
venv/lib/python3.14/site-packages/torch/distributed/nn/functional.py ADDED
@@ -0,0 +1,538 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import warnings
3
+
4
+ import torch
5
+ import torch.distributed as dist
6
+ from torch.autograd import Function
7
+
8
+ # The two imports below are not always available depending on the
9
+ # USE_DISTRIBUTED compile flag. Make sure they raise import error
10
+ # if we're trying to use them.
11
+ from torch.distributed import group, ReduceOp
12
+
13
+
14
+ def _not_supported_under_compile(name, *, suggestion=None):
15
+ msg = (
16
+ f"torch.distributed.nn.functional.{name} is not supported under torch.compile."
17
+ )
18
+ if suggestion:
19
+ msg += f" Use {suggestion} instead."
20
+ raise RuntimeError(msg)
21
+
22
+
23
+ def _deprecated(name, suggestion):
24
+ warnings.warn(
25
+ f"torch.distributed.nn.functional.{name} is deprecated, "
26
+ f"use {suggestion} instead.",
27
+ category=FutureWarning,
28
+ stacklevel=3,
29
+ )
30
+
31
+
32
+ def broadcast(tensor, src, group=group.WORLD):
33
+ """
34
+ Broadcasts the tensor to the whole group.
35
+
36
+ ``tensor`` must have the same number of elements in all processes
37
+ participating in the collective.
38
+
39
+ Arguments:
40
+ tensor (Tensor): Data to be sent if ``src`` is the rank of current
41
+ process.
42
+ src (int): Source rank.
43
+ group (ProcessGroup, optional): The process group to work on.
44
+
45
+ Returns:
46
+ Tensor: Received tensor from the broadcast op.
47
+
48
+ """
49
+ if torch.compiler.is_compiling():
50
+ _not_supported_under_compile(
51
+ "broadcast",
52
+ suggestion="torch.distributed._functional_collectives.broadcast",
53
+ )
54
+ _deprecated("broadcast", "torch.distributed._functional_collectives.broadcast")
55
+ return _Broadcast.apply(src, group, tensor)
56
+
57
+
58
+ def gather(tensor, dst=0, group=group.WORLD):
59
+ """
60
+ Gathers a list of tensors in a single process.
61
+
62
+ Arguments:
63
+ tensor (Tensor): Input tensor.
64
+ dst (int, optional): Destination rank (default is 0).
65
+ group (ProcessGroup, optional): The process group to work on.
66
+
67
+ Returns:
68
+ tuple[Tensor]: List of appropriately-sized tensors with the gathered data.
69
+ """
70
+ if torch.compiler.is_compiling():
71
+ _not_supported_under_compile("gather")
72
+ return _Gather.apply(dst, group, tensor)
73
+
74
+
75
+ def scatter(tensors, src=0, group=group.WORLD):
76
+ """
77
+ Scatters a list of tensors to all processes in a group.
78
+
79
+ Each process will receive exactly one tensor and store its data in the
80
+ ``tensor`` argument.
81
+
82
+ Arguments:
83
+ tensors (list[Tensor]): List of tensors to scatter on the source rank.
84
+ Receivers must pass ``None`.
85
+ src (int, optional): Source rank (default is 0).
86
+ group (ProcessGroup, optional): The process group to work on.
87
+
88
+ Returns:
89
+ Tensor: Output tensor from the scatter operation.
90
+
91
+ """
92
+ if torch.compiler.is_compiling():
93
+ _not_supported_under_compile("scatter")
94
+ return _Scatter.apply(src, group, *tensors)
95
+
96
+
97
+ def reduce(tensor, dst, op=ReduceOp.SUM, group=group.WORLD):
98
+ """
99
+ Reduces the tensor data across all machines.
100
+
101
+ Only the process with rank ``dst`` is going to receive the final result.
102
+
103
+ Arguments:
104
+ tensor (Tensor): Input of the collective.
105
+ dst (int): Destination rank.
106
+ op (optional): One of the values from
107
+ ``torch.distributed.ReduceOp``
108
+ enum. Specifies an operation used for element-wise reductions.
109
+ group (ProcessGroup, optional): The process group to work on.
110
+
111
+ Returns:
112
+ Tensor: Output of the collective.
113
+
114
+ """
115
+ if torch.compiler.is_compiling():
116
+ _not_supported_under_compile("reduce")
117
+ return _Reduce.apply(dst, op, group, tensor)
118
+
119
+
120
+ def reduce_scatter(output, input_list, op=ReduceOp.SUM, group=group.WORLD):
121
+ """
122
+ Reduces, then scatters a list of tensors to all processes in a group.
123
+
124
+ Arguments:
125
+ output (Tensor): Output tensor.
126
+ input_list (list[Tensor]): List of tensors to reduce and scatter.
127
+ op (optional): One of the values from
128
+ ``torch.distributed.ReduceOp``
129
+ enum. Specifies an operation used for element-wise reductions.
130
+ group (ProcessGroup, optional): The process group to work on.
131
+
132
+ Returns:
133
+ Tensor: Output of the collective.
134
+
135
+ """
136
+ if torch.compiler.is_compiling():
137
+ _not_supported_under_compile(
138
+ "reduce_scatter",
139
+ suggestion="torch.distributed._functional_collectives.reduce_scatter_tensor",
140
+ )
141
+ _deprecated(
142
+ "reduce_scatter",
143
+ "torch.distributed._functional_collectives.reduce_scatter_tensor",
144
+ )
145
+ return _Reduce_Scatter.apply(op, group, output, *input_list)
146
+
147
+
148
+ def all_gather(tensor, group=group.WORLD):
149
+ """
150
+ Gathers tensors from the whole group in a list.
151
+
152
+ Arguments:
153
+ tensor (Tensor): Tensor to be broadcast from current process.
154
+ group (ProcessGroup, optional): The process group to work on.
155
+
156
+ Returns:
157
+ tuple([Tensor]): Output of the collective.
158
+
159
+ """
160
+ if torch.compiler.is_compiling():
161
+ _not_supported_under_compile(
162
+ "all_gather",
163
+ suggestion="torch.distributed._functional_collectives.all_gather_tensor",
164
+ )
165
+ _deprecated(
166
+ "all_gather", "torch.distributed._functional_collectives.all_gather_tensor"
167
+ )
168
+ return _AllGather.apply(group, tensor)
169
+
170
+
171
+ def _all_gather_base(output_tensor, input_tensor, group=group.WORLD):
172
+ """
173
+ Single tensor all gather. Gathers a single tensor from all ranks, and puts them in a single output tensor.
174
+
175
+ Args:
176
+ output_tensor (Tensor): Output tensor. It should contain
177
+ correctly-sized tensors to be used for output of the collective.
178
+ input_tensor (Tensor): Tensor to be broadcast from current process.
179
+ group (ProcessGroup, optional): The process group to work on. If None,
180
+ the default process group will be used.
181
+
182
+ Examples:
183
+ >>> # All tensors below are of torch.int64 dtype.
184
+ >>> # We have 2 process groups, 2 ranks.
185
+ >>> # xdoctest: +SKIP("incorrect want text")
186
+ >>> output_tensor = torch.zeros(2, dtype=torch.int64)
187
+ >>> output_tensor
188
+ [tensor([0, 0])] # Rank 0 and 1
189
+ >>> tensor = torch.arange(1, dtype=torch.int64) + 1 + rank
190
+ >>> tensor
191
+ tensor([1]) # Rank 0
192
+ tensor([2]) # Rank 1
193
+ >>> dist.all_gather_base(output_tensor, tensor)
194
+ >>> output_tensor
195
+ tensor([1,2]) # Rank 0
196
+ tensor([1,2]) # Rank 1
197
+
198
+ .. warning::
199
+ `_all_gather_base` is experimental and subject to change.
200
+ It is the caller's responsibility to ensure the output_tensor
201
+ is correctly sized.
202
+
203
+ """
204
+ if torch.compiler.is_compiling():
205
+ _not_supported_under_compile("_all_gather_base")
206
+ return _AllGatherBase.apply(output_tensor, input_tensor, group)
207
+
208
+
209
+ def all_to_all(output_tensor_list, input_tensor_list, group=group.WORLD):
210
+ """
211
+ Each process scatters list of input tensors to all processes in a group and return gathered list of tensors in output list.
212
+
213
+ Arguments:
214
+ output_tensor_list (list[Tensor]): list of tensors to gather one per rank.
215
+ input_tensor_list (list[Tensor]): List of tensors to scatter one per rank.
216
+ group (ProcessGroup, optional): The process group to work on.
217
+
218
+ Returns:
219
+ tuple([Tensor]): Output of the collective.
220
+
221
+ """
222
+ if torch.compiler.is_compiling():
223
+ _not_supported_under_compile("all_to_all")
224
+ return _AlltoAll.apply(group, output_tensor_list, *input_tensor_list)
225
+
226
+
227
+ def all_to_all_single(
228
+ output,
229
+ input,
230
+ output_split_sizes=None,
231
+ input_split_sizes=None,
232
+ group=group.WORLD,
233
+ ):
234
+ """
235
+ Each process splits input tensor and then scatters the split list to all processes in a group.
236
+
237
+ Then concatenate the received tensors from all the processes in the group and return single output tensor.
238
+
239
+ Arguments:
240
+ output (Tensor): Gathered concatenated output tensor.
241
+ input (Tensor): Input tensor to scatter.
242
+ output_split_sizes: (list[Int], optional): Output split sizes for dim 0
243
+ if specified None or empty, dim 0 of ``output`` tensor must divide
244
+ equally by ``world_size``.
245
+ input_split_sizes: (list[Int], optional): Input split sizes for dim 0
246
+ if specified None or empty, dim 0 of ``input`` tensor must divide
247
+ equally by ``world_size``.
248
+
249
+ Returns:
250
+ Tensor: Output of the collective.
251
+
252
+ """
253
+ if torch.compiler.is_compiling():
254
+ _not_supported_under_compile(
255
+ "all_to_all_single",
256
+ suggestion="torch.distributed._functional_collectives.all_to_all_single",
257
+ )
258
+ _deprecated(
259
+ "all_to_all_single",
260
+ "torch.distributed._functional_collectives.all_to_all_single",
261
+ )
262
+ return _AlltoAllSingle.apply(
263
+ group, output, output_split_sizes, input_split_sizes, input
264
+ )
265
+
266
+
267
+ def all_reduce(tensor, op=ReduceOp.SUM, group=group.WORLD):
268
+ """
269
+ Reduces the tensor data across all machines in such a way that all get the final result.
270
+
271
+ After the call the returned tensor is going to be bitwise
272
+ identical in all processes.
273
+
274
+ Arguments:
275
+ tensor (Tensor): Input of the collective.
276
+ op (optional): One of the values from
277
+ ``torch.distributed.ReduceOp``
278
+ enum. Specifies an operation used for element-wise reductions.
279
+ group (ProcessGroup, optional): The process group to work on.
280
+
281
+ Returns:
282
+ Tensor: Output of the collective
283
+
284
+ """
285
+ if torch.compiler.is_compiling():
286
+ _not_supported_under_compile(
287
+ "all_reduce",
288
+ suggestion="torch.distributed._functional_collectives.all_reduce",
289
+ )
290
+ _deprecated("all_reduce", "torch.distributed._functional_collectives.all_reduce")
291
+ return _AllReduce.apply(op, group, tensor)
292
+
293
+
294
+ class _Broadcast(Function):
295
+ @staticmethod
296
+ # pyrefly: ignore [bad-override]
297
+ def forward(ctx, src, group, tensor):
298
+ ctx.src = src
299
+ ctx.group = group
300
+ ctx.rank = dist.get_rank(group=group)
301
+ # torch.distributed makes all the calls in place
302
+ # we allocate new tensors to avoid this
303
+ tensor = tensor.clone()
304
+ dist.broadcast(tensor, src, group=group)
305
+ return tensor
306
+
307
+ @staticmethod
308
+ # pyrefly: ignore [bad-override]
309
+ def backward(ctx, grad_output):
310
+ gx = _Reduce.apply(ctx.src, ReduceOp.SUM, ctx.group, grad_output)
311
+ if ctx.src != ctx.rank:
312
+ gx.zero_()
313
+ return (None, None, gx)
314
+
315
+
316
+ class _Gather(Function):
317
+ @staticmethod
318
+ # pyrefly: ignore [bad-override]
319
+ def forward(ctx, dst, group, tensor):
320
+ ctx.dst = dst
321
+ ctx.group = group
322
+ # Need to create a list of tensors here to do the
323
+ # aggregation, get it from the group size
324
+ # tensor should be correctly sized for the method
325
+ # gathering
326
+ tensor_list = [
327
+ torch.zeros_like(tensor) for i in range(dist.get_world_size(group=group))
328
+ ]
329
+
330
+ tensor = tensor.contiguous()
331
+ if dist.get_rank(group=group) == dst:
332
+ dist.gather(tensor, tensor_list, dst, group=group)
333
+ else:
334
+ dist.gather(tensor, None, dst, group=group)
335
+ return tuple(tensor_list)
336
+
337
+ @staticmethod
338
+ def backward(ctx, *grad_outputs):
339
+ return (None, None) + (_Scatter.apply(ctx.dst, ctx.group, *grad_outputs),)
340
+
341
+
342
+ class _Scatter(Function):
343
+ @staticmethod
344
+ # pyrefly: ignore [bad-override]
345
+ def forward(ctx, src, group, *tensors):
346
+ ctx.src = src
347
+ ctx.group = group
348
+ if not all(t.size() == tensors[0].size() for t in tensors):
349
+ raise AssertionError
350
+ output = torch.zeros_like(tensors[0])
351
+ if dist.get_rank(group=group) == src:
352
+ dist.scatter(output, list(tensors), src, group=group)
353
+ else:
354
+ dist.scatter(output, None, src, group=group)
355
+ return output
356
+
357
+ @staticmethod
358
+ # pyrefly: ignore [bad-override]
359
+ def backward(ctx, grad_output):
360
+ return (None, None) + _Gather.apply(ctx.src, ctx.group, grad_output)
361
+
362
+
363
+ class _Reduce(Function):
364
+ @staticmethod
365
+ # pyrefly: ignore [bad-override]
366
+ def forward(ctx, src, op, group, tensor):
367
+ ctx.src = src
368
+ ctx.group = group
369
+ tensor = tensor.clone()
370
+ dist.reduce(tensor, src, op=op, group=group)
371
+ return tensor
372
+
373
+ @staticmethod
374
+ # pyrefly: ignore [bad-override]
375
+ def backward(ctx, grad_output):
376
+ return (None, None, None) + (_Broadcast.apply(ctx.src, ctx.group, grad_output),)
377
+
378
+
379
+ class _Reduce_Scatter(Function):
380
+ @staticmethod
381
+ # pyrefly: ignore [bad-override]
382
+ def forward(ctx, op, group, tensor, *input_tensor_list):
383
+ ctx.group = group
384
+ # Need contiguous tensors for collectives.
385
+ tensor = tensor.contiguous()
386
+ input_tensor_list = tuple(t.contiguous() for t in input_tensor_list)
387
+ dist.reduce_scatter(tensor, list(input_tensor_list), op=op, group=group)
388
+ return tensor
389
+
390
+ @staticmethod
391
+ # pyrefly: ignore [bad-override]
392
+ def backward(ctx, grad_output):
393
+ return (None, None, None) + _AllGather.apply(ctx.group, grad_output)
394
+
395
+
396
+ class _AllGather(Function):
397
+ @staticmethod
398
+ # pyrefly: ignore [bad-override]
399
+ def forward(ctx, group, tensor):
400
+ # Need contiguous tensors for collectives.
401
+ tensor = tensor.contiguous()
402
+
403
+ ctx.group = group
404
+ out_tensor_list = [
405
+ torch.empty_like(tensor) for _ in range(dist.get_world_size(group=group))
406
+ ]
407
+
408
+ dist.all_gather(out_tensor_list, tensor, group=group)
409
+ return tuple(out_tensor_list)
410
+
411
+ @staticmethod
412
+ def backward(ctx, *grad_outputs):
413
+ if dist.get_backend(group=ctx.group) in (dist.Backend.NCCL, dist.Backend.XCCL):
414
+ rank = dist.get_rank(group=ctx.group)
415
+ gx = torch.empty_like(grad_outputs[rank])
416
+ gx = _Reduce_Scatter.apply(ReduceOp.SUM, ctx.group, gx, *grad_outputs)
417
+ else:
418
+ # As many backends doesn't support ReduceScatter, we use AlltoAll with .sum()
419
+ # to emulate the ReduceScatter behavior
420
+ tensor_list = [torch.empty_like(tensor) for tensor in grad_outputs]
421
+ gxs = _AlltoAll.apply(ctx.group, tensor_list, *grad_outputs)
422
+ gx = torch.sum(torch.stack(gxs), dim=0)
423
+ return (None, gx)
424
+
425
+
426
+ class _AllGatherBase(Function):
427
+ @staticmethod
428
+ # pyrefly: ignore [bad-override]
429
+ def forward(ctx, output_tensor, input_tensor, group):
430
+ ctx.group = group
431
+ dist._all_gather_base(output_tensor, input_tensor.contiguous(), group=group)
432
+ return output_tensor
433
+
434
+ @staticmethod
435
+ # pyrefly: ignore [bad-override]
436
+ def backward(ctx, grad_output):
437
+ if dist.get_backend(group=ctx.group) in (dist.Backend.NCCL, dist.Backend.XCCL):
438
+ world_size = dist.get_world_size(group=ctx.group)
439
+ out_size = list(grad_output.size())
440
+ if out_size[0] % world_size != 0:
441
+ raise RuntimeError(
442
+ f"Tensor with dimensions: {out_size} does "
443
+ f"not have first dimension divisible by world_size: {world_size}"
444
+ )
445
+ out_size[0] = out_size[0] // dist.get_world_size(group=ctx.group)
446
+ gx = torch.empty(
447
+ out_size, device=grad_output.device, dtype=grad_output.dtype
448
+ )
449
+ dist._reduce_scatter_base(gx, grad_output, ReduceOp.SUM, ctx.group)
450
+ else:
451
+ raise RuntimeError("Backend not supported!")
452
+ return (None, gx, None)
453
+
454
+
455
+ class _AlltoAll(Function):
456
+ @staticmethod
457
+ # pyrefly: ignore [bad-override]
458
+ def forward(ctx, group, out_tensor_list, *tensors):
459
+ ctx.group = group
460
+ ctx.input_tensor_size_list = [
461
+ tensors[i].size() for i in range(dist.get_world_size(group=group))
462
+ ]
463
+ my_rank = dist.get_rank(group=group)
464
+ tensors = tuple(t.contiguous() for t in tensors)
465
+ # Implement it on means of scatter/gather, send/recv async operations have issues
466
+ if dist.get_backend(group=group) is dist.Backend.GLOO:
467
+ for i in range(dist.get_world_size(group=group)):
468
+ to_send = None
469
+ if i == my_rank:
470
+ to_send = list(tensors)
471
+ dist.scatter(out_tensor_list[i], to_send, i, group=group)
472
+ else:
473
+ dist.all_to_all(
474
+ out_tensor_list,
475
+ list(tensors),
476
+ group=group,
477
+ )
478
+ return tuple(out_tensor_list)
479
+
480
+ @staticmethod
481
+ def backward(ctx, *grad_outputs):
482
+ tensor_list = [
483
+ torch.empty(
484
+ size, device=grad_outputs[0].device, dtype=grad_outputs[0].dtype
485
+ )
486
+ for size in ctx.input_tensor_size_list
487
+ ]
488
+ return (None, None) + _AlltoAll.apply(ctx.group, tensor_list, *grad_outputs)
489
+
490
+
491
+ class _AlltoAllSingle(Function):
492
+ @staticmethod
493
+ # pyrefly: ignore [bad-override]
494
+ def forward(ctx, group, output, output_split_sizes, input_split_sizes, input):
495
+ ctx.group = group
496
+ ctx.input_size = input.size()
497
+ ctx.output_split_sizes = input_split_sizes
498
+ ctx.input_split_sizes = output_split_sizes
499
+ dist.all_to_all_single(
500
+ output,
501
+ input,
502
+ output_split_sizes=output_split_sizes,
503
+ input_split_sizes=input_split_sizes,
504
+ group=group,
505
+ )
506
+ return output
507
+
508
+ @staticmethod
509
+ # pyrefly: ignore [bad-override]
510
+ def backward(ctx, grad_output):
511
+ tensor = torch.empty(
512
+ ctx.input_size, device=grad_output.device, dtype=grad_output.dtype
513
+ )
514
+ return (None, None, None, None) + (
515
+ _AlltoAllSingle.apply(
516
+ ctx.group,
517
+ tensor,
518
+ ctx.output_split_sizes,
519
+ ctx.input_split_sizes,
520
+ grad_output.contiguous(),
521
+ ),
522
+ )
523
+
524
+
525
+ class _AllReduce(Function):
526
+ @staticmethod
527
+ # pyrefly: ignore [bad-override]
528
+ def forward(ctx, op, group, tensor):
529
+ ctx.group = group
530
+ ctx.op = op
531
+ tensor = tensor.clone(memory_format=torch.contiguous_format)
532
+ dist.all_reduce(tensor, op=op, group=group)
533
+ return tensor
534
+
535
+ @staticmethod
536
+ # pyrefly: ignore [bad-override]
537
+ def backward(ctx, grad_output):
538
+ return (None, None) + (_AllReduce.apply(ctx.op, ctx.group, grad_output),)
venv/lib/python3.14/site-packages/torch/distributed/nn/jit/__init__.py ADDED
File without changes
venv/lib/python3.14/site-packages/torch/distributed/nn/jit/instantiator.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ # mypy: allow-untyped-defs
3
+ import importlib.abc
4
+ import importlib.util
5
+ import sys
6
+
7
+ import torch
8
+ from torch.distributed.nn.jit.templates.remote_module_template import (
9
+ get_remote_module_template,
10
+ )
11
+
12
+
13
+ _FILE_PREFIX = "_remote_module_"
14
+
15
+
16
+ def get_arg_return_types_from_interface(module_interface):
17
+ if not getattr(module_interface, "__torch_script_interface__", False):
18
+ raise AssertionError(
19
+ "Expect a TorchScript class interface decorated by @torch.jit.interface."
20
+ )
21
+ qualified_name = torch._jit_internal._qualified_name(module_interface)
22
+ cu = torch.jit._state._python_cu
23
+ module_interface_c = cu.get_interface(qualified_name)
24
+ if "forward" not in module_interface_c.getMethodNames():
25
+ raise AssertionError(
26
+ f"Expect forward in interface methods, while it has {module_interface_c.getMethodNames()}"
27
+ )
28
+ method_schema = module_interface_c.getMethod("forward")
29
+
30
+ arg_str_list = []
31
+ arg_type_str_list = []
32
+ if method_schema is None:
33
+ raise AssertionError
34
+ for argument in method_schema.arguments:
35
+ arg_str_list.append(argument.name)
36
+
37
+ if argument.has_default_value():
38
+ default_value_str = f" = {argument.default_value}"
39
+ else:
40
+ default_value_str = ""
41
+ arg_type_str = f"{argument.name}: {argument.type}{default_value_str}"
42
+ arg_type_str_list.append(arg_type_str)
43
+
44
+ arg_str_list = arg_str_list[1:] # Remove "self".
45
+ args_str = ", ".join(arg_str_list)
46
+
47
+ arg_type_str_list = arg_type_str_list[1:] # Remove "self".
48
+ arg_types_str = ", ".join(arg_type_str_list)
49
+
50
+ if len(method_schema.returns) != 1:
51
+ raise AssertionError
52
+ argument = method_schema.returns[0]
53
+ return_type_str = str(argument.type)
54
+
55
+ return args_str, arg_types_str, return_type_str
56
+
57
+
58
+ class _StringLoader(importlib.abc.SourceLoader):
59
+ """
60
+ A custom loader for dynamically generated Python source code.
61
+
62
+ Inherits from SourceLoader for API compatibility but overrides exec_module()
63
+ to avoid bytecode caching issues. The default SourceLoader.exec_module() calls
64
+ cache_from_source() which fails with IndexError when the filename doesn't
65
+ correspond to a real filesystem path with a .py extension.
66
+ """
67
+
68
+ def __init__(self, data: str) -> None:
69
+ self.data = data
70
+
71
+ def get_source(self, fullname: str) -> str:
72
+ return self.data
73
+
74
+ def get_data(self, path: str) -> bytes:
75
+ return self.data.encode("utf-8")
76
+
77
+ def get_filename(self, fullname: str) -> str:
78
+ return f"<{fullname}>.py"
79
+
80
+ def path_stats(self, path: str) -> dict:
81
+ # Raise OSError since source is dynamically generated (no filesystem stats)
82
+ raise OSError("dynamically generated module has no filesystem stats")
83
+
84
+ def exec_module(self, module) -> None:
85
+ """
86
+ Execute the module by compiling and running the source directly.
87
+
88
+ This overrides SourceLoader.exec_module() to bypass the problematic
89
+ get_code() -> cache_from_source() code path that fails on dynamic modules.
90
+ """
91
+ source = self.get_source(module.__name__)
92
+ filename = self.get_filename(module.__name__)
93
+ code = compile(source, filename, "exec", dont_inherit=True)
94
+ exec(code, module.__dict__)
95
+
96
+
97
+ def _do_instantiate_remote_module_template(
98
+ generated_module_name, str_dict, enable_moving_cpu_tensors_to_cuda
99
+ ):
100
+ if generated_module_name in sys.modules:
101
+ return sys.modules[generated_module_name]
102
+
103
+ loader = _StringLoader(
104
+ get_remote_module_template(enable_moving_cpu_tensors_to_cuda).format(**str_dict)
105
+ )
106
+ spec = importlib.util.spec_from_loader(
107
+ generated_module_name, loader, origin="torch-git"
108
+ )
109
+ if spec is None:
110
+ raise AssertionError
111
+ module = importlib.util.module_from_spec(spec)
112
+ sys.modules[generated_module_name] = module
113
+ loader.exec_module(module)
114
+ return module
115
+
116
+
117
+ def instantiate_scriptable_remote_module_template(
118
+ module_interface_cls, enable_moving_cpu_tensors_to_cuda=True
119
+ ):
120
+ if not getattr(module_interface_cls, "__torch_script_interface__", False):
121
+ raise ValueError(
122
+ f"module_interface_cls {module_interface_cls} must be a type object decorated by "
123
+ "@torch.jit.interface"
124
+ )
125
+
126
+ # Generate the template instance name.
127
+ module_interface_cls_name = torch._jit_internal._qualified_name(
128
+ module_interface_cls
129
+ ).replace(".", "_")
130
+ generated_module_name = f"{_FILE_PREFIX}{module_interface_cls_name}"
131
+
132
+ # Generate type annotation strs.
133
+ assign_module_interface_cls_str = (
134
+ f"from {module_interface_cls.__module__} import "
135
+ f"{module_interface_cls.__name__} as module_interface_cls"
136
+ )
137
+ args_str, arg_types_str, return_type_str = get_arg_return_types_from_interface(
138
+ module_interface_cls
139
+ )
140
+ kwargs_str = ""
141
+ arrow_and_return_type_str = f" -> {return_type_str}"
142
+ arrow_and_future_return_type_str = f" -> Future[{return_type_str}]"
143
+
144
+ str_dict = dict(
145
+ assign_module_interface_cls=assign_module_interface_cls_str,
146
+ arg_types=arg_types_str,
147
+ arrow_and_return_type=arrow_and_return_type_str,
148
+ arrow_and_future_return_type=arrow_and_future_return_type_str,
149
+ args=args_str,
150
+ kwargs=kwargs_str,
151
+ jit_script_decorator="@torch.jit.script",
152
+ )
153
+ return _do_instantiate_remote_module_template(
154
+ generated_module_name, str_dict, enable_moving_cpu_tensors_to_cuda
155
+ )
156
+
157
+
158
+ def instantiate_non_scriptable_remote_module_template():
159
+ generated_module_name = f"{_FILE_PREFIX}non_scriptable"
160
+ str_dict = dict(
161
+ assign_module_interface_cls="module_interface_cls = None",
162
+ args="*args",
163
+ kwargs="**kwargs",
164
+ arg_types="*args, **kwargs",
165
+ arrow_and_return_type="",
166
+ arrow_and_future_return_type="",
167
+ jit_script_decorator="",
168
+ )
169
+ # For a non-scriptable template, always enable moving CPU tensors to a cuda device,
170
+ # because there is no syntax limitation on the extra handling caused by the script.
171
+ return _do_instantiate_remote_module_template(generated_module_name, str_dict, True)
venv/lib/python3.14/site-packages/torch/distributed/nn/jit/templates/__init__.py ADDED
File without changes
venv/lib/python3.14/site-packages/torch/distributed/nn/jit/templates/remote_module_template.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ # mypy: allow-untyped-defs
3
+
4
+
5
+ def get_remote_module_template(enable_moving_cpu_tensors_to_cuda: bool):
6
+ return _TEMPLATE_PREFIX + (
7
+ _REMOTE_FORWARD_TEMPLATE_ENABLE_MOVING_CPU_TENSORS_TO_CUDA
8
+ if enable_moving_cpu_tensors_to_cuda
9
+ else _REMOTE_FORWARD_TEMPLATE
10
+ )
11
+
12
+
13
+ _TEMPLATE_PREFIX = """from typing import *
14
+
15
+ import torch
16
+ import torch.distributed.rpc as rpc
17
+ from torch import Tensor
18
+ from torch._jit_internal import Future
19
+ from torch.distributed.rpc import RRef
20
+ from typing import Tuple # pyre-ignore: unused import
21
+
22
+
23
+ {assign_module_interface_cls}
24
+
25
+
26
+ def forward_async(self, {arg_types}){arrow_and_future_return_type}:
27
+ args = (self.module_rref, self.device, self.is_device_map_set, {args})
28
+ kwargs = {{{kwargs}}}
29
+ return rpc.rpc_async(
30
+ self.module_rref.owner(),
31
+ _remote_forward,
32
+ args,
33
+ kwargs,
34
+ )
35
+
36
+
37
+ def forward(self, {arg_types}){arrow_and_return_type}:
38
+ args = (self.module_rref, self.device, self.is_device_map_set, {args})
39
+ kwargs = {{{kwargs}}}
40
+ ret_fut = rpc.rpc_async(
41
+ self.module_rref.owner(),
42
+ _remote_forward,
43
+ args,
44
+ kwargs,
45
+ )
46
+ return ret_fut.wait()
47
+
48
+
49
+ _generated_methods = [
50
+ forward_async,
51
+ forward,
52
+ ]
53
+
54
+
55
+ {jit_script_decorator}
56
+ """
57
+
58
+ # This template may cause typing error (the mismatch between ``Tuple[()]`` and ``Tuple[Any]``)
59
+ # even if the code is only used for instantiation but not execution.
60
+ # Therefore, only include handling moving CPU tensors to a cuda device if necessary.
61
+ # TODO: Merge these two templates together in the future once TorchScript syntax is improved.
62
+ _REMOTE_FORWARD_TEMPLATE_ENABLE_MOVING_CPU_TENSORS_TO_CUDA = """
63
+ def _remote_forward(
64
+ module_rref: RRef[module_interface_cls], device: str, is_device_map_set: bool, {arg_types}){arrow_and_return_type}:
65
+ module = module_rref.local_value()
66
+ device = torch.device(device)
67
+
68
+ if device.type != "cuda":
69
+ return module.forward({args}, {kwargs})
70
+
71
+ # If the module is on a cuda device,
72
+ # move any CPU tensor in args or kwargs to the same cuda device.
73
+ # Since torch script does not support generator expression,
74
+ # have to use concatenation instead of
75
+ # ``tuple(i.to(device) if isinstance(i, Tensor) else i for i in *args)``.
76
+ args = ({args},)
77
+ out_args: Tuple[()] = ()
78
+ for arg in args:
79
+ arg = (arg.to(device),) if isinstance(arg, Tensor) else (arg,)
80
+ out_args = out_args + arg
81
+
82
+ kwargs = {{{kwargs}}}
83
+ for k, v in kwargs.items():
84
+ if isinstance(v, Tensor):
85
+ kwargs[k] = kwargs[k].to(device)
86
+
87
+ if is_device_map_set:
88
+ return module.forward(*out_args, {kwargs})
89
+
90
+ # If the device map is empty, then only CPU tensors are allowed to send over wire,
91
+ # so have to move any GPU tensor to CPU in the output.
92
+ # Since torch script does not support generator expression,
93
+ # have to use concatenation instead of
94
+ # ``tuple(i.cpu() if isinstance(i, Tensor) else i for i in module.forward(*out_args, {kwargs}))``.
95
+ ret: Tuple[()] = ()
96
+ for i in module.forward(*out_args, {kwargs}):
97
+ i = (i.cpu(),) if isinstance(i, Tensor) else (i,)
98
+ ret = ret + i
99
+ return ret
100
+ """
101
+
102
+ _REMOTE_FORWARD_TEMPLATE = """
103
+ def _remote_forward(
104
+ module_rref: RRef[module_interface_cls], device: str, is_device_map_set: bool, {arg_types}){arrow_and_return_type}:
105
+ module = module_rref.local_value()
106
+
107
+ return module.forward({args}, {kwargs})
108
+ """
venv/lib/python3.14/site-packages/torch/distributed/optim/__init__.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ :mod:`torch.distributed.optim` exposes DistributedOptimizer, which takes a list
3
+ of remote parameters (:class:`~torch.distributed.rpc.RRef`) and runs the
4
+ optimizer locally on the workers where the parameters live. The distributed
5
+ optimizer can use any of the local optimizer :ref:`optimizer-algorithms` to
6
+ apply the gradients on each worker.
7
+ """
8
+
9
+ import warnings
10
+
11
+ import torch
12
+ from torch import optim
13
+
14
+ from .apply_optimizer_in_backward import (
15
+ _apply_optimizer_in_backward,
16
+ _get_in_backward_optimizers,
17
+ )
18
+ from .functional_adadelta import _FunctionalAdadelta
19
+ from .functional_adagrad import _FunctionalAdagrad
20
+ from .functional_adam import _FunctionalAdam
21
+ from .functional_adamax import _FunctionalAdamax
22
+ from .functional_adamw import _FunctionalAdamW
23
+ from .functional_rmsprop import _FunctionalRMSprop
24
+ from .functional_rprop import _FunctionalRprop
25
+ from .functional_sgd import _FunctionalSGD
26
+ from .named_optimizer import _NamedOptimizer
27
+ from .utils import as_functional_optim
28
+
29
+
30
+ # DistributedOptimizer imports torch.distributed.rpc names, so gate availability
31
+ # based on RPC being available.
32
+ if hasattr(torch._C, "_rpc_init"):
33
+ from .optimizer import DistributedOptimizer
34
+
35
+ from .post_localSGD_optimizer import PostLocalSGDOptimizer
36
+ from .zero_redundancy_optimizer import ZeroRedundancyOptimizer
37
+
38
+
39
+ __all__ = [
40
+ "as_functional_optim",
41
+ "DistributedOptimizer",
42
+ "PostLocalSGDOptimizer",
43
+ "ZeroRedundancyOptimizer",
44
+ ]
venv/lib/python3.14/site-packages/torch/distributed/optim/_deprecation_warning.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+
3
+ import torch
4
+
5
+
6
+ @torch.jit.ignore # type: ignore[misc]
7
+ def _scripted_functional_optimizer_deprecation_warning(stacklevel: int = 0) -> None:
8
+ with warnings.catch_warnings():
9
+ warnings.simplefilter("always")
10
+ warnings.warn(
11
+ "`TorchScript` support for functional optimizers is deprecated "
12
+ "and will be removed in a future PyTorch release. "
13
+ "Consider using the `torch.compile` optimizer instead.",
14
+ DeprecationWarning,
15
+ stacklevel=stacklevel + 2,
16
+ )
venv/lib/python3.14/site-packages/torch/distributed/optim/apply_optimizer_in_backward.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Iterable
2
+ from typing import Any, no_type_check
3
+
4
+ import torch
5
+
6
+
7
+ __all__: list[str] = []
8
+
9
+ # WeakTensorKeyDictionary to store relevant meta-data for the Tensor/Parameter
10
+ # without changing it's life-time.
11
+ # NOTE: Alternative is to add the meta-data as an attribute to the tensor,
12
+ # but that will serialize the meta-data if Tensor is serialized.
13
+ param_to_optim_hook_handle_map = torch.utils.weak.WeakTensorKeyDictionary()
14
+ param_to_acc_grad_map = torch.utils.weak.WeakTensorKeyDictionary()
15
+
16
+
17
+ @no_type_check
18
+ def _apply_optimizer_in_backward(
19
+ optimizer_class: type[torch.optim.Optimizer],
20
+ params: Iterable[torch.nn.Parameter],
21
+ optimizer_kwargs: dict[str, Any],
22
+ register_hook: bool = True,
23
+ ) -> None:
24
+ """
25
+ Upon ``backward()``, the optimizer specified for each parameter will fire after
26
+ the gradient has been accumulated into the parameter.
27
+
28
+ Note - gradients for these parameters will be set to None after ``backward()``.
29
+ This means that any other optimizer not specified via `_apply_optimizer_in_backward`
30
+ over this parameter will be a no-op.
31
+
32
+ Args:
33
+ optimizer_class: (Type[torch.optim.Optimizer]): Optimizer to apply to parameter
34
+ params: (Iterator[nn.Parameter]): parameters to apply optimizer state to
35
+ optimizer_kwargs: (Dict[str, Any]): kwargs to pass to optimizer constructor
36
+ register_hook: (bool): whether to register a hook that runs the optimizer
37
+ after gradient for this parameter is accumulated. This is the default
38
+ way that optimizer in backward is implemented, but specific use cases
39
+ (such as DDP) may wish to override this to implement custom behavior.
40
+ (Default = True)
41
+
42
+ Example::
43
+ params_generator = model.parameters()
44
+ param_1 = next(params_generator)
45
+ remainder_params = list(params_generator)
46
+
47
+ apply_optimizer_in_backward(torch.optim.SGD, [param_1], {"lr": 0.02})
48
+ apply_optimizer_in_backward(torch.optim.Adam, remainder_params, {"lr": 0.04})
49
+
50
+ model(...).sum().backward() # after backward, parameters will already
51
+ # have their registered optimizer(s) applied.
52
+
53
+ """
54
+ torch._C._log_api_usage_once("torch.distributed.optim.apply_optimizer_in_backward")
55
+
56
+ @no_type_check
57
+ def _apply_optimizer_in_backward_to_param(param: torch.nn.Parameter) -> None:
58
+ # view_as creates a node in autograd graph that allows us access to the
59
+ # parameter's AccumulateGrad autograd function object. We register a
60
+ # hook on this object to fire the optimizer when the gradient for
61
+ # this parameter is ready (has been accumulated into .grad field)
62
+
63
+ # Don't create a new acc_grad if we already have one
64
+ # i.e. for shared parameters or attaching multiple optimizers to a param.
65
+ if param not in param_to_acc_grad_map:
66
+ param_to_acc_grad_map[param] = param.view_as(param).grad_fn.next_functions[
67
+ 0
68
+ ][0]
69
+
70
+ optimizer = optimizer_class([param], **optimizer_kwargs)
71
+
72
+ if not hasattr(param, "_in_backward_optimizers"):
73
+ param._in_backward_optimizers = [] # type: ignore[attr-defined]
74
+ # TODO: Remove these attributes once we have a better way of accessing
75
+ # optimizer classes and kwargs for a parameter.
76
+ param._optimizer_classes = [] # type: ignore[attr-defined]
77
+ param._optimizer_kwargs = [] # type: ignore[attr-defined]
78
+
79
+ param._in_backward_optimizers.append(optimizer) # type: ignore[attr-defined]
80
+ param._optimizer_classes.append(optimizer_class) # type: ignore[attr-defined]
81
+ param._optimizer_kwargs.append(optimizer_kwargs) # type: ignore[attr-defined]
82
+
83
+ if not register_hook:
84
+ return
85
+
86
+ def optimizer_hook(*_unused) -> None:
87
+ for opt in param._in_backward_optimizers: # type: ignore[attr-defined]
88
+ opt.step()
89
+
90
+ param.grad = None
91
+
92
+ handle = param_to_acc_grad_map[param].register_hook(optimizer_hook) # type: ignore[attr-defined]
93
+ if param not in param_to_optim_hook_handle_map:
94
+ param_to_optim_hook_handle_map[param] = []
95
+ param_to_optim_hook_handle_map[param].append(handle)
96
+
97
+ for param in params:
98
+ _apply_optimizer_in_backward_to_param(param)
99
+
100
+
101
+ def _get_in_backward_optimizers(module: torch.nn.Module) -> list[torch.optim.Optimizer]:
102
+ """
103
+ Return a list of in-backward optimizers applied to ``module``'s parameters. Note that these
104
+ optimizers are not intended to directly have their ``step`` or ``zero_grad`` methods called
105
+ by the user and are intended to be used for things like checkpointing.
106
+
107
+ Args:
108
+ module: (torch.nn.Module): model to retrieve in-backward optimizers for
109
+
110
+ Returns:
111
+ List[torch.optim.Optimizer]: the in-backward optimizers.
112
+
113
+ Example::
114
+ _apply_optimizer_in_backward(torch.optim.SGD, model.parameters(), {"lr": 0.01})
115
+ optims = _get_optimizers_in_backward(model)
116
+ """
117
+ optims: list[torch.optim.Optimizer] = []
118
+ for param in module.parameters():
119
+ optims.extend(getattr(param, "_in_backward_optimizers", []))
120
+
121
+ return optims
venv/lib/python3.14/site-packages/torch/distributed/optim/functional_adadelta.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ import torch
4
+ import torch.optim._functional as F
5
+ from torch import Tensor
6
+ from torch.distributed.optim._deprecation_warning import (
7
+ _scripted_functional_optimizer_deprecation_warning,
8
+ )
9
+
10
+
11
+ __all__: list[str] = []
12
+
13
+
14
+ # Define a TorchScript compatible Functional Adadelta Optimizer
15
+ # where we use these optimizer in a functional way.
16
+ # Instead of using the `param.grad` when updating parameters,
17
+ # we explicitly allow the distributed optimizer pass gradients to
18
+ # the `step` function. In this way, we could separate the gradients
19
+ # and parameters and allow multithreaded trainer to update the
20
+ # parameters without data traces on accumulating to the same .grad.
21
+ # NOTE: This should be only used by distributed optimizer internals
22
+ # and not meant to expose to the user.
23
+ @torch.jit.script
24
+ class _FunctionalAdadelta:
25
+ def __init__(
26
+ self,
27
+ params: list[Tensor],
28
+ lr: float = 1.0,
29
+ rho: float = 0.9,
30
+ eps: float = 1e-6,
31
+ weight_decay: float = 0.0,
32
+ foreach: bool = False,
33
+ maximize: bool = False,
34
+ _allow_empty_param_list: bool = False,
35
+ ):
36
+ _scripted_functional_optimizer_deprecation_warning(stacklevel=2)
37
+ self.defaults = {
38
+ "lr": lr,
39
+ "rho": rho,
40
+ "eps": eps,
41
+ "weight_decay": weight_decay,
42
+ }
43
+ self.foreach = foreach
44
+ self.maximize = maximize
45
+
46
+ if len(params) == 0 and not _allow_empty_param_list:
47
+ raise ValueError("optimizer got an empty parameter list")
48
+
49
+ # NOTE: we only have one param_group and don't allow user to add additional
50
+ # param group as it's not a common use case.
51
+ self.param_group = {"params": params}
52
+
53
+ self.state = torch.jit.annotate(dict[torch.Tensor, dict[str, torch.Tensor]], {})
54
+
55
+ def step(self, gradients: list[Tensor | None]):
56
+ params = self.param_group["params"]
57
+ params_with_grad = []
58
+ grads = []
59
+ square_avgs = []
60
+ acc_deltas = []
61
+ state_steps = []
62
+ lr = self.defaults["lr"]
63
+ rho = self.defaults["rho"]
64
+ eps = self.defaults["eps"]
65
+ weight_decay = self.defaults["weight_decay"]
66
+
67
+ if len(params) != len(gradients):
68
+ raise ValueError(
69
+ "the gradients passed in does not equal to the size of the parameters!"
70
+ + f"Params length: {len(params)}. "
71
+ + f"Gradients length: {len(gradients)}"
72
+ )
73
+ has_complex = False
74
+ for param, gradient in zip(params, gradients):
75
+ if gradient is not None:
76
+ has_complex |= torch.is_complex(param)
77
+ params_with_grad.append(param)
78
+ grads.append(gradient)
79
+ # Lazy state initialization
80
+ if param not in self.state:
81
+ self.state[param] = {}
82
+ state = self.state[param]
83
+ state["step"] = torch.tensor(0.0)
84
+ state["square_avg"] = torch.zeros_like(
85
+ param, memory_format=torch.preserve_format
86
+ )
87
+ state["acc_delta"] = torch.zeros_like(
88
+ param, memory_format=torch.preserve_format
89
+ )
90
+
91
+ state = self.state[param]
92
+ square_avgs.append(state["square_avg"])
93
+ acc_deltas.append(state["acc_delta"])
94
+ state_steps.append(state["step"])
95
+
96
+ with torch.no_grad():
97
+ F.adadelta(
98
+ params_with_grad,
99
+ grads,
100
+ square_avgs,
101
+ acc_deltas,
102
+ state_steps,
103
+ lr=lr,
104
+ rho=rho,
105
+ eps=eps,
106
+ weight_decay=weight_decay,
107
+ foreach=self.foreach,
108
+ maximize=self.maximize,
109
+ has_complex=has_complex,
110
+ )
venv/lib/python3.14/site-packages/torch/distributed/optim/functional_adagrad.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ import torch
4
+ import torch.optim._functional as F
5
+ from torch import Tensor
6
+ from torch.distributed.optim._deprecation_warning import (
7
+ _scripted_functional_optimizer_deprecation_warning,
8
+ )
9
+
10
+
11
+ __all__: list[str] = []
12
+
13
+
14
+ # Define a TorchScript compatible Functional Adagrad Optimizer
15
+ # where we use these optimizer in a functional way.
16
+ # Instead of using the `param.grad` when updating parameters,
17
+ # we explicitly let the user pass gradients to the `step` function
18
+ # this is so that we could separate the gradients and parameters
19
+ # and allow multithreaded trainer to update the parameters
20
+ # without data traces on accumulating to the same .grad.
21
+ # NOTE: This should be only used by distributed optimizer internals
22
+ # and not meant to expose to the user.
23
+ @torch.jit.script
24
+ class _FunctionalAdagrad:
25
+ def __init__(
26
+ self,
27
+ params: list[Tensor],
28
+ lr: float = 1e-2,
29
+ lr_decay: float = 0.0,
30
+ weight_decay: float = 0.0,
31
+ initial_accumulator_value: float = 0.0,
32
+ warmup_lr_multiplier: float = 1.0,
33
+ warmup_num_iters: float = 0.0,
34
+ eps: float = 1e-10,
35
+ coalesce_grad: bool = True,
36
+ foreach: bool = False,
37
+ fused: bool = False,
38
+ maximize: bool = False,
39
+ _allow_empty_param_list: bool = False,
40
+ ):
41
+ _scripted_functional_optimizer_deprecation_warning(stacklevel=2)
42
+ self.defaults = {
43
+ "lr": lr,
44
+ "lr_decay": lr_decay,
45
+ "eps": eps,
46
+ "weight_decay": weight_decay,
47
+ "initial_accumulator_value": initial_accumulator_value,
48
+ "warmup_lr_multiplier": warmup_lr_multiplier,
49
+ "warmup_num_iters": warmup_num_iters,
50
+ }
51
+ self.coalesce_grad = coalesce_grad
52
+ self.foreach = foreach
53
+ self.fused = fused
54
+ self.maximize = maximize
55
+ self.state = torch.jit.annotate(dict[torch.Tensor, dict[str, torch.Tensor]], {})
56
+
57
+ if len(params) == 0 and not _allow_empty_param_list:
58
+ raise ValueError("optimizer got an empty parameter list")
59
+
60
+ # NOTE: we only have one param_group and don't allow user to add additional
61
+ # param group as it's not a common use case.
62
+ self.param_group = {"params": params}
63
+
64
+ # TODO: no union or any types in TorchScript, make step a scalar tensor instead
65
+ # This is also needed by if we want to share_memory on the step across processes
66
+ for p in self.param_group["params"]:
67
+ self.state[p] = {
68
+ "sum": torch.full_like(p.data, initial_accumulator_value),
69
+ "step": torch.tensor(0.0),
70
+ }
71
+
72
+ def step(self, gradients: list[Tensor | None]):
73
+ params = self.param_group["params"]
74
+ params_with_grad = []
75
+ grads = []
76
+ state_sums = []
77
+ state_steps: list[Tensor] = []
78
+
79
+ if len(params) != len(gradients):
80
+ raise ValueError(
81
+ "the gradients passed in does not equal to the size of the parameters!"
82
+ + f"Params length: {len(params)}. "
83
+ + f"Gradients length: {len(gradients)}"
84
+ )
85
+
86
+ has_sparse_grad, has_complex = False, False
87
+ for param, gradient in zip(self.param_group["params"], gradients):
88
+ if gradient is not None:
89
+ has_sparse_grad |= gradient.is_sparse
90
+ has_complex |= torch.is_complex(param)
91
+ params_with_grad.append(param)
92
+ grads.append(gradient)
93
+ state = self.state[param]
94
+ state_sums.append(state["sum"])
95
+ state_steps.append(state["step"])
96
+
97
+ with torch.no_grad():
98
+ F.adagrad(
99
+ params,
100
+ grads,
101
+ state_sums,
102
+ state_steps,
103
+ lr=self.defaults["lr"],
104
+ weight_decay=self.defaults["weight_decay"],
105
+ lr_decay=self.defaults["lr_decay"],
106
+ eps=self.defaults["eps"],
107
+ has_sparse_grad=has_sparse_grad,
108
+ foreach=self.foreach,
109
+ maximize=self.maximize,
110
+ has_complex=has_complex,
111
+ fused=self.fused,
112
+ grad_scale=None,
113
+ found_inf=None,
114
+ )
venv/lib/python3.14/site-packages/torch/distributed/optim/functional_adam.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ import torch
4
+ import torch.optim._functional as F
5
+ from torch import Tensor
6
+ from torch.distributed.optim._deprecation_warning import (
7
+ _scripted_functional_optimizer_deprecation_warning,
8
+ )
9
+
10
+
11
+ __all__: list[str] = []
12
+
13
+
14
+ # Define a TorchScript compatible Functional Adam Optimizer
15
+ # where we use these optimizer in a functional way.
16
+ # Instead of using the `param.grad` when updating parameters,
17
+ # we explicitly allow the distributed optimizer pass gradients to
18
+ # the `step` function. In this way, we could separate the gradients
19
+ # and parameters and allow multithreaded trainer to update the
20
+ # parameters without data traces on accumulating to the same .grad.
21
+ # NOTE: This should be only used by distributed optimizer internals
22
+ # and not meant to expose to the user.
23
+ @torch.jit.script
24
+ class _FunctionalAdam:
25
+ def __init__(
26
+ self,
27
+ params: list[Tensor],
28
+ lr: float = 1e-3,
29
+ betas: tuple[float, float] = (0.9, 0.999),
30
+ eps: float = 1e-8,
31
+ weight_decay: float = 0.0,
32
+ amsgrad: bool = False,
33
+ maximize: bool = False,
34
+ foreach: bool = False,
35
+ fused: bool = False,
36
+ _allow_empty_param_list: bool = False,
37
+ ):
38
+ _scripted_functional_optimizer_deprecation_warning(stacklevel=2)
39
+ if not 0.0 <= lr:
40
+ raise ValueError(f"Invalid learning rate: {lr}")
41
+ if not 0.0 <= eps:
42
+ raise ValueError(f"Invalid epsilon value: {eps}")
43
+ if not 0.0 <= betas[0] < 1.0:
44
+ raise ValueError(f"Invalid beta parameter at index 0: {betas[0]}")
45
+ if not 0.0 <= betas[1] < 1.0:
46
+ raise ValueError(f"Invalid beta parameter at index 1: {betas[1]}")
47
+ if not 0.0 <= weight_decay:
48
+ raise ValueError(f"Invalid weight_decay value: {weight_decay}")
49
+
50
+ self.defaults = {
51
+ "lr": lr,
52
+ "eps": eps,
53
+ "beta1": betas[0],
54
+ "beta2": betas[1],
55
+ "weight_decay": weight_decay,
56
+ }
57
+ self.amsgrad = amsgrad
58
+ self.maximize = maximize
59
+ self.foreach = foreach
60
+ self.fused = fused
61
+ self.state = torch.jit.annotate(dict[torch.Tensor, dict[str, torch.Tensor]], {})
62
+
63
+ if len(params) == 0 and not _allow_empty_param_list:
64
+ raise ValueError("optimizer got an empty parameter list")
65
+
66
+ # NOTE: we only have one param_group and don't allow user to add additional
67
+ # param group as it's not a common use case.
68
+ self.param_group = {"params": params}
69
+
70
+ def step_param(self, param: Tensor, grad: Tensor | None):
71
+ """
72
+ Similar to step, but operates on a single parameter and optionally a
73
+ gradient tensor.
74
+ """
75
+ params_with_grad = []
76
+ grads = []
77
+ exp_avgs = []
78
+ exp_avg_sqs = []
79
+ max_exp_avg_sqs = []
80
+ state_steps: list[Tensor] = []
81
+ has_complex = torch.is_complex(param)
82
+ if grad is not None:
83
+ params_with_grad.append(param)
84
+ grads.append(grad)
85
+ if param not in self.state:
86
+ self.state[param] = {}
87
+ state = self.state[param]
88
+ state["step"] = torch.tensor(0.0)
89
+ state["exp_avg"] = torch.zeros_like(
90
+ param, memory_format=torch.preserve_format
91
+ )
92
+ state["exp_avg_sq"] = torch.zeros_like(
93
+ param, memory_format=torch.preserve_format
94
+ )
95
+ if self.amsgrad:
96
+ state["max_exp_avg_sq"] = torch.zeros_like(
97
+ param, memory_format=torch.preserve_format
98
+ )
99
+
100
+ state = self.state[param]
101
+ exp_avgs.append(state["exp_avg"])
102
+ exp_avg_sqs.append(state["exp_avg_sq"])
103
+
104
+ if self.amsgrad:
105
+ max_exp_avg_sqs.append(state["max_exp_avg_sq"])
106
+
107
+ state_steps.append(state["step"])
108
+ with torch.no_grad():
109
+ F.adam(
110
+ params_with_grad,
111
+ grads,
112
+ exp_avgs,
113
+ exp_avg_sqs,
114
+ max_exp_avg_sqs,
115
+ state_steps,
116
+ amsgrad=self.amsgrad,
117
+ has_complex=has_complex,
118
+ maximize=self.maximize,
119
+ beta1=self.defaults["beta1"],
120
+ beta2=self.defaults["beta2"],
121
+ lr=self.defaults["lr"],
122
+ weight_decay=self.defaults["weight_decay"],
123
+ eps=self.defaults["eps"],
124
+ foreach=self.foreach,
125
+ fused=self.fused,
126
+ grad_scale=None,
127
+ found_inf=None,
128
+ )
129
+
130
+ def step(self, gradients: list[Tensor | None]):
131
+ params = self.param_group["params"]
132
+ params_with_grad = []
133
+ grads = []
134
+ exp_avgs = []
135
+ exp_avg_sqs = []
136
+ max_exp_avg_sqs = []
137
+ state_steps: list[Tensor] = []
138
+ has_complex = False
139
+
140
+ if len(params) != len(gradients):
141
+ raise ValueError(
142
+ "the gradients passed in does not equal to the size of the parameters!"
143
+ + f"Params length: {len(params)}. "
144
+ + f"Gradients length: {len(gradients)}"
145
+ )
146
+
147
+ for param, gradient in zip(self.param_group["params"], gradients):
148
+ if gradient is not None:
149
+ has_complex |= torch.is_complex(param)
150
+ params_with_grad.append(param)
151
+ grads.append(gradient)
152
+ # Lazy state initialization
153
+ if param not in self.state:
154
+ self.state[param] = {}
155
+ state = self.state[param]
156
+ state["step"] = torch.tensor(0.0)
157
+ # Exponential moving average of gradient values
158
+ state["exp_avg"] = torch.zeros_like(
159
+ param, memory_format=torch.preserve_format
160
+ )
161
+ # Exponential moving average of squared gradient values
162
+ state["exp_avg_sq"] = torch.zeros_like(
163
+ param, memory_format=torch.preserve_format
164
+ )
165
+ if self.amsgrad:
166
+ # Maintains max of all exp. moving avg. of sq. grad. values
167
+ state["max_exp_avg_sq"] = torch.zeros_like(
168
+ param, memory_format=torch.preserve_format
169
+ )
170
+
171
+ state = self.state[param]
172
+
173
+ exp_avgs.append(state["exp_avg"])
174
+ exp_avg_sqs.append(state["exp_avg_sq"])
175
+
176
+ if self.amsgrad:
177
+ max_exp_avg_sqs.append(state["max_exp_avg_sq"])
178
+
179
+ state_steps.append(state["step"])
180
+
181
+ with torch.no_grad():
182
+ F.adam(
183
+ params_with_grad,
184
+ grads,
185
+ exp_avgs,
186
+ exp_avg_sqs,
187
+ max_exp_avg_sqs,
188
+ state_steps,
189
+ amsgrad=self.amsgrad,
190
+ has_complex=has_complex,
191
+ maximize=self.maximize,
192
+ beta1=self.defaults["beta1"],
193
+ beta2=self.defaults["beta2"],
194
+ lr=self.defaults["lr"],
195
+ weight_decay=self.defaults["weight_decay"],
196
+ eps=self.defaults["eps"],
197
+ foreach=self.foreach,
198
+ fused=self.fused,
199
+ grad_scale=None,
200
+ found_inf=None,
201
+ )
venv/lib/python3.14/site-packages/torch/distributed/optim/functional_adamax.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ import torch
4
+ import torch.optim._functional as F
5
+ from torch import Tensor
6
+ from torch.distributed.optim._deprecation_warning import (
7
+ _scripted_functional_optimizer_deprecation_warning,
8
+ )
9
+
10
+
11
+ __all__: list[str] = []
12
+
13
+
14
+ # Define a TorchScript compatible Functional Adamax Optimizer
15
+ # where we use these optimizer in a functional way.
16
+ # Instead of using the `param.grad` when updating parameters,
17
+ # we explicitly allow the distributed optimizer pass gradients to
18
+ # the `step` function. In this way, we could separate the gradients
19
+ # and parameters and allow multithreaded trainer to update the
20
+ # parameters without data traces on accumulating to the same .grad.
21
+ # NOTE: This should be only used by distributed optimizer internals
22
+ # and not meant to expose to the user.
23
+ @torch.jit.script
24
+ class _FunctionalAdamax:
25
+ def __init__(
26
+ self,
27
+ params: list[Tensor],
28
+ lr: float = 1e-3,
29
+ betas: tuple[float, float] = (0.9, 0.999),
30
+ eps: float = 1e-8,
31
+ weight_decay: float = 0.0,
32
+ foreach: bool = False,
33
+ maximize: bool = False,
34
+ _allow_empty_param_list: bool = False,
35
+ ):
36
+ _scripted_functional_optimizer_deprecation_warning(stacklevel=2)
37
+ if not 0.0 <= lr:
38
+ raise ValueError(f"Invalid learning rate: {lr}")
39
+ if not 0.0 <= eps:
40
+ raise ValueError(f"Invalid epsilon value: {eps}")
41
+ if not 0.0 <= betas[0] < 1.0:
42
+ raise ValueError(f"Invalid beta parameter at index 0: {betas[0]}")
43
+ if not 0.0 <= betas[1] < 1.0:
44
+ raise ValueError(f"Invalid beta parameter at index 1: {betas[1]}")
45
+ if not 0.0 <= weight_decay:
46
+ raise ValueError(f"Invalid weight_decay value: {weight_decay}")
47
+
48
+ self.defaults = {
49
+ "lr": lr,
50
+ "eps": eps,
51
+ "beta1": betas[0],
52
+ "beta2": betas[1],
53
+ "weight_decay": weight_decay,
54
+ }
55
+ self.foreach = foreach
56
+ self.maximize = maximize
57
+ self.state = torch.jit.annotate(dict[torch.Tensor, dict[str, torch.Tensor]], {})
58
+
59
+ if len(params) == 0 and not _allow_empty_param_list:
60
+ raise ValueError("optimizer got an empty parameter list")
61
+
62
+ # NOTE: we only have one param_group and don't allow user to add additional
63
+ # param group as it's not a common use case.
64
+ self.param_group = {"params": params}
65
+
66
+ def step(self, gradients: list[Tensor | None]):
67
+ params = self.param_group["params"]
68
+ params_with_grad = []
69
+ grads = []
70
+ exp_avgs = []
71
+ exp_infs = []
72
+ state_steps: list[Tensor] = []
73
+
74
+ if len(params) != len(gradients):
75
+ raise ValueError(
76
+ "the gradients passed in does not equal to the size of the parameters!"
77
+ + f"Params length: {len(params)}. "
78
+ + f"Gradients length: {len(gradients)}"
79
+ )
80
+
81
+ has_complex = False
82
+ for param, gradient in zip(self.param_group["params"], gradients):
83
+ if gradient is not None:
84
+ has_complex |= torch.is_complex(param)
85
+ params_with_grad.append(param)
86
+ grads.append(gradient)
87
+ # Lazy state initialization
88
+ if param not in self.state:
89
+ self.state[param] = {}
90
+ state = self.state[param]
91
+ state["step"] = torch.tensor(0.0)
92
+ # Exponential moving average of gradient values
93
+ state["exp_avg"] = torch.zeros_like(
94
+ param, memory_format=torch.preserve_format
95
+ )
96
+ # Exponential moving average of squared gradient values
97
+ state["exp_inf"] = torch.zeros_like(
98
+ param, memory_format=torch.preserve_format
99
+ )
100
+
101
+ state = self.state[param]
102
+
103
+ exp_avgs.append(state["exp_avg"])
104
+ exp_infs.append(state["exp_inf"])
105
+ state_steps.append(state["step"])
106
+
107
+ with torch.no_grad():
108
+ F.adamax(
109
+ params_with_grad,
110
+ grads,
111
+ exp_avgs,
112
+ exp_infs,
113
+ state_steps,
114
+ eps=self.defaults["eps"],
115
+ beta1=self.defaults["beta1"],
116
+ beta2=self.defaults["beta2"],
117
+ lr=self.defaults["lr"],
118
+ weight_decay=self.defaults["weight_decay"],
119
+ foreach=self.foreach,
120
+ maximize=self.maximize,
121
+ has_complex=has_complex,
122
+ )
venv/lib/python3.14/site-packages/torch/distributed/optim/functional_adamw.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ import torch
4
+ import torch.optim._functional as F
5
+ from torch import Tensor
6
+ from torch.distributed.optim._deprecation_warning import (
7
+ _scripted_functional_optimizer_deprecation_warning,
8
+ )
9
+
10
+
11
+ __all__: list[str] = []
12
+
13
+
14
+ # Define a TorchScript compatible Functional AdamW Optimizer
15
+ # where we use these optimizer in a functional way.
16
+ # Instead of using the `param.grad` when updating parameters,
17
+ # we explicitly allow the distributed optimizer pass gradients to
18
+ # the `step` function. In this way, we could separate the gradients
19
+ # and parameters and allow multithreaded trainer to update the
20
+ # parameters without data traces on accumulating to the same .grad.
21
+ # NOTE: This should be only used by distributed optimizer internals
22
+ # and not meant to expose to the user.
23
+ @torch.jit.script
24
+ class _FunctionalAdamW:
25
+ def __init__(
26
+ self,
27
+ params: list[Tensor],
28
+ lr: float = 1e-3,
29
+ betas: tuple[float, float] = (0.9, 0.999),
30
+ eps: float = 1e-8,
31
+ weight_decay: float = 1e-2,
32
+ amsgrad: bool = False,
33
+ maximize: bool = False,
34
+ foreach: bool = False,
35
+ fused: bool = False,
36
+ _allow_empty_param_list: bool = False,
37
+ ):
38
+ _scripted_functional_optimizer_deprecation_warning(stacklevel=2)
39
+ if not 0.0 <= lr:
40
+ raise ValueError(f"Invalid learning rate: {lr}")
41
+ if not 0.0 <= eps:
42
+ raise ValueError(f"Invalid epsilon value: {eps}")
43
+ if not 0.0 <= betas[0] < 1.0:
44
+ raise ValueError(f"Invalid beta parameter at index 0: {betas[0]}")
45
+ if not 0.0 <= betas[1] < 1.0:
46
+ raise ValueError(f"Invalid beta parameter at index 1: {betas[1]}")
47
+ if not 0.0 <= weight_decay:
48
+ raise ValueError(f"Invalid weight_decay value: {weight_decay}")
49
+
50
+ self.defaults = {
51
+ "lr": lr,
52
+ "eps": eps,
53
+ "beta1": betas[0],
54
+ "beta2": betas[1],
55
+ "weight_decay": weight_decay,
56
+ }
57
+ self.amsgrad = amsgrad
58
+ self.maximize = maximize
59
+ self.foreach = foreach
60
+ self.fused = fused
61
+ self.state = torch.jit.annotate(dict[torch.Tensor, dict[str, torch.Tensor]], {})
62
+
63
+ if len(params) == 0 and not _allow_empty_param_list:
64
+ raise ValueError("optimizer got an empty parameter list")
65
+
66
+ # NOTE: we only have one param_group and don't allow user to add additional
67
+ # param group as it's not a common use case.
68
+ self.param_group = {"params": params}
69
+
70
+ def step_param(self, param: Tensor, grad: Tensor | None):
71
+ params_with_grad = []
72
+ grads = []
73
+ exp_avgs = []
74
+ exp_avg_sqs = []
75
+ max_exp_avg_sqs = []
76
+ state_steps: list[Tensor] = []
77
+ has_complex = torch.is_complex(param)
78
+ if grad is not None:
79
+ params_with_grad.append(param)
80
+ grads.append(grad)
81
+ # Lazy state initialization
82
+ if param not in self.state:
83
+ self.state[param] = {}
84
+ state = self.state[param]
85
+ state["step"] = torch.tensor(0.0)
86
+ # Exponential moving average of gradient values
87
+ state["exp_avg"] = torch.zeros_like(
88
+ param, memory_format=torch.preserve_format
89
+ )
90
+ # Exponential moving average of squared gradient values
91
+ state["exp_avg_sq"] = torch.zeros_like(
92
+ param, memory_format=torch.preserve_format
93
+ )
94
+ if self.amsgrad:
95
+ # Maintains max of all exp. moving avg. of sq. grad. values
96
+ state["max_exp_avg_sq"] = torch.zeros_like(
97
+ param, memory_format=torch.preserve_format
98
+ )
99
+
100
+ state = self.state[param]
101
+
102
+ exp_avgs.append(state["exp_avg"])
103
+ exp_avg_sqs.append(state["exp_avg_sq"])
104
+
105
+ if self.amsgrad:
106
+ max_exp_avg_sqs.append(state["max_exp_avg_sq"])
107
+
108
+ state_steps.append(state["step"])
109
+ with torch.no_grad():
110
+ F.adamw(
111
+ params_with_grad,
112
+ grads,
113
+ exp_avgs,
114
+ exp_avg_sqs,
115
+ max_exp_avg_sqs,
116
+ state_steps,
117
+ amsgrad=self.amsgrad,
118
+ maximize=self.maximize,
119
+ beta1=self.defaults["beta1"],
120
+ beta2=self.defaults["beta2"],
121
+ lr=self.defaults["lr"],
122
+ weight_decay=self.defaults["weight_decay"],
123
+ eps=self.defaults["eps"],
124
+ foreach=self.foreach,
125
+ fused=self.fused,
126
+ grad_scale=None,
127
+ found_inf=None,
128
+ has_complex=has_complex,
129
+ )
130
+
131
+ def step(self, gradients: list[Tensor | None]):
132
+ params = self.param_group["params"]
133
+ params_with_grad = []
134
+ grads = []
135
+ exp_avgs = []
136
+ exp_avg_sqs = []
137
+ max_exp_avg_sqs = []
138
+ state_steps: list[Tensor] = []
139
+
140
+ if len(params) != len(gradients):
141
+ raise ValueError(
142
+ "the gradients passed in does not equal to the size of the parameters!"
143
+ + f"Params length: {len(params)}. "
144
+ + f"Gradients length: {len(gradients)}"
145
+ )
146
+
147
+ has_complex = False
148
+ for param, gradient in zip(self.param_group["params"], gradients):
149
+ if gradient is not None:
150
+ has_complex |= torch.is_complex(param)
151
+ params_with_grad.append(param)
152
+ grads.append(gradient)
153
+ # Lazy state initialization
154
+ if param not in self.state:
155
+ self.state[param] = {}
156
+ state = self.state[param]
157
+ state["step"] = torch.tensor(0.0)
158
+ # Exponential moving average of gradient values
159
+ state["exp_avg"] = torch.zeros_like(
160
+ param, memory_format=torch.preserve_format
161
+ )
162
+ # Exponential moving average of squared gradient values
163
+ state["exp_avg_sq"] = torch.zeros_like(
164
+ param, memory_format=torch.preserve_format
165
+ )
166
+ if self.amsgrad:
167
+ # Maintains max of all exp. moving avg. of sq. grad. values
168
+ state["max_exp_avg_sq"] = torch.zeros_like(
169
+ param, memory_format=torch.preserve_format
170
+ )
171
+
172
+ state = self.state[param]
173
+
174
+ exp_avgs.append(state["exp_avg"])
175
+ exp_avg_sqs.append(state["exp_avg_sq"])
176
+
177
+ if self.amsgrad:
178
+ max_exp_avg_sqs.append(state["max_exp_avg_sq"])
179
+
180
+ state_steps.append(state["step"])
181
+
182
+ with torch.no_grad():
183
+ F.adamw(
184
+ params_with_grad,
185
+ grads,
186
+ exp_avgs,
187
+ exp_avg_sqs,
188
+ max_exp_avg_sqs,
189
+ state_steps,
190
+ amsgrad=self.amsgrad,
191
+ maximize=self.maximize,
192
+ beta1=self.defaults["beta1"],
193
+ beta2=self.defaults["beta2"],
194
+ lr=self.defaults["lr"],
195
+ weight_decay=self.defaults["weight_decay"],
196
+ eps=self.defaults["eps"],
197
+ foreach=self.foreach,
198
+ fused=self.fused,
199
+ grad_scale=None,
200
+ found_inf=None,
201
+ has_complex=has_complex,
202
+ )
venv/lib/python3.14/site-packages/torch/distributed/optim/functional_rmsprop.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ import torch
4
+ import torch.optim._functional as F
5
+ from torch import Tensor
6
+ from torch.distributed.optim._deprecation_warning import (
7
+ _scripted_functional_optimizer_deprecation_warning,
8
+ )
9
+
10
+
11
+ __all__: list[str] = []
12
+
13
+
14
+ # Define a TorchScript compatible Functional RMSprop Optimizer
15
+ # where we use these optimizer in a functional way.
16
+ # Instead of using the `param.grad` when updating parameters,
17
+ # we explicitly allow the distributed optimizer pass gradients to
18
+ # the `step` function. In this way, we could separate the gradients
19
+ # and parameters and allow multithreaded trainer to update the
20
+ # parameters without data traces on accumulating to the same .grad.
21
+ # NOTE: This should be only used by distributed optimizer internals
22
+ # and not meant to expose to the user.
23
+ @torch.jit.script
24
+ class _FunctionalRMSprop:
25
+ def __init__(
26
+ self,
27
+ params: list[Tensor],
28
+ lr: float = 1e-2,
29
+ alpha: float = 0.99,
30
+ eps: float = 1e-8,
31
+ weight_decay: float = 0.0,
32
+ momentum: float = 0.0,
33
+ centered: bool = False,
34
+ foreach: bool = False,
35
+ maximize: bool = False,
36
+ _allow_empty_param_list: bool = False,
37
+ ):
38
+ _scripted_functional_optimizer_deprecation_warning(stacklevel=2)
39
+ self.defaults = {
40
+ "lr": lr,
41
+ "alpha": alpha,
42
+ "eps": eps,
43
+ "weight_decay": weight_decay,
44
+ "momentum": momentum,
45
+ }
46
+ self.centered = centered
47
+ self.foreach = foreach
48
+ self.maximize = maximize
49
+
50
+ if len(params) == 0 and not _allow_empty_param_list:
51
+ raise ValueError("optimizer got an empty parameter list")
52
+
53
+ # NOTE: we only have one param_group and don't allow user to add additional
54
+ # param group as it's not a common use case.
55
+ self.param_group = {"params": params}
56
+
57
+ self.state = torch.jit.annotate(dict[torch.Tensor, dict[str, torch.Tensor]], {})
58
+
59
+ def step(self, gradients: list[Tensor | None]):
60
+ params = self.param_group["params"]
61
+ params_with_grad = []
62
+ grads = []
63
+ square_avgs = []
64
+ grad_avgs = []
65
+ momentum_buffer_list = []
66
+ state_steps = []
67
+ lr = self.defaults["lr"]
68
+ alpha = self.defaults["alpha"]
69
+ eps = self.defaults["eps"]
70
+ momentum = self.defaults["momentum"]
71
+ weight_decay = self.defaults["weight_decay"]
72
+
73
+ if len(params) != len(gradients):
74
+ raise ValueError(
75
+ "the gradients passed in does not equal to the size of the parameters!"
76
+ + f"Params length: {len(params)}. "
77
+ + f"Gradients length: {len(gradients)}"
78
+ )
79
+
80
+ has_complex = False
81
+ for param, gradient in zip(params, gradients):
82
+ if gradient is not None:
83
+ has_complex |= torch.is_complex(param)
84
+ params_with_grad.append(param)
85
+ grads.append(gradient)
86
+ # Lazy state initialization
87
+ if param not in self.state:
88
+ self.state[param] = {}
89
+ state = self.state[param]
90
+ state["step"] = torch.tensor(0.0)
91
+ state["square_avg"] = torch.zeros_like(
92
+ param, memory_format=torch.preserve_format
93
+ )
94
+ if momentum > 0:
95
+ state["momentum_buffer"] = torch.zeros_like(
96
+ param, memory_format=torch.preserve_format
97
+ )
98
+ if self.centered:
99
+ state["grad_avg"] = torch.zeros_like(
100
+ param, memory_format=torch.preserve_format
101
+ )
102
+
103
+ state = self.state[param]
104
+ square_avgs.append(state["square_avg"])
105
+ if momentum > 0:
106
+ momentum_buffer_list.append(state["momentum_buffer"])
107
+ if self.centered:
108
+ grad_avgs.append(state["grad_avg"])
109
+
110
+ state_steps.append(state["step"])
111
+
112
+ with torch.no_grad():
113
+ F.rmsprop(
114
+ params_with_grad,
115
+ grads,
116
+ square_avgs,
117
+ grad_avgs,
118
+ momentum_buffer_list,
119
+ state_steps,
120
+ lr=lr,
121
+ alpha=alpha,
122
+ eps=eps,
123
+ weight_decay=weight_decay,
124
+ momentum=momentum,
125
+ centered=self.centered,
126
+ foreach=self.foreach,
127
+ maximize=self.maximize,
128
+ has_complex=has_complex,
129
+ )
venv/lib/python3.14/site-packages/torch/distributed/optim/functional_rprop.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ import torch
4
+ import torch.optim._functional as F
5
+ from torch import Tensor
6
+ from torch.distributed.optim._deprecation_warning import (
7
+ _scripted_functional_optimizer_deprecation_warning,
8
+ )
9
+
10
+
11
+ __all__: list[str] = []
12
+
13
+
14
+ # Define a TorchScript compatible Functional Rprop Optimizer
15
+ # where we use these optimizer in a functional way.
16
+ # Instead of using the `param.grad` when updating parameters,
17
+ # we explicitly allow the distributed optimizer pass gradients to
18
+ # the `step` function. In this way, we could separate the gradients
19
+ # and parameters and allow multithreaded trainer to update the
20
+ # parameters without data traces on accumulating to the same .grad.
21
+ # NOTE: This should be only used by distributed optimizer internals
22
+ # and not meant to expose to the user.
23
+ @torch.jit.script
24
+ class _FunctionalRprop:
25
+ def __init__(
26
+ self,
27
+ params: list[Tensor],
28
+ lr: float = 1e-2,
29
+ etas: tuple[float, float] = (0.5, 1.2),
30
+ step_sizes: tuple[float, float] = (1e-6, 50),
31
+ foreach: bool = False,
32
+ maximize: bool = False,
33
+ _allow_empty_param_list: bool = False,
34
+ ):
35
+ _scripted_functional_optimizer_deprecation_warning(stacklevel=2)
36
+ self.defaults = {
37
+ "lr": lr,
38
+ }
39
+ self.etas = etas
40
+ self.step_sizes = step_sizes
41
+ self.foreach = foreach
42
+ self.maximize = maximize
43
+
44
+ if len(params) == 0 and not _allow_empty_param_list:
45
+ raise ValueError("optimizer got an empty parameter list")
46
+
47
+ # NOTE: we only have one param_group and don't allow user to add additional
48
+ # param group as it's not a common use case.
49
+ self.param_group = {"params": params}
50
+
51
+ self.state = torch.jit.annotate(dict[torch.Tensor, dict[str, torch.Tensor]], {})
52
+
53
+ def step(self, gradients: list[Tensor | None]):
54
+ params = self.param_group["params"]
55
+ params_with_grad = []
56
+ grads = []
57
+ prevs = []
58
+ step_sizes = []
59
+ state_steps = []
60
+ lr = self.defaults["lr"]
61
+ etaminus, etaplus = self.etas
62
+ step_size_min, step_size_max = self.step_sizes
63
+
64
+ if len(params) != len(gradients):
65
+ raise ValueError(
66
+ "the gradients passed in does not equal to the size of the parameters!"
67
+ + f"Params length: {len(params)}. "
68
+ + f"Gradients length: {len(gradients)}"
69
+ )
70
+
71
+ has_complex = False
72
+ for param, gradient in zip(params, gradients):
73
+ if gradient is not None:
74
+ has_complex |= torch.is_complex(param)
75
+ params_with_grad.append(param)
76
+ grads.append(gradient)
77
+ # Lazy state initialization
78
+ if param not in self.state:
79
+ self.state[param] = {}
80
+ state = self.state[param]
81
+ state["step"] = torch.tensor(0.0)
82
+ state["prev"] = torch.zeros_like(
83
+ param, memory_format=torch.preserve_format
84
+ )
85
+ state["step_size"] = torch.full_like(gradient, lr)
86
+
87
+ state = self.state[param]
88
+ prevs.append(state["prev"])
89
+ step_sizes.append(state["step_size"])
90
+ state_steps.append(state["step"])
91
+
92
+ with torch.no_grad():
93
+ F.rprop(
94
+ params_with_grad,
95
+ grads,
96
+ prevs,
97
+ step_sizes,
98
+ state_steps,
99
+ step_size_min=step_size_min,
100
+ step_size_max=step_size_max,
101
+ etaminus=etaminus,
102
+ etaplus=etaplus,
103
+ foreach=self.foreach,
104
+ maximize=self.maximize,
105
+ has_complex=has_complex,
106
+ )
venv/lib/python3.14/site-packages/torch/distributed/optim/functional_sgd.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ import torch
4
+ import torch.optim._functional as F
5
+ from torch import Tensor
6
+ from torch.distributed.optim._deprecation_warning import (
7
+ _scripted_functional_optimizer_deprecation_warning,
8
+ )
9
+
10
+
11
+ __all__: list[str] = []
12
+
13
+
14
+ # Define a TorchScript compatible Functional SGD Optimizer
15
+ # where we use these optimizer in a functional way.
16
+ # Instead of using the `param.grad` when updating parameters,
17
+ # we explicitly allow the distributed optimizer pass gradients to
18
+ # the `step` function. In this way, we could separate the gradients
19
+ # and parameters and allow multithreaded trainer to update the
20
+ # parameters without data traces on accumulating to the same .grad.
21
+ # NOTE: This should be only used by distributed optimizer internals
22
+ # and not meant to expose to the user.
23
+ @torch.jit.script
24
+ class _FunctionalSGD:
25
+ def __init__(
26
+ self,
27
+ params: list[Tensor],
28
+ lr: float = 1e-2,
29
+ momentum: float = 0.0,
30
+ dampening: float = 0.0,
31
+ weight_decay: float = 0.0,
32
+ nesterov: bool = False,
33
+ maximize: bool = False,
34
+ foreach: bool = False,
35
+ fused: bool = False,
36
+ _allow_empty_param_list: bool = False,
37
+ ):
38
+ _scripted_functional_optimizer_deprecation_warning(stacklevel=2)
39
+ self.defaults = {
40
+ "lr": lr,
41
+ "momentum": momentum,
42
+ "dampening": dampening,
43
+ "weight_decay": weight_decay,
44
+ }
45
+ self.nesterov = nesterov
46
+ self.maximize = maximize
47
+ self.foreach = foreach
48
+ self.fused = fused
49
+ self.state = torch.jit.annotate(dict[torch.Tensor, dict[str, torch.Tensor]], {})
50
+
51
+ if len(params) == 0 and not _allow_empty_param_list:
52
+ raise ValueError("optimizer got an empty parameter list")
53
+
54
+ # NOTE: we only have one param_group and don't allow user to add additional
55
+ # param group as it's not a common use case.
56
+ self.param_group = {"params": params}
57
+
58
+ def step_param(self, param: Tensor, grad: Tensor | None):
59
+ """Similar to self.step, but operates on a single parameter and
60
+ its gradient.
61
+ """
62
+ # TODO: Once step_param interface is robust, refactor step to call
63
+ # step param on each param.
64
+ weight_decay = self.defaults["weight_decay"]
65
+ momentum = self.defaults["momentum"]
66
+ dampening = self.defaults["dampening"]
67
+ lr = self.defaults["lr"]
68
+ params = [param]
69
+ momentum_buffer_list: list[Tensor | None] = []
70
+ grads = []
71
+
72
+ has_sparse_grad = False
73
+ if grad is not None:
74
+ grads.append(grad)
75
+ if grad.is_sparse:
76
+ has_sparse_grad = True
77
+ if param not in self.state:
78
+ self.state[param] = {}
79
+ state = self.state[param]
80
+ if "momentum_buffer" not in state:
81
+ momentum_buffer_list.append(None)
82
+ else:
83
+ momentum_buffer_list.append(state["momentum_buffer"])
84
+
85
+ with torch.no_grad():
86
+ F.sgd(
87
+ params,
88
+ grads,
89
+ momentum_buffer_list,
90
+ weight_decay=weight_decay,
91
+ momentum=momentum,
92
+ lr=lr,
93
+ dampening=dampening,
94
+ nesterov=self.nesterov,
95
+ maximize=self.maximize,
96
+ has_sparse_grad=has_sparse_grad,
97
+ foreach=self.foreach,
98
+ fused=self.fused,
99
+ grad_scale=None,
100
+ found_inf=None,
101
+ )
102
+ # update momentum_buffer in state
103
+ state = self.state[param]
104
+ momentum_buffer = momentum_buffer_list[0]
105
+ if momentum_buffer is not None:
106
+ state["momentum_buffer"] = momentum_buffer
107
+
108
+ def step(self, gradients: list[Tensor | None]):
109
+ params = self.param_group["params"]
110
+ params_with_grad = []
111
+ grads = []
112
+ momentum_buffer_list: list[Tensor | None] = []
113
+ lr = self.defaults["lr"]
114
+ weight_decay = self.defaults["weight_decay"]
115
+ momentum = self.defaults["momentum"]
116
+ dampening = self.defaults["dampening"]
117
+
118
+ if len(params) != len(gradients):
119
+ raise ValueError(
120
+ "the gradients passed in does not equal to the size of the parameters!"
121
+ + f"Params length: {len(params)}. "
122
+ + f"Gradients length: {len(gradients)}"
123
+ )
124
+
125
+ has_sparse_grad = False
126
+ for param, gradient in zip(params, gradients):
127
+ if gradient is not None:
128
+ params_with_grad.append(param)
129
+ grads.append(gradient)
130
+ if gradient.is_sparse:
131
+ has_sparse_grad = True
132
+
133
+ if param not in self.state:
134
+ self.state[param] = {}
135
+
136
+ state = self.state[param]
137
+ if "momentum_buffer" not in state:
138
+ momentum_buffer_list.append(None)
139
+ else:
140
+ momentum_buffer_list.append(state["momentum_buffer"])
141
+
142
+ with torch.no_grad():
143
+ F.sgd(
144
+ params_with_grad,
145
+ grads,
146
+ momentum_buffer_list,
147
+ weight_decay=weight_decay,
148
+ momentum=momentum,
149
+ lr=lr,
150
+ dampening=dampening,
151
+ nesterov=self.nesterov,
152
+ maximize=self.maximize,
153
+ has_sparse_grad=has_sparse_grad,
154
+ foreach=self.foreach,
155
+ fused=self.fused,
156
+ grad_scale=None,
157
+ found_inf=None,
158
+ )
159
+
160
+ # update momentum_buffers in state
161
+ for i, p in enumerate(params_with_grad):
162
+ state = self.state[p]
163
+ momentum_buffer = momentum_buffer_list[i]
164
+ if momentum_buffer is not None:
165
+ state["momentum_buffer"] = momentum_buffer
venv/lib/python3.14/site-packages/torch/distributed/optim/named_optimizer.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import warnings
3
+ from collections.abc import Callable, Collection, Mapping
4
+ from copy import deepcopy
5
+ from typing import Any, overload
6
+
7
+ import torch
8
+ import torch.nn as nn
9
+ from torch import optim
10
+ from torch.distributed._shard.sharded_tensor import ShardedTensor
11
+ from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
12
+
13
+
14
+ __all__: list[str] = []
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ class _NamedOptimizer(optim.Optimizer):
20
+ """
21
+ ``_NamedOptimizer`` takes a dict of parameters and exposes ``state_dict`` by parameter key.
22
+
23
+ We replace the original key (number) in an optim to the
24
+ fully qualified name (FQN) string. User can initialize the optim as they
25
+ initialize a PyTorch optim, the only difference is that they also need to
26
+ pass in the FQN of each parameters.
27
+
28
+ Args:
29
+ named_parameters (Mapping[str, Union[torch.Tensor, ShardedTensor]]):
30
+ Mapping from FQN to parameter.
31
+ optimizer_class (optim.Optimizer):
32
+ The class of optimizer to instantiate.
33
+ param_groups (Collection[Mapping[str, Any]]):
34
+ `param_groups` to pass to optimizer if specified.
35
+ The key of the inner map needs to be FQNs.
36
+ Default: None
37
+ module (nn.Module): the module whose parameters to updated
38
+ by the optimizer.
39
+ args: arguments to pass to the optimizer constructor.
40
+ kwargs: arguments to pass to the optimizer constructor.
41
+
42
+ Example::
43
+ >>> # xdoctest: +SKIP("distributed")
44
+ >>> from torch import optim
45
+ >>> from torch.distributed.optim import _NamedOptimizer
46
+ >>>
47
+ >>> # Define the named optimizer.
48
+ >>> m = Model(...)
49
+ >>> named_optim = _NamedOptimizer(m.named_parameters(), optim.SGD)
50
+ >>> # Forward pass + backward pass.
51
+ >>> named_optim.step()
52
+ >>> ...
53
+ >>> # Call state_dict for the named optimizer returns a FQN state_dict.
54
+ >>> named_optim.state_dict()
55
+
56
+ Warning: This API is still in development and subject to change.
57
+
58
+ TODO: Add tutorial for _NamedOptimizer.
59
+ TODO: Add documentation in the docstring for the public attributes
60
+ like self.param_groups and self.named_parameters.
61
+ """
62
+
63
+ def __init__(
64
+ self,
65
+ named_parameters: Mapping[str, torch.Tensor | ShardedTensor],
66
+ optimizer_class: optim.Optimizer,
67
+ param_groups: Collection[Mapping[str, Any]] | None = None,
68
+ module: nn.Module | None = None,
69
+ *args: tuple[Any, ...],
70
+ **kwargs: dict[str, Any],
71
+ ) -> None:
72
+ torch._C._log_api_usage_once("torch.distributed.optim._NamedOptimizer")
73
+ self.param_groups: Collection[Mapping[str, Any]] = param_groups # type: ignore[assignment]
74
+ self._param_groups_check()
75
+ self.named_parameters = dict(named_parameters)
76
+ params_for_optimizer = (
77
+ self.named_parameters.values() if param_groups is None else param_groups
78
+ )
79
+ self._optimizer = optimizer_class( # type: ignore[operator]
80
+ params_for_optimizer,
81
+ *args,
82
+ **kwargs,
83
+ )
84
+ self.module = module
85
+ if param_groups is None:
86
+ self.ordered_param_keys = list(self.named_parameters.keys())
87
+ else:
88
+ warnings.warn(
89
+ "Since we pass in param_groups, we will use param_groups to "
90
+ "initialize the optimizer, not all parameters of the module.",
91
+ stacklevel=2,
92
+ )
93
+ param_to_key = {param: key for key, param in self.named_parameters.items()} # type: ignore[misc, has-type]
94
+ ordered_param_keys = []
95
+ for group in param_groups:
96
+ for param in group["params"]:
97
+ if param not in param_to_key:
98
+ raise ValueError(
99
+ f"Expect param name {param} found in param group but is missing."
100
+ )
101
+ ordered_param_keys.append(param_to_key[param])
102
+ self.ordered_param_keys = ordered_param_keys
103
+ # Update param_groups from optimizer.
104
+ self.param_groups = self._optimizer.param_groups
105
+
106
+ def _param_groups_check(self) -> None:
107
+ if self.param_groups is not None:
108
+ for param_group in self.param_groups:
109
+ if not isinstance(param_group, dict):
110
+ raise AssertionError("param group must be a dict")
111
+ if "params" not in param_group:
112
+ raise AssertionError("param group must contain key params")
113
+ params = param_group["params"]
114
+ if isinstance(params, torch.Tensor):
115
+ params = [params]
116
+ params = list(params)
117
+ for param in params:
118
+ if not isinstance(param, torch.Tensor):
119
+ raise TypeError(
120
+ "optimizer can only optimize Tensors, "
121
+ "but one of the params is " + torch.typename(param)
122
+ )
123
+ param_group["params"] = params
124
+
125
+ def state_dict(self) -> dict[str, Any]:
126
+ """
127
+ Return the ``state_dict`` of the optimizer.
128
+
129
+ Instead of using number to index
130
+ parameters, we will use module fully qualified name (FQN) as the key.
131
+ """
132
+ state_dict = self._optimizer.state_dict()
133
+ param_groups = state_dict["param_groups"]
134
+
135
+ ret_state = {
136
+ self.ordered_param_keys[st_key]: state_val
137
+ for st_key, state_val in state_dict["state"].items()
138
+ }
139
+
140
+ ret_groups = []
141
+ for group in param_groups:
142
+ param_keys = [self.ordered_param_keys[param] for param in group["params"]]
143
+ ret_group = {"params": sorted(param_keys)}
144
+ for k, v in group.items():
145
+ if k != "params":
146
+ ret_group[k] = deepcopy(v)
147
+ ret_groups.append(ret_group)
148
+
149
+ return self._post_state_dict({"state": ret_state, "param_groups": ret_groups})
150
+
151
+ @overload
152
+ def step(self, closure: None = None) -> None: ...
153
+
154
+ @overload
155
+ def step(self, closure: Callable[[], float]) -> float: ...
156
+
157
+ def step(self, closure: Callable[[], float] | None = None) -> float | None:
158
+ """
159
+ Perform a single optimization step.
160
+
161
+ This will call :meth:`torch.optim.Optimizer.step` on the wrapped
162
+ optimizer.
163
+ """
164
+ return self._optimizer.step(closure=closure)
165
+
166
+ @property
167
+ def state(self) -> Mapping[torch.Tensor, Any]: # type: ignore[override]
168
+ return self._optimizer.state
169
+
170
+ def load_state_dict(self, state_dict: dict[str, Any]) -> None:
171
+ """
172
+ Define the default behavior to load a state_dict for ``_NamedOptimizer``.
173
+
174
+ Sample Code
175
+ ```
176
+ my_model = MyModule()
177
+ optimizer = _NamedOptimizer(my_model.named_parameters(), Adagrad)
178
+ ...
179
+
180
+ optim_state_dict = optimizer.state_dict()
181
+ ...
182
+ ...
183
+
184
+ optimizer.load_state_dict(optim_state_dict)
185
+ ...
186
+ ```
187
+ Args:
188
+ state_dict (dict[str, Any]) : A ``state_dict`` to load into the optimizer.
189
+ Note that this state dict update is performed in place.
190
+
191
+ .. note:: PyTorch is using lazy init to initialize the optim states.
192
+ So it is possible that there is no optim state when user call
193
+ ``load_state_dict`` and for ``_NamedOptimizer`` we make it stricter
194
+ that users can only call ``load_state_dict`` after the state is initialized.
195
+ By doing this, we can validate the optim ``state_dict`` to be loaded.
196
+ """
197
+ new_state_dict = self._optimizer.state_dict()
198
+ state_dict = self._pre_load_state_dict(state_dict)
199
+ state = state_dict["state"]
200
+ new_state = new_state_dict["state"]
201
+ if len(new_state) == 0:
202
+ raise ValueError(
203
+ "Expects the optim to be initialized before load but found not initialized."
204
+ )
205
+
206
+ for idx, param_key in enumerate(self.ordered_param_keys):
207
+ # When the conditional training is performed, not all parameters are updated in the optim.
208
+ if param_key not in state:
209
+ continue
210
+ if len(state[param_key]) != len(new_state[idx]):
211
+ raise ValueError(
212
+ f"Expects equal length as {len(new_state[idx])} for parameter {param_key} but found: {len(state[param_key])}"
213
+ )
214
+ # Iterate through all optimizer states.
215
+ for state_key, state_val in new_state[idx].items():
216
+ if state_key not in state[param_key]:
217
+ raise ValueError(
218
+ f"Expects state {state_key} for parameter {param_key} but not found."
219
+ )
220
+
221
+ src_state_val = state[param_key][state_key]
222
+ if isinstance(state_val, ShardedTensor):
223
+ if not isinstance(src_state_val, ShardedTensor):
224
+ raise AssertionError
225
+ num_shards = len(state_val.local_shards())
226
+ num_new_shards = len(src_state_val.local_shards())
227
+ if num_shards != num_new_shards:
228
+ raise ValueError(
229
+ f"Expects equal number of shards as {num_new_shards} but found {num_shards} for {param_key}/{state_key}"
230
+ )
231
+ for shard, src_shard in zip(
232
+ state_val.local_shards(), src_state_val.local_shards()
233
+ ):
234
+ shard.tensor.detach().copy_(src_shard.tensor)
235
+ elif isinstance(state_val, torch.Tensor):
236
+ if not isinstance(src_state_val, torch.Tensor):
237
+ raise AssertionError
238
+ state_val.detach().copy_(src_state_val)
239
+ else:
240
+ new_state[idx][state_key] = deepcopy(src_state_val)
241
+
242
+ # Load param_groups of state_dict
243
+ src_param_groups = state_dict["param_groups"]
244
+ new_param_groups = new_state_dict["param_groups"]
245
+
246
+ src_group_map = {}
247
+ for group in src_param_groups:
248
+ param_keys = list(group["params"])
249
+ src_group_map[_gen_param_group_key(param_keys)] = group
250
+ new_group_map = {}
251
+ for new_group in new_param_groups:
252
+ param_keys = []
253
+ for param_key in new_group["params"]:
254
+ param_keys.append(self.ordered_param_keys[param_key]) # type: ignore[call-overload]
255
+ new_group_map[_gen_param_group_key(param_keys)] = new_group
256
+ for group_key, new_group in new_group_map.items():
257
+ # When not all parameters are used in training or receive gradient, aka., not all parameters
258
+ # would be in the param_group. Thus we skip the group_key here.
259
+ if group_key not in src_group_map:
260
+ continue
261
+ src_group = src_group_map[group_key]
262
+ if len(src_group) != len(new_group):
263
+ raise ValueError(
264
+ f"Expects equal param_group size as {len(new_group)} for group {group_key} but found {len(src_group)}."
265
+ )
266
+ for k in src_group:
267
+ if k not in new_group:
268
+ raise ValueError(
269
+ f"Expects group key {k} to be in group {group_key} in `state_dict` but is missing."
270
+ )
271
+ if k != "params":
272
+ new_group[k] = deepcopy(src_group[k])
273
+
274
+ self._optimizer.load_state_dict(new_state_dict)
275
+
276
+ def add_param_group(self, param_group: Mapping[str, Any]) -> None:
277
+ """
278
+ Add a param group to the :class:`_NamedOptimizer` s `param_groups`.
279
+
280
+ Warning: This API is still in development and subject to change.
281
+ """
282
+ if not isinstance(param_group, dict):
283
+ raise AssertionError("param group must be a dict")
284
+
285
+ params = param_group["params"]
286
+ if isinstance(params, torch.Tensor):
287
+ param_group["params"] = [params]
288
+ else:
289
+ param_group["params"] = list(params)
290
+
291
+ param_to_key = {param: key for key, param in self.named_parameters.items()} # type: ignore[misc, has-type]
292
+ for param in param_group["params"]:
293
+ if param not in param_to_key:
294
+ raise ValueError("some parameters are not in the module")
295
+ self.ordered_param_keys.append(param_to_key[param])
296
+
297
+ self._optimizer.add_param_group(param_group)
298
+ # Update param_groups from optimizer.
299
+ self.param_groups = self._optimizer.param_groups
300
+
301
+ def init_state(self) -> None:
302
+ """
303
+ Run a dummy optimizer step, which allows to initialize optimizer state because we do lazy init for most optimizers.
304
+
305
+ This allows doing in-place loading of optimizer state from a checkpoint.
306
+ """
307
+ for param in self.named_parameters.values():
308
+ if param.requires_grad:
309
+ t = torch.zeros_like(param)
310
+ param.grad = torch.autograd.Variable(t)
311
+ # Calling ``step`` will load the initial state for optimizer states.
312
+ self.step(closure=None)
313
+
314
+ def _pre_load_state_dict(self, state_dict: dict[str, Any]) -> dict[str, Any]:
315
+ # TODO(chienchin): This API should be FSDP agnostic and should support
316
+ # general user hooks.
317
+ if isinstance(self.module, FSDP):
318
+ return FSDP.optim_state_dict_to_load(
319
+ self.module, self._optimizer, state_dict, is_named_optimizer=True
320
+ )
321
+ return state_dict
322
+
323
+ def _post_state_dict(self, state_dict: dict[str, Any]) -> dict[str, Any]:
324
+ # TODO(chienchin): This API should be FSDP agnostic and should support
325
+ # general user hooks.
326
+ if isinstance(self.module, FSDP):
327
+ FSDP.optim_state_dict(self.module, self._optimizer, state_dict)
328
+ return state_dict
329
+
330
+
331
+ def _gen_param_group_key(param_keys: list[str]) -> str:
332
+ """Concatenate all param keys as a unique identifier for one param group."""
333
+ return "/".join(sorted(param_keys))
venv/lib/python3.14/site-packages/torch/distributed/optim/optimizer.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import logging
3
+ from collections import defaultdict
4
+ from threading import Lock
5
+
6
+ import torch
7
+ import torch.distributed.autograd as dist_autograd
8
+ import torch.distributed.rpc as rpc
9
+ import torch.jit as jit
10
+ import torch.nn as nn
11
+ from torch import Tensor
12
+ from torch.distributed.rpc import RRef
13
+
14
+ from .utils import functional_optim_map
15
+
16
+
17
+ __all__ = ["DistributedOptimizer"]
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ # XXX: we define a _ScriptModuleOptimizer here to explicitly
23
+ # compile the FunctionalOptimizer class into TorchScript
24
+ # This is because ScriptClass instance still lives in
25
+ # python unless you explicitly compile it as an attribute
26
+ # in ScriptModule or pass it to a ScriptFunction
27
+ # _ScriptLocalOptimizerInterface serves as a common
28
+ # interface type for Optimizer ScriptModules.
29
+ #
30
+ # TODO (wanchaol): remove this once we added TorchScript
31
+ # class reference semantics
32
+ @jit.interface
33
+ class _ScriptLocalOptimizerInterface:
34
+ def step(self, autograd_ctx_id: int) -> None:
35
+ pass
36
+
37
+
38
+ class _ScriptLocalOptimizer(nn.Module):
39
+ # TorchScript does not support multithread concurrent compiling.
40
+ # request_callback might invoke concurrent compiling, so we
41
+ # serialize the compiling with a lock
42
+ compile_lock = Lock()
43
+
44
+ def __init__(self, optim_cls, local_params_rref, *args, **kwargs):
45
+ super().__init__()
46
+ self._local_params = [rref.local_value() for rref in local_params_rref]
47
+ self.optim = optim_cls(self._local_params, *args, **kwargs)
48
+
49
+ @jit.export
50
+ def step(self, autograd_ctx_id: int):
51
+ all_local_grads = dist_autograd.get_gradients(autograd_ctx_id)
52
+ # apply functional optimizer step with a list of gradients
53
+ grads: list[Tensor | None] = [
54
+ all_local_grads[p] if p in all_local_grads else None # noqa: SIM401
55
+ for p in self._local_params
56
+ ]
57
+
58
+ self.optim.step(grads)
59
+
60
+
61
+ # TODO (wanchaol): remove/merge this with ScriptLocalOptimizer once
62
+ # we have converted all to functional optimizer in distributed.optim
63
+ class _LocalOptimizer:
64
+ # Ideally we would only need to share a lock for instances of
65
+ # _LocalOptimizer that deal with the same parameters. We are
66
+ # making a simplifying assumption here that if there is more
67
+ # than one instance of _LocalOptimizer per worker, they will
68
+ # be optimizing the same parameters (e.g. each data parallel
69
+ # trainer will create its own instance of _LocalOptimizer but
70
+ # they will all optimize the same parameters on each worker)
71
+ global_lock = Lock()
72
+
73
+ def __init__(self, optim_cls, local_params_rref, *args, **kwargs):
74
+ self._local_params = [rref.local_value() for rref in local_params_rref]
75
+ self.optim = optim_cls(self._local_params, *args, **kwargs)
76
+
77
+ def step(self, autograd_ctx_id):
78
+ all_local_grads = dist_autograd.get_gradients(autograd_ctx_id)
79
+
80
+ with _LocalOptimizer.global_lock:
81
+ for param, grad in all_local_grads.items():
82
+ param.grad = grad
83
+ self.optim.step()
84
+
85
+
86
+ def _new_local_optimizer(optim_cls, local_params_rref, *args, **kwargs):
87
+ return rpc.RRef(_LocalOptimizer(optim_cls, local_params_rref, *args, **kwargs))
88
+
89
+
90
+ def _local_optimizer_step(local_optim_rref, autograd_ctx_id):
91
+ local_optim = local_optim_rref.local_value()
92
+ local_optim.step(autograd_ctx_id)
93
+
94
+
95
+ # new/step functions combined with _ScriptLocalOptimizer to provide GIL-free optimizer
96
+ def _new_script_local_optimizer(optim_cls, local_params_rref, *args, **kwargs):
97
+ optim = _ScriptLocalOptimizer(optim_cls, local_params_rref, *args, **kwargs)
98
+
99
+ with _ScriptLocalOptimizer.compile_lock:
100
+ script_optim = jit.script(optim)
101
+ return rpc.RRef(script_optim, _ScriptLocalOptimizerInterface)
102
+
103
+
104
+ @jit.script
105
+ def _script_local_optimizer_step(
106
+ local_optim_rref: RRef[_ScriptLocalOptimizerInterface], autograd_ctx_id: int
107
+ ) -> None:
108
+ local_optim = local_optim_rref.local_value()
109
+ local_optim.step(autograd_ctx_id)
110
+
111
+
112
+ def _wait_for_all(rpc_futs):
113
+ # TODO: improve error propagation
114
+ exception = None
115
+ results = []
116
+ for fut in rpc_futs:
117
+ try:
118
+ results.append(fut.wait())
119
+ except Exception as e:
120
+ results.append(e)
121
+ exception = e
122
+ if exception is not None:
123
+ raise exception
124
+ return results
125
+
126
+
127
+ class DistributedOptimizer:
128
+ """
129
+ DistributedOptimizer takes remote references to parameters scattered
130
+ across workers and applies the given optimizer locally for each parameter.
131
+
132
+ This class uses :meth:`~torch.distributed.autograd.get_gradients` in order
133
+ to retrieve the gradients for specific parameters.
134
+
135
+ Concurrent calls to
136
+ :meth:`~torch.distributed.optim.DistributedOptimizer.step`,
137
+ either from the same or different clients, will
138
+ be serialized on each worker -- as each worker's optimizer can only work
139
+ on one set of gradients at a time. However, there is no guarantee that
140
+ the full forward-backward-optimizer sequence will execute for one client
141
+ at a time. This means that the gradients being applied may not correspond
142
+ to the latest forward pass executed on a given worker. Also, there is no
143
+ guaranteed ordering across workers.
144
+
145
+ `DistributedOptimizer` creates the local optimizer with TorchScript enabled
146
+ by default, so that optimizer updates are not blocked by the Python Global
147
+ Interpreter Lock (GIL) in the case of multithreaded training (e.g. Distributed
148
+ Model Parallel). This feature is currently enabled for most optimizers. You
149
+ can also follow `the recipe`__ in PyTorch tutorials to enable TorchScript support
150
+ for your own custom optimizers.
151
+
152
+ Args:
153
+ optimizer_class (optim.Optimizer): the class of optimizer to
154
+ instantiate on each worker.
155
+ params_rref (list[RRef]): list of RRefs to local or remote parameters
156
+ to optimize.
157
+ args: arguments to pass to the optimizer constructor on each worker.
158
+ kwargs: arguments to pass to the optimizer constructor on each worker.
159
+
160
+ Example::
161
+ >>> # xdoctest: +SKIP("distributed")
162
+ >>> import torch.distributed.autograd as dist_autograd
163
+ >>> import torch.distributed.rpc as rpc
164
+ >>> from torch import optim
165
+ >>> from torch.distributed.optim import DistributedOptimizer
166
+ >>>
167
+ >>> with dist_autograd.context() as context_id:
168
+ >>> # Forward pass.
169
+ >>> rref1 = rpc.remote("worker1", torch.add, args=(torch.ones(2), 3))
170
+ >>> rref2 = rpc.remote("worker1", torch.add, args=(torch.ones(2), 1))
171
+ >>> loss = rref1.to_here() + rref2.to_here()
172
+ >>>
173
+ >>> # Backward pass.
174
+ >>> dist_autograd.backward(context_id, [loss.sum()])
175
+ >>>
176
+ >>> # Optimizer.
177
+ >>> dist_optim = DistributedOptimizer(
178
+ >>> optim.SGD,
179
+ >>> [rref1, rref2],
180
+ >>> lr=0.05,
181
+ >>> )
182
+ >>> dist_optim.step(context_id)
183
+
184
+ __ https://github.com/pytorch/tutorials/pull/1465
185
+ """
186
+
187
+ def __init__(self, optimizer_class, params_rref, *args, **kwargs):
188
+ torch._C._log_api_usage_once("torch.distributed.optim.DistributedOptimizer")
189
+ per_worker_params_rref = defaultdict(list)
190
+ for param in params_rref:
191
+ per_worker_params_rref[param.owner()].append(param)
192
+
193
+ if optimizer_class in functional_optim_map and jit._state._enabled:
194
+ optim_ctor = functional_optim_map.get(optimizer_class)
195
+ else:
196
+ optim_ctor = optimizer_class
197
+ self.is_functional_optim = optim_ctor != optimizer_class
198
+
199
+ if self.is_functional_optim:
200
+ optimizer_new_func = _new_script_local_optimizer
201
+ else:
202
+ logger.warning(
203
+ "Creating the optimizer %s without TorchScript support, "
204
+ "this might result in slow computation time in multithreading environment"
205
+ "(i.e. Distributed Model Parallel training on CPU) due to the Python's "
206
+ "Global Interpreter Lock (GIL). Please file an issue if you need this "
207
+ "optimizer in TorchScript. ",
208
+ optimizer_class,
209
+ )
210
+ optimizer_new_func = _new_local_optimizer
211
+
212
+ remote_optim_futs = []
213
+ for worker, param_rrefs in per_worker_params_rref.items():
214
+ remote_optim_rref_fut = rpc.rpc_async(
215
+ worker,
216
+ optimizer_new_func,
217
+ args=(optim_ctor, param_rrefs) + args,
218
+ kwargs=kwargs,
219
+ )
220
+ remote_optim_futs.append(remote_optim_rref_fut)
221
+
222
+ self.remote_optimizers = _wait_for_all(remote_optim_futs)
223
+
224
+ def step(self, context_id):
225
+ """
226
+ Performs a single optimization step.
227
+
228
+ This will call :meth:`torch.optim.Optimizer.step` on each worker
229
+ containing parameters to be optimized, and will block until all workers
230
+ return. The provided ``context_id`` will be used to retrieve the
231
+ corresponding :class:`~torch.distributed.autograd.context` that
232
+ contains the gradients that should be applied to the parameters.
233
+
234
+ Args:
235
+ context_id: the autograd context id for which we should run the
236
+ optimizer step.
237
+ """
238
+ dist_autograd._is_valid_context(context_id)
239
+
240
+ optimizer_step_func = (
241
+ _script_local_optimizer_step
242
+ if self.is_functional_optim
243
+ else _local_optimizer_step
244
+ )
245
+
246
+ rpc_futs = [
247
+ rpc.rpc_async(
248
+ optimizer.owner(),
249
+ optimizer_step_func,
250
+ args=(optimizer, context_id),
251
+ )
252
+ for optimizer in self.remote_optimizers
253
+ ]
254
+ _wait_for_all(rpc_futs)
venv/lib/python3.14/site-packages/torch/distributed/optim/post_localSGD_optimizer.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import warnings
3
+
4
+ import torch
5
+ import torch.distributed.algorithms.model_averaging.averagers as averagers
6
+
7
+
8
+ class PostLocalSGDOptimizer(torch.optim.Optimizer):
9
+ r"""
10
+ Wraps an arbitrary :class:`torch.optim.Optimizer` and runs `post-local SGD <https://arxiv.org/abs/1808.07217>`_,
11
+ This optimizer runs local optimizer at every step.
12
+ After the warm-up stage, it averages parameters periodically after the local optimizer is applied.
13
+
14
+ Args:
15
+ optim: The local optimizer.
16
+ averager: A model averager instance to run post-localSGD algorithm.
17
+
18
+ Example::
19
+
20
+ >>> # xdoctest: +SKIP("undefined variables")
21
+ >>> import torch
22
+ >>> import torch.distributed as dist
23
+ >>> import torch.distributed.algorithms.model_averaging.averagers as averagers
24
+ >>> import torch.nn as nn
25
+ >>> from torch.distributed.optim import PostLocalSGDOptimizer
26
+ >>> from torch.distributed.algorithms.ddp_comm_hooks.post_localSGD_hook import (
27
+ >>> PostLocalSGDState,
28
+ >>> post_localSGD_hook,
29
+ >>> )
30
+ >>>
31
+ >>> model = nn.parallel.DistributedDataParallel(
32
+ >>> module, device_ids=[rank], output_device=rank
33
+ >>> )
34
+ >>>
35
+ >>> # Register a post-localSGD communication hook.
36
+ >>> state = PostLocalSGDState(process_group=None, subgroup=None, start_localSGD_iter=100)
37
+ >>> model.register_comm_hook(state, post_localSGD_hook)
38
+ >>>
39
+ >>> # Create a post-localSGD optimizer that wraps a local optimizer.
40
+ >>> # Note that ``warmup_steps`` used in ``PostLocalSGDOptimizer`` must be the same as
41
+ >>> # ``start_localSGD_iter`` used in ``PostLocalSGDState``.
42
+ >>> local_optim = torch.optim.SGD(params=model.parameters(), lr=0.01)
43
+ >>> opt = PostLocalSGDOptimizer(
44
+ >>> optim=local_optim,
45
+ >>> averager=averagers.PeriodicModelAverager(period=4, warmup_steps=100)
46
+ >>> )
47
+ >>>
48
+ >>> # In the first 100 steps, DDP runs global gradient averaging at every step.
49
+ >>> # After 100 steps, DDP runs gradient averaging within each subgroup (intra-node by default),
50
+ >>> # and post-localSGD optimizer runs global model averaging every 4 steps after applying the local optimizer.
51
+ >>> for step in range(0, 200):
52
+ >>> opt.zero_grad()
53
+ >>> loss = loss_fn(output, labels)
54
+ >>> loss.backward()
55
+ >>> opt.step()
56
+ """
57
+
58
+ def __init__(self, optim: torch.optim.Optimizer, averager: averagers.ModelAverager):
59
+ self.optim = optim
60
+ self.param_groups = self.optim.param_groups
61
+ self.averager = averager
62
+
63
+ @property
64
+ def state(self): # type: ignore[override]
65
+ return self.optim.state
66
+
67
+ def __repr__(self):
68
+ return self.optim.__repr__()
69
+
70
+ def state_dict(self):
71
+ r"""
72
+ This is the same as :class:`torch.optim.Optimizer` :meth:`state_dict`,
73
+ but adds an extra entry to record model averager's step to the checkpoint
74
+ to ensure reload does not cause unnecessary warm up again.
75
+ """
76
+ optim_state_dict = self.optim.state_dict()
77
+ optim_state_dict["step"] = self.averager.step
78
+ return optim_state_dict
79
+
80
+ def load_state_dict(self, state_dict):
81
+ r"""
82
+ This is the same as :class:`torch.optim.Optimizer` :meth:`load_state_dict`,
83
+ but also restores model averager's step value to the one
84
+ saved in the provided ``state_dict``.
85
+
86
+ If there is no ``"step"`` entry in ``state_dict``,
87
+ it will raise a warning and initialize the model averager's step to 0.
88
+ """
89
+ self.optim.load_state_dict(state_dict)
90
+ if "step" in state_dict:
91
+ self.averager.step = state_dict["step"]
92
+ else:
93
+ warnings.warn(
94
+ "Loaded state dict does not contain a step counter for an averager. "
95
+ "Setting step counter to 0.",
96
+ stacklevel=2,
97
+ )
98
+ self.averager.step = 0
99
+
100
+ def step(self): # type: ignore[override]
101
+ r"""
102
+ Performs a single optimization step (parameter update).
103
+ """
104
+ self.optim.step()
105
+ self.averager.average_parameters(params=self.param_groups)
106
+
107
+ def zero_grad(self, set_to_none: bool = True): # type: ignore[override]
108
+ self.optim.zero_grad(set_to_none=set_to_none)
109
+
110
+ def add_param_group(self, param_group):
111
+ self.optim.add_param_group(param_group)
venv/lib/python3.14/site-packages/torch/distributed/optim/utils.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ from torch import optim
4
+
5
+ from .functional_adadelta import _FunctionalAdadelta
6
+ from .functional_adagrad import _FunctionalAdagrad
7
+ from .functional_adam import _FunctionalAdam
8
+ from .functional_adamax import _FunctionalAdamax
9
+ from .functional_adamw import _FunctionalAdamW
10
+ from .functional_rmsprop import _FunctionalRMSprop
11
+ from .functional_rprop import _FunctionalRprop
12
+ from .functional_sgd import _FunctionalSGD
13
+
14
+
15
+ # dict to map a user passed in optimizer_class to a functional
16
+ # optimizer class if we have already defined inside the
17
+ # distributed.optim package, this is so that we hide the
18
+ # functional optimizer to user and still provide the same API.
19
+ functional_optim_map = {
20
+ optim.Adagrad: _FunctionalAdagrad,
21
+ optim.Adam: _FunctionalAdam,
22
+ optim.AdamW: _FunctionalAdamW,
23
+ optim.SGD: _FunctionalSGD,
24
+ optim.Adadelta: _FunctionalAdadelta,
25
+ optim.RMSprop: _FunctionalRMSprop,
26
+ optim.Rprop: _FunctionalRprop,
27
+ optim.Adamax: _FunctionalAdamax,
28
+ }
29
+
30
+
31
+ def register_functional_optim(key, optim):
32
+ """
33
+ Interface to insert a new functional optimizer to functional_optim_map
34
+ ``fn_optim_key`` and ``fn_optimizer`` are user defined. The optimizer and key
35
+ need not be of :class:`torch.optim.Optimizer` (e.g. for custom optimizers)
36
+ Example::
37
+ >>> # import the new functional optimizer
38
+ >>> # xdoctest: +SKIP
39
+ >>> from xyz import fn_optimizer
40
+ >>> from torch.distributed.optim.utils import register_functional_optim
41
+ >>> fn_optim_key = "XYZ_optim"
42
+ >>> register_functional_optim(fn_optim_key, fn_optimizer)
43
+ """
44
+ if key not in functional_optim_map:
45
+ functional_optim_map[key] = optim
46
+
47
+
48
+ def as_functional_optim(optim_cls: type, *args, **kwargs):
49
+ try:
50
+ functional_cls = functional_optim_map[optim_cls]
51
+ except KeyError as e:
52
+ raise ValueError(
53
+ f"Optimizer {optim_cls} does not have a functional counterpart!"
54
+ ) from e
55
+
56
+ return _create_functional_optim(functional_cls, *args, **kwargs)
57
+
58
+
59
+ def _create_functional_optim(functional_optim_cls: type, *args, **kwargs):
60
+ return functional_optim_cls(
61
+ [],
62
+ *args,
63
+ **kwargs,
64
+ _allow_empty_param_list=True,
65
+ )
venv/lib/python3.14/site-packages/torch/distributed/optim/zero_redundancy_optimizer.py ADDED
@@ -0,0 +1,1700 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
2
+ #
3
+ # This source code is licensed under the BSD license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ r"""Zero Redundancy Optimizer."""
7
+
8
+ import collections
9
+ import copy
10
+ import enum
11
+ import inspect
12
+ import io
13
+ import logging
14
+ from collections.abc import Callable
15
+ from itertools import chain
16
+ from typing import Any
17
+
18
+ import torch
19
+ import torch.distributed as dist
20
+ from torch.distributed.algorithms.join import Join, Joinable, JoinHook
21
+ from torch.distributed.optim.utils import functional_optim_map
22
+ from torch.optim import Optimizer
23
+
24
+
25
+ __all__ = ["ZeroRedundancyOptimizer"]
26
+
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+
31
+ # Credits: classy_vision/generic/distributed_util.py
32
+ def _recursive_copy_to_device(
33
+ value: Any,
34
+ non_blocking: bool,
35
+ device: torch.device,
36
+ ) -> Any:
37
+ r"""
38
+ Recursively searches lists, tuples, dicts and copies tensors to device if possible.
39
+
40
+ Non-tensor values are passed as-is in the result.
41
+
42
+ .. note::
43
+ These are all copies, so if there are two objects that reference
44
+ the same object, then after this call, there will be two different objects
45
+ referenced on the device.
46
+ """
47
+ if isinstance(value, torch.Tensor):
48
+ return value.to(device, non_blocking=non_blocking)
49
+
50
+ if isinstance(value, (list, tuple)):
51
+ values = [
52
+ _recursive_copy_to_device(val, non_blocking=non_blocking, device=device)
53
+ for val in value
54
+ ]
55
+ return values if isinstance(value, list) else tuple(values)
56
+
57
+ if isinstance(value, collections.abc.Mapping):
58
+ return {
59
+ key: _recursive_copy_to_device(
60
+ val, non_blocking=non_blocking, device=device
61
+ )
62
+ for key, val in value.items()
63
+ }
64
+
65
+ return value
66
+
67
+
68
+ def _is_trainable(param: torch.Tensor) -> bool:
69
+ r"""Return if a parameter is trainable, where trainability is equivalent to requiring a gradient."""
70
+ return param.requires_grad
71
+
72
+
73
+ def _broadcast_object(
74
+ obj: Any,
75
+ src_rank: int,
76
+ group: object = dist.group.WORLD,
77
+ device: torch.device = torch.device("cpu"),
78
+ ) -> Any:
79
+ r"""
80
+ Broadcasts an object to the given group.
81
+
82
+ It will be sending the object if called from the source rank and receiving
83
+ the object otherwise.
84
+
85
+ Arguments:
86
+ obj: object to broadcast; only used if called on the source rank.
87
+ src_rank (int): source rank.
88
+ group (``ProcessGroup``, optional): group used for the broadcast
89
+ (default: ``dist.group.WORLD``).
90
+ device (``torch.device``, optional): device to send from or receive
91
+ to (default: ``torch.device("cpu")``).
92
+
93
+ Returns:
94
+ The broadcasted object.
95
+ """
96
+ if dist.get_rank() == src_rank:
97
+ # Send the object
98
+ buffer = io.BytesIO()
99
+ torch.save(obj, buffer)
100
+ data = bytearray(buffer.getbuffer())
101
+ length_tensor = torch.LongTensor([len(data)]).to(device)
102
+ data_send_tensor = torch.ByteTensor(data).to(device)
103
+ # pyrefly: ignore [bad-argument-type]
104
+ dist.broadcast(length_tensor, src=src_rank, group=group, async_op=False)
105
+ # pyrefly: ignore [bad-argument-type]
106
+ dist.broadcast(data_send_tensor, src=src_rank, group=group, async_op=False)
107
+ else:
108
+ # Receive the object
109
+ length_tensor = torch.LongTensor([0]).to(device)
110
+ # pyrefly: ignore [bad-argument-type]
111
+ dist.broadcast(length_tensor, src=src_rank, group=group, async_op=False)
112
+ data_recv_tensor = torch.empty(
113
+ [int(length_tensor.item())], dtype=torch.uint8, device=device
114
+ )
115
+ # pyrefly: ignore [bad-argument-type]
116
+ dist.broadcast(data_recv_tensor, src=src_rank, group=group, async_op=False)
117
+ buffer = io.BytesIO(data_recv_tensor.cpu().numpy())
118
+ obj = torch.load(buffer, map_location=device, weights_only=False)
119
+ return obj
120
+
121
+
122
+ class _ZeROJoinHook(JoinHook):
123
+ def __init__(self, zero):
124
+ if not isinstance(zero, ZeroRedundancyOptimizer):
125
+ raise AssertionError(
126
+ "ZeRO join hook requires passing in a "
127
+ "ZeroRedundancyOptimizer instance as the state"
128
+ )
129
+ self.zero = zero
130
+ super().__init__()
131
+
132
+ def main_hook(self):
133
+ """
134
+ Perform an optimizer step.
135
+
136
+ This step updates the joined process's shard of
137
+ the parameters and broadcasts those parameters.
138
+ """
139
+ self.zero.step()
140
+
141
+
142
+ class _DDPBucketAssignment:
143
+ r"""
144
+ Represent a :class:`DistributedDataParallel` bucket assignment.
145
+
146
+ This means that a (possibly non-strict) subset of the parameters corresponding to
147
+ a DDP bucket assigned to a rank to update.
148
+
149
+ Attributes:
150
+ bucket_index (int): index of the bucket determined by the DDP gradient
151
+ bucket all-reduce order.
152
+ parameters (List[torch.Tensor]): model parameters in the bucket
153
+ assigned to this rank.
154
+ offset (int): offset into the :class:`GradBucket` 's :meth:`parameters`
155
+ giving the index of the first element in the passed-in
156
+ ``parameters``; this equivalently indexes into the
157
+ :class:`GradBucket` 's :meth:`gradients`.
158
+ device (torch.device): device on which the parameters are stored.
159
+ tensor (torch.Tensor): flattened tensor giving the data of the
160
+ parameter subset assigned to the rank.
161
+ """
162
+
163
+ def __init__(
164
+ self,
165
+ bucket_index: int,
166
+ parameters: list[torch.Tensor],
167
+ offset: int,
168
+ ):
169
+ self.bucket_index = bucket_index
170
+ self.parameters = parameters
171
+ self.offset = offset
172
+ if len(self.parameters) == 0:
173
+ raise ValueError("Empty bucket assignment")
174
+ # DDP guarantees all parameters in the bucket have the same device
175
+ self.device: torch.device = self.parameters[0].device
176
+ self.tensor: torch.Tensor | None = None
177
+
178
+
179
+ class _OverlapStatus(enum.IntEnum):
180
+ r"""
181
+ Define possible statuses that :class:`ZeroRedundancyOptimizer` can be in when overlapping with :class:`DistributedDataParallel`.
182
+
183
+ Attributes:
184
+ ``UNINITIALIZED``: The ZeRO instance is effectively uninitialized and
185
+ is waiting for DDP to finalize its bucketing.
186
+ ``DDP_HAS_REBUILT_BUCKETS``: DDP has rebuilt its buckets, meaning that
187
+ its bucketing is finalized. The ZeRO instance can now collect the
188
+ necessary information about the DDP bucketing.
189
+ ``INITIALIZED``: The ZeRO instance is fully initialized and can now
190
+ optimize parameters.
191
+ """
192
+
193
+ UNINITIALIZED = 0
194
+ DDP_HAS_REBUILT_BUCKETS = 1
195
+ INITIALIZED = 2
196
+
197
+
198
+ class _OverlapInfo:
199
+ r"""
200
+ Information needed by :class:`ZeroRedundancyOptimizer` to overlap with :class:`DistributedDataParallel`.
201
+
202
+ Arguments:
203
+ world_size (int): world size of the process group being used.
204
+
205
+ Attributes:
206
+ shard_buckets (bool): if ``True``, then the assignment of each
207
+ :class:`DistributedDataParallel` bucket is partitioned across
208
+ possibly multiple :class:`ZeroRedundancyOptimizer` instances (i.e.
209
+ across possibly multiple ranks) to approximate uniformity following
210
+ a threshold given by the total parameter size divided by the world
211
+ size; if ``False``, then each bucket is wholly assigned to a single
212
+ :class:`ZeroRedundancyOptimizer` instance (i.e. to a single rank);
213
+ this should be set to the value passed into the hook constructor.
214
+ status (_OverlapStatus): current status; see :class:`_OverlapStatus`
215
+ for more information.
216
+ params_per_bucket (List[List[torch.Tensor]]): ``params_per_bucket[i]``
217
+ gives the model parameters in the ``i``th bucket.
218
+ params_per_rank (List[List[torch.Tensor]]): ``params_per_rank[i]``
219
+ gives the model parameters assigned to the ``i``th rank, where the
220
+ parameters are grouped by increasing bucket indices.
221
+ offsets (Dict[int, int]): maps from bucket index to the offset in
222
+ ``self.params_per_rank[rank]`` giving the index of the first
223
+ parameter in that bucket, where ``rank`` is this process's own
224
+ rank; the keys of this :class:`dict` are the bucket indices
225
+ assigned to this rank.
226
+ num_bucket_assignments (int): total number of bucket assignments across
227
+ all ranks; this is equal to the number of
228
+ :class:`DistributedDataParallel` gradient buckets if
229
+ ``shard_buckets=False`` and possibly greater otherwise.
230
+ total_size (int, optional): total size of all buckets (i.e. sum of
231
+ ``param.numel()`` for all ``param`` across all buckets) if
232
+ ``shard_buckets=True``; otherwise, ``None``.
233
+ broadcast_handles (List[Work]): :class:`list` of async work handles for
234
+ the parameter broadcasts.
235
+ bucket_index_to_future (Dict[int, torch.futures.Future]):
236
+ :class:`dict` mapping bucket index to the corresponding all-reduce
237
+ future.
238
+ bucket_index_to_bucket (Dict[int, dist.GradBucket]): :class:`dict`
239
+ mapping bucket index to the corresponding bucket.
240
+ bucket_indices_seen (List[int]): :class:`list` of the bucket indices
241
+ seen on this iteration.
242
+ """
243
+
244
+ def __init__(self, world_size) -> None:
245
+ self.status: _OverlapStatus = _OverlapStatus.UNINITIALIZED
246
+ self.shard_buckets: bool = False
247
+
248
+ # Modified per bucket reconstruction
249
+ self.params_per_bucket: list[list[torch.Tensor]] = []
250
+ self.params_per_rank: list[list[torch.Tensor]] = [[] for _ in range(world_size)]
251
+ self.offsets: dict[int, int] = {}
252
+ # Group Ranks
253
+ self.assigned_ranks_per_bucket: list[set[int]] = []
254
+ self.num_bucket_assignments: int = 0
255
+ self.total_size: int | None = None
256
+
257
+ # Modified per iteration
258
+ self.broadcast_handles: list[Any] = []
259
+ self.bucket_indices_seen: list[int] = []
260
+ # Used by `hook_with_zero_step()`
261
+ self.bucket_index_to_future: dict[int, torch.futures.Future] = {}
262
+ self.bucket_index_to_bucket: dict[int, dist.GradBucket] = {}
263
+
264
+ def wait_for_broadcasts(self) -> None:
265
+ r"""
266
+ Wait for all parameter broadcasts.
267
+
268
+ This function should be called once all broadcasts have been scheduled,
269
+ meaning ``self.broadcast_handles`` is filled. This clears ``self.broadcast_handles``
270
+ in preparation for the next iteration.
271
+ """
272
+ if len(self.broadcast_handles) != self.num_bucket_assignments:
273
+ raise AssertionError(
274
+ f"Missing at least one broadcast handle on rank {dist.get_rank()}"
275
+ )
276
+ _ = [x.wait() for x in self.broadcast_handles]
277
+ self.broadcast_handles.clear()
278
+
279
+ def clear_per_iter_info(self) -> None:
280
+ r"""
281
+ Clear the data structures that are modified per-iteration.
282
+
283
+ This function should be called at the end of an iteration.
284
+ """
285
+ self.bucket_indices_seen.clear()
286
+ self.bucket_index_to_future.clear()
287
+ self.bucket_index_to_bucket.clear()
288
+
289
+
290
+ class ZeroRedundancyOptimizer(Optimizer, Joinable):
291
+ r"""
292
+ Wrap an arbitrary :class:`optim.Optimizer <torch.optim.Optimizer>` and shards its states across ranks in the group.
293
+
294
+ The sharing is done as described by `ZeRO <https://arxiv.org/abs/1910.02054>`_.
295
+
296
+ The local optimizer instance in each rank is only
297
+ responsible for updating approximately ``1 / world_size`` parameters and
298
+ hence only needs to keep ``1 / world_size`` optimizer states. After
299
+ parameters are updated locally, each rank will broadcast its parameters to
300
+ all other peers to keep all model replicas in the same state.
301
+ ``ZeroRedundancyOptimizer`` can be used in conjunction with
302
+ :class:`torch.nn.parallel.DistributedDataParallel` to reduce per-rank peak
303
+ memory consumption.
304
+
305
+ ``ZeroRedundancyOptimizer`` uses a sorted-greedy algorithm to pack a number
306
+ of parameters at each rank. Each parameter belongs to a single rank and is
307
+ not divided among ranks. The partition is arbitrary and might not match the
308
+ the parameter registration or usage order.
309
+
310
+ Arguments:
311
+ params (``Iterable``): an ``Iterable`` of :class:`torch.Tensor` s
312
+ or :class:`dict` s giving all parameters, which will be sharded
313
+ across ranks.
314
+
315
+ Keyword Args:
316
+ optimizer_class (:class:`torch.nn.Optimizer`): the class of the local
317
+ optimizer.
318
+ process_group (``ProcessGroup``, optional): ``torch.distributed``
319
+ ``ProcessGroup`` (default: ``dist.group.WORLD`` initialized by
320
+ :meth:`torch.distributed.init_process_group`).
321
+ parameters_as_bucket_view (bool, optional): if ``True``, parameters are
322
+ packed into buckets to speed up communication, and ``param.data``
323
+ fields point to bucket views at different offsets; if ``False``,
324
+ each individual parameter is communicated separately, and each
325
+ ``params.data`` stays intact (default: ``False``).
326
+ overlap_with_ddp (bool, optional): if ``True``, :meth:`step` is
327
+ overlapped with :class:`DistributedDataParallel` 's gradient
328
+ synchronization; this requires (1) either a functional optimizer
329
+ for the ``optimizer_class`` argument or one with a functional
330
+ equivalent and (2) registering a DDP communication hook
331
+ constructed from one of the functions in ``ddp_zero_hook.py``;
332
+ parameters are packed into buckets matching those in
333
+ :class:`DistributedDataParallel`, meaning that the
334
+ ``parameters_as_bucket_view`` argument is ignored.
335
+ If ``False``, :meth:`step` runs disjointly after the backward pass
336
+ (per normal).
337
+ (default: ``False``)
338
+ **defaults: any trailing arguments, which are forwarded to the local
339
+ optimizer.
340
+
341
+ Example::
342
+
343
+ >>> # xdoctest: +SKIP
344
+ >>> import torch.nn as nn
345
+ >>> from torch.distributed.optim import ZeroRedundancyOptimizer
346
+ >>> from torch.nn.parallel import DistributedDataParallel as DDP
347
+ >>> model = nn.Sequential(*[nn.Linear(2000, 2000).to(rank) for _ in range(20)])
348
+ >>> ddp = DDP(model, device_ids=[rank])
349
+ >>> opt = ZeroRedundancyOptimizer(
350
+ >>> ddp.parameters(),
351
+ >>> optimizer_class=torch.optim.Adam,
352
+ >>> lr=0.01
353
+ >>> )
354
+ >>> ddp(inputs).sum().backward()
355
+ >>> opt.step()
356
+
357
+ .. warning::
358
+ Currently, ``ZeroRedundancyOptimizer`` requires that all of the
359
+ passed-in parameters are the same dense type.
360
+
361
+ .. warning::
362
+ If you pass ``overlap_with_ddp=True``, be wary of the following: Given
363
+ the way that overlapping :class:`DistributedDataParallel` with
364
+ :class:`ZeroRedundancyOptimizer` is currently implemented, the first
365
+ two or three training iterations do not perform parameter updates in
366
+ the optimizer step, depending on if ``static_graph=False`` or
367
+ ``static_graph=True``, respectively. This is because it needs
368
+ information about the gradient bucketing strategy used by
369
+ :class:`DistributedDataParallel`, which is not finalized until the
370
+ second forward pass if ``static_graph=False`` or until the third
371
+ forward pass if ``static_graph=True``. To adjust for this, one option
372
+ is to prepend dummy inputs.
373
+
374
+ .. warning:: ZeroRedundancyOptimizer is experimental and subject to change.
375
+ """
376
+
377
+ def __init__(
378
+ self,
379
+ params,
380
+ optimizer_class: type[Optimizer],
381
+ process_group: Any | None = None,
382
+ parameters_as_bucket_view: bool = False,
383
+ overlap_with_ddp: bool = False,
384
+ **defaults: Any,
385
+ ):
386
+ r"""Init."""
387
+ # Perform type and assumption checks on the input parameters
388
+ params = self._verify_and_init_params(params)
389
+ self._verify_same_dense_param_type()
390
+
391
+ # NOTE: The parent constructor uses `add_param_group()` which is
392
+ # partially overloaded in ZeroRedundancyOptimizer, so we use the
393
+ # `initialized` flag to dissociate the behaviour of `add_param_group()`
394
+ # between the parent and child.
395
+ self.initialized = False
396
+
397
+ Optimizer.__init__(self, params, defaults)
398
+ Joinable.__init__(self)
399
+ # Now, all parameters are held in both `self._all_params` and
400
+ # `self.param_groups`
401
+
402
+ # Internal data structures (`_cache` indicates lazily evaluated)
403
+ self._param_to_rank_cache: dict[torch.Tensor, int] = {}
404
+ self._param_to_index_cache: dict[torch.Tensor, int] = {}
405
+ self._partition_parameters_cache: list[list[dict]] = []
406
+ self._index_to_param_cache: list[torch.Tensor] = []
407
+ self._device_to_params_per_rank_cache: dict[
408
+ torch.device, list[list[torch.Tensor]]
409
+ ] = {}
410
+ self._bucket_assignments_per_rank_cache: list[
411
+ dict[int, _DDPBucketAssignment]
412
+ ] = []
413
+ self._is_trainable_mask = self._get_is_trainable_mask()
414
+
415
+ # Default device for collective communication and buckets
416
+ self._default_device = self._all_params[0].device
417
+
418
+ self.process_group = (
419
+ process_group if process_group is not None else dist.group.WORLD
420
+ )
421
+ self.world_size: int = dist.get_world_size(self.process_group)
422
+ self.rank: int = dist.get_rank(self.process_group)
423
+ self.global_rank: int = dist.distributed_c10d.get_global_rank(
424
+ # pyrefly: ignore [bad-argument-type]
425
+ self.process_group,
426
+ self.rank,
427
+ )
428
+
429
+ self._overlap_with_ddp: bool = overlap_with_ddp
430
+ self._optim_defaults = defaults
431
+ self._optim_constructor = self._get_optimizer_constructor(optimizer_class)
432
+
433
+ # If `overlap_with_ddp=True`, local optimizer initialization is delayed
434
+ # to run time after the necessary information has been collected
435
+ if not overlap_with_ddp:
436
+ self._init_local_optimizer()
437
+ else:
438
+ self._overlap_info: _OverlapInfo = _OverlapInfo(self.world_size)
439
+ if parameters_as_bucket_view:
440
+ logger.warning(
441
+ "`parameters_as_bucket_view=True` will be ignored since "
442
+ "`overlap_with_ddp=True`; instead, a different bucketing "
443
+ "strategy will be used"
444
+ )
445
+
446
+ # `self._buckets` is used if `parameters_as_bucket_view=True`, in
447
+ # which case parameter data is flattened into contiguous bucket tensors
448
+ self.parameters_as_bucket_view = parameters_as_bucket_view
449
+ self._buckets: list[list[torch.Tensor]] = []
450
+ self._build_param_buckets()
451
+
452
+ # Optional consolidated optimizer state, only populated if this rank
453
+ # is the target in `consolidate_state_dict()`
454
+ self._all_state_dicts: list[dict[str, Any]] = []
455
+
456
+ self.initialized = True
457
+
458
+ def _clear_cache(self) -> None:
459
+ r"""Clear the cached data structures giving partition information."""
460
+ self._partition_parameters_cache.clear()
461
+ self._param_to_rank_cache.clear()
462
+ self._index_to_param_cache.clear()
463
+ self._param_to_index_cache.clear()
464
+ self._device_to_params_per_rank_cache.clear()
465
+ self._bucket_assignments_per_rank_cache.clear()
466
+
467
+ def add_param_group(self, param_group: dict[str, Any]) -> None:
468
+ r"""
469
+ Add a parameter group to the :class:`Optimizer` 's ``param_groups``.
470
+
471
+ This can be useful when fine tuning a pre-trained network, as frozen
472
+ layers can be made trainable and added to the :class:`Optimizer` as
473
+ training progresses.
474
+
475
+ Arguments:
476
+ param_group (dict): specifies the parameters to be optimized and
477
+ group-specific optimization options.
478
+
479
+ .. warning:: This method handles updating the shards on all partitions
480
+ but needs to be called on all ranks. Calling this on a subset of
481
+ the ranks will cause the training to hang because communication
482
+ primitives are called depending on the managed parameters and
483
+ expect all the ranks to participate on the same set of parameters.
484
+ """
485
+ if self.initialized and self._overlap_with_ddp:
486
+ raise RuntimeError(
487
+ "ZeroRedundancyOptimizer with `overlap_with_ddp=True` only "
488
+ "supports a single parameter group"
489
+ )
490
+
491
+ super().add_param_group(param_group)
492
+ # NOTE: The rest of the method assumes that the call to the parent's
493
+ # `add_param_group()` appends the new parameter group and preserves
494
+ # the previous parameter-group ordering
495
+
496
+ if self.initialized:
497
+ # Force a re-partitioning of the parameters
498
+ self._clear_cache()
499
+ param_groups = self._partition_parameters()[self.rank]
500
+ # NOTE: All parameters in the old parameter groups should be
501
+ # assigned to the same ranks so that the local optimizers do not
502
+ # need to be reinitialized
503
+
504
+ # Add the parameters assigned to this rank from the new parameter
505
+ # group to the local optimizer, if any
506
+ if len(param_groups) == len(self.optim.param_groups) + 1:
507
+ self.optim.add_param_group(param_groups[-1])
508
+
509
+ # Update the bucketing strategy accordingly
510
+ if self.parameters_as_bucket_view:
511
+ self._build_param_buckets()
512
+
513
+ def consolidate_state_dict(self, to: int = 0) -> None:
514
+ r"""
515
+ Consolidate a list of ``state_dict`` s (one per rank) on the target rank.
516
+
517
+ Arguments:
518
+ to (int): the rank that receives the optimizer states (default: 0).
519
+
520
+ Raises:
521
+ RuntimeError: if ``overlap_with_ddp=True`` and this method is
522
+ called before this :class:`ZeroRedundancyOptimizer` instance
523
+ has been fully initialized, which happens once
524
+ :class:`DistributedDataParallel` gradient buckets have been
525
+ rebuilt.
526
+
527
+ .. warning:: This needs to be called on all ranks.
528
+ """
529
+ self._check_overlap_initialized()
530
+
531
+ # Sync the exposed `param_groups` attributes to the local optimizer in
532
+ # case they have been updated
533
+ self._sync_param_groups(self.param_groups, self.optim.param_groups)
534
+
535
+ # Pull the sharded state from all ranks and store them in rank order
536
+ empty_messenger = torch.tensor(
537
+ [0], dtype=torch.uint8, device=self._default_device
538
+ )
539
+
540
+ # NOTE: We wastefully use `broadcast()` (e.g. instead of `gather()`)
541
+ # due to compatibility issues with NCCL backend; a possible follow-up
542
+ # is to move all sharded state management to RPC RRef
543
+ self._all_state_dicts = []
544
+ for rank in range(self.world_size):
545
+ global_rank = dist.distributed_c10d.get_global_rank(
546
+ # pyrefly: ignore [bad-argument-type]
547
+ self.process_group,
548
+ rank,
549
+ )
550
+ if self.rank == to:
551
+ # Consolidate all local `state_dict`s on this rank, storing on
552
+ # CPU to save GPU memory
553
+ if rank == self.rank:
554
+ # Directly append own optimizer state
555
+ self._all_state_dicts.append(
556
+ _recursive_copy_to_device(
557
+ self.optim.state_dict(),
558
+ non_blocking=True,
559
+ device=torch.device("cpu"),
560
+ )
561
+ )
562
+ else:
563
+ # Receive the optimizer state from the source rank
564
+ local_state_dict = _broadcast_object(
565
+ empty_messenger,
566
+ src_rank=global_rank,
567
+ group=self.process_group,
568
+ device=self._default_device,
569
+ )
570
+ self._all_state_dicts.append(
571
+ _recursive_copy_to_device(
572
+ local_state_dict,
573
+ non_blocking=True,
574
+ device=torch.device("cpu"),
575
+ )
576
+ )
577
+ else:
578
+ if rank == self.rank:
579
+ # Send the optimizer state to the target rank
580
+ _ = _broadcast_object(
581
+ self.optim.state_dict(),
582
+ src_rank=self.global_rank,
583
+ group=self.process_group,
584
+ device=self._default_device,
585
+ )
586
+ elif rank != to:
587
+ # Discard the received object; `broadcast()` is used for
588
+ # compatibility reasons
589
+ _ = _broadcast_object(
590
+ empty_messenger,
591
+ src_rank=global_rank,
592
+ group=self.process_group,
593
+ device=self._default_device,
594
+ )
595
+
596
+ def _verify_params_per_rank(
597
+ self,
598
+ params_per_rank: list[list[torch.Tensor]],
599
+ ) -> None:
600
+ r"""
601
+ Verify ``params_per_rank`` for :meth:`_partition_parameters`.
602
+
603
+ The verification is done by checking that ``params_per_rank`` has length equal
604
+ to the world size and that it does not contain any parameters not passed into the
605
+ :class:`ZeroRedundancyOptimizer` constructor.
606
+
607
+ The parameters in ``params_per_rank`` being a strict subset of those
608
+ passed into the constructor is valid since some parameters may be
609
+ frozen.
610
+
611
+ Raises:
612
+ ValueError: if ``params_per_rank`` does not have length equal to
613
+ the world size or if it contains a parameter that was not
614
+ passed into the :class:`ZeroRedundancyOptimizer` constructor.
615
+ """
616
+ if len(params_per_rank) != self.world_size:
617
+ raise ValueError(
618
+ "`params_per_rank` must have length equal to the world size"
619
+ )
620
+ all_params_set = set(self._all_params)
621
+ for params in params_per_rank:
622
+ for param in params:
623
+ if param not in all_params_set:
624
+ raise ValueError(
625
+ "Passing a new parameter in `params_per_rank` that "
626
+ "was not passed into the ZeroRedundancyOptimizer "
627
+ "constructor"
628
+ )
629
+
630
+ def _partition_param_group(
631
+ self, param_group: dict[str, Any], params_per_rank: list[list[torch.Tensor]]
632
+ ) -> None:
633
+ r"""
634
+ Partition the parameter group ``param_group`` according to ``params_per_rank``.
635
+
636
+ The partition will modify the ``self._partition_parameters_cache``. This method should
637
+ only be used as a subroutine for :meth:`_partition_parameters`.
638
+
639
+ Arguments:
640
+ param_group (dict[str, Any]): a parameter group as normally defined
641
+ in an optimizer state.
642
+ params_per_rank (list[list[torch.Tensor]]): a :class:`list` of
643
+ length world size containing :class:`list` s of parameters to
644
+ assign to each rank.
645
+ """
646
+ for rank, params in enumerate(params_per_rank):
647
+ rank_param_group = copy.copy(param_group)
648
+ rank_param_group["params"] = params
649
+ self._partition_parameters_cache[rank].append(rank_param_group)
650
+
651
+ def _partition_parameters(
652
+ self,
653
+ params_per_rank: list[list[torch.Tensor]] | None = None,
654
+ ) -> list[list[dict]]:
655
+ r"""
656
+ Partitions parameters across distributed data parallel ranks.
657
+
658
+ Arguments:
659
+ params_per_rank (list[list[torch.Tensor]], optional): a
660
+ :class:`list` of length world size containing :class:`list` s
661
+ of parameters to assign to each rank; this provides a way to
662
+ specify a partition manually.
663
+ If ``None``, the parameters are partitioned according to an
664
+ internal algorithm.
665
+ (default: ``None``)
666
+
667
+ Returns:
668
+ A :class:`list` where each element of the list contains the
669
+ ``param_groups`` for a rank (which itself is a :class:`list` of
670
+ :class:`dict`); element 0 corresponds to rank 0, etc.; each rank
671
+ stores the ``param_groups`` for all ranks for the collective
672
+ communication in :meth:`step`.
673
+
674
+ Raises:
675
+ ValueError: see :meth:`_validate_params_per_rank`.
676
+ RuntimeError: if ``params_per_rank`` is not ``None`` and this
677
+ :class:`ZeroRedundancyOptimizer` instance is using more than
678
+ one parameter group.
679
+ """
680
+ if params_per_rank is None:
681
+ # Partition the parameters optimizing for uniformity
682
+ if len(self._partition_parameters_cache) == 0:
683
+ self._partition_parameters_cache = [[] for _ in range(self.world_size)]
684
+ sizes = [0] * self.world_size
685
+ for param_group in self.param_groups:
686
+ param_group_params_per_rank: list[list] = [
687
+ [] for _ in range(self.world_size)
688
+ ]
689
+ # Sort the parameters by size (largest first)
690
+ params_sorted = sorted(
691
+ param_group["params"], key=lambda t: t.numel(), reverse=True
692
+ )
693
+ for param in params_sorted:
694
+ # Greedily add the parameter to rank with smallest size so far
695
+ rank = self._get_min_index(sizes)
696
+ param_group_params_per_rank[rank].append(param)
697
+ sizes[rank] += param.numel()
698
+ # Apply the constructed partition of the parameter group
699
+ self._partition_param_group(
700
+ param_group, param_group_params_per_rank
701
+ )
702
+
703
+ return self._partition_parameters_cache
704
+
705
+ # Partition the parameters according to `params_per_rank`
706
+ if len(self._partition_parameters_cache) != 0:
707
+ raise AssertionError(
708
+ "Specifying `params_per_rank` should only be done when the "
709
+ "parameters have not been partitioned yet"
710
+ )
711
+ if len(self.param_groups) != 1:
712
+ raise RuntimeError(
713
+ "Specifying `params_per_rank` only supports a single parameter group"
714
+ )
715
+ self._verify_params_per_rank(params_per_rank)
716
+ self._partition_parameters_cache = [[] for _ in range(self.world_size)]
717
+
718
+ # Apply the passed-in partition of the parameter group
719
+ param_group = self.param_groups[0]
720
+ self._partition_param_group(param_group, params_per_rank)
721
+
722
+ return self._partition_parameters_cache
723
+
724
+ @property
725
+ def _param_to_rank(self) -> dict[torch.Tensor, int]:
726
+ r""":class:`dict` mapping parameters to their assigned data parallel rank in the partition."""
727
+ if len(self._param_to_rank_cache) == 0:
728
+ for rank, param_groups in enumerate(self._partition_parameters()):
729
+ for param_group in param_groups:
730
+ for param in param_group["params"]:
731
+ self._param_to_rank_cache[param] = rank
732
+ return self._param_to_rank_cache
733
+
734
+ @property
735
+ def _param_to_index(self) -> dict[torch.Tensor, int]:
736
+ r"""
737
+ :class:`dict` mapping parameters to their indices in the global optimizer state.
738
+
739
+ NOTE: This assumes that the global optimizer state's indexing (in
740
+ ``state_dict``) follows a linear ordering over the parameter groups.
741
+ """
742
+ if len(self._param_to_index_cache) == 0:
743
+ self._param_to_index_cache = {
744
+ p: i
745
+ for i, p in enumerate(
746
+ chain.from_iterable(g["params"] for g in self.param_groups)
747
+ )
748
+ }
749
+ return self._param_to_index_cache
750
+
751
+ @property
752
+ def _index_to_param(self) -> list[torch.Tensor]:
753
+ r"""List mapping parameter indices in the global optimizer scheme to the actual params."""
754
+ if len(self._index_to_param_cache) == 0:
755
+ self._index_to_param_cache = list(
756
+ chain.from_iterable(g["params"] for g in self.param_groups)
757
+ )
758
+ return self._index_to_param_cache
759
+
760
+ def _broadcast_params_from_rank(self, rank: int):
761
+ r"""
762
+ Broadcast the shard of parameters from a given rank to all other ranks asynchronously.
763
+
764
+ Arguments:
765
+ rank (int): the source rank.
766
+
767
+ Returns:
768
+ A :class:`list` of async work handles for the ``broadcast()`` s
769
+ performed to synchronize the parameters.
770
+ """
771
+ if self._overlap_with_ddp:
772
+ raise AssertionError(
773
+ "`_broadcast_params_from_rank()` should not be used if "
774
+ "`overlap_with_ddp=True`; instead, the broadcasting should "
775
+ "happen in the DDP communication hook"
776
+ )
777
+ handles = []
778
+ if self.parameters_as_bucket_view:
779
+ for dev_i_buckets in self._buckets:
780
+ bucket = dev_i_buckets[rank]
781
+ global_rank = dist.distributed_c10d.get_global_rank(
782
+ # pyrefly: ignore [bad-argument-type]
783
+ self.process_group,
784
+ rank,
785
+ )
786
+ handles.append(
787
+ dist.broadcast(
788
+ tensor=bucket,
789
+ src=global_rank,
790
+ group=self.process_group,
791
+ async_op=True,
792
+ )
793
+ )
794
+ else:
795
+ param_groups = self._partition_parameters()[rank]
796
+ global_rank = dist.distributed_c10d.get_global_rank(
797
+ # pyrefly: ignore [bad-argument-type]
798
+ self.process_group,
799
+ rank,
800
+ )
801
+ for param_group in param_groups:
802
+ handles.extend(
803
+ dist.broadcast(
804
+ tensor=param.data,
805
+ src=global_rank,
806
+ group=self.process_group,
807
+ async_op=True,
808
+ )
809
+ for param in param_group["params"]
810
+ )
811
+ return handles
812
+
813
+ def _sync_params(self):
814
+ r"""
815
+ Sync all parameter shards across the ranks.
816
+
817
+ This rank sends its shard of the parameters to all other ranks and
818
+ receives a shard from each other rank. This is done using
819
+ ``broadcast()``. Parameters are sent bucket-by-bucket if
820
+ ``parameters_as_bucket_view=True``and sent parameter-by-parameter
821
+ otherwise.
822
+ """
823
+ handles = []
824
+ for rank in range(self.world_size):
825
+ handles.extend(self._broadcast_params_from_rank(rank))
826
+ _ = [x.wait() for x in handles]
827
+
828
+ @property
829
+ def _device_to_params_per_rank(
830
+ self,
831
+ ) -> dict[torch.device, list[list[torch.Tensor]]]:
832
+ r"""
833
+ Return device parameters assigned per rank.
834
+
835
+ :class:`dict` mapping each device to a :class:`list` of the per-rank parameter
836
+ lists filtered to only include the parameters stored on that device.
837
+ Each per-rank parameter list gives the parameters assigned to that rank
838
+ to update.
839
+
840
+ This is used for constructing the parameter buckets if
841
+ ``parameters_as_bucket_view=True``.
842
+
843
+ Let ``dev_i`` denote the ``i``th device for this rank. Then:
844
+ ``dev_0`` maps to a list containing:
845
+ rank 0's assigned parameters stored on ``dev_0``,
846
+ rank 1's assigned parameters stored on ``dev_0``,
847
+ ...
848
+ ``dev_1`` maps to a list containing:
849
+ rank 0's assigned parameters stored on ``dev_1``,
850
+ rank 1's assigned parameters stored on ``dev_1``,
851
+ ...
852
+ ...
853
+ """
854
+ if not self.parameters_as_bucket_view:
855
+ raise AssertionError(
856
+ "`_device_to_params_per_rank` should only be used if "
857
+ "`parameters_as_bucket_view=True`"
858
+ )
859
+ if len(self._device_to_params_per_rank_cache) == 0:
860
+ for rank, param_groups in enumerate(self._partition_parameters()):
861
+ for param_group in param_groups:
862
+ for param in param_group["params"]:
863
+ device = param.device
864
+ if device not in self._device_to_params_per_rank_cache:
865
+ self._device_to_params_per_rank_cache[device] = [
866
+ [] for _ in range(self.world_size)
867
+ ]
868
+ self._device_to_params_per_rank_cache[device][rank].append(
869
+ param
870
+ )
871
+ return self._device_to_params_per_rank_cache
872
+
873
+ def _get_min_index(
874
+ self,
875
+ values: list[int],
876
+ disallowed_indices: set[int] | None = None,
877
+ ) -> int:
878
+ r"""
879
+ Return ``values.index(min(values))``, except only uses one pass.
880
+
881
+ It also excludes any indices in ``disallowed_indices`` if provided.
882
+
883
+ Arguments:
884
+ values: (List[int]): :class:`list` of values.
885
+ disallowed_indices (Optional[set[int]]): indices that are
886
+ disallowed from being the returned min index.
887
+ """
888
+ min_index = -1
889
+ min_value = float("inf")
890
+ for i, value in enumerate(values):
891
+ if disallowed_indices and i in disallowed_indices:
892
+ continue
893
+ if value < min_value:
894
+ min_value = value
895
+ min_index = i
896
+ if min_index < 0:
897
+ raise AssertionError("All indices are disallowed")
898
+ return min_index
899
+
900
+ def _assign_bucket_subset_to_rank(
901
+ self,
902
+ bucket_index: int,
903
+ bucket_params: list[torch.Tensor],
904
+ bucket_offset: int,
905
+ assigned_rank: int,
906
+ assigned_ranks_per_bucket: list[set[int]],
907
+ ) -> None:
908
+ r"""
909
+ Assign ``bucket_params`` to the rank with the least size assigned so far and collects relevant information.
910
+
911
+ The model parameters given by ``bucket_params`` represents a (possibly non-strict)
912
+ subset of the parameters corresponding to a :class:`DistributedDataParallel` bucket.
913
+
914
+ Arguments:
915
+ bucket_index (int): index of the :class:`DistributedDataParallel`
916
+ gradient bucket.
917
+ bucket_params (List[torch.Tensor]): subset of the parameters
918
+ corresponding to the bucket to assign.
919
+ bucket_offset (int): offset giving the index of the first element
920
+ in ``bucket_params`` in the bucket's full parameter list.
921
+ assigned_rank (int): group rank to assign to.
922
+ assigned_ranks_per_bucket (list[set[int]]): :class:`set` of group ranks
923
+ assigned to each bucket.
924
+ """
925
+ overlap_info = self._overlap_info
926
+ if len(bucket_params) == 0:
927
+ raise ValueError("Empty bucket assignment")
928
+ params_per_rank = overlap_info.params_per_rank
929
+ offsets = overlap_info.offsets
930
+
931
+ self._bucket_assignments_per_rank_cache[assigned_rank][bucket_index] = (
932
+ _DDPBucketAssignment(bucket_index, bucket_params, bucket_offset)
933
+ )
934
+ if self.global_rank == assigned_rank:
935
+ offsets[bucket_index] = len(params_per_rank[assigned_rank])
936
+ params_per_rank[assigned_rank].extend(bucket_params)
937
+ assigned_ranks_per_bucket[bucket_index].add(assigned_rank)
938
+ self._overlap_info.num_bucket_assignments += 1
939
+
940
+ @property
941
+ def _bucket_assignments_per_rank(self) -> list[dict[int, _DDPBucketAssignment]]:
942
+ r"""
943
+ Return DDP bucket parameters assigned per rank.
944
+
945
+ :class:`list` of length world size consisting of :class:`dict` s
946
+ mapping bucket indices to :class:`_DDPBucketAssignment` s for each
947
+ rank.
948
+ """
949
+ if not self._overlap_with_ddp:
950
+ raise AssertionError(
951
+ "`_bucket_assignments_per_rank` only be used if `overlap_with_ddp=True`"
952
+ )
953
+ if len(self._bucket_assignments_per_rank_cache) > 0:
954
+ return self._bucket_assignments_per_rank_cache
955
+
956
+ overlap_info = self._overlap_info
957
+ if overlap_info.status != _OverlapStatus.INITIALIZED:
958
+ raise AssertionError
959
+
960
+ self._bucket_assignments_per_rank_cache = [{} for _ in range(self.world_size)]
961
+ params_per_bucket = overlap_info.params_per_bucket
962
+
963
+ if overlap_info.shard_buckets:
964
+ # Define the assignment threshold to approximate uniformity
965
+ if overlap_info.total_size is None:
966
+ raise AssertionError("`total_size` was not computed")
967
+ threshold = overlap_info.total_size / self.world_size # type: ignore[operator]
968
+ size_per_rank = [0 for _ in range(self.world_size)]
969
+
970
+ num_buckets = len(params_per_bucket)
971
+ overlap_info.assigned_ranks_per_bucket = [set() for _ in range(num_buckets)]
972
+ assigned_ranks_per_bucket = overlap_info.assigned_ranks_per_bucket
973
+ if not overlap_info.shard_buckets:
974
+ # Assign each DDP bucket entirely to a single rank
975
+ for bucket_index, bucket_params in enumerate(params_per_bucket):
976
+ if len(bucket_params) <= 0:
977
+ raise AssertionError("Empty bucket")
978
+ assigned_rank = self._get_assigned_rank(bucket_index)
979
+ self._assign_bucket_subset_to_rank(
980
+ bucket_index,
981
+ bucket_params,
982
+ 0,
983
+ assigned_rank,
984
+ assigned_ranks_per_bucket,
985
+ )
986
+ else:
987
+ # Assign each DDP bucket to possibly multiple ranks
988
+ # Specifically, sort the DDP buckets by increasing size, and for
989
+ # each bucket, iteratively assign the maximal unassigned subset
990
+ # with size less than `threshold` to the rank with the least total
991
+ # size so far -- each such assignment is represented by a
992
+ # `_DDPBucketAssignment` instance and only contains parameters from
993
+ # a single DDP bucket
994
+ params_per_bucket_enum = sorted(
995
+ enumerate(params_per_bucket), key=lambda x: sum(p.numel() for p in x[1])
996
+ )
997
+ for bucket_index, bucket_params in params_per_bucket_enum:
998
+ if len(bucket_params) <= 0:
999
+ raise AssertionError("Empty bucket")
1000
+ bucket_offset = 0
1001
+ assignment_size = 0
1002
+ for param_index, param in enumerate(bucket_params):
1003
+ param_numel = param.numel()
1004
+ if (
1005
+ # pyrefly: ignore [unbound-name]
1006
+ assignment_size + param_numel >= threshold
1007
+ and param_index > bucket_offset
1008
+ ):
1009
+ assigned_rank = self._get_min_index(
1010
+ # pyrefly: ignore [unbound-name]
1011
+ size_per_rank,
1012
+ assigned_ranks_per_bucket[bucket_index],
1013
+ )
1014
+ # Include up to but not including the parameter that
1015
+ # exceeded the threshold
1016
+ self._assign_bucket_subset_to_rank(
1017
+ bucket_index,
1018
+ bucket_params[bucket_offset:param_index],
1019
+ bucket_offset,
1020
+ assigned_rank,
1021
+ assigned_ranks_per_bucket,
1022
+ )
1023
+ # pyrefly: ignore [unbound-name]
1024
+ size_per_rank[assigned_rank] += assignment_size
1025
+ bucket_offset = param_index
1026
+ assignment_size = 0
1027
+ assignment_size += param_numel
1028
+ # Assign the remainder of the bucket so that no assignment
1029
+ # spans across two buckets
1030
+ assigned_rank = self._get_min_index(
1031
+ # pyrefly: ignore [unbound-name]
1032
+ size_per_rank,
1033
+ assigned_ranks_per_bucket[bucket_index],
1034
+ )
1035
+ self._assign_bucket_subset_to_rank(
1036
+ bucket_index,
1037
+ bucket_params[bucket_offset:],
1038
+ bucket_offset,
1039
+ assigned_rank,
1040
+ assigned_ranks_per_bucket,
1041
+ )
1042
+ # pyrefly: ignore [unbound-name]
1043
+ size_per_rank[assigned_rank] += assignment_size
1044
+
1045
+ return self._bucket_assignments_per_rank_cache
1046
+
1047
+ def _local_step(
1048
+ self,
1049
+ gradients: list[torch.Tensor | None] | None = None,
1050
+ closure: Callable[[], float] | None = None,
1051
+ **kwargs: Any,
1052
+ ) -> float | None:
1053
+ r"""
1054
+ Perform a single optimizer step without syncing parameters across ranks.
1055
+
1056
+ Arguments:
1057
+ gradients (list[Optional[torch.Tensor]], optional): a :class:`list`
1058
+ of length equal to the number of parameters assigned to this
1059
+ rank containing gradient tensors or ``None`` as its elements;
1060
+ a ``None`` in the :class:`list` indicates that the
1061
+ corresponding parameter should not be updated.
1062
+ If the argument itself is ``None``, then all parameters are
1063
+ updated, and the gradients are assumed to be already populated.
1064
+ (default: ``None``)
1065
+ closure (Callable): a closure that re-evaluates the model and
1066
+ returns the loss; optional for most optimizers and should be
1067
+ ``None`` if ``gradients`` is not ``None``; (default: ``None``)
1068
+ Returns:
1069
+ Optional loss depending on the underlying local optimizer.
1070
+
1071
+ .. warning::
1072
+ The argument ``gradients`` should only be specified (i.e. not
1073
+ ``None``) if ``overlap_with_ddp=True``, in which case
1074
+ :class:`ZeroRedundancyOptimizer` wraps a functional optimizer.
1075
+ """
1076
+ Join.notify_join_context(self)
1077
+ # Check if the model trainability has changed
1078
+ is_trainable_mask = self._get_is_trainable_mask()
1079
+ if is_trainable_mask != self._is_trainable_mask:
1080
+ if self._overlap_with_ddp:
1081
+ raise RuntimeError(
1082
+ "ZeroRedundancyOptimizer with `overlap_with_ddp=True` "
1083
+ "does not support changing parameter trainability at run "
1084
+ "time"
1085
+ )
1086
+ logger.warning(
1087
+ "ZeroRedundancyOptimizer detected that the trainable "
1088
+ "parameters changed; rebuilding the parameter buckets if "
1089
+ "enabled"
1090
+ )
1091
+ self._build_param_buckets()
1092
+ self._is_trainable_mask = is_trainable_mask
1093
+
1094
+ # Sync the exposed `param_groups` attributes to the local optimizer in
1095
+ # case they have been updated
1096
+ self._sync_param_groups(self.param_groups, self.optim.param_groups)
1097
+
1098
+ # Run the optimizer step on this shard only
1099
+ if gradients is None:
1100
+ loss = (
1101
+ self.optim.step(**kwargs)
1102
+ if closure is None
1103
+ else self.optim.step(closure=closure, **kwargs)
1104
+ )
1105
+ else:
1106
+ if not self._overlap_with_ddp:
1107
+ raise AssertionError(
1108
+ "Specifying `gradients` should not "
1109
+ "be used when `overlap_with_ddp=False`"
1110
+ )
1111
+ if closure is not None:
1112
+ raise AssertionError(
1113
+ "`closure` is not supported when using a local functional optimizer"
1114
+ )
1115
+ loss = self.optim.step(gradients=gradients)
1116
+
1117
+ # Sync any updated attributes in the local optimizer to the exposed
1118
+ # `param_groups`
1119
+ self._sync_param_groups(self.optim.param_groups, self.param_groups)
1120
+
1121
+ return loss
1122
+
1123
+ # pyrefly: ignore [bad-override]
1124
+ def step(
1125
+ self,
1126
+ closure: Callable[[], float] | None = None,
1127
+ **kwargs: Any,
1128
+ ) -> float | None:
1129
+ r"""
1130
+ Perform a single optimizer step and syncs parameters across all ranks.
1131
+
1132
+ Arguments:
1133
+ closure (Callable): a closure that re-evaluates the model and
1134
+ returns the loss; optional for most optimizers.
1135
+ Returns:
1136
+ Optional loss depending on the underlying local optimizer.
1137
+
1138
+ .. note:: Any extra parameters are passed to the base optimizer as-is.
1139
+ """
1140
+ if self._overlap_with_ddp:
1141
+ logger.warning(
1142
+ "`step()` should not be included in the training loop when "
1143
+ "`overlap_with_ddp=True`"
1144
+ )
1145
+ return None
1146
+
1147
+ # Perform the local optimizer step
1148
+ loss = self._local_step(closure=closure, **kwargs)
1149
+
1150
+ # Sync all of the updated parameter shards across the ranks
1151
+ self._sync_params()
1152
+
1153
+ return loss
1154
+
1155
+ def join_hook(self, **_kwargs: Any) -> JoinHook:
1156
+ r"""
1157
+ Return the ZeRO join hook.
1158
+
1159
+ It enables training on uneven inputs by
1160
+ shadowing the collective communications in the optimizer step.
1161
+
1162
+ Gradients must be properly set before this hook is called.
1163
+
1164
+ Arguments:
1165
+ kwargs (dict): a :class:`dict` containing any keyword arguments
1166
+ to modify the behavior of the join hook at run time; all
1167
+ :class:`Joinable` instances sharing the same join context
1168
+ manager are forwarded the same value for ``kwargs``.
1169
+
1170
+ This hook does not support any keyword arguments; i.e. ``kwargs`` is
1171
+ unused.
1172
+ """
1173
+ return _ZeROJoinHook(self)
1174
+
1175
+ @property
1176
+ def join_device(self) -> torch.device:
1177
+ r"""Return default device."""
1178
+ return self._default_device
1179
+
1180
+ @property
1181
+ def join_process_group(self) -> Any:
1182
+ r"""Return process group."""
1183
+ return self.process_group
1184
+
1185
+ def load_state_dict(self, state_dict: dict[str, Any]) -> None:
1186
+ r"""
1187
+ Load the state pertaining to the given rank from the input ``state_dict``, updating the local optimizer as needed.
1188
+
1189
+ Arguments:
1190
+ state_dict (dict): optimizer state; should be an object returned
1191
+ from a call to :meth:`state_dict`.
1192
+
1193
+ Raises:
1194
+ RuntimeError: if ``overlap_with_ddp=True`` and this method is
1195
+ called before this :class:`ZeroRedundancyOptimizer` instance
1196
+ has been fully initialized, which happens once
1197
+ :class:`DistributedDataParallel` gradient buckets have been
1198
+ rebuilt.
1199
+ """
1200
+ self._check_overlap_initialized()
1201
+
1202
+ for index, value in state_dict["state"].items():
1203
+ param = self._index_to_param[index]
1204
+ if self._param_to_rank[param] != self.rank:
1205
+ # Clear any state irrelevant to this rank
1206
+ state_dict["state"][index] = None
1207
+ else:
1208
+ # Load the parameter state to the local optimizer
1209
+ self.optim.state[param] = _recursive_copy_to_device(
1210
+ value, non_blocking=True, device=param.device
1211
+ )
1212
+ # Force zero-dimensional tensors (like Adam "step") on CPU
1213
+ for state_name, state_value in self.optim.state[param].items():
1214
+ if torch.is_tensor(state_value) and state_value.dim() == 0:
1215
+ self.optim.state[param][state_name] = state_value.cpu()
1216
+
1217
+ super().load_state_dict(state_dict)
1218
+
1219
+ # Sync the input state with the exposed and local optimizer states
1220
+ self._sync_param_groups(state_dict["param_groups"], self.param_groups)
1221
+ self._sync_param_groups(self.param_groups, self.optim.param_groups)
1222
+
1223
+ def state_dict(self) -> dict[str, Any]:
1224
+ r"""
1225
+ Return the last global optimizer state known to this rank.
1226
+
1227
+ .. warning:
1228
+ If the state has not been consolidated to this rank, this raises a
1229
+ runtime error, and even if it has, the state may not be up-to-date,
1230
+ depending on when :meth:`consolidate_state_dict` was last called.
1231
+
1232
+ Raises:
1233
+ RuntimeError: if ``overlap_with_ddp=True`` and this method is
1234
+ called before this :class:`ZeroRedundancyOptimizer` instance
1235
+ has been fully initialized, which happens once
1236
+ :class:`DistributedDataParallel` gradient buckets have been
1237
+ rebuilt; or if this method is called without a preceding call
1238
+ to :meth:`consolidate_state_dict`.
1239
+ """
1240
+ self._check_overlap_initialized()
1241
+
1242
+ if len(self._all_state_dicts) == 0:
1243
+ raise RuntimeError(
1244
+ "Optimizer state has not been consolidated on this rank. "
1245
+ f"Please call `consolidate_state_dict(to={self.rank})` on "
1246
+ "all ranks beforehand if you meant to save the global state."
1247
+ )
1248
+
1249
+ # Get the possibly-stale global optimizer state that uses global
1250
+ # parameter indexing
1251
+ state_dict = super().state_dict()
1252
+
1253
+ # Update the global optimizer state with local state information,
1254
+ # factoring in the translation from local to global indexing
1255
+ for rank, local_state_dict in enumerate(self._all_state_dicts):
1256
+ local_param_groups = local_state_dict["param_groups"]
1257
+ global_param_groups = self._partition_parameters()[rank]
1258
+ if len(local_param_groups) != len(global_param_groups):
1259
+ raise AssertionError(
1260
+ "Mismatch between number of local and global parameter groups"
1261
+ )
1262
+
1263
+ for local_param_group, global_param_group in zip(
1264
+ local_param_groups, global_param_groups
1265
+ ):
1266
+ # `local_param_group` stores local indices, while
1267
+ # `global_param_group` stores the tensors directly
1268
+ local_param_indices = local_param_group["params"]
1269
+ global_params = global_param_group["params"]
1270
+
1271
+ if len(local_param_indices) != len(global_params):
1272
+ raise AssertionError(
1273
+ "Mismatch between number of local and global "
1274
+ "parameters in parameter group"
1275
+ )
1276
+ for local_param_index, global_param in zip(
1277
+ local_param_indices, global_params
1278
+ ):
1279
+ # Update the global parameter state, if any
1280
+ if local_param_index in local_state_dict["state"]:
1281
+ global_param_index = self._param_to_index[global_param]
1282
+ state_dict["state"][global_param_index] = local_state_dict[
1283
+ "state"
1284
+ ][local_param_index]
1285
+
1286
+ # Sort the parameters in the state
1287
+ state_dict["state"] = dict(sorted(state_dict["state"].items()))
1288
+ return state_dict
1289
+
1290
+ @staticmethod
1291
+ def _sync_param_groups(
1292
+ src_param_groups: list[dict[Any, Any]],
1293
+ dst_param_groups: list[dict[Any, Any]],
1294
+ ) -> None:
1295
+ r"""
1296
+ Sync the attributes from the source parameter groups to the destination parameter groups.
1297
+
1298
+ Example attributes include learning rate or scheduler attributes. The
1299
+ two parameter groups should have the same length (i.e. same number of
1300
+ parameter groups).
1301
+
1302
+ Arguments:
1303
+ src_param_groups (list[dict]): parameter groups giving the
1304
+ attribute settings to copy.
1305
+ dst_param_groups (list[dict]): parameter groups giving the
1306
+ attribute settings to set.
1307
+ """
1308
+ if len(src_param_groups) != len(dst_param_groups):
1309
+ raise AssertionError(
1310
+ "Mismatch between number of source and destination parameter groups"
1311
+ )
1312
+ for src_param_group, dst_param_group in zip(src_param_groups, dst_param_groups):
1313
+ # Sync all attributes except the parameters
1314
+ for attr in filter(lambda x: x != "params", src_param_group.keys()):
1315
+ dst_param_group[attr] = src_param_group[attr]
1316
+
1317
+ def _build_param_buckets(self) -> None:
1318
+ r"""
1319
+ Build parameter buckets if ``parameters_as_bucket_view=True``.
1320
+
1321
+ For each device that stores this rank's parameters, there is a
1322
+ bucket (represented as a tensor) containing all of the parameters on
1323
+ that device that are assigned to a given rank in the parameter update
1324
+ partition.
1325
+
1326
+ This method is called in the constructor and any time parameter
1327
+ trainability is changed.
1328
+
1329
+ .. warning::
1330
+ The current implementation assumes that all of the parameters in a
1331
+ bucket are of the same dense type when allocating the bucket's
1332
+ tensor.
1333
+
1334
+ .. warning::
1335
+ If the model parameters are stored across more than one device,
1336
+ then the storage partitioning must be the same across all
1337
+ processes in order for parameter synchronization to work.
1338
+ """
1339
+ if not self.parameters_as_bucket_view or self._overlap_with_ddp:
1340
+ return
1341
+
1342
+ # `self._buckets[i][j]` are the parameters stored on device i and
1343
+ # assigned to rank j
1344
+ num_devices = len(self._device_to_params_per_rank)
1345
+ self._buckets = [[] for _ in range(num_devices)] # type: ignore[assignment]
1346
+
1347
+ for dev_i, (device, params_per_rank) in enumerate(
1348
+ self._device_to_params_per_rank.items()
1349
+ ):
1350
+ for params in params_per_rank:
1351
+ bucket_size = 0
1352
+ dtype = None
1353
+ trainable_params = []
1354
+ for param in params:
1355
+ if not _is_trainable(param):
1356
+ # Clone in case the parameter was previously part of
1357
+ # a bucket to avoid the data from being destroyed
1358
+ param.data = param.data.detach().clone()
1359
+ else:
1360
+ bucket_size += param.numel()
1361
+ trainable_params.append(param)
1362
+ dtype = param.dtype # assumes all same dtype
1363
+
1364
+ if bucket_size == 0:
1365
+ # Create a dummy bucket if there are no parameters
1366
+ bucket = torch.zeros(1, device=device)
1367
+ else:
1368
+ # Construct the bucket (assuming all dense and same dtype)
1369
+ bucket = torch.empty(bucket_size, dtype=dtype, device=device)
1370
+ offset = 0
1371
+ for param in trainable_params:
1372
+ offset_next = offset + param.numel()
1373
+ bucket[offset:offset_next].copy_(param.data.flatten())
1374
+ param.data = bucket[offset:offset_next].view_as(param.data)
1375
+ offset = offset_next
1376
+ self._buckets[dev_i].append(bucket) # type: ignore[arg-type]
1377
+
1378
+ def _build_ddp_param_buckets(self) -> None:
1379
+ r"""
1380
+ Build the DDP bucket with parameters assigned to this rank.
1381
+
1382
+ For each DDP bucket with parameters assigned to this rank, flattens the
1383
+ data of those parameters into a single tensor and saves the tensor to
1384
+ the ``tensor`` attribute in the corresponding
1385
+ :class:`_DDPBucketAssignment` instance stored in
1386
+ ``self._bucket_assignments_per_rank``.
1387
+
1388
+ :class:`DistributedDataParallel` guarantees that the parameters
1389
+ corresponding to a gradient bucket have the same device and the same
1390
+ dtype.
1391
+ """
1392
+ for bucket_assignments in self._bucket_assignments_per_rank:
1393
+ for bucket_assignment in bucket_assignments.values():
1394
+ params = bucket_assignment.parameters
1395
+ bucket_size = 0
1396
+ dtype = None
1397
+ for param in params:
1398
+ if not _is_trainable(param):
1399
+ raise AssertionError(
1400
+ "Model parameter "
1401
+ "corresponding to a gradient in a DDP bucket should "
1402
+ "require a gradient"
1403
+ )
1404
+ bucket_size += param.numel()
1405
+ dtype = param.dtype # assumes all same dtype
1406
+ if bucket_size <= 0:
1407
+ raise AssertionError("Empty bucket")
1408
+
1409
+ # Construct the bucket tensor (assuming all dense and same dtype)
1410
+ tensor = torch.empty(
1411
+ bucket_size, dtype=dtype, device=bucket_assignment.device
1412
+ )
1413
+ offset = 0
1414
+ for param in params:
1415
+ offset_next = offset + param.numel()
1416
+ tensor[offset:offset_next].copy_(param.data.flatten())
1417
+ param.data = tensor[offset:offset_next].view_as(param.data)
1418
+ offset = offset_next
1419
+ bucket_assignment.tensor = tensor
1420
+
1421
+ def _verify_and_init_params(
1422
+ self,
1423
+ params: Any,
1424
+ ) -> list[torch.Tensor] | list[dict]:
1425
+ r"""
1426
+ Verify the type of ``params`` and initializes ``self._all_params`` as a :class:`list` of all parameters.
1427
+
1428
+ The initializagtion will first make sure that provided ``params`` is valid.
1429
+
1430
+ Arguments:
1431
+ params (Any): Candidate parameter list or parameter groups to verify.
1432
+
1433
+ Raises:
1434
+ TypeError: ``params`` has an invalid type.
1435
+ ValueError: ``params`` is empty.
1436
+
1437
+ Returns:
1438
+ The persistent form of ``params`` to be passed into the parent
1439
+ :class:`Optimizer` constructor -- i.e. returns ``params`` as a
1440
+ :class:`list` to ensure that it can be iterated over again.
1441
+ """
1442
+ if isinstance(params, torch.Tensor):
1443
+ raise TypeError(
1444
+ "`params` argument should be an iterable of "
1445
+ f"Tensors, but got {torch.typename(params)}"
1446
+ )
1447
+ try:
1448
+ all_params = list(params)
1449
+ except TypeError as e:
1450
+ raise TypeError(
1451
+ "`params` argument should be an iterable of Tensors"
1452
+ f" or dicts, but got {torch.typename(params)}"
1453
+ ) from e
1454
+ if len(all_params) == 0:
1455
+ raise ValueError("ZeroRedundancyOptimizer got an empty parameter list")
1456
+ all_tensors = True
1457
+ all_dicts = True
1458
+ for param in all_params:
1459
+ all_tensors &= isinstance(param, torch.Tensor)
1460
+ all_dicts &= isinstance(param, dict)
1461
+ if not all_tensors and not all_dicts:
1462
+ raise TypeError(
1463
+ "`params` argument should be an iterable of Tensors or dicts"
1464
+ )
1465
+ # Ensure that `self._all_params` contains a list of all parameters
1466
+ if all_tensors:
1467
+ self._all_params = all_params
1468
+ elif all_dicts:
1469
+ self._all_params = []
1470
+ # `all_params` contains parameter groups (not parameters)
1471
+ for param_group in all_params:
1472
+ if "params" not in param_group:
1473
+ raise ValueError(
1474
+ "Each parameter group passed-in via `params` must "
1475
+ "have a 'params' key mapping to the parameters in "
1476
+ "the group"
1477
+ )
1478
+ self._all_params.extend(param_group["params"])
1479
+ return all_params
1480
+
1481
+ def _verify_same_dense_param_type(self) -> None:
1482
+ r"""
1483
+ Verify that all parameters are of the same dense type.
1484
+
1485
+ The method assumes that ``self._all_params`` has been initialized
1486
+ and is non-empty.
1487
+
1488
+ Raises:
1489
+ ValueError: ``params`` contains sparse parameters or parameters
1490
+ of varying dense types.
1491
+
1492
+ NOTE: This method can be removed once support for sparse parameters
1493
+ and varying parameter types is added.
1494
+ """
1495
+ typename = torch.typename(self._all_params[0])
1496
+ if self._all_params[0].is_sparse:
1497
+ raise ValueError(
1498
+ "ZeroRedundancyOptimizer only supports using "
1499
+ "the same dense type for all parameters but got "
1500
+ f"{typename}"
1501
+ )
1502
+ for param in self._all_params[1:]:
1503
+ other_typename = torch.typename(param)
1504
+ if other_typename != typename:
1505
+ raise ValueError(
1506
+ "ZeroRedundancyOptimizer only supports "
1507
+ "using the same dense type for all "
1508
+ f"parameters but got both {typename} and "
1509
+ f"{other_typename}"
1510
+ )
1511
+
1512
+ def _get_is_trainable_mask(self) -> list[bool]:
1513
+ r"""Return a boolean mask indicating if each parameter is trainable (``requires_grad``) or not."""
1514
+ return list(map(_is_trainable, self._all_params))
1515
+
1516
+ def _init_local_optimizer(self) -> None:
1517
+ r"""
1518
+ Initialize this rank's local optimizer, responsible for its subset of the parameters.
1519
+
1520
+ The local optimizer is saved in ``self.optim``.
1521
+ """
1522
+ if self._optim_constructor is None:
1523
+ raise AssertionError("The local optimizer class has not been set")
1524
+
1525
+ param_groups = self._partition_parameters()[self.rank]
1526
+ # `overlap_with_ddp=True` requires a local functional optimizer
1527
+ if self._overlap_with_ddp:
1528
+ # Functional optimizers only support a single parameter group and
1529
+ # require passing in the parameters as a list
1530
+ if len(param_groups) != 1:
1531
+ raise AssertionError(
1532
+ "Initializing the local functional optimizer "
1533
+ "with more than one parameter group"
1534
+ )
1535
+ params = param_groups[0]["params"]
1536
+ # Try to pass `_allow_empty_param_list=True` to avoid erroring
1537
+ if (
1538
+ "_allow_empty_param_list"
1539
+ in inspect.signature(self._optim_constructor).parameters
1540
+ ):
1541
+ self.optim: Any = self._optim_constructor(
1542
+ params, **self._optim_defaults, _allow_empty_param_list=True
1543
+ )
1544
+ else:
1545
+ logger.warning(
1546
+ "%s does not support the argument "
1547
+ "`_allow_empty_param_list`; ZeroRedundancyOptimizer may "
1548
+ "error due to an empty parameter list",
1549
+ self._optim_constructor,
1550
+ )
1551
+ self.optim: Any = self._optim_constructor(
1552
+ params, **self._optim_defaults
1553
+ ) # type: ignore[no-redef]
1554
+
1555
+ # Log information about the DDP and ZeRO bucketing
1556
+ if dist.get_debug_level() != dist.DebugLevel.OFF:
1557
+ local_numel = sum(p.numel() for p in params)
1558
+ num_assigned_buckets = len(
1559
+ self._bucket_assignments_per_rank[self.global_rank]
1560
+ )
1561
+ logger.info(
1562
+ "rank %s with %s parameters across %s buckets",
1563
+ self.global_rank,
1564
+ local_numel,
1565
+ num_assigned_buckets,
1566
+ )
1567
+ if self.global_rank == 0:
1568
+ logger.info(
1569
+ "%s DDP buckets and %s bucket assignments",
1570
+ len(self._overlap_info.params_per_bucket),
1571
+ self._overlap_info.num_bucket_assignments,
1572
+ )
1573
+ else:
1574
+ # NOTE: Passing `param_groups` into the local optimizer constructor
1575
+ # bypasses the empty parameter list check
1576
+ self.optim: Optimizer = self._optim_constructor(
1577
+ param_groups, **self._optim_defaults
1578
+ ) # type: ignore[no-redef]
1579
+
1580
+ # TODO: Manually add `self.param_groups` if using a functional
1581
+ # optimizer; remove this if/when the functional optimizers support
1582
+ # multiple parameter groups
1583
+ if self._overlap_with_ddp and not hasattr(self.optim, "param_groups"):
1584
+ if not hasattr(self.optim, "param_group"):
1585
+ raise AssertionError(
1586
+ "The functional optimizer should set at least one of "
1587
+ "the attributes `param_group` or `param_groups`"
1588
+ )
1589
+ self.optim.param_groups = [self.optim.param_group] # type: ignore[attr-defined]
1590
+
1591
+ self._sync_param_groups(self.optim.param_groups, self.param_groups)
1592
+
1593
+ def _init_zero_for_overlap(self) -> None:
1594
+ r"""Perform a delayed initialization of the local optimizer and the supporting data structures."""
1595
+ if not self._overlap_with_ddp:
1596
+ raise AssertionError(
1597
+ "`_init_zero_for_overlap()` should only be called when "
1598
+ "`overlap_with_ddp=True`"
1599
+ )
1600
+ self._overlap_info.status = _OverlapStatus.INITIALIZED
1601
+ self._clear_cache()
1602
+ self._partition_parameters(self._overlap_info.params_per_rank)
1603
+ self._build_ddp_param_buckets()
1604
+ self._init_local_optimizer()
1605
+
1606
+ def _get_assigned_rank(self, bucket_index: int) -> int:
1607
+ r"""
1608
+ Return the single rank assigned to a :class:`DistributedDataParallel` gradient bucket.
1609
+
1610
+ Arguments:
1611
+ bucket_index (int): index of the :class:`DistributedDataParallel`
1612
+ bucket for which to get the assigned rank.
1613
+ """
1614
+ if self._overlap_info.shard_buckets:
1615
+ raise AssertionError(
1616
+ "The bucket assignment requires global bucket information "
1617
+ "and will be computed later; there should be no need to "
1618
+ "use this method"
1619
+ )
1620
+ return bucket_index % self.world_size
1621
+
1622
+ def _check_overlap_initialized(self):
1623
+ r"""
1624
+ Check the delayed initialization depending on the value of ``overlap_with_ddp``.
1625
+
1626
+ The delayed initialization has occurred (see
1627
+ :meth:`_init_zero_for_overlap`) if ``overlap_with_ddp=True``, and
1628
+ raises a ``RuntimeError`` if not. This should preface methods that
1629
+ should not be run before that delayed initialization.
1630
+
1631
+ Raises:
1632
+ RuntimeError: if ``overlap_with_ddp=True`` and
1633
+ :meth:`_init_zero_for_overlap` has not been called.
1634
+ """
1635
+ if (
1636
+ self._overlap_with_ddp
1637
+ and self._overlap_info.status != _OverlapStatus.INITIALIZED
1638
+ ):
1639
+ raise RuntimeError(
1640
+ "This method should not be called until this "
1641
+ "ZeroRedundancyOptimizer instance has been fully "
1642
+ "initialized"
1643
+ )
1644
+
1645
+ def _get_optimizer_constructor(self, optimizer_class: Any) -> Any:
1646
+ r"""
1647
+ Return the optimizer constructor using validation and transformation depending on ``overlap_with_ddp``.
1648
+
1649
+ Returns:
1650
+ - ``optimizer_class`` if ``overlap_with_ddp=False`` and
1651
+ ``optimizer_class`` is not a functional optimizer.
1652
+ - ``optimizer_class`` if ``overlap_with_ddp=True`` and
1653
+ ``optimizer_class`` is already a functional optimizer.
1654
+ - The functional equivalent of ``optimizer_class`` if
1655
+ ``overlap_with_ddp=True`` and ``optimizer_class`` is not
1656
+ already a functional optimizer (assuming the equivalent
1657
+ exists).
1658
+
1659
+ Raises:
1660
+ ValueError:
1661
+
1662
+ - if ``overlap_with_ddp=True`` but ``optimizer_class`` is
1663
+ neither a functional optimizer nor translatable to a
1664
+ functional optimizer.
1665
+ - if ``overlap_with_ddp=False`` and ``optimizer_class`` is a
1666
+ functional optimizer.
1667
+ """
1668
+ functional_optims = functional_optim_map.values()
1669
+ if not self._overlap_with_ddp:
1670
+ if optimizer_class in functional_optims:
1671
+ # Using a functional optimizer is only supported when
1672
+ # `overlap_with_ddp=True`
1673
+ raise ValueError(
1674
+ f"Passing in a functional optimizer {optimizer_class} "
1675
+ "when `overlap_with_ddp=False`"
1676
+ )
1677
+ else:
1678
+ return optimizer_class
1679
+ else:
1680
+ if optimizer_class in functional_optims:
1681
+ # Already a functional optimizer
1682
+ return optimizer_class
1683
+ elif optimizer_class in functional_optim_map:
1684
+ # Translate the passed-in optimizer class to its functional
1685
+ # equivalent if `overlap_with_ddp=True`
1686
+ optim_constructor = functional_optim_map[optimizer_class]
1687
+ logger.info(
1688
+ "Using the functional optimizer %s "
1689
+ "instead of %s since "
1690
+ "`overlap_with_ddp=True`",
1691
+ optim_constructor,
1692
+ optimizer_class,
1693
+ )
1694
+ return optim_constructor
1695
+ else:
1696
+ raise ValueError(
1697
+ "Using `ddp_with_overlap=True` requires using a "
1698
+ "functional optimizer, but there is no supported functional "
1699
+ f"optimizer equivalent for {optimizer_class}"
1700
+ )
venv/lib/python3.14/site-packages/torch/distributed/optim/zero_redundancy_optimizer.pyi ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import enum
3
+ from collections.abc import Callable
4
+ from typing import Any, overload
5
+
6
+ import torch
7
+ from torch.distributed.algorithms.join import Joinable, JoinHook
8
+ from torch.optim import Optimizer
9
+
10
+ class _ZeROJoinHook(JoinHook):
11
+ zero: Any = ...
12
+ def __init__(self, zero: Any) -> None: ...
13
+ def main_hook(self) -> None: ...
14
+
15
+ class _DDPBucketAssignment:
16
+ bucket_index: int
17
+ parameters: list[torch.Tensor]
18
+ offset: int
19
+ device: torch.device
20
+ tensor: torch.Tensor | None
21
+
22
+ class _OverlapStatus(enum.IntEnum):
23
+ UNINITIALIZED = ...
24
+ DDP_HAS_REBUILT_BUCKETS = ...
25
+ INITIALIZED = ...
26
+
27
+ class _OverlapInfo:
28
+ status: Any = ...
29
+ params_per_bucket: Any = ...
30
+ params_per_rank: Any = ...
31
+ offsets: Any = ...
32
+ broadcast_handles: Any = ...
33
+ bucket_index_to_future: Any = ...
34
+ bucket_index_to_bucket: Any = ...
35
+ bucket_indices_seen: Any = ...
36
+ assigned_ranks_per_bucket: list[set[int]] = ...
37
+ total_size: int = ...
38
+ shard_buckets: bool = ...
39
+ def __init__(self) -> None: ...
40
+ def wait_for_broadcasts(self) -> None: ...
41
+ def clear_per_iter_info(self) -> None: ...
42
+
43
+ class ZeroRedundancyOptimizer(Optimizer, Joinable):
44
+ functional_optim_map: Any = ...
45
+ initialized: bool = ...
46
+ process_group: Any = ...
47
+ world_size: int = ...
48
+ rank: int = ...
49
+ global_rank: int = ...
50
+ parameters_as_bucket_view: bool = ...
51
+ optim: Any = ...
52
+ _device_to_device_index: dict[torch.device, int] = ...
53
+ _overlap_with_ddp: bool = ...
54
+ _overlap_info: _OverlapInfo = ...
55
+ _buckets: list[list[torch.Tensor]] = ...
56
+ _bucket_assignments_per_rank: list[dict[int, _DDPBucketAssignment]] = ...
57
+ def __init__(
58
+ self,
59
+ params: Any,
60
+ optimizer_class: type[Optimizer],
61
+ process_group: Any | None = ...,
62
+ parameters_as_bucket_view: bool = ...,
63
+ overlap_with_ddp: bool = ...,
64
+ **defaults: Any,
65
+ ) -> None: ...
66
+ def add_param_group(self, param_group: dict[str, Any]) -> None: ...
67
+ def consolidate_state_dict(self, to: int = ...) -> None: ...
68
+ @overload
69
+ def step(self, closure: None = None, **kwargs: Any) -> None: ...
70
+ @overload
71
+ def step(self, closure: Callable[[], float], **kwargs: Any) -> float: ...
72
+ def load_state_dict(self, state_dict: dict[str, Any]) -> None: ...
73
+ def state_dict(self) -> dict[str, Any]: ...
74
+ def _local_step(
75
+ self,
76
+ gradients: list[torch.Tensor | None] | None = None,
77
+ closure: Callable[[], float] | None = None,
78
+ **kwargs: Any,
79
+ ) -> float | None: ...
80
+ def _get_assigned_rank(self, bucket_index: int) -> int: ...
81
+ def _init_zero_for_overlap(self) -> None: ...
82
+ def join_hook(self, **_kwargs: Any) -> JoinHook: ...
83
+ @property
84
+ def join_device(self) -> torch.device: ...
85
+ def join_process_group(self) -> Any: ...
venv/lib/python3.14/site-packages/torch/distributed/pipelining/_IR.py ADDED
@@ -0,0 +1,1274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates
3
+ import copy
4
+ import logging
5
+ import operator
6
+ from collections import defaultdict
7
+ from collections.abc import Callable
8
+ from enum import Enum
9
+ from inspect import Parameter, Signature, signature
10
+ from types import MethodType
11
+ from typing import Any
12
+
13
+ import torch
14
+ import torch.fx as fx
15
+ from torch.distributed import ProcessGroup
16
+ from torch.export import ExportedProgram
17
+ from torch.export.unflatten import (
18
+ _assign_attr,
19
+ _AttrKind,
20
+ _sink_params,
21
+ InterpreterModule,
22
+ )
23
+ from torch.fx.node import map_aggregate
24
+ from torch.fx.passes.split_module import split_module
25
+
26
+ from ._backward import _null_coalesce_accumulate, stage_backward
27
+ from ._unflatten import _outline_submodules
28
+ from ._utils import PipeInfo
29
+ from .stage import _PipelineStage
30
+
31
+
32
+ logger = logging.getLogger(__name__)
33
+
34
+ # TODO:
35
+ # 1. investigate gradient sync for shared parameters. how does DDP do it?
36
+ # 2. Add parameter movement to split_module
37
+
38
+
39
+ PP_SUBMOD_PREFIX = "submod_pp"
40
+
41
+
42
+ def get_submod_name(stage_idx: int):
43
+ """Returns the name of the submod for a given stage index.
44
+ For example, "submod_pp_0", "submod_pp_1", etc.
45
+ """
46
+ return "_".join([PP_SUBMOD_PREFIX, str(stage_idx)])
47
+
48
+
49
+ def _find_loss_from_output_and_spec(output_val, spec_val):
50
+ if spec_val is False:
51
+ return None
52
+ if spec_val is True:
53
+ if not isinstance(output_val, fx.Node):
54
+ raise RuntimeError(
55
+ f"Loss spec must specify a dynamic value but got {output_val}"
56
+ )
57
+ return output_val
58
+
59
+ if isinstance(spec_val, (tuple, list)):
60
+ if not isinstance(output_val, (tuple, list)):
61
+ raise RuntimeError(
62
+ f"Output value {output_val} must match type of loss specification "
63
+ f"{spec_val}"
64
+ )
65
+ if len(output_val) != len(spec_val):
66
+ raise RuntimeError(
67
+ f"Output value {output_val} must match length of loss specification "
68
+ f"{spec_val}"
69
+ )
70
+ for out, spec in zip(output_val, spec_val):
71
+ loss_val = _find_loss_from_output_and_spec(out, spec)
72
+ if loss_val is not None:
73
+ return loss_val
74
+ raise RuntimeError(f"Did not find loss value in specification {spec_val}")
75
+
76
+ if isinstance(spec_val, dict):
77
+ if not isinstance(output_val, dict):
78
+ raise RuntimeError(
79
+ f"Output value {output_val} must match type of loss specification "
80
+ f"{spec_val}"
81
+ )
82
+ if set(output_val.keys()) != set(spec_val.keys()):
83
+ raise RuntimeError(
84
+ f"Output value {output_val} must match keys of loss specification "
85
+ f"{spec_val}"
86
+ )
87
+ for k in spec_val:
88
+ loss_val = _find_loss_from_output_and_spec(output_val[k], spec_val[k])
89
+ if loss_val is not None:
90
+ return loss_val
91
+ raise RuntimeError(f"Did not find loss value in specification {spec_val}")
92
+
93
+ raise RuntimeError(f"Unsupported type {type(spec_val)} in loss specification")
94
+
95
+
96
+ def _find_loss_output(mod: torch.nn.Module, g: fx.Graph, output_loss_value_spec):
97
+ output_nodes = [n for n in g.nodes if n.op == "output"]
98
+ if not len(output_nodes) == 1:
99
+ raise AssertionError(f"Expected 1 output node, got {len(output_nodes)}")
100
+ output_node = output_nodes[0]
101
+ output_val = output_node.args[0]
102
+ generated_spec: Any = None
103
+
104
+ if isinstance(mod, TrivialLossWrapper):
105
+ # TrivialLossWrapper is pre-defined by PiPPy.
106
+ # It has loss as the only output so we can safely assume the first output arg is the loss.
107
+ if not len(output_node.args) == 1:
108
+ raise AssertionError(f"Expected 1 output arg, got {len(output_node.args)}")
109
+ loss_node = output_val
110
+ generated_spec = TrivialLossWrapper.loss_spec
111
+ elif output_loss_value_spec is None:
112
+ # Use default spec, i.e. search for "loss" in output values
113
+ if isinstance(output_val, dict) and "loss" in output_val:
114
+ loss_node = output_val["loss"]
115
+ generated_spec = {k: k == "loss" for k in output_val}
116
+ else:
117
+ loss_node = None
118
+ generated_spec = None
119
+ else:
120
+ loss_node = _find_loss_from_output_and_spec(output_val, output_loss_value_spec)
121
+ generated_spec = output_loss_value_spec
122
+
123
+ return loss_node, output_node, generated_spec
124
+
125
+
126
+ def _insert_stage_symbolic_backward(
127
+ g: fx.Graph,
128
+ loss_node: fx.Node,
129
+ output_node: fx.Node,
130
+ ):
131
+ # Collect metadata about tuple output values. TODO: move this to split_module or FX IR
132
+ tuples: dict[fx.Node, tuple] = {}
133
+ for node in reversed(g.nodes):
134
+ if node.op == "call_function":
135
+ # In the forward pass, only emit placeholder, module calls, and
136
+ # getitem calls. If we have a target other than getitem in this
137
+ # (forward-only) code, there is a bug.
138
+ if not node.target == operator.getitem:
139
+ raise AssertionError(
140
+ "Found non-getitem call in forward pass. Please report a bug to PiPPy"
141
+ )
142
+ if not len(node.args) == 2:
143
+ raise AssertionError(
144
+ "Found malformed getitem call. Please report a bug to PiPPy"
145
+ )
146
+ indexed_value, node_idx = tuple(node.args)
147
+
148
+ # indexed_value is a collection that we are indexing into. It could
149
+ # exist in the tuples map if we've processed another `getitem`
150
+ # already.
151
+ existing_list_size = (
152
+ len(tuples[indexed_value]) if indexed_value in tuples else -1
153
+ )
154
+ new_list_size = max(node_idx + 1, existing_list_size)
155
+
156
+ reconstructed_list = [None for _ in range(new_list_size)]
157
+
158
+ # Copy over existing elements if present
159
+ if indexed_value in tuples:
160
+ for i, val in enumerate(tuples[indexed_value]):
161
+ reconstructed_list[i] = val
162
+
163
+ # Populate value represented by this node
164
+ reconstructed_list[node_idx] = node
165
+
166
+ tuples[indexed_value] = tuple(reconstructed_list)
167
+
168
+ # Keep track of nodes that dominate the loss node.
169
+ # We will only emit backward operations for nodes that can contribute
170
+ # to the specified loss value.
171
+ live_nodes = {loss_node: None}
172
+ val_to_grad: dict[fx.Node, fx.Node | None] = {loss_node: None}
173
+
174
+ def assign_or_accumulate_grad(forward_node, grad_value):
175
+ if forward_node in val_to_grad and forward_node.op != "placeholder":
176
+ grad_value = g.call_function(
177
+ _null_coalesce_accumulate,
178
+ (val_to_grad[forward_node], grad_value),
179
+ )
180
+ val_to_grad[forward_node] = grad_value
181
+
182
+ with g.inserting_before(output_node):
183
+ for node in reversed(g.nodes):
184
+ if node not in live_nodes:
185
+ continue
186
+
187
+ def add_to_live_nodes(n):
188
+ live_nodes.setdefault(n, None)
189
+
190
+ fx.node.map_arg(node.args, add_to_live_nodes)
191
+ fx.node.map_arg(node.kwargs, add_to_live_nodes)
192
+ if node.op == "call_module":
193
+ output_grads: tuple[fx.Node | None, ...] | fx.Node | None
194
+ if node in tuples:
195
+ stage_output = tuples[node]
196
+ output_grads = tuple(val_to_grad.get(n) for n in tuples[node])
197
+ outputs_with_grads_idxs = [
198
+ i for i, n in enumerate(tuples[node]) if n in live_nodes
199
+ ]
200
+ else:
201
+ stage_output = (node,)
202
+ output_grads = val_to_grad[node]
203
+ outputs_with_grads_idxs = [0]
204
+
205
+ output_grads = (
206
+ (output_grads,)
207
+ if not isinstance(output_grads, tuple)
208
+ else output_grads
209
+ )
210
+
211
+ grad_call = g.call_function(
212
+ stage_backward,
213
+ kwargs={
214
+ "stage_output": stage_output,
215
+ "output_grads": output_grads,
216
+ "input_values": list(node.all_input_nodes),
217
+ "outputs_with_grads_idxs": outputs_with_grads_idxs,
218
+ },
219
+ )
220
+ # Insert backward stage debug info
221
+ kwargs_copy = dict(grad_call.kwargs)
222
+ grad_call.kwargs = kwargs_copy
223
+
224
+ grad_call_proxy = fx.Proxy(grad_call)
225
+ grads = grad_call_proxy.node
226
+
227
+ input_nodes = list(node.all_input_nodes)
228
+ grads_proxy = fx.Proxy(grads)
229
+ for i, input_node in enumerate(input_nodes):
230
+ assign_or_accumulate_grad(input_node, grads_proxy[i].node) # type: ignore[index]
231
+
232
+ return g
233
+
234
+
235
+ class PipeSequential(torch.nn.Sequential):
236
+ @staticmethod
237
+ def from_sequential(sequential_instance: torch.nn.Sequential):
238
+ return PipeSequential(*[copy.copy(m) for m in sequential_instance])
239
+
240
+ def forward(self, input):
241
+ for i, module in enumerate(self):
242
+ input = module(input)
243
+ if i != len(self) - 1:
244
+ pipe_split()
245
+ return input
246
+
247
+
248
+ class LossWrapper(torch.nn.Module):
249
+ """
250
+ LossWrapper is a convenient abstract class that allows you to wrap up both
251
+ your model as well as its loss function and specify the connectivity between
252
+ the inputs, model, loss function, and output value. Example::
253
+
254
+ class MyModelWrapper(LossWrapper):
255
+ def forward(self, x, targets):
256
+ model_out = self.module(x)
257
+ loss_value = self.loss_fn(model_out, targets)
258
+ return loss_value
259
+
260
+ The above example defines a connectivity where we expect the forward/loss/backward
261
+ training procedure to take two arguments (x and targets), pass x into the module
262
+ to get the output of the feedforward computation, pass the model output and the
263
+ targets value into the loss function, and get and return the loss value, which will
264
+ be backpropagated by PiPPy. The above class would then be instantiated like::
265
+
266
+ model = ... # instantiate the model
267
+ loss_fn = torch.nn.MSELoss() # for the sake of demonstration
268
+
269
+ wrapper = MyModelWrapper(model, loss_fn)
270
+ pipe = Pipe.from_tracing(wrapper, ...)
271
+
272
+ """
273
+
274
+ def __init__(self, module, loss_fn):
275
+ super().__init__()
276
+ self.module = module
277
+ self.loss_fn = loss_fn
278
+
279
+ def forward(self, *args, **kwargs):
280
+ raise NotImplementedError(
281
+ "This instance of LossWrapper does not have an overridden"
282
+ "forward(). Please implement forward() to specify the arguments, "
283
+ "connection between the module and loss, and loss output "
284
+ "value."
285
+ )
286
+
287
+
288
+ class TrivialLossWrapper(LossWrapper):
289
+ # pyrefly: ignore [bad-override]
290
+ def forward(self, x, targets):
291
+ model_out = self.module(x)
292
+ return self.loss_fn(model_out, targets)
293
+
294
+ loss_spec = True
295
+
296
+
297
+ # Pipe model representation
298
+ #
299
+ # Pipe can be thought of as an `nn.Sequential++`. That is to say: it specifies
300
+ # a single topological ordering of pipeline "stages" that, when run in series,
301
+ # constitutes all of the operations of the program. However, unlike `nn.Sequential`,
302
+ # Pipe allows non-local usages of values, so long as those uses still respect
303
+ # topological ordering. In particular:
304
+ #
305
+ # 1. Non-local activations. This type of usage can appear in, for example, skip
306
+ # connections. These values will be directly transmitted from the "def" stage
307
+ # to all stages that use them skipping intermediate stages. During autograd,
308
+ # gradients will be propagated back through this skip connection reverse
309
+ # to how activations propagated in the forward pass.
310
+ # 2. Non-local parameter/module invocations. This occurs when a parameter is used
311
+ # in a stage downstream of where it is resident. These values can be carried
312
+ # forward similarly to (1), but in addition one might want to replicate the
313
+ # value on multiple stages. Gradients for these shared parameters will be
314
+ # accumulated separately on each stage, but there will be an additional
315
+ # gradient accumulation before the optimizer step.
316
+
317
+
318
+ # Register `_pipe_split()` as an ATen operator. This is required for Export to
319
+ # preserve this marker in the graph.
320
+ torch.library.define("pippy::_pipe_split", "() -> ()")
321
+
322
+
323
+ @torch.library.impl("pippy::_pipe_split", "BackendSelect")
324
+ def _pipe_split():
325
+ return None
326
+
327
+
328
+ @torch.library.register_fake("pippy::_pipe_split") # type: ignore[no-redef]
329
+ def _pipe_split(): # noqa: F811
330
+ return None
331
+
332
+
333
+ # Add an alias for convenience
334
+ aten_pipe_split_alias = torch.ops.pippy._pipe_split.default
335
+
336
+ # Ask Export to preserve the `_pipe_split` op.
337
+ # See examples in pytorch/torch/fx/node.py
338
+ fx.node._side_effectful_functions.add(aten_pipe_split_alias)
339
+
340
+
341
+ # User facing API
342
+ def pipe_split():
343
+ """
344
+ pipe_split is a special operator that is used to mark the boundary between
345
+ stages in a module. It is used to split the module into stages. It is a
346
+ no-op if your annotated module is run eagerly.
347
+
348
+ Example:
349
+ >>> # xdoctest: +SKIP
350
+ >>> def forward(self, x):
351
+ >>> x = torch.mm(x, self.mm_param)
352
+ >>> x = torch.relu(x)
353
+ >>> pipe_split()
354
+ >>> x = self.lin(x)
355
+ >>> return x
356
+
357
+ The above example will be split into two stages.
358
+ """
359
+ return torch.ops.pippy._pipe_split()
360
+
361
+
362
+ class MultiUseParameterConfig(Enum):
363
+ TRANSMIT = 1
364
+ REPLICATE = 2
365
+
366
+
367
+ MultiUseParamSpec = MultiUseParameterConfig | dict[str, MultiUseParameterConfig]
368
+
369
+
370
+ class DetachExecutor(fx.Interpreter):
371
+ """
372
+ Special interpreter to run the split_gm in testing that detaches all inputs to
373
+ a module invocation. This is needed so that the values at the boundary are
374
+ leaf modules in autograd execution.
375
+ """
376
+
377
+ def __init__(self, module, garbage_collect_values=True):
378
+ garbage_collect_values = False
379
+ super().__init__(module, garbage_collect_values)
380
+ self.value_remap = {}
381
+
382
+ def run(self, *args, initial_env=None): # type: ignore[override]
383
+ self.value_remap = {}
384
+ return super().run(*args, initial_env=initial_env)
385
+
386
+ def call_module(self, target, args, kwargs):
387
+ def detach_tensors(a):
388
+ if isinstance(a, torch.Tensor) and a.requires_grad:
389
+ if a not in self.value_remap:
390
+ new_val = a.detach().requires_grad_(True)
391
+ self.value_remap[a] = new_val
392
+ return self.value_remap[a]
393
+ else:
394
+ return a
395
+
396
+ """
397
+ def dont_traverse_size(a):
398
+ return type(a) is not torch.Size
399
+ """
400
+
401
+ args = map_aggregate(
402
+ args,
403
+ detach_tensors, # dont_traverse_size
404
+ )
405
+ kwargs = map_aggregate(
406
+ kwargs,
407
+ detach_tensors, # dont_traverse_size
408
+ )
409
+
410
+ return super().call_module(target, args, kwargs)
411
+
412
+ def call_function(self, target, args, kwargs):
413
+ # HACK to reroute saved input tensors to point to the detach()ed version
414
+ if target is stage_backward:
415
+ kwargs = dict(kwargs)
416
+ kwargs["input_values"] = [
417
+ self.value_remap.get(v, v) for v in kwargs["input_values"]
418
+ ]
419
+ return super().call_function(target, args, kwargs)
420
+
421
+
422
+ class _NodeReference:
423
+ def __init__(self, name):
424
+ self.name = name
425
+
426
+ name: str
427
+
428
+
429
+ class _LinearNodeList:
430
+ def __init__(self, node_list):
431
+ self.serialize_node_list = []
432
+ for node in node_list:
433
+ node_args = fx.node.map_arg(node.args, lambda n: _NodeReference(n.name)) # type: ignore[arg-type,return-value]
434
+ node_kwargs = fx.node.map_arg(node.kwargs, lambda n: _NodeReference(n.name)) # type: ignore[arg-type,return-value]
435
+ serialize_node = fx.Node(
436
+ graph=None, # type: ignore[arg-type]
437
+ name=node.name,
438
+ op=node.op,
439
+ target=node.target,
440
+ args=node_args, # type: ignore[arg-type]
441
+ kwargs=node_kwargs, # type: ignore[arg-type]
442
+ return_type=node.type,
443
+ )
444
+ serialize_node.meta = copy.copy(node.meta)
445
+ self.serialize_node_list.append(serialize_node)
446
+
447
+ def to_graph(self):
448
+ graph = fx.Graph()
449
+
450
+ ref_str_to_node: dict[str, fx.Node] = {}
451
+
452
+ def ref_to_node(arg):
453
+ if isinstance(arg, _NodeReference):
454
+ return ref_str_to_node[arg.name]
455
+ else:
456
+ return arg
457
+
458
+ for node in self.serialize_node_list:
459
+ node_args = map_aggregate(node.args, ref_to_node)
460
+ node_kwargs = map_aggregate(node.kwargs, ref_to_node)
461
+ deser_node = graph.create_node(
462
+ op=node.op,
463
+ target=node.target,
464
+ args=node_args, # type: ignore[arg-type]
465
+ kwargs=node_kwargs, # type: ignore[arg-type]
466
+ name=node.name,
467
+ type_expr=node.type,
468
+ )
469
+ ref_str_to_node[node.name] = deser_node
470
+
471
+ return graph
472
+
473
+
474
+ def _direct_serialization_deserialize(body, nodes):
475
+ """
476
+ Custom `__reduce__` method for serialization.
477
+ DO AS I SAY -- NOT AS I DO. This violates the principle that
478
+ GraphModules serialize via code export & re-tracing. We allow
479
+ for this here because **PIPE STAGES SHOULD NOT BE PERSISTED
480
+ TO DISK -- THIS IS ONLY FOR TRANSMISSION VIA RPC**. Persisting
481
+ these instances to disk will expose internal implementation
482
+ details of `fx.Graph` and related data structures and is
483
+ NOT advised.
484
+ """
485
+
486
+ class DummyModule(torch.nn.Module):
487
+ def __init__(self, body):
488
+ super().__init__()
489
+ self.__dict__.update(body)
490
+
491
+ dummy = DummyModule(body)
492
+
493
+ return fx.GraphModule(dummy, nodes.to_graph())
494
+
495
+
496
+ def _direct_serialization_reduce(self):
497
+ serialization_dict = dict(self.__dict__)
498
+ serialization_dict.pop("_graph")
499
+ return (
500
+ _direct_serialization_deserialize,
501
+ (serialization_dict, _LinearNodeList(self.graph.nodes)),
502
+ )
503
+
504
+
505
+ def _modify_graph_op_device(
506
+ gm: torch.fx.GraphModule,
507
+ new_device: torch.device,
508
+ ):
509
+ """
510
+ Modify the device argument of all "call_function" nodes in the graph. This
511
+ is useful for moving the graph to a different device. In particular for
512
+ generator ops, like torch.ones.
513
+ """
514
+ modified = False
515
+ for node in gm.graph.nodes:
516
+ if node.op == "call_function":
517
+ if "device" in node.kwargs and node.kwargs["device"] != new_device:
518
+ logger.debug(
519
+ f"Changing device of Node {node.name} from {node.kwargs['device']} to {new_device}" # noqa: G004
520
+ )
521
+ node.update_kwarg("device", new_device)
522
+ modified = True
523
+ elif node.op == "call_module":
524
+ # Recursively modify "device" in submodules
525
+ submod = gm.get_submodule(node.target)
526
+ if isinstance(submod, torch.fx.GraphModule):
527
+ _modify_graph_op_device(submod, new_device)
528
+ elif isinstance(submod, InterpreterModule):
529
+ # If unflattening has been performed, we need to access its graph module by `.graph_module`
530
+ _modify_graph_op_device(submod.graph_module, new_device) # type: ignore[arg-type]
531
+ else:
532
+ logger.warning(
533
+ f"Skipping device modification for submodule {node.target} because it is a {type(submod)}" # noqa: G004
534
+ )
535
+
536
+ if modified:
537
+ gm.recompile()
538
+
539
+
540
+ class Pipe(torch.nn.Module):
541
+ def __init__(
542
+ self,
543
+ split_gm: fx.GraphModule,
544
+ num_stages: int,
545
+ has_loss_and_backward: bool,
546
+ loss_spec,
547
+ ):
548
+ # TODO: is there a way not to hard wire init?
549
+ torch.nn.Module.__init__(self)
550
+ self.split_gm: fx.GraphModule = split_gm
551
+ self.executor: DetachExecutor = DetachExecutor(self.split_gm)
552
+ self.num_stages: int = num_stages
553
+ self.has_loss_and_backward = has_loss_and_backward
554
+ self.loss_spec = loss_spec
555
+
556
+ for node in split_gm.graph.nodes:
557
+ if not (
558
+ node.op in {"call_module", "placeholder", "output"}
559
+ or (node.op, node.target) == ("call_function", operator.getitem)
560
+ or (node.op, node.target) == ("call_method", "backward")
561
+ or (node.op, node.target) == ("call_function", stage_backward)
562
+ or (node.op, node.target)
563
+ == ("call_function", _null_coalesce_accumulate)
564
+ ):
565
+ raise AssertionError(f"Unexpected node: {node}")
566
+
567
+ # Detect replicated parameters so we know that we have to do an additional allreduce
568
+ # before applying the optimizer
569
+ #
570
+ # Note that this also handles the case where there were multiple calls to a single
571
+ # module from different stages, regardless of whether that module invocation
572
+ # was handled by the logic above.
573
+
574
+ # Map parameter value to a dictionary that maps the user pipeline module
575
+ # to the local qualname within that module
576
+ params_to_users: dict[torch.nn.Parameter, dict[str, str]] = {}
577
+
578
+ for m_qualname, mod in self.split_gm.named_children():
579
+ for p_qualname, param in mod.named_parameters():
580
+ params_to_users.setdefault(param, {})
581
+ params_to_users[param][m_qualname] = p_qualname
582
+
583
+ self.replicated_params: list[dict[str, str]] = [
584
+ use_mapping
585
+ for _, use_mapping in params_to_users.items()
586
+ if len(use_mapping) > 1
587
+ ]
588
+
589
+ # We must break the aliasing relationship between the replicated parameters for correct
590
+ # numerics in reference runs. If we do not do this, the autograd tape in separate stages
591
+ # will have a reference to the same tensor value and will erroneously apply gradient
592
+ # updates multiple times. Therefore, for each replicated parameter set, we deepcopy the
593
+ # values so that we have separate instances.
594
+ for param_mapping in self.replicated_params:
595
+ for submod_name, param_qualname in param_mapping.items():
596
+ submod = getattr(self.split_gm, submod_name)
597
+ atoms = param_qualname.split(".")
598
+ for atom in atoms[:-1]:
599
+ submod = getattr(submod, atom)
600
+ setattr(submod, atoms[-1], copy.deepcopy(getattr(submod, atoms[-1])))
601
+
602
+ def throw(self, *args, **kwargs):
603
+ raise RuntimeError(
604
+ "To run pipeline locally, invoke the Pipe object directly, not `split_gm`"
605
+ )
606
+
607
+ self.split_gm.forward = throw
608
+
609
+ # Make submodules use custom direct-serialized GraphModule
610
+ i = 0
611
+ while True:
612
+ try:
613
+ name = get_submod_name(i)
614
+ submod = getattr(self.split_gm, name)
615
+ submod.__class__.__reduce__ = _direct_serialization_reduce
616
+ i += 1
617
+ except AttributeError:
618
+ break
619
+
620
+ def forward(self, *args, **kwargs):
621
+ executor_args = args
622
+ if len(kwargs) > 0:
623
+ parameters = []
624
+ for node in self.split_gm.graph.nodes:
625
+ if node.op == "placeholder":
626
+ if node.args and len(node.args) > 0:
627
+ parameters.append(
628
+ Parameter(
629
+ node.target,
630
+ Parameter.POSITIONAL_OR_KEYWORD,
631
+ default=node.args[0],
632
+ )
633
+ )
634
+ else:
635
+ parameter_kind = Parameter.POSITIONAL_OR_KEYWORD
636
+ param_name = node.target
637
+ if node.target.startswith("**"):
638
+ parameter_kind = Parameter.VAR_KEYWORD # type: ignore[assignment]
639
+ param_name = param_name[2:]
640
+ elif node.target.startswith("*"):
641
+ parameter_kind = Parameter.VAR_POSITIONAL # type: ignore[assignment]
642
+ param_name = param_name[1:]
643
+ parameters.append(Parameter(param_name, parameter_kind))
644
+ signature = Signature(parameters)
645
+ ba = signature.bind(*args, **kwargs)
646
+ ba.apply_defaults()
647
+ executor_args = ba.arguments.values() # type: ignore[assignment]
648
+
649
+ res = self.executor.run(*executor_args)
650
+
651
+ return res
652
+
653
+ def get_stage_module(self, stage_idx: int) -> torch.nn.Module:
654
+ """
655
+ Return a stage module corresponding to `stage_idx` of the `pipe`.
656
+ """
657
+ if stage_idx < 0 or stage_idx >= self.num_stages:
658
+ raise ValueError(f"Invalid stage index {stage_idx}!")
659
+
660
+ submod_name = get_submod_name(stage_idx)
661
+ return getattr(self.split_gm, submod_name)
662
+
663
+ @staticmethod
664
+ def _number_and_count_forward_stages(gm: fx.GraphModule):
665
+ num_stages = 0
666
+ found_idxs: dict[int, None] = {}
667
+ for node in gm.graph.nodes:
668
+ if node.op == "call_module" and node.target.startswith(PP_SUBMOD_PREFIX):
669
+ node.meta["stage_idx"] = int(node.target[len(PP_SUBMOD_PREFIX) + 1 :])
670
+ found_idxs.setdefault(node.meta["stage_idx"])
671
+ num_stages += 1
672
+
673
+ # this assert will fail if a split point is inserted before the first layer, which creates empty first submodule
674
+ # Update: the following assert may fail against some torch versions >=
675
+ # 2.2.0, as:
676
+ # submod_0, submod_1, submod_2, ...
677
+ # may be named as
678
+ # submod_0, submod_2, submod_4, ...
679
+ # TODO: investigate
680
+ # assert all(i in found_idxs for i in range(num_stages))
681
+
682
+ return num_stages
683
+
684
+ @staticmethod
685
+ def _from_traced(
686
+ mod: torch.nn.Module,
687
+ exported_program: ExportedProgram,
688
+ multi_use_param_spec: MultiUseParamSpec | None = None,
689
+ output_loss_value_spec=None,
690
+ split_policy: Callable[[torch.fx.GraphModule], torch.fx.GraphModule]
691
+ | None = None,
692
+ ):
693
+ """
694
+ Additionally, the ``output_loss_value_spec`` value can be specified to disambiguate
695
+ which value in the output of `forward` is the loss value on which PiPPy should apply
696
+ backpropagation. For example, if your ``forward`` returns a tuple ``(loss, model_out)``,
697
+ you can specify ``output_loss_value_spec=(True, False)``. Or, if your ``forward`` returns
698
+ a dict ``{'loss': loss_value, 'model_out': model_out}``, you can specify
699
+ ``output_loss_value_spec={'loss': True, 'model_out': False}``
700
+ """
701
+
702
+ traced = exported_program.module(check_guards=False)
703
+
704
+ if split_policy is not None:
705
+ logger.info("Auto-splitting model")
706
+ traced = split_policy(traced) # type: ignore[arg-type]
707
+
708
+ logger.debug(traced.print_readable(print_output=False)) # type: ignore[operator]
709
+
710
+ # Deduplicate `get_attr` nodes that refer to the same parameter . Downstream code for moving
711
+ # parameters relies on the invariant that parameter accesses happen once. This is not necessarily
712
+ # the case (especially with custom tracers), so fix that up here.
713
+ get_attr_nodes: dict[str, fx.Node] = {}
714
+ for node in traced.graph.nodes: # type: ignore[union-attr]
715
+ if node.op == "get_attr":
716
+ get_attr_nodes.setdefault(node.target, node)
717
+
718
+ if get_attr_nodes[node.target] != node:
719
+ node.replace_all_uses_with(get_attr_nodes[node.target])
720
+ traced.graph.erase_node(node) # type: ignore[operator, union-attr]
721
+
722
+ # avoid looking at next node by keeping track of previous pipe_split
723
+ prev_pipe_split_idx = -1
724
+ pipe_split_nodes_to_erase = set()
725
+ for i, node in enumerate(traced.graph.nodes): # type: ignore[arg-type, union-attr]
726
+ if (node.op, node.target) == ("call_function", pipe_split):
727
+ if prev_pipe_split_idx == i - 1:
728
+ pipe_split_nodes_to_erase.add(node)
729
+ prev_pipe_split_idx = i
730
+
731
+ for node in pipe_split_nodes_to_erase:
732
+ traced.graph.erase_node(node) # type: ignore[operator, union-attr]
733
+
734
+ traced.recompile() # type: ignore[operator]
735
+
736
+ part_idx = 0
737
+
738
+ def split_callback(n: fx.Node):
739
+ nonlocal part_idx
740
+ if (n.op, n.target) == (
741
+ "call_function",
742
+ aten_pipe_split_alias,
743
+ ):
744
+ logger.debug(f"Found pipe_split {part_idx}") # noqa: G004
745
+ part_idx += 1
746
+ return part_idx
747
+
748
+ # TODO: what does split do with module invocations? does it move the modules
749
+ # into the submodules?
750
+ split = split_module(traced, mod, split_callback, partition_affix="pp") # type: ignore[arg-type]
751
+ # a (custom) tracer can produce dead code like orphan get_attr nodes
752
+ split.graph.eliminate_dead_code()
753
+
754
+ # peephole to remove pipe_split
755
+ for submodule in split.modules():
756
+ if isinstance(submodule, fx.GraphModule):
757
+ for node in submodule.graph.nodes:
758
+ if (node.op, node.target) == (
759
+ "call_function",
760
+ aten_pipe_split_alias,
761
+ ):
762
+ submodule.graph.erase_node(node)
763
+ submodule.recompile()
764
+
765
+ for name, submodule in split.named_children():
766
+ if isinstance(submodule, fx.GraphModule):
767
+ new_submod = _outline_submodules(submodule.graph)
768
+ # Replace old submod
769
+ split.register_module(name, new_submod)
770
+
771
+ # TODO: backport this into split_module
772
+ def delete_user_reference(node, user):
773
+ """
774
+ Delete reference of `node` from `user`'s arg list.
775
+ Args:
776
+ - node: a `get_attr` node at root.
777
+ - user: a submodule node that uses `node`.
778
+ """
779
+ if not len(user.kwargs) == 0:
780
+ raise AssertionError(
781
+ f"Expected user.kwargs to be empty, got {len(user.kwargs)}"
782
+ )
783
+ use_idxs = [i for i, arg in enumerate(user.args) if arg == node]
784
+ if not len(use_idxs) == 1:
785
+ raise AssertionError(f"Expected 1 use index, got {len(use_idxs)}")
786
+ args_copy = list(user.args)
787
+ args_copy.pop(use_idxs[0])
788
+ user.args = tuple(args_copy)
789
+ logger.debug(
790
+ f"Deleted {node} from user {user}, arg index = {use_idxs[0]}" # noqa: G004
791
+ )
792
+
793
+ # A list of param referrals for deferred deletion.
794
+ # To be accumulated in `move_param_to_callee`.
795
+ to_delete = []
796
+
797
+ def _recursive_getattr_with_parent(mod, fqn):
798
+ # Returns getattr call given a nested FQN, and the last parent
799
+ atoms = fqn.split(".")
800
+ for atom in atoms[:-1]:
801
+ if not hasattr(mod, atom):
802
+ return None, None
803
+ mod = getattr(mod, atom)
804
+ if not hasattr(mod, atoms[-1]):
805
+ return mod, None
806
+ attr = getattr(mod, atoms[-1])
807
+ return mod, attr
808
+
809
+ def move_param_to_callee(
810
+ root,
811
+ callee_name,
812
+ param_fqn,
813
+ ):
814
+ """
815
+ Move a parameter from the root module to a submodule.
816
+ Args:
817
+ root: The root module.
818
+ callee_name: The name of the submodule to move the parameter to.
819
+ param_fqn: The fully qualified name of the parameter to move.
820
+ """
821
+ # `atoms` is a list of strings representing the path to the
822
+ # parameter in the original model
823
+ atoms = param_fqn.split(".")
824
+ mod_itr, param_val = _recursive_getattr_with_parent(split, param_fqn)
825
+ # Check whether the parameter is a buffer or a parameter
826
+ is_buffer = atoms[-1] in mod_itr._buffers
827
+
828
+ # Check whether the parameter is a tensor
829
+ if not isinstance(param_val, torch.Tensor):
830
+ raise AssertionError(
831
+ f"Expected '{param_fqn}' to be {torch.Tensor} but got {type(param_val)}."
832
+ + (
833
+ f" It might happen if module '{param_fqn}' was passed to some 'leaf function'"
834
+ f"(see https://pytorch.org/docs/stable/fx.html#fx.wrap). Please inspect "
835
+ f"usages of '{param_fqn}' in the traced graph."
836
+ if isinstance(param_val, torch.nn.Module)
837
+ else ""
838
+ )
839
+ )
840
+
841
+ # Get submodule
842
+ callee = root.get_submodule(callee_name)
843
+ if hasattr(callee, param_fqn):
844
+ raise AssertionError(
845
+ f"Module {callee_name} already has a parameter named {param_fqn}"
846
+ )
847
+
848
+ # Assign the parameter to the submodule
849
+ if is_buffer:
850
+ _assign_attr(
851
+ param_val,
852
+ callee,
853
+ param_fqn,
854
+ attr_kind=_AttrKind.BUFFER,
855
+ persistent=True, # TODO: handle non-persistent buffer
856
+ )
857
+ else:
858
+ _assign_attr(
859
+ param_val,
860
+ callee,
861
+ param_fqn,
862
+ attr_kind=_AttrKind.PARAMETER,
863
+ )
864
+ logger.debug(f"Moved parameter {param_fqn} to {callee_name}") # noqa: G004
865
+
866
+ # Next step is to replace placeholder of submodule with a get_attr.
867
+ # Those placeholders are created by `split_module` inside each
868
+ # submodule.
869
+ # Update: this step is now moved to `_sink_params` because
870
+ # `_sink_params` can do it recursively (i.e. for modules inside
871
+ # submodule)
872
+
873
+ to_delete.append((mod_itr, atoms[-1]))
874
+
875
+ # Get the list of all parameters in the root module
876
+ attr_nodes = list(filter(lambda n: n.op == "get_attr", split.graph.nodes))
877
+ for node in attr_nodes:
878
+ # Check whether the parameter is used in only one submodule
879
+ if len(node.users) > 1:
880
+ logger.info(
881
+ f"Parameter {node.target} used in multiple stages: {node.users}." # noqa: G004
882
+ )
883
+ for user in node.users:
884
+ if not user.op == "call_module":
885
+ raise AssertionError(
886
+ f"Expected user.op to be 'call_module', got {user.op}"
887
+ )
888
+ # Move parameter into submodule
889
+ move_param_to_callee(
890
+ split,
891
+ user.target,
892
+ node.target,
893
+ )
894
+
895
+ # [aliasing] store tensor id -> list of FQNs, built from state dict
896
+ # Also assign non-persistent buffers
897
+ id_to_fqns: dict[int, set[str]] = defaultdict(set)
898
+ for fqn, tensor in mod.state_dict(keep_vars=True).items():
899
+ id_to_fqns[id(tensor)].add(fqn)
900
+ for fqn, tensor in mod.named_buffers():
901
+ id_to_fqns[id(tensor)].add(fqn)
902
+
903
+ # After moving the params to their corresponding hierarchies, we also
904
+ # need to move the `get_attr` nodes from the root of the graph to those
905
+ # hierarchies.
906
+ # [aliasing] use id -> fqn mapping to list out all valid FQNs
907
+ inputs_to_state: dict[str, list[str]] = {}
908
+ for attr in attr_nodes:
909
+ _, tensor = _recursive_getattr_with_parent(mod, attr.target)
910
+ fqns = list(id_to_fqns[id(tensor)])
911
+ if fqns:
912
+ inputs_to_state[attr.name] = fqns
913
+ elif attr.target in exported_program.constants: # lifted constants
914
+ inputs_to_state[attr.name] = [attr.target]
915
+
916
+ # [aliasing] for each submodule split, assign attributes on FQNs that may be used.
917
+ # We determine this based on whether or not the FQN attribute parent exists.
918
+ # i.e. if the last submodule exists, assign the attribute.
919
+ added_attributes: dict[str, list[str]] = defaultdict(list)
920
+ for fqn, tensor in mod.state_dict(keep_vars=True).items():
921
+ for name, submod in split.named_children():
922
+ if isinstance(submod, fx.GraphModule):
923
+ parent, child = _recursive_getattr_with_parent(submod, fqn)
924
+ if (
925
+ parent and child is None
926
+ ): # parent exists, attribute doesn't -> assign
927
+ added_attributes[name].append(fqn)
928
+ setattr(parent, fqn.split(".")[-1], tensor)
929
+
930
+ # Deferral deletion: Remove the original attributes (to params) from the
931
+ # root GraphModule
932
+ for mod_itr, last_atom in to_delete:
933
+ try:
934
+ delattr(mod_itr, last_atom)
935
+ except AttributeError:
936
+ # This is expected if the parameter is used in multiple stages
937
+ pass
938
+
939
+ # This is done by (1) `_sink_params` at each submodule;
940
+ for submod in split.children():
941
+ if isinstance(submod, fx.GraphModule):
942
+ _sink_params(submod, inputs_to_state, [])
943
+ submod.graph.lint()
944
+ submod.recompile()
945
+
946
+ # [aliasing] This step is not super necessary, but helps reduce parameter usage/memory.
947
+ # After _sink_params() routine has run, clean up unused attributes that we previously added.
948
+ # Determine this based on the get_attr nodes - if not used, remove it.
949
+ for name, attributes in added_attributes.items():
950
+ submod = getattr(split, name)
951
+ unused_attributes = set(attributes)
952
+ # track used attributes in the submodule, running DFS on subgraph hierarchy
953
+ stack = [("", submod)] # (scope, submodule)
954
+ while stack:
955
+ scope, _mod = stack.pop()
956
+ if isinstance(_mod, (fx.GraphModule, InterpreterModule)):
957
+ for node in _mod.graph.nodes:
958
+ if node.op == "get_attr":
959
+ # get_attr might get access deeper level attribute
960
+ fqn = scope + "." + node.target if scope else node.target
961
+ unused_attributes.discard(fqn)
962
+ for _name, _submod in _mod.named_children():
963
+ stack.append((scope + "." + _name if scope else _name, _submod))
964
+ # delete unused attributes
965
+ for attr in unused_attributes:
966
+ mod_itr, atoms = submod, attr.split(".")
967
+ for atom in atoms[:-1]:
968
+ mod_itr = getattr(mod_itr, atom)
969
+ delattr(mod_itr, atoms[-1])
970
+
971
+ for node in attr_nodes:
972
+ # And (2): remove `get_attr` node from submod's arg list
973
+ for user in copy.copy(node.users):
974
+ if not user.op == "call_module":
975
+ raise AssertionError(
976
+ f"Expected user.op to be 'call_module', got {user.op}"
977
+ )
978
+ delete_user_reference(node, user)
979
+ # And (3): remove the `get_attr` node from the root graph.
980
+ split.graph.erase_node(node)
981
+
982
+ split.delete_all_unused_submodules()
983
+ split.graph.lint()
984
+ split.recompile()
985
+
986
+ num_stages = Pipe._number_and_count_forward_stages(split)
987
+
988
+ has_loss_and_backward = False
989
+ generated_loss_spec = output_loss_value_spec
990
+
991
+ if output_loss_value_spec is not None:
992
+ loss_node, output_node, generated_loss_spec = _find_loss_output(
993
+ mod, split.graph, output_loss_value_spec
994
+ )
995
+ if loss_node is not None:
996
+ _insert_stage_symbolic_backward(
997
+ split.graph,
998
+ loss_node,
999
+ output_node,
1000
+ )
1001
+ split.recompile()
1002
+ has_loss_and_backward = True
1003
+ logger.debug("Pipeline is in training mode, backward pass generated")
1004
+ else:
1005
+ raise RuntimeError(
1006
+ f"Did not find any loss value according to {output_loss_value_spec=}"
1007
+ )
1008
+ else:
1009
+ logger.debug("Pipeline is in inference mode, backward pass not generated")
1010
+
1011
+ logger.debug(f"Full pipe model:\n{split}") # noqa: G004
1012
+
1013
+ return Pipe(
1014
+ split,
1015
+ num_stages,
1016
+ has_loss_and_backward,
1017
+ generated_loss_spec,
1018
+ )
1019
+
1020
+ def print_readable(self):
1021
+ """
1022
+ Print the pipe in a human-readable format.
1023
+ This will print both the root pipe and each stage module.
1024
+ """
1025
+ self.split_gm.print_readable()
1026
+
1027
+ @staticmethod
1028
+ def _trace_with_export(
1029
+ mod: torch.nn.Module,
1030
+ example_args: tuple[Any, ...],
1031
+ example_kwargs: dict[str, Any] | None = None,
1032
+ ) -> ExportedProgram:
1033
+ logger.info("Tracing model ...")
1034
+ try:
1035
+ ep = torch.export.export(mod, example_args, example_kwargs)
1036
+ except Exception as e:
1037
+ raise RuntimeError(
1038
+ "It seems that we cannot capture your model as a full graph. "
1039
+ "Typical reasons include graph breaks, data/shape-dependent "
1040
+ "control flow, or missing meta kernels for custom operators. "
1041
+ "You can use our manual pipeline interfaces, or try to fix the "
1042
+ "graph breaks, see https://pytorch.org/docs/stable/export.html"
1043
+ ) from e
1044
+
1045
+ return ep
1046
+
1047
+ @staticmethod
1048
+ def from_tracing(
1049
+ mod: torch.nn.Module,
1050
+ example_args: tuple[Any, ...],
1051
+ example_kwargs: dict[str, Any] | None = None,
1052
+ split_policy: Callable[[fx.GraphModule], fx.GraphModule] | None = None,
1053
+ ):
1054
+ # If a param will be used in multiple pipeline stages, we default the strategy to REPLICATE'ing the param across
1055
+ # stages instead of TRANSMIT'ting it
1056
+ multi_use_param_spec = MultiUseParameterConfig.REPLICATE
1057
+
1058
+ # Figure out which output is loss from output_chunk_spec
1059
+ output_loss_value_spec: Any = None
1060
+ # Deprecated
1061
+ """
1062
+ if output_chunk_spec is not None:
1063
+ output_loss_value_spec = map_aggregate(
1064
+ output_chunk_spec, lambda v: isinstance(v, _LossReducer)
1065
+ )
1066
+ """
1067
+
1068
+ # Trace with export
1069
+ exported_program = Pipe._trace_with_export(
1070
+ mod,
1071
+ example_args,
1072
+ example_kwargs,
1073
+ )
1074
+
1075
+ pipe = Pipe._from_traced(
1076
+ mod,
1077
+ exported_program,
1078
+ multi_use_param_spec,
1079
+ output_loss_value_spec=output_loss_value_spec,
1080
+ split_policy=split_policy,
1081
+ )
1082
+
1083
+ # Users want the first pipeline stage to accept kwargs if the original
1084
+ # program does. This is controlled by the `_codegen` field of the graph,
1085
+ # so we make a copy here. Note: we only want the input spec and not the
1086
+ # output spec, because the output spec is for the last stage. Maybe a
1087
+ # TODO? Not sure yet.
1088
+ split = pipe.split_gm
1089
+ traced = exported_program.module()
1090
+ submod0 = next(iter(split.children()))
1091
+ submod0_sign = signature(submod0.forward)
1092
+ model_sign = signature(traced.forward)
1093
+ if len(model_sign.parameters) != len(submod0_sign.parameters):
1094
+ # We don't change the signature of the first stage if it takes
1095
+ # different number of args than original model
1096
+ logger.info(
1097
+ f"Original model takes {len(model_sign.parameters)} args but the " # noqa: G004
1098
+ f"first pipeline stage takes {len(submod0_sign.parameters)}. "
1099
+ "Please provide args to respective pipeline stages."
1100
+ )
1101
+ else:
1102
+ # Support kwargs for the first stage
1103
+ submod0.graph._codegen = copy.deepcopy(traced.graph._codegen) # type: ignore[union-attr]
1104
+ # `_replace` is actually not "private" or internal. based on this doc:
1105
+ # To prevent conflicts with field names, the method and attribute names
1106
+ # start with an underscore
1107
+ submod0.graph._codegen.pytree_info = ( # type: ignore[union-attr]
1108
+ submod0.graph._codegen.pytree_info._replace(out_spec=None) # type: ignore[operator, union-attr]
1109
+ )
1110
+ submod0.recompile()
1111
+
1112
+ return pipe
1113
+
1114
+ def __str__(self):
1115
+ return self.split_gm.__str__()
1116
+
1117
+ def __repr__(self):
1118
+ return self.split_gm.__repr__()
1119
+
1120
+ def info(self) -> PipeInfo:
1121
+ """
1122
+ Get information about the pipe.
1123
+
1124
+ Returns
1125
+ -------
1126
+ PipeInfo
1127
+ A dataclass containing information about the pipe.
1128
+ """
1129
+ return PipeInfo(
1130
+ graph=self.split_gm.graph,
1131
+ num_stages=self.num_stages,
1132
+ has_loss_and_backward=self.has_loss_and_backward,
1133
+ )
1134
+
1135
+ def build_stage(
1136
+ self,
1137
+ stage_index: int,
1138
+ device: torch.device,
1139
+ group: ProcessGroup | None = None,
1140
+ ) -> _PipelineStage:
1141
+ """
1142
+ Create a `PipelineStage` given a stage index and distributed group.
1143
+ The `PipelineStage` can run with `PipelineSchedule`s.
1144
+ """
1145
+ # Find stage module
1146
+ stage_module = self.get_stage_module(stage_index)
1147
+
1148
+ # Move ops argument to device
1149
+ # Today PT2 tracer does not treat `x.device` as a symbolic device;
1150
+ # instead, the device of tracing time got burned into the generated
1151
+ # code. Here we provide a workaround for users to manually modify the
1152
+ # "device" kwarg of operations. Such operation may include:
1153
+ # `torch.ones`, `torch.zeros`, `torch.rand`, etc.
1154
+ if isinstance(stage_module, torch.fx.GraphModule):
1155
+ _modify_graph_op_device(stage_module, device)
1156
+ else:
1157
+ logger.warning(
1158
+ f"Expected a `torch.fx.GraphModule` but got {type(stage_module)}" # noqa: G004
1159
+ )
1160
+
1161
+ # Detach pipe info
1162
+ # Note: be careful what's included in `pipe_info`. We don't want to keep
1163
+ # a reference to `Pipe` or `Pipe.split_gm` which stops python from
1164
+ # recycling them. When python recycles them, other stage modules (which
1165
+ # are irrelevant to current rank) can be automatically freed.
1166
+ pipe_info = self.info()
1167
+ return _PipelineStage(stage_module, stage_index, pipe_info, device, group)
1168
+
1169
+
1170
+ class SplitPoint(Enum):
1171
+ """
1172
+ Enum representing the points at which a split can occur in the execution of a submodule.
1173
+ Attributes:
1174
+ BEGINNING: Represents adding a split point *before* the execution of a certain submodule in the `forward` function.
1175
+ END: Represents adding a split point *after* the execution of a certain submodule in the `forward` function.
1176
+ """
1177
+
1178
+ BEGINNING = 1
1179
+ END = 2
1180
+
1181
+
1182
+ # For backward compatibility, we kept the PipeSplitWrapper class because `class
1183
+ # SplitPoint` used to be defined in this class.
1184
+ class PipeSplitWrapper:
1185
+ # Create a class alias for BC
1186
+ SplitPoint = SplitPoint
1187
+
1188
+
1189
+ def _split_before_forward(self, *args, **kwargs):
1190
+ pipe_split()
1191
+ return self._orig_forward(*args, **kwargs)
1192
+
1193
+
1194
+ def _split_after_forward(self, *args, **kwargs):
1195
+ try:
1196
+ return self._orig_forward(*args, **kwargs)
1197
+ finally:
1198
+ pipe_split()
1199
+
1200
+
1201
+ def annotate_split_points(mod: torch.nn.Module, spec: dict[str, SplitPoint]):
1202
+ # TODO: make this implementation out-of-place?
1203
+ for qualname, split_type in spec.items():
1204
+ atoms = qualname.split(".")
1205
+ predecessor_module = mod
1206
+ for i, atom in enumerate(atoms[:-1]):
1207
+ try:
1208
+ predecessor_module = getattr(predecessor_module, atom)
1209
+ except AttributeError as e:
1210
+ raise AttributeError(
1211
+ f"Specified target {qualname} referenced "
1212
+ f"nonexistent module {'.'.join(atoms[: i + 1])}"
1213
+ ) from e
1214
+
1215
+ mod_to_wrap = getattr(predecessor_module, atoms[-1])
1216
+ mod_to_wrap._orig_forward = mod_to_wrap.forward
1217
+ if split_type == SplitPoint.BEGINNING:
1218
+ mod_to_wrap.forward = MethodType(_split_before_forward, mod_to_wrap)
1219
+ elif split_type == SplitPoint.END:
1220
+ mod_to_wrap.forward = MethodType(_split_after_forward, mod_to_wrap)
1221
+ else:
1222
+ raise ValueError("Unknown split point type.")
1223
+
1224
+
1225
+ def pipeline(
1226
+ module: torch.nn.Module,
1227
+ mb_args: tuple[Any, ...],
1228
+ mb_kwargs: dict[str, Any] | None = None,
1229
+ split_spec: dict[str, SplitPoint] | None = None,
1230
+ split_policy: Callable[[fx.GraphModule], fx.GraphModule] | None = None,
1231
+ ) -> Pipe:
1232
+ """
1233
+ Split a module based on a specification.
1234
+
1235
+ See `Pipe` for more details.
1236
+
1237
+ Arguments
1238
+ ---------
1239
+ module:
1240
+ The module to be split.
1241
+ mb_args:
1242
+ Example positional inputs, in micro-batch form.
1243
+ mb_kwargs:
1244
+ Example keyword inputs, in micro-batch form. (default: `None`)
1245
+ split_spec:
1246
+ A dictionary using submodule names as split marker. (default: `None`)
1247
+ split_policy:
1248
+ The policy to use for splitting the module. (default: `None`)
1249
+
1250
+ Returns
1251
+ -------
1252
+ A pipeline representation of class `Pipe`.
1253
+ """
1254
+ if split_spec is not None and split_policy is not None:
1255
+ raise ValueError(
1256
+ "Cannot specify both `split_spec` and `split_policy`. Please use only one of them."
1257
+ )
1258
+
1259
+ if split_spec is not None:
1260
+ # Annotate split points in the module based on user spec
1261
+ annotate_split_points(module, split_spec)
1262
+ return Pipe.from_tracing(
1263
+ mod=module,
1264
+ example_args=mb_args,
1265
+ example_kwargs=mb_kwargs,
1266
+ )
1267
+ else:
1268
+ # Use split policy
1269
+ return Pipe.from_tracing(
1270
+ mod=module,
1271
+ example_args=mb_args,
1272
+ example_kwargs=mb_kwargs,
1273
+ split_policy=split_policy,
1274
+ )
venv/lib/python3.14/site-packages/torch/distributed/pipelining/__init__.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+ from ._IR import Pipe, pipe_split, pipeline, SplitPoint
3
+ from .schedules import (
4
+ _ScheduleForwardOnly,
5
+ Schedule1F1B,
6
+ ScheduleDualPipeV,
7
+ ScheduleGPipe,
8
+ ScheduleInterleaved1F1B,
9
+ ScheduleInterleavedZeroBubble,
10
+ ScheduleLoopedBFS,
11
+ ScheduleZBVZeroBubble,
12
+ )
13
+ from .stage import build_stage, PipelineStage
14
+
15
+
16
+ __all__ = [
17
+ "Pipe",
18
+ "pipe_split",
19
+ "SplitPoint",
20
+ "pipeline",
21
+ "PipelineStage",
22
+ "build_stage",
23
+ "Schedule1F1B",
24
+ "ScheduleGPipe",
25
+ "ScheduleInterleaved1F1B",
26
+ "ScheduleLoopedBFS",
27
+ "ScheduleInterleavedZeroBubble",
28
+ "ScheduleZBVZeroBubble",
29
+ "ScheduleDualPipeV",
30
+ ]
venv/lib/python3.14/site-packages/torch/distributed/pipelining/_backward.py ADDED
@@ -0,0 +1,460 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates
3
+ import collections
4
+ import logging
5
+ from collections.abc import Iterator, Sequence
6
+ from typing import Any
7
+
8
+ import torch
9
+ from torch.autograd.graph import GradientEdge, Node
10
+ from torch.nn import Parameter
11
+
12
+ from ._debug import map_debug_info
13
+
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ def _get_grad_fn_or_grad_acc(t: torch.Tensor) -> Node | None:
19
+ """
20
+ Get the grad function or grad accumulator for a tensor.
21
+
22
+ Accumulate grad nodes are lazily created, so we need to a
23
+ dummy view in order to trigger its creation.
24
+ """
25
+ if t.requires_grad and t.grad_fn is None:
26
+ # if no grad function (leaf tensors) we use view
27
+ viewed_t = t.view_as(t)
28
+ grad_fn = viewed_t.grad_fn
29
+ if grad_fn is not None:
30
+ return grad_fn.next_functions[0][0]
31
+ else:
32
+ raise RuntimeError(
33
+ "Attempted to get grad_fn, but got None."
34
+ "Is this being created in a no-grad context?"
35
+ )
36
+ else:
37
+ return t.grad_fn
38
+
39
+
40
+ def reverse_closure(
41
+ roots: list[Node], target_nodes: set[Node], reverse_edges_dict
42
+ ) -> tuple[set[Node], set[Node]]:
43
+ """
44
+ This function returns the reverse closure of the given roots,
45
+ i.e. the set of nodes that can be reached from the roots by following the
46
+ reverse edges of the graph. The target_nodes are the nodes that we want to
47
+ include in the closure.
48
+ """
49
+ # Recurse until we reach a target node
50
+ closure: set[Node] = set()
51
+ visited_target_nodes = set()
52
+ q: collections.deque[Node] = collections.deque()
53
+ for node in roots:
54
+ if node is not None and node not in closure:
55
+ closure.add(node)
56
+ q.append(node)
57
+ while q:
58
+ node = q.popleft()
59
+ reverse_edges = reverse_edges_dict[node]
60
+ for fn in reverse_edges:
61
+ if fn in closure or fn is None:
62
+ continue
63
+ if fn in target_nodes:
64
+ visited_target_nodes.add(fn)
65
+ continue
66
+ closure.add(fn)
67
+ q.append(fn)
68
+ return closure, visited_target_nodes
69
+
70
+
71
+ def construct_reverse_graph(roots: list[Node]) -> dict[Node, list[Node]]:
72
+ q: collections.deque[Node] = collections.deque()
73
+ root_seen: set[Node] = set()
74
+ reverse_edges_dict: dict[Node, list[Node]] = collections.defaultdict(list)
75
+ for node in roots:
76
+ if node is not None and node not in root_seen:
77
+ q.append(node)
78
+ root_seen.add(node)
79
+ while q:
80
+ node = q.popleft()
81
+ for fn, _ in node.next_functions:
82
+ if fn is not None:
83
+ if len(reverse_edges_dict[fn]) == 0:
84
+ q.append(fn)
85
+ reverse_edges_dict[fn].append(node)
86
+ return reverse_edges_dict
87
+
88
+
89
+ def get_param_groups(
90
+ inputs: list[Node], params: list[Node], reverse_edges_dict
91
+ ) -> list[dict[str, Any]]:
92
+ """
93
+ Given a list of inputs and a list of parameters, return a list of parameter
94
+ groups, where each group contains the parameters and the intermediates that
95
+ are connected to the parameters.
96
+
97
+ The returned list of parameter groups is a list of dictionaries, where each
98
+ dictionary contains the following keys:
99
+ - "params": a set of parameters
100
+ - "intermediates": a set of intermediates
101
+
102
+ The returned list of parameter groups is a list of dictionaries,
103
+ """
104
+ # reverse graph that starts with inputs, and goes up to the dOutput or the loss,
105
+ # but omits weights and any subgraphs connecting weights to this closure
106
+ inputs_closure, _ = reverse_closure(inputs, set(), reverse_edges_dict)
107
+ param_groups: dict[Node, dict[str, set]] = dict() # keyed on intermediates
108
+ for param in params:
109
+ closure, intersected = reverse_closure(
110
+ [param], inputs_closure, reverse_edges_dict
111
+ )
112
+ param_group: dict[str, set] = {
113
+ "params": {param},
114
+ "intermediates": intersected,
115
+ }
116
+ for input_node in intersected:
117
+ existing = param_groups.get(input_node)
118
+ if existing is not None:
119
+ existing["params"] = existing["params"].union(param_group["params"])
120
+ existing["intermediates"] = existing["intermediates"].union(
121
+ param_group["intermediates"]
122
+ )
123
+ param_group = existing
124
+ else:
125
+ param_groups[input_node] = param_group
126
+
127
+ # Sanity check: union of all param_groups params should be equal to all params
128
+ union_params: set[Node] = set()
129
+ seen_ids: set[int] = set()
130
+ unique_param_groups = []
131
+ for param_group in param_groups.values():
132
+ if id(param_group) not in seen_ids:
133
+ seen_ids.add(id(param_group))
134
+ unique_param_groups.append(param_group)
135
+ union_params = union_params.union(param_group["params"])
136
+
137
+ # The assert will only be true if the input tensor requires gradients,
138
+ # otherwise the autograd graph will miss the first layer of inputs
139
+ # assert union_params == set(params)
140
+ return unique_param_groups
141
+
142
+
143
+ def _autograd_grad_for_inputs(
144
+ outputs: Sequence[torch.Tensor],
145
+ inputs: Sequence[torch.Tensor],
146
+ grad_outputs: Sequence[torch.Tensor | None] | None = None,
147
+ retain_graph: bool = False,
148
+ allow_unused: bool = False,
149
+ ) -> tuple[torch.Tensor | None, ...]:
150
+ """Compute input gradients, returning ``None`` for non-grad inputs."""
151
+ # Some inputs may not be used or may not require gradients, so we filter them out
152
+ # before calling autograd.grad and place None for those positions in the result.
153
+ grad_indices: list[int] = []
154
+ inputs_requiring_grad: list[torch.Tensor] = []
155
+ for i, inp in enumerate(inputs):
156
+ if isinstance(inp, torch.Tensor) and inp.requires_grad:
157
+ grad_indices.append(i)
158
+ inputs_requiring_grad.append(inp)
159
+
160
+ if not inputs_requiring_grad:
161
+ return tuple(None for _ in inputs)
162
+
163
+ grads = torch.autograd.grad(
164
+ outputs=outputs,
165
+ inputs=inputs_requiring_grad,
166
+ grad_outputs=grad_outputs,
167
+ retain_graph=retain_graph,
168
+ allow_unused=allow_unused,
169
+ )
170
+
171
+ result: list[torch.Tensor | None] = [None] * len(inputs)
172
+ for idx, g in zip(grad_indices, grads, strict=True):
173
+ result[idx] = g
174
+ return tuple(result)
175
+
176
+
177
+ def stage_backward_input(
178
+ stage_outputs_or_loss: list[torch.Tensor],
179
+ output_grads: list[torch.Tensor] | None,
180
+ input_values: list[torch.Tensor],
181
+ weights: Iterator[Parameter],
182
+ ) -> tuple[tuple[torch.Tensor | None, ...], list[dict[str, Any]]]:
183
+ """
184
+ Compute the gradients for only the stage inputs with
185
+ respect to the stage outputs (if non-last stage) or loss (if last stage)
186
+
187
+ After computing input gradients, we save the intermediate nodes in `param_groups`
188
+ for later use in stage_backward_weight. We don't need to save any other intermediate nodes
189
+ that aren't needed for dW because when we do dW calculation, we start from saved intermediates.
190
+ Detaching the stage_outputs_or_loss at the end of this function is important as
191
+ it frees up the memory that the autograd graph is anticipating to be used later (but doesn't actually need).
192
+ """
193
+ stage_output_grad_fns: list[Node] = list(
194
+ filter(None, map(_get_grad_fn_or_grad_acc, stage_outputs_or_loss))
195
+ )
196
+ stage_input_grad_fns: list[Node] = list(
197
+ filter(None, map(_get_grad_fn_or_grad_acc, input_values))
198
+ )
199
+ weight_grad_fns: list[Node] = list(
200
+ filter(None, map(_get_grad_fn_or_grad_acc, weights))
201
+ )
202
+
203
+ reverse_edges_dict = construct_reverse_graph(stage_output_grad_fns)
204
+ param_groups = get_param_groups(
205
+ stage_input_grad_fns, weight_grad_fns, reverse_edges_dict
206
+ )
207
+
208
+ handles = []
209
+ for param_group in param_groups:
210
+ for i, intermediate in enumerate(param_group["intermediates"]):
211
+
212
+ def get_hook(param_group, i):
213
+ def hook(grad_inputs):
214
+ if param_group.get("grads", None) is None:
215
+ param_group["grads"] = [None] * len(
216
+ param_group["intermediates"]
217
+ )
218
+ param_group["grads"][i] = grad_inputs
219
+
220
+ return hook
221
+
222
+ # These are always "split" nodes that we need to recompute, so
223
+ # save their inputs.
224
+ handle = intermediate.register_prehook(get_hook(param_group, i))
225
+ handles.append(handle)
226
+
227
+ if output_grads is None:
228
+ # In case this is the loss and there are no output_grads, then we just use 1s
229
+ output_grads = [
230
+ torch.ones_like(stage_output) for stage_output in stage_outputs_or_loss
231
+ ]
232
+
233
+ dinputs = _autograd_grad_for_inputs(
234
+ stage_outputs_or_loss,
235
+ input_values,
236
+ output_grads,
237
+ retain_graph=True,
238
+ )
239
+
240
+ # Accumulate into .grad
241
+ for inp, dinput in zip(input_values, dinputs):
242
+ if isinstance(inp, torch.Tensor) and dinput is not None:
243
+ if inp.grad is None:
244
+ inp.grad = dinput
245
+ else:
246
+ inp.grad += dinput
247
+
248
+ # stage_outputs_or_loss are not used in backwards after this point, so we can safely remove it from the autograd graph
249
+ # this allows autograd to clear up the graph dedicated for this tensor and free up significant memory
250
+ for t in stage_outputs_or_loss:
251
+ t.detach_()
252
+
253
+ # hooks are no longer necessary, clean up for consistency
254
+ for handle in handles:
255
+ handle.remove()
256
+
257
+ return dinputs, param_groups
258
+
259
+
260
+ def stage_backward_weight(
261
+ weights: Iterator[Parameter], param_groups: list[dict[str, Any]], retain_graph=False
262
+ ) -> tuple[torch.Tensor | None, ...]:
263
+ # map weights to param_group_weights
264
+ grad_acc_to_weight = {}
265
+ weight_grads: list[torch.Tensor | None] = []
266
+ for index, weight in enumerate(weights):
267
+ grad_acc = _get_grad_fn_or_grad_acc(weight)
268
+ grad_acc_to_weight[grad_acc] = weight, index
269
+ weight_grads.append(weight.grad)
270
+
271
+ for param_group in param_groups:
272
+ valid_edges = []
273
+ valid_grad_outputs: list[torch.Tensor] = []
274
+
275
+ for grads_tuple, intermediate in zip(
276
+ param_group["grads"], param_group["intermediates"]
277
+ ):
278
+ for i, grad in enumerate(grads_tuple):
279
+ if grad is not None:
280
+ valid_edges.append(GradientEdge(intermediate, i))
281
+ # pyrefly: ignore [bad-argument-type]
282
+ valid_grad_outputs.append(grad)
283
+
284
+ # Break a reference cycle caused inside stage_backward_input->get_hook->hook
285
+ # The summarized cycle is:
286
+ # `hook` -> cell -> param_group -> intermediates -> `hook`
287
+ # because we install the hook function onto each of the intermediate autograd nodes.
288
+ # We need to keep intermediates alive up until backward_weight, but we can free it now.
289
+ del param_group["intermediates"]
290
+
291
+ if valid_edges: # Only call autograd.grad if we have valid gradients
292
+ # [NEW!] Able to pass a GradientEdge to autograd.grad as output
293
+ weights_edges = tuple(GradientEdge(w, 0) for w in param_group["params"])
294
+ dweights = torch.autograd.grad(
295
+ valid_edges,
296
+ weights_edges,
297
+ grad_outputs=valid_grad_outputs,
298
+ retain_graph=retain_graph,
299
+ )
300
+
301
+ # release grad memory early after use
302
+ del param_group["grads"]
303
+
304
+ for grad_acc, dw in zip(param_group["params"], dweights):
305
+ weight, index = grad_acc_to_weight[grad_acc]
306
+ if weight.grad is None:
307
+ weight.grad = dw
308
+ else:
309
+ weight.grad += dw
310
+ # return grads in the original order weights were provided in
311
+ return tuple(weight_grads)
312
+
313
+
314
+ def stage_backward(
315
+ stage_output,
316
+ output_grads,
317
+ input_values,
318
+ outputs_with_grads_idxs: list[int] | None = None, # deprecated, not used
319
+ ) -> tuple[torch.Tensor | None, ...]:
320
+ """
321
+ This is a helper function to:
322
+ 1. compute the gradients for the stage inputs, and
323
+ 2. accumulate gradients for the stage module's parameters.
324
+
325
+ Given the input value(s) and the corresponding gradient for the output
326
+ value(s), compute and accumulate gradients for all parameter values (leaves
327
+ in the autograd trace) as well as return a list of the gradients for the
328
+ input values
329
+ """
330
+ if outputs_with_grads_idxs is not None:
331
+ # Deprecated, not used in runtime calls, only exists in compiler
332
+ stage_output = [stage_output[i] for i in outputs_with_grads_idxs]
333
+ output_grads = [output_grads[i] for i in outputs_with_grads_idxs]
334
+
335
+ try:
336
+ # stage_output may be a composite datatype like dict. Extract all individual
337
+ # tensor values here
338
+ stage_output_tensors: list[torch.Tensor] = []
339
+ output_grad_tensors: list[torch.Tensor | None] = []
340
+
341
+ def extract_tensors_with_grads(
342
+ output_val,
343
+ grad_val,
344
+ # Don't delete me- see [Note: ref cycle]
345
+ extract_tensors_with_grads,
346
+ ):
347
+ if isinstance(output_val, torch.Tensor):
348
+ if not output_val.requires_grad and output_val.grad_fn is None:
349
+ return
350
+ if not isinstance(grad_val, (torch.Tensor, type(None))):
351
+ raise AssertionError(
352
+ f"Expected Tensor or None gradient but got {type(grad_val)}"
353
+ )
354
+ stage_output_tensors.append(output_val)
355
+ output_grad_tensors.append(grad_val)
356
+ elif isinstance(output_val, (tuple, list)):
357
+ if grad_val is None:
358
+ return
359
+ if not isinstance(grad_val, (tuple, list)):
360
+ raise AssertionError(
361
+ f"grad_value expected to have type {type(output_val)} but got {type(grad_val)}"
362
+ )
363
+ if not len(output_val) == len(grad_val):
364
+ raise AssertionError(
365
+ f"Expected len(output_val) == len(grad_val), got {len(output_val)} != {len(grad_val)}"
366
+ )
367
+ for ov, gv in zip(output_val, grad_val):
368
+ extract_tensors_with_grads(
369
+ ov,
370
+ gv,
371
+ extract_tensors_with_grads,
372
+ )
373
+ elif isinstance(output_val, dict):
374
+ if grad_val is None:
375
+ return
376
+ if not isinstance(grad_val, dict):
377
+ raise AssertionError(f"Expected dict, got {type(grad_val)}")
378
+ if not set(output_val.keys()) == set(grad_val.keys()):
379
+ raise AssertionError(
380
+ f"Expected keys {set(output_val.keys())}, got {set(grad_val.keys())}"
381
+ )
382
+ for k in output_val:
383
+ extract_tensors_with_grads(
384
+ output_val[k], grad_val[k], extract_tensors_with_grads
385
+ )
386
+ else:
387
+ # Output is a non-tensor type; just ignore it
388
+ pass
389
+
390
+ # Note: ref cycle
391
+ # break a ref cycle that would keep tensors alive until GC runs
392
+ # 1. extract_tensors_with_grads refers to a cell that holds refs to any vars defined in stage_backward
393
+ # and used in extract_tensors_with_grads
394
+ # 2. extract_tensors_with_grads referred to both stage_output_tensors, output_grad_tensors,
395
+ # and to itself (extract_tensors_with_grads) since it makes a recursive call
396
+ # 3. stage_output_tensors was kept alive by the above refcycle, and it holds activation tensors, which is bad
397
+ # fix -> explicitly pass in the ref to the fn, so there is no gc cycle anymore
398
+ extract_tensors_with_grads(
399
+ stage_output, output_grads, extract_tensors_with_grads
400
+ )
401
+
402
+ torch.autograd.backward(
403
+ stage_output_tensors,
404
+ grad_tensors=output_grad_tensors, # type: ignore[arg-type]
405
+ )
406
+
407
+ # Extract gradients wrt the input values
408
+ grad_inputs: list[torch.Tensor | None] = []
409
+ for val in input_values:
410
+ if isinstance(val, torch.Tensor):
411
+ grad_inputs.append(val.grad)
412
+ # Since gradients that will pass back to previous stages do not require gradient accumulation,
413
+ # by decrementing the gradients' reference count at this point, the memory of gradients will be
414
+ # returned to the allocator as soon as the next micro batch's get_bwd_send_ops comes and current
415
+ # asynchronous send completes.
416
+ # This prevents the gradients from persisting in GPU memory for the entire duration of step_microbatches
417
+ # until clear_runtime_states() is called.
418
+ val.grad = None
419
+ else:
420
+ grad_inputs.append(None)
421
+
422
+ # Alternative impl: `torch.autograd.grad`.
423
+ # Note that `torch.autograd.grad` will not accumulate gradients into the
424
+ # model's parameters.
425
+ """
426
+ inputs_with_grad = []
427
+ for val in input_values:
428
+ if isinstance(val, torch.Tensor) and val.requires_grad:
429
+ inputs_with_grad.append(val)
430
+
431
+ grad_inputs = torch.autograd.grad(
432
+ stage_output_tensors, inputs_with_grad, output_grad_tensors, # type: ignore[arg-type]
433
+ )
434
+ """
435
+
436
+ except Exception as e:
437
+ exc_msg = f"""
438
+ Failed to run stage backward:
439
+ Stage output: {map_debug_info(stage_output)}
440
+ Output gradient: {map_debug_info(output_grads)}
441
+ Input: {map_debug_info(input_values)}
442
+ """
443
+ raise RuntimeError(exc_msg) from e
444
+
445
+ return tuple(grad_inputs)
446
+
447
+
448
+ # TODO: handling requires_grad=False dynamically. Can we analyze this during initial
449
+ # IR emission?
450
+ def _null_coalesce_accumulate(lhs, rhs):
451
+ """
452
+ Coalesce two values, even if one of them is null, returning the non-null
453
+ value.
454
+ """
455
+ if lhs is None:
456
+ return rhs
457
+ elif rhs is None:
458
+ return lhs
459
+ else:
460
+ return torch.add(lhs, rhs)
venv/lib/python3.14/site-packages/torch/distributed/pipelining/_debug.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+
3
+ import torch
4
+ from torch.fx.node import Argument
5
+
6
+
7
+ def friendly_debug_info(v: object) -> Argument:
8
+ """
9
+ Helper function to print out debug info in a friendly way.
10
+ """
11
+ if isinstance(v, torch.Tensor):
12
+ return f"Tensor({v.shape}, grad={v.requires_grad}, dtype={v.dtype})"
13
+ else:
14
+ return str(v)
15
+
16
+
17
+ def map_debug_info(a: Argument) -> Argument:
18
+ """
19
+ Helper function to apply `friendly_debug_info` to items in `a`.
20
+ `a` may be a list, tuple, or dict.
21
+ """
22
+ return torch.fx.node.map_aggregate(a, friendly_debug_info)
venv/lib/python3.14/site-packages/torch/distributed/pipelining/_schedule_visualizer.py ADDED
@@ -0,0 +1,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+
3
+ """
4
+ This visualizer requires matplotlib to be installed.
5
+
6
+ Example usage:
7
+
8
+ ops = get_schedule_ops("InterleavedZeroBubble", 4, 8)
9
+ visualize_schedule(ops, "test.png")
10
+ """
11
+
12
+ import collections
13
+ from typing import NamedTuple
14
+ from unittest import mock
15
+
16
+ from torch.distributed.pipelining.schedules import (
17
+ _Action,
18
+ _ComputationType,
19
+ _PipelineSchedule,
20
+ _PipelineScheduleRuntime,
21
+ get_schedule_class,
22
+ PipelineScheduleMulti,
23
+ PipelineScheduleSingle,
24
+ )
25
+ from torch.distributed.pipelining.stage import PipelineStage
26
+
27
+
28
+ class OpKey(NamedTuple):
29
+ stage_index: int
30
+ computation_type: _ComputationType
31
+ microbatch_index: int
32
+
33
+
34
+ def get_schedule_ops(
35
+ schedule: str | type[_PipelineSchedule],
36
+ pp_degree: int,
37
+ num_microbatches: int,
38
+ num_stages_per_rank: int | None = None,
39
+ add_spacing: bool = False,
40
+ with_comms: bool = False,
41
+ ) -> list[list[_Action | None]]:
42
+ """
43
+ Get all actions for a given schedule, pp_degree, and num_microbatches. The actions are returned in a list of lists
44
+ where each inner list represents a rank and each element in the inner list represents an action.
45
+
46
+ The schedule can be specified as a string which is passed into get_schedule_class() or a _PipelineSchedule instance.
47
+ """
48
+ if add_spacing and with_comms:
49
+ raise ValueError("Cannot add spacing and view comms at the same time")
50
+
51
+ if isinstance(schedule, str):
52
+ schedule_class = get_schedule_class(schedule)
53
+ elif issubclass(schedule, _PipelineSchedule):
54
+ schedule_class = schedule
55
+ else:
56
+ raise ValueError(f"Invalid schedule: {schedule}")
57
+
58
+ # Create a mock of the PipelineStage class
59
+ mock_pipeline_stage = mock.create_autospec(PipelineStage, instance=True)
60
+ # Set the return values for group_rank and group_size methods
61
+ mock_pipeline_stage.group_rank = 0
62
+ mock_pipeline_stage.group_size = pp_degree
63
+ mock_pipeline_stage.submod = None
64
+
65
+ # Check num_stages_per_rank is valid
66
+ if issubclass(schedule_class, PipelineScheduleSingle):
67
+ if num_stages_per_rank is None:
68
+ num_stages_per_rank = 1
69
+ if not num_stages_per_rank == 1:
70
+ raise AssertionError(
71
+ f"Expected num_stages_per_rank to be 1, got {num_stages_per_rank}"
72
+ )
73
+ stages = mock_pipeline_stage
74
+ stages.num_stages = num_stages_per_rank * pp_degree
75
+ elif issubclass(schedule_class, PipelineScheduleMulti):
76
+ if num_stages_per_rank is None:
77
+ num_stages_per_rank = 2
78
+ if not num_stages_per_rank >= 2:
79
+ raise AssertionError(
80
+ f"Expected num_stages_per_rank >= 2, got {num_stages_per_rank}"
81
+ )
82
+ stages = [mock_pipeline_stage for _ in range(num_stages_per_rank)]
83
+ for stage in stages:
84
+ stage.num_stages = num_stages_per_rank * pp_degree
85
+
86
+ else:
87
+ raise ValueError(f"Invalid schedule: {schedule_class}")
88
+
89
+ # Instantiate the schedule class
90
+ # pyrefly: ignore [bad-argument-type]
91
+ schedule_instance = schedule_class(stages, num_microbatches)
92
+ if schedule_instance.pipeline_order is None:
93
+ raise AssertionError("Expected pipeline_order to not be None")
94
+
95
+ # Convert to List[List[_Action]]
96
+ all_actions: list[list[_Action | None]] = []
97
+ if with_comms:
98
+ runtime = _PipelineScheduleRuntime(stages, num_microbatches)
99
+ runtime._prepare_schedule_with_comms(schedule_instance.pipeline_order)
100
+ for rank in range(pp_degree):
101
+ all_actions.append(list(runtime.pipeline_order_with_comms[rank]))
102
+ else:
103
+ for rank in range(pp_degree):
104
+ all_actions.append(schedule_instance.pipeline_order[rank])
105
+
106
+ # Add spacing
107
+ if add_spacing:
108
+ # remove all Nones, then respace
109
+ # TODO: later we can change this at the schedule creation level to not use Nones
110
+ all_actions = [
111
+ [action for action in rank if action is not None] for rank in all_actions
112
+ ]
113
+ all_actions = add_schedule_op_spacing(all_actions)
114
+
115
+ # Return the pipeline order
116
+ return all_actions
117
+
118
+
119
+ class _ComputationTypeVisual:
120
+ def __init__(
121
+ self,
122
+ color: str,
123
+ text: str = "",
124
+ width: int = 1,
125
+ ):
126
+ self.color = color
127
+ self.width = width
128
+ self.text = text
129
+
130
+
131
+ # Update the mapping to use _ComputationTypeVisual instances
132
+ action_type_to_color_mapping = {
133
+ _ComputationType.FORWARD: _ComputationTypeVisual("blue", "Forward"),
134
+ _ComputationType.BACKWARD_INPUT: _ComputationTypeVisual("teal", "Backward Input"),
135
+ _ComputationType.BACKWARD_WEIGHT: _ComputationTypeVisual(
136
+ "green", "Backward Weight"
137
+ ),
138
+ _ComputationType.FULL_BACKWARD: _ComputationTypeVisual(
139
+ "orange", "Full Backward", 2
140
+ ),
141
+ _ComputationType.OVERLAP_F_B: _ComputationTypeVisual("purple", "Overlap F+B", 3),
142
+ }
143
+
144
+
145
+ def add_schedule_op_spacing(
146
+ schedule: list[list[_Action | None]],
147
+ ) -> list[list[_Action | None]]:
148
+ """
149
+ Add spacing to the schedule based on dependencies between ranks.
150
+
151
+ Before adding an operation to the list, this function checks if there are
152
+ dependencies from other ranks. If there are dependencies (other ranks have
153
+ not finished processing the required microbatch), it adds None instead.
154
+
155
+ For example, Forward microbatch 0 on rank 1 depends on rank 0 processing
156
+ Forward microbatch 0 first.
157
+
158
+ Args:
159
+ schedule: The original schedule as a list of lists where each inner list
160
+ represents a rank and each element represents an action.
161
+
162
+ Returns:
163
+ A new schedule with proper spacing based on dependencies.
164
+ """
165
+ if not schedule:
166
+ return schedule
167
+
168
+ num_stages = (
169
+ max(
170
+ action.stage_index
171
+ for rank_actions in schedule
172
+ for action in rank_actions
173
+ if action is not None
174
+ )
175
+ + 1
176
+ )
177
+
178
+ num_ranks = len(schedule)
179
+ spaced_schedule: list[list[_Action | None]] = [[] for _ in range(num_ranks)]
180
+ rank_ops = [collections.deque(ops) for ops in schedule]
181
+
182
+ # Track completion times: (stage_index, action_type, microbatch_index) -> completion_time
183
+ scheduled_ops: dict[OpKey, int] = {}
184
+
185
+ def is_dependency_ready(dependency_key: OpKey, timestep: int) -> bool:
186
+ """Check if a dependency operation has completed by the given timestep."""
187
+ return (
188
+ dependency_key in scheduled_ops
189
+ and timestep >= scheduled_ops[dependency_key]
190
+ )
191
+
192
+ def get_dependencies(action: _Action) -> list[OpKey]:
193
+ """Get the list of dependencies for an action."""
194
+ stage_idx = action.stage_index
195
+ comp_type = action.computation_type
196
+ mb_idx = action.microbatch_index
197
+
198
+ # Ensure mb_idx is not None for dependency tracking
199
+ if mb_idx is None:
200
+ raise AssertionError(f"Action {action} has None microbatch_index")
201
+
202
+ # First stage forward has no dependencies
203
+ if stage_idx == 0 and comp_type == _ComputationType.FORWARD:
204
+ return []
205
+
206
+ # Last stage backward depends on forward from previous stage
207
+ if stage_idx == num_stages - 1 and comp_type in (
208
+ _ComputationType.FULL_BACKWARD,
209
+ _ComputationType.BACKWARD_INPUT,
210
+ ):
211
+ return [OpKey(stage_idx - 1, _ComputationType.FORWARD, mb_idx)]
212
+
213
+ # Forward depends on previous stage forward
214
+ if comp_type == _ComputationType.FORWARD:
215
+ return [OpKey(stage_idx - 1, _ComputationType.FORWARD, mb_idx)]
216
+
217
+ # Backward depends on next stage backward
218
+ if comp_type in (
219
+ _ComputationType.FULL_BACKWARD,
220
+ _ComputationType.BACKWARD_INPUT,
221
+ ):
222
+ return [
223
+ OpKey(stage_idx + 1, _ComputationType.FULL_BACKWARD, mb_idx),
224
+ OpKey(stage_idx + 1, _ComputationType.BACKWARD_INPUT, mb_idx),
225
+ ]
226
+
227
+ # Weight backward depends on input backward
228
+ if comp_type == _ComputationType.BACKWARD_WEIGHT:
229
+ return [OpKey(stage_idx, _ComputationType.BACKWARD_INPUT, mb_idx)]
230
+
231
+ raise RuntimeError(f"Unknown computation type: {comp_type}")
232
+
233
+ def is_action_ready(action: _Action, timestep: int) -> bool:
234
+ """Check if an action is ready to be scheduled at the given timestep."""
235
+ # For OR dependencies (like backward), check if any dependency is satisfied
236
+ if action.computation_type in (
237
+ _ComputationType.FULL_BACKWARD,
238
+ _ComputationType.BACKWARD_INPUT,
239
+ _ComputationType.BACKWARD_WEIGHT,
240
+ ):
241
+ dependencies = get_dependencies(action)
242
+ return any(is_dependency_ready(dep, timestep) for dep in dependencies)
243
+ # For AND dependencies, all must be satisfied
244
+ elif action.computation_type == _ComputationType.FORWARD:
245
+ dependencies = get_dependencies(action)
246
+ return all(is_dependency_ready(dep, timestep) for dep in dependencies)
247
+ elif action.computation_type == _ComputationType.OVERLAP_F_B:
248
+ if action.sub_actions is None:
249
+ raise AssertionError(
250
+ f"OVERLAP_F_B action {action} has None sub_actions"
251
+ )
252
+ dep_list: list[bool] = []
253
+ for sub_action in action.sub_actions:
254
+ dep_list.append(is_action_ready(sub_action, timestep))
255
+ return all(dep_list)
256
+ else:
257
+ raise RuntimeError(f"Unknown computation type: {action.computation_type}")
258
+
259
+ def schedule_action(action: _Action, rank: int, timestep: int) -> int:
260
+ """Schedule an action and return completion time."""
261
+ spaced_schedule[rank].append(action)
262
+ comp_type = action.computation_type
263
+ comp_time = action_type_to_color_mapping[comp_type].width
264
+ completion_time = timestep + comp_time
265
+
266
+ if comp_type == _ComputationType.OVERLAP_F_B:
267
+ # For overlap actions, schedule each sub-action with cumulative timing
268
+ if action.sub_actions is None:
269
+ raise AssertionError(
270
+ f"OVERLAP_F_B action {action} has None sub_actions"
271
+ )
272
+ cumulative_time = 0
273
+ for sub_action in action.sub_actions:
274
+ if sub_action.microbatch_index is None:
275
+ raise AssertionError(
276
+ f"Sub-action {sub_action} has None microbatch_index"
277
+ )
278
+ sub_comp_time = action_type_to_color_mapping[
279
+ sub_action.computation_type
280
+ ].width
281
+ cumulative_time += sub_comp_time
282
+ scheduled_ops[
283
+ OpKey(
284
+ sub_action.stage_index,
285
+ sub_action.computation_type,
286
+ sub_action.microbatch_index,
287
+ )
288
+ ] = timestep + cumulative_time
289
+ else:
290
+ if action.microbatch_index is None:
291
+ raise AssertionError(f"Action {action} has None microbatch_index")
292
+ scheduled_ops[
293
+ OpKey(action.stage_index, comp_type, action.microbatch_index)
294
+ ] = completion_time
295
+
296
+ return completion_time
297
+
298
+ # Main scheduling loop
299
+ current_timestep = 0
300
+ timesteps_without_progress = 0
301
+ rank_completion_times = dict.fromkeys(range(num_ranks), 0)
302
+ while rank_ops:
303
+ print(f"Current timestep: {current_timestep}")
304
+ # Process all operations during timestep until we run out of ready operations
305
+ for rank, op_queue in enumerate(rank_ops):
306
+ if not op_queue:
307
+ continue
308
+
309
+ op_queue = rank_ops[rank]
310
+ action = op_queue[0]
311
+ print(f"Rank: {rank}, {action=}")
312
+ if action is None:
313
+ spaced_schedule[rank].append(None)
314
+ op_queue.popleft()
315
+ timesteps_without_progress = 0
316
+ elif current_timestep >= rank_completion_times[rank] and is_action_ready(
317
+ action, current_timestep
318
+ ):
319
+ rank_completion_times[rank] = schedule_action(
320
+ action, rank, current_timestep
321
+ )
322
+ op_queue.popleft()
323
+ timesteps_without_progress = 0
324
+
325
+ # Add None for ranks that are waiting
326
+ for rank in range(num_ranks):
327
+ if current_timestep >= rank_completion_times[rank]:
328
+ spaced_schedule[rank].append(None)
329
+
330
+ # Remove empty queues and advance timestep
331
+ rank_ops = [op_queue for op_queue in rank_ops if op_queue]
332
+ current_timestep += 1
333
+ timesteps_without_progress += 1
334
+
335
+ if timesteps_without_progress > max(
336
+ visual.width for visual in action_type_to_color_mapping.values()
337
+ ):
338
+ raise RuntimeError("No progress made in scheduling - possible deadlock")
339
+
340
+ return spaced_schedule
341
+
342
+
343
+ def visualize_schedule(
344
+ schedule: list[list[_Action | None]],
345
+ filename: str | None = None,
346
+ ) -> None:
347
+ """
348
+ Visualize the schedule using matplotlib.
349
+ The schedule is a list of lists where each inner list represents a rank and each element in the inner list represents an action.
350
+ The actions are represented as rectangles with different colors based on their computation type.
351
+ The filename is optional and if provided, the plot will be saved to that file.
352
+
353
+ Args:
354
+ schedule: The schedule to visualize.
355
+ filename: The filename to save the plot to. If not provided, the plot will be displayed.
356
+ add_schedule_spacing: If True, add spacing to the schedule based on dependencies between ranks.
357
+
358
+ """
359
+
360
+ import matplotlib.pyplot as plt
361
+ from matplotlib.patches import Rectangle
362
+
363
+ plt.rcParams["font.family"] = (
364
+ "DejaVu Sans" # or any other font available on your system
365
+ )
366
+ num_ranks = len(schedule)
367
+ max_actions = max(len(rank) for rank in schedule)
368
+
369
+ # Increase the figure size to provide more space for the legend
370
+ fig, ax = plt.subplots(figsize=(max_actions + 2, num_ranks + 2))
371
+ max_draw_position = -1
372
+ # Calculate dynamic font size based on figure size
373
+ font_size = min(max_actions, num_ranks) + 4
374
+ used_computation = set()
375
+ for rank_idx, actions in enumerate(schedule):
376
+ draw_position = 0 # Initialize drawing position for each rank
377
+ for action in actions:
378
+ if action is not None:
379
+ comp_type_color = action_type_to_color_mapping.get(
380
+ action.computation_type, _ComputationTypeVisual("black")
381
+ )
382
+ used_computation.add(action.computation_type)
383
+ color = comp_type_color.color
384
+ width = comp_type_color.width
385
+
386
+ # Check if action has sub_actions to determine styling
387
+ if action.sub_actions is not None:
388
+ linewidth = 2 # Thicker border for compound actions
389
+ text_weight = "normal" # Bold text for compound actions
390
+ else:
391
+ linewidth = 1 # Default linewidth for regular actions
392
+ text_weight = "normal" # Default text weight
393
+
394
+ # Draw the rectangle to represent the action duration
395
+ rect = Rectangle(
396
+ (draw_position, num_ranks - rank_idx - 1),
397
+ width,
398
+ 1,
399
+ facecolor=color,
400
+ edgecolor="black",
401
+ linewidth=linewidth,
402
+ )
403
+ ax.add_patch(rect)
404
+
405
+ # Draw the text centered within the rectangle
406
+ ax.text(
407
+ draw_position + width / 2,
408
+ num_ranks - rank_idx - 1 + 0.5,
409
+ str(action),
410
+ ha="center",
411
+ va="center",
412
+ fontsize=font_size,
413
+ color="white",
414
+ weight=text_weight,
415
+ )
416
+
417
+ draw_position += width
418
+ else:
419
+ draw_position += 1 # Move to the next
420
+ max_draw_position = max(max_draw_position, draw_position)
421
+ ax.set_xlim(-0.5, max_draw_position + 1)
422
+ ax.set_ylim(-0.5, num_ranks + 0.5) # Add extra space at the top
423
+ # Set y-ticks to be in the middle of each rank's row
424
+ ax.set_yticks([num_ranks - rank_idx - 0.5 for rank_idx in range(num_ranks)])
425
+ ax.set_yticklabels([f"Rank {i}" for i in range(num_ranks)], fontsize=font_size)
426
+ ax.set_xticklabels([])
427
+
428
+ # Remove grid lines and ticks
429
+ ax.grid(False)
430
+ # Add legend with larger font size
431
+ legend_elements = [
432
+ Rectangle(
433
+ (0, 0),
434
+ 1,
435
+ 1,
436
+ facecolor=action_type_to_color_mapping[comp_type].color,
437
+ edgecolor="black",
438
+ label=action_type_to_color_mapping[comp_type].text,
439
+ )
440
+ for comp_type in used_computation
441
+ ]
442
+ ax.legend(handles=legend_elements, loc="upper right", fontsize=font_size)
443
+ # Save to file if filename is provided, otherwise display the plot
444
+ if filename:
445
+ plt.savefig(filename, bbox_inches="tight")
446
+ else:
447
+ plt.show()
venv/lib/python3.14/site-packages/torch/distributed/pipelining/_unflatten.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates
2
+ from collections import defaultdict
3
+
4
+ import torch
5
+ from torch.export.unflatten import _ModuleFrame, _SubmoduleEntry
6
+
7
+
8
+ def _outline_submodules(orig_graph: torch.fx.Graph) -> torch.fx.GraphModule:
9
+ # Create an empty GraphModule to hold the outlined modules
10
+ new_module = torch.fx.GraphModule(torch.nn.Module(), torch.fx.Graph())
11
+ seen_nodes: dict[str, torch.fx.Node] = {}
12
+ seen_modules: dict[int, list[_SubmoduleEntry]] = defaultdict(list)
13
+ seen_attrs: dict[str, set[str]] = defaultdict(set)
14
+ created_modules: dict[str, torch.nn.Module] = {}
15
+ _ModuleFrame(
16
+ orig_graph,
17
+ tuple(orig_graph.nodes),
18
+ seen_nodes,
19
+ seen_modules,
20
+ seen_attrs,
21
+ created_modules,
22
+ None,
23
+ [("", None, 0)],
24
+ "",
25
+ {},
26
+ module=new_module,
27
+ ).run_outer()
28
+ new_module.graph.lint()
29
+ new_module.recompile()
30
+ return new_module
venv/lib/python3.14/site-packages/torch/distributed/pipelining/_utils.py ADDED
@@ -0,0 +1,938 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates
3
+
4
+ from __future__ import annotations
5
+
6
+ import logging
7
+ import warnings
8
+ from dataclasses import dataclass, field
9
+ from enum import Enum
10
+ from typing import cast, Literal, overload, Protocol, TYPE_CHECKING, TypeAlias
11
+
12
+ import torch
13
+ from torch import fx
14
+ from torch.distributed._mesh_layout import _MeshLayout
15
+ from torch.distributed.tensor import DTensor
16
+ from torch.utils._pytree import tree_flatten, tree_unflatten
17
+
18
+
19
+ if TYPE_CHECKING:
20
+ from torch.distributed.device_mesh import DeviceMesh
21
+ from torch.distributed.tensor.placement_types import Placement
22
+
23
+
24
+ logger = logging.getLogger(__name__)
25
+
26
+
27
+ class GetMeshCallback(Protocol):
28
+ """Callback to create/retrieve a DeviceMesh from its cache key components."""
29
+
30
+ def __call__(
31
+ self,
32
+ mesh_dim_names: tuple[str, ...],
33
+ mesh_layout: _MeshLayout | None,
34
+ ) -> DeviceMesh: ...
35
+
36
+
37
+ # Key for mesh cache: (mesh_dim_names, mesh_layout)
38
+ # mesh_layout is the _MeshLayout object containing shape and stride (not actual ranks).
39
+ # This uniquely identifies a mesh within the same "universe" where all stages share
40
+ # the same rank tensor.
41
+ MeshCacheKey: TypeAlias = tuple[tuple[str, ...], _MeshLayout | None]
42
+
43
+
44
+ class PipeliningMetadataError(RuntimeError):
45
+ """Raised on metadata mismatches during pipeline communication."""
46
+
47
+
48
+ @dataclass(frozen=True, slots=True)
49
+ class _TensorMeta:
50
+ """Tensor metadata for recv buffer allocation and validation.
51
+
52
+ For plain tensors, these are the tensor's actual attributes.
53
+ For DTensors, these are LOCAL shard attributes; global attributes
54
+ are stored in :class:`_DTensorMeta`.
55
+ """
56
+
57
+ shape: torch.Size
58
+ stride: tuple[int, ...]
59
+ dtype: torch.dtype
60
+ requires_grad: bool
61
+
62
+ @staticmethod
63
+ def from_tensor(tensor: torch.Tensor) -> _TensorMeta:
64
+ """Create metadata from a plain tensor.
65
+
66
+ Args:
67
+ tensor: A plain ``torch.Tensor`` (not DTensor).
68
+
69
+ Returns:
70
+ Metadata capturing shape, stride, dtype, and requires_grad.
71
+
72
+ Raises:
73
+ TypeError: If ``tensor`` is a DTensor.
74
+ """
75
+ if isinstance(tensor, DTensor):
76
+ raise PipeliningMetadataError(
77
+ "Expected plain tensor, got DTensor. Use _DTensorMeta.from_dtensor instead."
78
+ )
79
+ return _TensorMeta(
80
+ shape=tensor.shape,
81
+ stride=tensor.stride(),
82
+ dtype=tensor.dtype,
83
+ requires_grad=tensor.requires_grad,
84
+ )
85
+
86
+ def to_tensor(self, device: torch.device | str) -> torch.Tensor:
87
+ """Reconstruct a tensor on ``device`` from this metadata.
88
+
89
+ Args:
90
+ device: Target device for the tensor.
91
+
92
+ Returns:
93
+ An empty strided tensor on ``device``.
94
+ """
95
+ t = _make_tensor_from_meta(self, device)
96
+ t.requires_grad_(self.requires_grad)
97
+ return t
98
+
99
+ def get_diff(self, other: _TensorMeta) -> list[str]:
100
+ """Return field-by-field differences with ``other``.
101
+
102
+ Args:
103
+ other: Metadata to compare against.
104
+
105
+ Returns:
106
+ List of human-readable difference strings (empty if equal).
107
+ """
108
+ if self == other:
109
+ return []
110
+
111
+ diffs = []
112
+ if self.shape != other.shape:
113
+ diffs.append(f"shape mismatch: {self.shape} vs {other.shape}")
114
+ if self.stride != other.stride:
115
+ diffs.append(f"stride mismatch: {self.stride} vs {other.stride}")
116
+ if self.dtype != other.dtype:
117
+ diffs.append(f"dtype mismatch: {self.dtype} vs {other.dtype}")
118
+ # requires_grad is intentionally excluded: it is a runtime concern
119
+ # determined by has_backward and grad context, not a metadata invariant.
120
+ return diffs
121
+
122
+
123
+ @dataclass(frozen=True, slots=True)
124
+ class _DTensorMeta(_TensorMeta):
125
+ """DTensor metadata extending :class:`_TensorMeta` with distribution info.
126
+
127
+ Inherited fields (shape, stride, etc.) are LOCAL shard attributes.
128
+ Additional fields capture global shape and placement information
129
+ needed to reconstruct a :class:`DTensor` via ``DTensor.from_local()``.
130
+
131
+ The :class:`DeviceMesh` is **not** stored (not serializable for P2P);
132
+ it is looked up from :class:`_MeshCache` using
133
+ ``(mesh_dim_names, mesh_layout)`` as the key.
134
+ """
135
+
136
+ # Global DTensor properties (for reconstruction)
137
+ global_shape: torch.Size = field(default_factory=lambda: torch.Size([]))
138
+ global_stride: tuple[int, ...] = field(default=())
139
+
140
+ # DTensor distribution properties
141
+ placements: tuple[Placement, ...] = field(
142
+ default=()
143
+ ) # e.g., (Shard(0), Replicate())
144
+
145
+ # Mesh identification - used to look up the correct DeviceMesh from cache
146
+ mesh_dim_names: tuple[str, ...] = field(default=()) # e.g., ("tp",) or ("dp", "tp")
147
+ mesh_layout: _MeshLayout | None = field(
148
+ default=None
149
+ ) # _MeshLayout with shape/stride - uniquely identifies mesh within the same universe
150
+
151
+ @staticmethod
152
+ def from_dtensor(dtensor: DTensor) -> _DTensorMeta:
153
+ """Create metadata from a DTensor.
154
+
155
+ Args:
156
+ dtensor: The DTensor to extract metadata from.
157
+
158
+ Returns:
159
+ Metadata capturing both local and global attributes.
160
+ """
161
+ device_mesh = dtensor.device_mesh
162
+
163
+ return _DTensorMeta(
164
+ # Local tensor attributes (for recv buffer allocation)
165
+ shape=dtensor._local_tensor.shape,
166
+ stride=dtensor._local_tensor.stride(),
167
+ dtype=dtensor.dtype,
168
+ requires_grad=dtensor.requires_grad,
169
+ # Global DTensor attributes (for reconstruction)
170
+ global_shape=dtensor.shape,
171
+ global_stride=dtensor.stride(),
172
+ # Distribution info
173
+ placements=dtensor._spec.placements,
174
+ mesh_dim_names=(
175
+ tuple(device_mesh.mesh_dim_names) if device_mesh.mesh_dim_names else ()
176
+ ),
177
+ mesh_layout=device_mesh._layout,
178
+ )
179
+
180
+ @property
181
+ def mesh_cache_key(self) -> MeshCacheKey:
182
+ """Cache key ``(mesh_dim_names, mesh_layout)`` for mesh lookup."""
183
+ return (self.mesh_dim_names, self.mesh_layout)
184
+
185
+ def to_dtensor(self, device: torch.device | str, mesh: DeviceMesh) -> DTensor:
186
+ """Reconstruct a DTensor on ``device`` with placements.
187
+
188
+ Args:
189
+ device: Target device for the local tensor.
190
+ mesh: The ``DeviceMesh`` to attach.
191
+
192
+ Returns:
193
+ A DTensor on ``device``.
194
+ """
195
+ local_tensor = _make_tensor_from_meta(self, device)
196
+ # Set requires_grad after from_local() so that the from_local
197
+ # operation itself is not recorded in the autograd graph.
198
+ return cast(
199
+ DTensor,
200
+ DTensor.from_local(
201
+ local_tensor,
202
+ device_mesh=mesh,
203
+ placements=self.placements,
204
+ shape=self.global_shape,
205
+ stride=self.global_stride,
206
+ run_check=False,
207
+ ).requires_grad_(self.requires_grad),
208
+ )
209
+
210
+ def get_diff(self, other: _TensorMeta) -> list[str]:
211
+ """Return field-by-field differences, including DTensor-specific fields.
212
+
213
+ Args:
214
+ other: Metadata to compare against.
215
+
216
+ Returns:
217
+ List of human-readable difference strings (empty if equal).
218
+ """
219
+ if self == other:
220
+ return []
221
+
222
+ # Get base class differences (compares local shape/stride/dtype/requires_grad)
223
+ # NOTE: Use explicit class call instead of super() because
224
+ # @dataclass(slots=True) on both parent and child can break super().
225
+ diffs = _TensorMeta.get_diff(self, other)
226
+
227
+ # Add DTensor-specific comparisons if other is also _DTensorMeta
228
+ if isinstance(other, _DTensorMeta):
229
+ if self.global_shape != other.global_shape:
230
+ diffs.append(
231
+ f"global_shape mismatch: {self.global_shape} vs {other.global_shape}"
232
+ )
233
+ if self.global_stride != other.global_stride:
234
+ diffs.append(
235
+ f"global_stride mismatch: {self.global_stride} vs {other.global_stride}"
236
+ )
237
+ if self.placements != other.placements:
238
+ diffs.append(
239
+ f"placements mismatch: {self.placements} vs {other.placements}"
240
+ )
241
+ if self.mesh_dim_names != other.mesh_dim_names:
242
+ diffs.append(
243
+ f"mesh_dim_names mismatch: {self.mesh_dim_names} vs {other.mesh_dim_names}"
244
+ )
245
+ if self.mesh_layout != other.mesh_layout:
246
+ diffs.append(
247
+ f"mesh_layout mismatch: {self.mesh_layout} vs {other.mesh_layout}"
248
+ )
249
+ else:
250
+ diffs.append("type: _DTensorMeta vs _TensorMeta")
251
+
252
+ return diffs
253
+
254
+
255
+ # Type alias for union of tensor metadata types
256
+ TensorMeta: TypeAlias = _TensorMeta | _DTensorMeta
257
+
258
+
259
+ # Not frozen: fields are populated incrementally during forward and
260
+ # backward metadata inference or from user provided static metadata
261
+ @dataclass(slots=True)
262
+ class _StageMeta:
263
+ """Consolidated tensor metadata for a pipeline stage's forward and backward passes."""
264
+
265
+ inputs: tuple[TensorMeta, ...] | None = None
266
+ outputs: tuple[TensorMeta, ...] | None = None
267
+ input_grads: tuple[TensorMeta | None, ...] | None = None
268
+ output_grads: tuple[TensorMeta | None, ...] | None = None
269
+
270
+ def has_any(self) -> bool:
271
+ """Check if any metadata field is populated."""
272
+ return any(
273
+ v is not None
274
+ for v in [self.inputs, self.outputs, self.input_grads, self.output_grads]
275
+ )
276
+
277
+ def has_dtensors(self) -> bool:
278
+ """Check if any input/output metadata is DTensor type."""
279
+ for metas in [self.inputs, self.outputs]:
280
+ if metas and any(isinstance(m, _DTensorMeta) for m in metas if m):
281
+ return True
282
+ return False
283
+
284
+ def is_complete_for_forward(self) -> bool:
285
+ """Check if forward metadata is fully populated."""
286
+ return self.inputs is not None and self.outputs is not None
287
+
288
+
289
+ @dataclass(frozen=True, slots=True)
290
+ class _StageForwardMeta:
291
+ """Forward metadata transmitted from stage *i* to stage *i+1* during inference."""
292
+
293
+ forward_metas: tuple[TensorMeta, ...] # Stage i's outputs → Stage i+1's inputs
294
+
295
+
296
+ @dataclass(frozen=True, slots=True)
297
+ class _StageBackwardMeta:
298
+ """Backward metadata transmitted from stage *i* to stage *i-1* during inference.
299
+
300
+ Gradient placements may differ from forward activations
301
+ (e.g., ``Replicate`` → ``Partial``).
302
+ """
303
+
304
+ backward_metas: tuple[
305
+ TensorMeta | None, ...
306
+ ] # Stage i's input_grads → Stage i-1's output_grads
307
+
308
+
309
+ def _make_tensor_from_meta(
310
+ meta: _TensorMeta,
311
+ device: torch.device | str,
312
+ ) -> torch.Tensor:
313
+ """Create a tensor from metadata.
314
+
315
+ Args:
316
+ meta: Metadata with shape, stride, and dtype.
317
+ device: Target device for the tensor.
318
+
319
+ Returns:
320
+ Empty tensor preserving the exact memory layout.
321
+ """
322
+ return torch.empty_strided(
323
+ size=meta.shape,
324
+ stride=meta.stride,
325
+ dtype=meta.dtype,
326
+ device=device,
327
+ )
328
+
329
+
330
+ def _derive_grad_metas(
331
+ tensor_metas: tuple[TensorMeta, ...],
332
+ ) -> tuple[_TensorMeta | None, ...]:
333
+ """Derive gradient metadata from tensor metadata.
334
+
335
+ Returns metadata with the same shape/stride/dtype but ``requires_grad=False``.
336
+ Entries where the source has ``requires_grad=False`` become ``None``.
337
+ """
338
+ return tuple(
339
+ _TensorMeta(shape=m.shape, stride=m.stride, dtype=m.dtype, requires_grad=False)
340
+ if m.requires_grad
341
+ else None
342
+ for m in tensor_metas
343
+ )
344
+
345
+
346
+ class _MeshCache:
347
+ """Cache for :class:`DeviceMesh` objects keyed by ``(mesh_dim_names, mesh_layout)``.
348
+
349
+ Assumes all pipeline stages share the same rank tensor (true for
350
+ TorchTitan-style frameworks where meshes derive from a common world).
351
+ """
352
+
353
+ def __init__(self, get_mesh_cb: GetMeshCallback | None = None) -> None:
354
+ self._cache: dict[MeshCacheKey, DeviceMesh] = {}
355
+ self._get_mesh_cb = get_mesh_cb
356
+
357
+ def get_mesh(self, key: MeshCacheKey) -> DeviceMesh:
358
+ """Return a cached mesh, or create one via the callback.
359
+
360
+ Args:
361
+ key: Cache key ``(mesh_dim_names, mesh_layout)``.
362
+
363
+ Returns:
364
+ The ``DeviceMesh``.
365
+
366
+ Raises:
367
+ PipeliningMetadataError: If not cached and no callback provided.
368
+ """
369
+ if key in self._cache:
370
+ return self._cache[key]
371
+
372
+ mesh_dim_names, mesh_layout = key
373
+
374
+ if self._get_mesh_cb is None:
375
+ raise PipeliningMetadataError(
376
+ f"Mesh not found in cache for mesh_dim_names={mesh_dim_names}, "
377
+ f"mesh_layout={mesh_layout}, and no get_mesh callback provided. "
378
+ f"Provide a get_mesh callback or use DTensors in static mode."
379
+ )
380
+
381
+ mesh = self._get_mesh_cb(mesh_dim_names, mesh_layout)
382
+ if mesh is None:
383
+ raise PipeliningMetadataError(
384
+ f"Mesh lookup failed: callback returned None for "
385
+ f"mesh_dim_names={mesh_dim_names}, mesh_layout={mesh_layout}. "
386
+ f"Ensure all stages use meshes from the same universe."
387
+ )
388
+ self._cache[key] = mesh
389
+ return mesh
390
+
391
+ def put(self, key: MeshCacheKey, mesh: DeviceMesh) -> None:
392
+ """Add a mesh to the cache."""
393
+ self._cache[key] = mesh
394
+
395
+ def update_from_tensors(self, tensors: tuple[torch.Tensor | None, ...]) -> None:
396
+ """Extract and cache meshes from any :class:`DTensor` instances in *tensors*."""
397
+ for tensor in tensors:
398
+ if isinstance(tensor, DTensor):
399
+ mesh = tensor.device_mesh
400
+ dim_names = tuple(mesh.mesh_dim_names) if mesh.mesh_dim_names else ()
401
+ mesh_layout = mesh._layout
402
+ key = (dim_names, mesh_layout)
403
+ if key not in self._cache:
404
+ self._cache[key] = mesh
405
+
406
+ def __contains__(self, key: MeshCacheKey) -> bool:
407
+ return key in self._cache
408
+
409
+ def __len__(self) -> int:
410
+ return len(self._cache)
411
+
412
+
413
+ # ============================================================================
414
+ # Inference mode enum
415
+ # ============================================================================
416
+
417
+
418
+ class InferenceMode(Enum):
419
+ """Pipeline-level metadata inference mode, determined collectively across all PP ranks.
420
+
421
+ The mode is set by the schedule (not individual stages) because
422
+ ``has_backward`` is only known at schedule creation time and all
423
+ stages must agree to avoid P2P hangs.
424
+
425
+ .. attribute:: STATIC
426
+
427
+ All stages have sufficient metadata; runtime inference is skipped.
428
+
429
+ .. attribute:: DYNAMIC
430
+
431
+ At least one stage requires runtime metadata inference.
432
+ """
433
+
434
+ STATIC = "static"
435
+ DYNAMIC = "dynamic"
436
+
437
+ @classmethod
438
+ def needs_dynamic(cls, meta: _StageMeta, stage_has_backward: bool) -> bool:
439
+ """Determine whether dynamic metadata inference is needed for a stage.
440
+
441
+ Args:
442
+ meta: Stage metadata from user-provided args.
443
+ stage_has_backward: Whether a backward pass will be performed.
444
+
445
+ Returns:
446
+ ``True`` if dynamic inference is needed.
447
+ """
448
+ # Case 1: Forward metadata incomplete → needs DYNAMIC
449
+ if not meta.is_complete_for_forward():
450
+ return True
451
+
452
+ # Case 2: No DTensors → STATIC is fine (bwd metadata derivable from fwd metadata)
453
+ if not meta.has_dtensors():
454
+ return False
455
+
456
+ # Case 3: No backward needed → STATIC is fine (don't need grad metadata)
457
+ if not stage_has_backward:
458
+ return False
459
+
460
+ # Case 4: DTensors with backward but missing ANY grad metadata → needs DYNAMIC
461
+ # Both input_grads AND output_grads are required for static mode with DTensors
462
+ if meta.input_grads is None or meta.output_grads is None:
463
+ return True
464
+
465
+ # Case 5: DTensors with complete grads → STATIC is fine
466
+ return False
467
+
468
+
469
+ # ============================================================================
470
+ # Utility functions
471
+ # ============================================================================
472
+
473
+
474
+ def flatten_args(args, *, detach: bool = False):
475
+ """Flatten ``args`` into a list, optionally detaching tensors.
476
+
477
+ Args:
478
+ args: Nested arguments to flatten.
479
+ detach: If ``True``, detach tensors while preserving ``requires_grad``.
480
+
481
+ Returns:
482
+ ``(new_args, flat_detached_args)`` when ``detach=True``;
483
+ ``flat_args`` list otherwise.
484
+ """
485
+ flat_args, treespec = tree_flatten(args)
486
+
487
+ if detach:
488
+ flat_detached = [
489
+ a.detach().requires_grad_(a.requires_grad)
490
+ if isinstance(a, torch.Tensor)
491
+ else a
492
+ for a in flat_args
493
+ ]
494
+ new_args = tree_unflatten(flat_detached, treespec)
495
+ return new_args, flat_detached
496
+
497
+ return flat_args
498
+
499
+
500
+ # Backward compatibility alias
501
+ def flatten_args_detach(args):
502
+ """Flatten and detach. Deprecated: use ``flatten_args(args, detach=True)``."""
503
+ return flatten_args(args, detach=True)
504
+
505
+
506
+ def generate_stage_to_rank_mapping(
507
+ pp_size: int, num_stages: int, style: str = "loop"
508
+ ) -> dict[int, int]:
509
+ """
510
+ Compute the stage id to rank mapping for either a looped or V-style schedule.
511
+
512
+ Most commonly num_stages == pp_size * 2, but this function can be used to
513
+ compute the mapping for any number of stages per rank.
514
+ """
515
+ mapping = {}
516
+ if style == "loop":
517
+ for stage_index in range(num_stages):
518
+ mapping[stage_index] = stage_index % pp_size
519
+ elif style == "v":
520
+ if num_stages % pp_size != 0:
521
+ raise ValueError(
522
+ f"num_stages {num_stages} must be evenly divisible by pp_size {pp_size} for V schedules"
523
+ )
524
+
525
+ rank_index = 0
526
+ for stage_index in range(num_stages):
527
+ mapping[stage_index] = rank_index
528
+ # dont change rank if we are on the border (to keep v shape)
529
+ if (stage_index + 1) % pp_size == 0:
530
+ continue
531
+ if (stage_index // pp_size) % 2 == 0:
532
+ rank_index += 1
533
+ else:
534
+ rank_index -= 1
535
+ else:
536
+ raise ValueError(f"Style {style} is not supported.")
537
+ return mapping
538
+
539
+
540
+ def generate_rank_to_stage_mapping(
541
+ pp_size: int, num_stages: int, style: str = "loop"
542
+ ) -> dict[int, list[int]]:
543
+ """
544
+ Compute the rank to stage id mapping for either a looped or V-style schedule.
545
+
546
+ This function inverts the stage_to_rank_mapping to get which stages are assigned to each rank.
547
+
548
+ Returns a dictionary mapping rank -> list of stage indices assigned to that rank.
549
+ """
550
+ stage_to_rank = generate_stage_to_rank_mapping(pp_size, num_stages, style)
551
+
552
+ # Invert the mapping: rank -> list of stages
553
+ rank_to_stages: dict[int, list[int]] = {}
554
+ for stage_id, rank in stage_to_rank.items():
555
+ if rank not in rank_to_stages:
556
+ rank_to_stages[rank] = []
557
+ rank_to_stages[rank].append(stage_id)
558
+
559
+ # Sort the stage lists for each rank to ensure consistent ordering
560
+ for stages in rank_to_stages.values():
561
+ stages.sort()
562
+
563
+ return rank_to_stages
564
+
565
+
566
+ @dataclass(slots=True)
567
+ class PipeInfo:
568
+ """
569
+ Captures information for a pipeline (`Pipe` object).
570
+ """
571
+
572
+ graph: fx.Graph
573
+ num_stages: int
574
+ has_loss_and_backward: bool
575
+
576
+
577
+ # ============================================================================
578
+ # Metadata extraction helpers
579
+ # ============================================================================
580
+
581
+
582
+ def extract_tensor_meta(tensor: torch.Tensor) -> TensorMeta:
583
+ """Extract metadata from a tensor.
584
+
585
+ Handles both plain Tensor and DTensor correctly: DTensors are
586
+ dispatched to ``_DTensorMeta.from_dtensor`` which captures local
587
+ shard attributes plus global shape/placement info, while plain
588
+ tensors use ``_TensorMeta.from_tensor``.
589
+
590
+ Args:
591
+ tensor: A plain tensor or DTensor.
592
+
593
+ Returns:
594
+ ``_TensorMeta`` for plain tensors, ``_DTensorMeta`` for DTensors.
595
+ """
596
+ if isinstance(tensor, DTensor):
597
+ return _DTensorMeta.from_dtensor(tensor)
598
+ else:
599
+ return _TensorMeta.from_tensor(tensor)
600
+
601
+
602
+ @overload
603
+ def extract_tensor_metas(
604
+ tensors: tuple[torch.Tensor, ...] | None,
605
+ *,
606
+ allow_none: Literal[False] = ...,
607
+ ) -> tuple[TensorMeta, ...] | None: ...
608
+
609
+
610
+ @overload
611
+ def extract_tensor_metas(
612
+ tensors: tuple[torch.Tensor | None, ...] | None,
613
+ *,
614
+ allow_none: Literal[True],
615
+ ) -> tuple[TensorMeta | None, ...] | None: ...
616
+
617
+
618
+ def extract_tensor_metas(
619
+ tensors: tuple[torch.Tensor | None, ...] | tuple[torch.Tensor, ...] | None,
620
+ *,
621
+ allow_none: bool = False,
622
+ ) -> tuple[TensorMeta | None, ...] | None:
623
+ """Extract metadata from a tuple of tensors.
624
+
625
+ Args:
626
+ tensors: Tuple of tensors (may include ``None`` when ``allow_none=True``).
627
+ allow_none: If ``True``, preserve ``None`` elements (for gradients).
628
+
629
+ Returns:
630
+ Tuple of ``TensorMeta``, or ``None`` if ``tensors`` is ``None``.
631
+
632
+ Raises:
633
+ PipeliningMetadataError: If ``None`` found and ``allow_none=False``.
634
+ """
635
+ if tensors is None:
636
+ return None
637
+
638
+ metas_with_none: list[TensorMeta | None] = []
639
+ has_none = False
640
+ for t in tensors:
641
+ if isinstance(t, torch.Tensor):
642
+ metas_with_none.append(extract_tensor_meta(t))
643
+ else:
644
+ has_none = True
645
+ metas_with_none.append(None)
646
+ if not allow_none and has_none:
647
+ raise PipeliningMetadataError(
648
+ "None values are not allowed in tensor metadata tuples. "
649
+ "Use allow_none=True for optional values."
650
+ )
651
+ return tuple(metas_with_none)
652
+
653
+
654
+ def to_local_if_dtensor(tensor: torch.Tensor, detach: bool = False) -> torch.Tensor:
655
+ """Convert a DTensor to its local shard, or return a plain tensor as-is.
656
+
657
+ When ``detach=True``, the tensor is detached before conversion —
658
+ this applies to both DTensors and plain tensors.
659
+
660
+ Args:
661
+ tensor: A tensor that may be a DTensor.
662
+ detach: If ``True``, detach before ``to_local()`` to avoid
663
+ redistribution during backward.
664
+
665
+ Returns:
666
+ The local tensor component.
667
+ """
668
+ maybe_detached_tensor = tensor.detach() if detach else tensor
669
+ if isinstance(maybe_detached_tensor, DTensor):
670
+ return maybe_detached_tensor.to_local()
671
+ return maybe_detached_tensor
672
+
673
+
674
+ @overload
675
+ def validate_and_normalize_to_tuple(
676
+ args: torch.Tensor | tuple[torch.Tensor, ...] | list[torch.Tensor] | None,
677
+ allow_none: Literal[False] = ...,
678
+ ) -> tuple[torch.Tensor, ...] | None: ...
679
+
680
+
681
+ @overload
682
+ def validate_and_normalize_to_tuple(
683
+ args: torch.Tensor
684
+ | tuple[torch.Tensor | None, ...]
685
+ | list[torch.Tensor | None]
686
+ | None,
687
+ allow_none: Literal[True] = ...,
688
+ ) -> tuple[torch.Tensor | None, ...] | None: ...
689
+
690
+
691
+ def validate_and_normalize_to_tuple(
692
+ args: torch.Tensor
693
+ | tuple[torch.Tensor, ...]
694
+ | tuple[torch.Tensor | None, ...]
695
+ | list[torch.Tensor]
696
+ | list[torch.Tensor | None]
697
+ | None,
698
+ allow_none: bool = False,
699
+ ) -> tuple[torch.Tensor | None, ...] | tuple[torch.Tensor, ...] | None:
700
+ """Normalize ``args`` to a tuple and validate that all elements are tensors.
701
+
702
+ Args:
703
+ args: A single tensor, tuple/list of tensors, or ``None``.
704
+ allow_none: If ``True``, permit ``None`` elements (for gradients).
705
+
706
+ Returns:
707
+ Tuple of tensors, or ``None`` if ``args`` is ``None``.
708
+
709
+ Raises:
710
+ PipeliningMetadataError: On non-tensor values
711
+ (or ``None`` when ``allow_none=False``).
712
+ """
713
+ if args is None:
714
+ return None
715
+ elif isinstance(args, torch.Tensor):
716
+ return (args,)
717
+ elif isinstance(args, (tuple, list)):
718
+ for i, arg in enumerate(args):
719
+ if arg is None:
720
+ if not allow_none:
721
+ raise PipeliningMetadataError(
722
+ f"Stage arg[{i}] is None. "
723
+ f"Stage args must be tensors. Use kwargs for optional values."
724
+ )
725
+ continue
726
+ if not isinstance(arg, torch.Tensor):
727
+ raise PipeliningMetadataError(
728
+ f"Stage arg[{i}] has type {type(arg).__name__}. "
729
+ f"All stage args must be tensors. Use kwargs for non-tensor inputs."
730
+ )
731
+ # Normalize list to tuple
732
+ return tuple(args) if isinstance(args, list) else args
733
+ else:
734
+ raise PipeliningMetadataError(
735
+ f"Stage args must be a tensor, tuple, or list of tensors, got {type(args).__name__}."
736
+ )
737
+
738
+
739
+ # ============================================================================
740
+ # Validation functions
741
+ # ============================================================================
742
+
743
+
744
+ def validate_metadata(
745
+ desc: str,
746
+ expected: TensorMeta,
747
+ actual: torch.Tensor | TensorMeta,
748
+ *,
749
+ raise_on_mismatch: bool = False,
750
+ warn_on_mismatch: bool = False,
751
+ ) -> list[str]:
752
+ """
753
+ Compare expected metadata against actual tensor or metadata.
754
+
755
+ This is the unified validation/comparison function that uses get_diff() from
756
+ metadata classes. Works with both plain tensors and DTensors.
757
+
758
+ For plain tensors: compares shape/stride/dtype/requires_grad.
759
+ For DTensors: compares all properties including global shape and placements.
760
+
761
+ Args:
762
+ desc: Description for error/warning messages.
763
+ expected: Expected tensor metadata (_TensorMeta or _DTensorMeta).
764
+ actual: Actual tensor or metadata to compare against.
765
+ raise_on_mismatch: If True, raise PipeliningMetadataError on mismatch.
766
+ warn_on_mismatch: If True, issue a warning on mismatch.
767
+
768
+ Returns:
769
+ List of differences (empty if metadata matches).
770
+
771
+ Raises:
772
+ PipeliningMetadataError: If raise_on_mismatch=True and differences exist.
773
+ """
774
+ # Extract metadata if actual is a tensor
775
+ if isinstance(actual, torch.Tensor):
776
+ actual_meta = extract_tensor_meta(actual)
777
+ else:
778
+ actual_meta = actual
779
+
780
+ # Type check: ensure both are same type for meaningful comparison
781
+ if type(expected) is not type(actual_meta):
782
+ type_diff = [
783
+ f"type: expected {type(expected).__name__}, got {type(actual_meta).__name__}"
784
+ ]
785
+ if raise_on_mismatch:
786
+ raise PipeliningMetadataError(f"{desc}: {type_diff[0]}")
787
+ if warn_on_mismatch:
788
+ warnings.warn(
789
+ f"{desc}: Metadata type mismatch. {type_diff[0]}. "
790
+ f"Using dynamically inferred metadata instead.",
791
+ UserWarning,
792
+ stacklevel=2,
793
+ )
794
+ return type_diff
795
+
796
+ # Use get_diff() from the metadata class
797
+ diffs = expected.get_diff(actual_meta)
798
+
799
+ if diffs:
800
+ if raise_on_mismatch:
801
+ raise PipeliningMetadataError(f"{desc}: {'; '.join(diffs)}")
802
+ if warn_on_mismatch:
803
+ warnings.warn(
804
+ f"{desc}: Metadata mismatch. {'; '.join(diffs)}. "
805
+ f"Using dynamically inferred metadata instead.",
806
+ UserWarning,
807
+ stacklevel=2,
808
+ )
809
+
810
+ return diffs
811
+
812
+
813
+ def validate_tensors_metadata(
814
+ desc: str,
815
+ expected: tuple[TensorMeta | None, ...],
816
+ actual: tuple[torch.Tensor | TensorMeta | None, ...],
817
+ *,
818
+ raise_on_mismatch: bool = True,
819
+ warn_on_mismatch: bool = False,
820
+ ) -> list[str]:
821
+ """Validate metadata for a tuple of tensors element-wise.
822
+
823
+ Args:
824
+ desc: Description prefix for error/warning messages.
825
+ expected: Tuple of expected metadata (may include ``None`` for grads).
826
+ actual: Tuple of actual tensors or metadata to compare against.
827
+ raise_on_mismatch: If ``True``, raise on the first mismatch.
828
+ warn_on_mismatch: If ``True``, issue warnings for mismatches.
829
+
830
+ Returns:
831
+ Aggregated list of difference strings.
832
+
833
+ Raises:
834
+ PipeliningMetadataError: If lengths differ or on mismatch.
835
+ """
836
+ if len(expected) != len(actual):
837
+ msg = f"{desc}: expected {len(expected)} tensors, got {len(actual)}"
838
+ if raise_on_mismatch:
839
+ raise PipeliningMetadataError(msg)
840
+ if warn_on_mismatch:
841
+ warnings.warn(msg, UserWarning, stacklevel=2)
842
+ return [msg]
843
+
844
+ all_diffs: list[str] = []
845
+ for i, (exp, act) in enumerate(zip(expected, actual, strict=True)):
846
+ if exp is None and act is None:
847
+ continue
848
+ if exp is None or act is None:
849
+ msg = (
850
+ f"{desc}[{i}]: expected {'None' if exp is None else 'metadata'}, "
851
+ f"got {'None' if act is None else 'metadata'}"
852
+ )
853
+ if raise_on_mismatch:
854
+ raise PipeliningMetadataError(msg)
855
+ if warn_on_mismatch:
856
+ warnings.warn(msg, UserWarning, stacklevel=2)
857
+ all_diffs.append(msg)
858
+ continue
859
+ diffs = validate_metadata(
860
+ f"{desc}[{i}]",
861
+ exp,
862
+ act,
863
+ raise_on_mismatch=raise_on_mismatch,
864
+ warn_on_mismatch=warn_on_mismatch,
865
+ )
866
+ all_diffs.extend(diffs)
867
+ return all_diffs
868
+
869
+
870
+ def validate_static_arg_grad_correspondence(
871
+ stage_index: int,
872
+ args: tuple[torch.Tensor, ...],
873
+ grads: tuple[torch.Tensor | None, ...],
874
+ is_input: bool,
875
+ ) -> None:
876
+ """
877
+ Validate the args↔grads contract for static mode.
878
+
879
+ Enforces four rules for each (arg, grad) pair:
880
+ 1. len(args) must equal len(grads).
881
+ 2. If arg.requires_grad is False, grad must be None.
882
+ 3. If arg.requires_grad is True and grad is None, emit a warning
883
+ (this is legal at pipeline boundaries but may indicate a bug).
884
+ 4. If arg is a DTensor with requires_grad=True and grad is not None,
885
+ grad must also be a DTensor.
886
+
887
+ Args:
888
+ stage_index: The stage index for error messages.
889
+ args: Tuple of forward tensors.
890
+ grads: Tuple of gradient tensors (can include None).
891
+ is_input: True for input_args/input_grads, False for output_args/output_grads.
892
+
893
+ Raises:
894
+ PipeliningMetadataError: If any hard rule (1, 2, or 4) is violated.
895
+ """
896
+ kind = "input" if is_input else "output"
897
+ args_name = f"{kind}_args"
898
+ grads_name = f"{kind}_grads"
899
+
900
+ # Rule 1: lengths must match
901
+ if len(args) != len(grads):
902
+ raise PipeliningMetadataError(
903
+ f"Stage {stage_index}: {grads_name} length ({len(grads)}) does not match "
904
+ f"{args_name} length ({len(args)}). Each forward tensor must have a "
905
+ f"corresponding gradient entry (use None for tensors that don't require grad)."
906
+ )
907
+
908
+ for i, (arg, grad) in enumerate(zip(args, grads, strict=True)):
909
+ # Rule 2: no grad for a non-differentiable arg
910
+ if not arg.requires_grad and grad is not None:
911
+ raise PipeliningMetadataError(
912
+ f"Stage {stage_index}: {args_name}[{i}] has requires_grad=False, "
913
+ f"but {grads_name}[{i}] is not None ({type(grad).__name__}). "
914
+ f"Non-differentiable tensors must have None as their gradient entry."
915
+ )
916
+
917
+ # Rule 3: missing grad for a differentiable arg (warn, don't raise)
918
+ if arg.requires_grad and grad is None:
919
+ warnings.warn(
920
+ f"Stage {stage_index}: {args_name}[{i}] has requires_grad=True, "
921
+ f"but {grads_name}[{i}] is None. This is legal at pipeline boundaries "
922
+ f"but may indicate a missing gradient.",
923
+ UserWarning,
924
+ stacklevel=2,
925
+ )
926
+
927
+ # Rule 4: DTensor arg must have DTensor grad
928
+ if (
929
+ isinstance(arg, DTensor)
930
+ and arg.requires_grad
931
+ and grad is not None
932
+ and not isinstance(grad, DTensor)
933
+ ):
934
+ raise PipeliningMetadataError(
935
+ f"Stage {stage_index}: {args_name}[{i}] is a DTensor with requires_grad=True, "
936
+ f"but {grads_name}[{i}] is {type(grad).__name__}, expected DTensor or None. "
937
+ f"DTensor gradients may have different placements than forward tensors."
938
+ )