Safetensors
English
amarinference commited on
Commit
65fef67
·
verified ·
1 Parent(s): 09706c0

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ tokenizer.json filter=lfs diff=lfs merge=lfs -text
_fsdp_api.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from dataclasses import dataclass
3
+ from typing import Optional
4
+
5
+ import torch
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class MixedPrecisionPolicy:
10
+ """
11
+ This configures FSDP's mixed precision. Unlike autocast, this applies mixed
12
+ precision at the module level, not op level, which means low-precision
13
+ activations are saved for backward and high-to-low-precision casts are
14
+ incurred only at module boundaries.
15
+
16
+ FSDP works well with module-level mixed precision since it keeps the
17
+ high-precision sharded parameters in memory anyway. In other words, FSDP
18
+ does not require any extra memory to keep a high-precision copy of the
19
+ parameters for the optimizer step.
20
+
21
+ Attributes:
22
+ param_dtype (Optional[torch.dtype]): This specifies the dtype for
23
+ the unsharded parameter and hence the dtype for forward/backward
24
+ computation and the parameter all-gather. If this is ``None``, then
25
+ the unsharded parameter uses the original dtype. The optimizer step
26
+ uses the sharded parameter in the original dtype. (Default:
27
+ ``None``)
28
+ reduce_dtype (Optional[torch.dtype]): This specifies the dtype for
29
+ gradient reduction (i.e. reduce-scatter or all-reduce). If this is
30
+ ``None`` but ``param_dtype`` is not ``None``, then the reduction
31
+ uses the compute dtype. This can be used to run gradient reduction
32
+ in full precision while using low precision for compute. If also
33
+ gradient reduction is disabled via :meth:`set_requires_gradient_sync`,
34
+ then FSDP will accumulate gradients using ``reduce_dtype``.
35
+ (Default: ``None``)
36
+ output_dtype (Optional[torch.dtype]): This specifies the dtype for
37
+ casting floating-point forward outputs. This can be used to
38
+ help implement cases where different modules have different mixed
39
+ precision policies. (Default: ``None``)
40
+ cast_forward_inputs (bool): This specifies whether FSDP should cast the
41
+ forward's floating-point input tensors to ``param_dtype`` or not.
42
+ """
43
+
44
+ param_dtype: Optional[torch.dtype] = None
45
+ reduce_dtype: Optional[torch.dtype] = None
46
+ output_dtype: Optional[torch.dtype] = None
47
+ cast_forward_inputs: bool = True
48
+
49
+
50
+ @dataclass
51
+ class OffloadPolicy:
52
+ """
53
+ This base class represents the policy of no offloading and is only used as
54
+ the default value for the ``offload_policy`` arg.
55
+ """
56
+
57
+
58
+ @dataclass
59
+ class CPUOffloadPolicy(OffloadPolicy):
60
+ """
61
+ This offload policy offloads parameters, gradients, and optimizer states to
62
+ CPU. Sharded parameters are copied host-to-device before all-gather. The
63
+ all-gathered parameters are freed according to ``reshard_after_forward``.
64
+ Sharded gradients are copied device-to-host in backward, and the optimizer
65
+ step runs on CPU with CPU optimizer states.
66
+
67
+ Attributes:
68
+ pin_memory (bool): Whether to pin sharded parameter and gradient
69
+ memory. Pinning memory allows both more efficient H2D/D2H copies
70
+ and for the copies to overlap with compute. However, the pinned
71
+ memory cannot be used by other processes. Set this to ``False`` if
72
+ you have insufficient CPU memory. (Default: ``True``)
73
+ """
74
+
75
+ pin_memory: bool = True
_fsdp_collectives.py ADDED
@@ -0,0 +1,580 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from itertools import chain
2
+ from typing import Callable, cast, NamedTuple, Optional, Union
3
+
4
+ import torch
5
+ import torch.distributed as dist
6
+ from torch.distributed.device_mesh import _get_device_handle
7
+ from torch.distributed.distributed_c10d import ReduceOp
8
+ from torch.distributed.tensor import DTensor
9
+
10
+ from ._fsdp_common import (
11
+ _get_dim0_padded_size,
12
+ _raise_assert_with_print,
13
+ _to_dtype_if_needed,
14
+ compiled_autograd_enabled,
15
+ )
16
+ from ._fsdp_param import FSDPParam, ShardedState
17
+
18
+
19
+ class AllGatherResult(NamedTuple):
20
+ all_gather_output: torch.Tensor
21
+ all_gather_event: Optional[torch.Event]
22
+ all_gather_work: Optional[dist.distributed_c10d.Work]
23
+ # For each parameter, the all-gather input dtype for each input
24
+ param_all_gather_input_dtypes: list[list[torch.dtype]]
25
+ # For each parameter, the all-gather input numel for each input
26
+ param_all_gather_input_numels: list[list[int]]
27
+ # 1D flattened version of `param_all_gather_input_numels` saved to avoid
28
+ # CPU overhead from recomputing
29
+ all_gather_input_split_sizes: list[int]
30
+
31
+
32
+ lib = torch.library.Library("fsdp", "FRAGMENT") # noqa: TOR901
33
+
34
+ lib.define(
35
+ """
36
+ all_gather_copy_in(
37
+ Tensor[] all_gather_inputs,
38
+ SymInt[] inp_split_sizes,
39
+ SymInt all_gather_input_numel,
40
+ SymInt world_size,
41
+ SymInt rank,
42
+ ScalarType dtype,
43
+ Device device
44
+ ) -> (Tensor, Tensor)
45
+ """
46
+ )
47
+
48
+
49
+ @torch.library.impl(lib, "all_gather_copy_in", "Meta")
50
+ def all_gather_copy_in_meta(
51
+ all_gather_inputs: list[torch.Tensor],
52
+ inp_split_sizes: list[int],
53
+ all_gather_input_numel: int,
54
+ world_size: int,
55
+ rank: int,
56
+ dtype: torch.dtype,
57
+ device: torch.device,
58
+ ) -> tuple[torch.Tensor, torch.Tensor]:
59
+ all_gather_output = torch.empty(
60
+ (all_gather_input_numel * world_size,), dtype=dtype, device="meta"
61
+ )
62
+ all_gather_input = all_gather_output.narrow(
63
+ 0, all_gather_input_numel * rank, all_gather_input_numel
64
+ )
65
+ return all_gather_input, all_gather_output
66
+
67
+
68
+ @torch.library.impl(lib, "all_gather_copy_in", "CUDA")
69
+ @torch.library.impl(lib, "all_gather_copy_in", "XPU")
70
+ @torch.library.impl(lib, "all_gather_copy_in", "HPU")
71
+ @torch.library.impl(lib, "all_gather_copy_in", "CPU")
72
+ @torch.library.impl(lib, "all_gather_copy_in", "MTIA")
73
+ def all_gather_copy_in_cuda(
74
+ all_gather_inputs: list[torch.Tensor],
75
+ inp_split_sizes: list[int],
76
+ all_gather_input_numel: int,
77
+ world_size: int,
78
+ rank: int,
79
+ dtype: torch.dtype,
80
+ device: torch.device,
81
+ ) -> tuple[torch.Tensor, torch.Tensor]:
82
+ all_gather_output = torch.empty(
83
+ (all_gather_input_numel * world_size,), dtype=dtype, device=device
84
+ )
85
+ all_gather_input = all_gather_output.narrow(
86
+ 0, all_gather_input_numel * rank, all_gather_input_numel
87
+ )
88
+ foreach_copy_dsts = torch.split(all_gather_input, inp_split_sizes)
89
+ with torch.no_grad():
90
+ torch._foreach_copy_(foreach_copy_dsts, all_gather_inputs)
91
+ return all_gather_input, all_gather_output
92
+
93
+
94
+ lib.define(
95
+ "split_with_sizes_copy(Tensor all_gather_output, SymInt[] all_gather_input_split_sizes, int dim=0, *, Tensor(a!)[] out) -> ()"
96
+ )
97
+
98
+
99
+ @torch.library.impl(lib, "split_with_sizes_copy", "Meta")
100
+ @torch.library.impl(lib, "split_with_sizes_copy", "CUDA")
101
+ @torch.library.impl(lib, "split_with_sizes_copy", "XPU")
102
+ @torch.library.impl(lib, "split_with_sizes_copy", "HPU")
103
+ @torch.library.impl(lib, "split_with_sizes_copy", "CPU")
104
+ @torch.library.impl(lib, "split_with_sizes_copy", "MTIA")
105
+ def split_with_sizes_copy(
106
+ all_gather_output: torch.Tensor,
107
+ all_gather_input_split_sizes: list[int],
108
+ dim: int,
109
+ out: list[torch.Tensor],
110
+ ) -> None:
111
+ torch.split_with_sizes_copy(
112
+ all_gather_output, all_gather_input_split_sizes, dim=dim, out=out
113
+ )
114
+
115
+
116
+ lib.define(
117
+ "chunk_cat(Tensor[] tensors, int dim, int num_chunks, *, Tensor(a!) out) -> ()"
118
+ )
119
+
120
+
121
+ @torch.library.impl(lib, "chunk_cat", "Meta")
122
+ @torch.library.impl(lib, "chunk_cat", "CUDA")
123
+ @torch.library.impl(lib, "chunk_cat", "XPU")
124
+ @torch.library.impl(lib, "chunk_cat", "HPU")
125
+ @torch.library.impl(lib, "chunk_cat", "CPU")
126
+ @torch.library.impl(lib, "chunk_cat", "MTIA")
127
+ def chunk_cat(
128
+ tensors: list[torch.Tensor],
129
+ dim: int,
130
+ num_chunks: int,
131
+ out: torch.Tensor,
132
+ ) -> None:
133
+ torch._chunk_cat(tensors, dim, num_chunks, out=out)
134
+
135
+
136
+ @torch.no_grad()
137
+ def foreach_all_gather(
138
+ fsdp_params: list[FSDPParam],
139
+ group: dist.ProcessGroup,
140
+ async_op: bool,
141
+ all_gather_copy_in_stream: torch.Stream,
142
+ all_gather_stream: torch.Stream,
143
+ device: torch.device,
144
+ ) -> Optional[AllGatherResult]:
145
+ world_size, rank = group.size(), group.rank()
146
+ device_handle = _get_device_handle(device.type)
147
+ with device_handle.stream(all_gather_copy_in_stream):
148
+ param_all_gather_inputs = _get_param_all_gather_inputs(fsdp_params)
149
+ (
150
+ param_all_gather_input_dtypes,
151
+ param_all_gather_input_numels,
152
+ dtype,
153
+ ) = _get_all_gather_input_metadatas(param_all_gather_inputs)
154
+ if dtype == torch.uint8:
155
+ all_gather_inputs = [
156
+ t.view(torch.uint8) for ts in param_all_gather_inputs for t in ts
157
+ ]
158
+ else:
159
+ all_gather_inputs = [*chain.from_iterable(param_all_gather_inputs)]
160
+ inp_split_sizes = [t.numel() for t in all_gather_inputs]
161
+ all_gather_input_numel = sum(inp_split_sizes)
162
+ all_gather_input, all_gather_output = torch.ops.fsdp.all_gather_copy_in(
163
+ all_gather_inputs,
164
+ inp_split_sizes,
165
+ all_gather_input_numel,
166
+ world_size,
167
+ rank,
168
+ dtype,
169
+ device,
170
+ )
171
+ del param_all_gather_inputs
172
+ all_gather_stream.wait_stream(all_gather_copy_in_stream)
173
+ with device_handle.stream(all_gather_stream):
174
+ all_gather_work = dist.all_gather_into_tensor(
175
+ output_tensor=all_gather_output,
176
+ input_tensor=all_gather_input,
177
+ group=group,
178
+ async_op=async_op,
179
+ )
180
+ all_gather_event = all_gather_stream.record_event()
181
+ return AllGatherResult(
182
+ all_gather_output,
183
+ all_gather_event,
184
+ all_gather_work,
185
+ param_all_gather_input_dtypes,
186
+ param_all_gather_input_numels,
187
+ inp_split_sizes,
188
+ )
189
+
190
+
191
+ @torch.no_grad()
192
+ def _get_param_all_gather_inputs(
193
+ fsdp_params: list[FSDPParam],
194
+ ) -> list[list[torch.Tensor]]:
195
+ if compiled_autograd_enabled():
196
+ return [fsdp_param.all_gather_inputs for fsdp_param in fsdp_params]
197
+
198
+ # Intentionally try to run a fast-path that bypasses abstractions for the
199
+ # common FSDP case of bf16/fp32 mixed precision in order to use foreach
200
+ # copy for lower CPU overhead and more efficient copying in eager
201
+ def use_foreach_copy(fsdp_param: FSDPParam) -> bool:
202
+ return (
203
+ fsdp_param.param_dtype is not None
204
+ and not fsdp_param.offload_to_cpu
205
+ and not hasattr(fsdp_param._sharded_local_tensor, "fsdp_pre_all_gather")
206
+ )
207
+
208
+ param_all_gather_inputs: list[list[torch.Tensor]] = [[] for _ in fsdp_params]
209
+ foreach_copy_indices: list[int] = []
210
+ foreach_copy_inputs: list[torch.Tensor] = []
211
+ foreach_copy_input_numels: list[int] = []
212
+
213
+ # 1st pass: for foreach-copy parameters, get inputs and metadata for the
214
+ # foreach copy, and for the others, actually get their all-gather inputs
215
+ for i, fsdp_param in enumerate(fsdp_params):
216
+ if use_foreach_copy(fsdp_param):
217
+ foreach_copy_indices.append(i)
218
+ all_gather_input = (
219
+ fsdp_param._sharded_param_data
220
+ if fsdp_param.sharded_state == ShardedState.SHARDED
221
+ else cast(torch.Tensor, fsdp_param._sharded_post_forward_param_data)
222
+ )
223
+ foreach_copy_inputs.append(all_gather_input)
224
+ foreach_copy_input_numels.append(all_gather_input.numel())
225
+ else:
226
+ param_all_gather_inputs[i] = fsdp_param.all_gather_inputs
227
+
228
+ # 2nd pass: use foreach copy to compute the remaining all-gather inputs
229
+ if foreach_copy_inputs:
230
+ fsdp_param_0 = fsdp_params[foreach_copy_indices[0]]
231
+ param_dtype, device = fsdp_param_0.param_dtype, fsdp_param_0.device
232
+ flat_foreach_copy_input = torch.empty(
233
+ (sum(foreach_copy_input_numels),), device=device, dtype=param_dtype
234
+ )
235
+ splits = torch.split(flat_foreach_copy_input, foreach_copy_input_numels)
236
+ torch._foreach_copy_(splits, foreach_copy_inputs)
237
+ for i, split in zip(foreach_copy_indices, splits):
238
+ param_all_gather_inputs[i] = [split]
239
+
240
+ return param_all_gather_inputs
241
+
242
+
243
+ @torch.no_grad()
244
+ def foreach_all_gather_copy_out(
245
+ all_gather_result: AllGatherResult,
246
+ fsdp_params: list[FSDPParam],
247
+ group: dist.ProcessGroup,
248
+ ) -> None:
249
+ (
250
+ all_gather_output,
251
+ all_gather_event,
252
+ all_gather_work,
253
+ param_all_gather_input_dtypes,
254
+ param_all_gather_input_numels,
255
+ all_gather_input_split_sizes,
256
+ ) = all_gather_result
257
+ _dtype, device = all_gather_output.dtype, all_gather_output.device
258
+ device_handle = _get_device_handle(device.type)
259
+ if all_gather_event is not None: # sync op
260
+ device_handle.current_stream().wait_event(all_gather_event)
261
+ if isinstance(all_gather_work, dist.distributed_c10d.Work): # async op
262
+ all_gather_work.wait()
263
+ world_size, device = group.size(), all_gather_output.device
264
+
265
+ split_with_sizes_out: list[torch.Tensor] = []
266
+ shard_i_copy_infos: list[tuple[FSDPParam, list[torch.Tensor]]] = []
267
+ for all_gather_input_numels, all_gather_input_dtypes, fsdp_param in zip(
268
+ param_all_gather_input_numels, param_all_gather_input_dtypes, fsdp_params
269
+ ):
270
+ # NOTE: Under compile, make sure we always recreate all_gather_outputs
271
+ # per AllGather. See [Note: Invariants for torch.compile Traceable FSDP2].
272
+ force_recreate = compiled_autograd_enabled()
273
+ fsdp_param.init_all_gather_outputs(
274
+ all_gather_input_numels,
275
+ all_gather_input_dtypes,
276
+ world_size,
277
+ device,
278
+ force_recreate=force_recreate,
279
+ )
280
+ if not force_recreate:
281
+ fsdp_param.alloc_all_gather_outputs()
282
+ param_all_gather_outputs = fsdp_param.all_gather_outputs
283
+ if fsdp_param.fsdp_placement.dim != 0:
284
+ # Copy to a temporary and then chunk-cat into the final all-gather
285
+ # output tensors
286
+ param_all_gather_outputs = [
287
+ torch.empty_like(t) for t in param_all_gather_outputs
288
+ ]
289
+ shard_i_copy_infos.append((fsdp_param, param_all_gather_outputs))
290
+ split_with_sizes_out.extend(param_all_gather_outputs)
291
+
292
+ all_gather_output = all_gather_output.view(world_size, -1)
293
+ if all_gather_output.dtype == torch.uint8:
294
+ out = [t.view(world_size, -1).view(torch.uint8) for t in split_with_sizes_out]
295
+ else:
296
+ out = [t.view(world_size, -1) for t in split_with_sizes_out]
297
+
298
+ # only avoid VC bump if we are not in inference mode
299
+ non_inference_outs = [o for o in out if not o.is_inference()]
300
+ if len(non_inference_outs) > 0:
301
+ with torch.autograd._unsafe_preserve_version_counter(tuple(non_inference_outs)):
302
+ torch.ops.fsdp.split_with_sizes_copy(
303
+ all_gather_output, all_gather_input_split_sizes, dim=1, out=out
304
+ )
305
+ else:
306
+ torch.ops.fsdp.split_with_sizes_copy(
307
+ all_gather_output, all_gather_input_split_sizes, dim=1, out=out
308
+ )
309
+
310
+ for fsdp_param, param_all_gather_outputs in shard_i_copy_infos:
311
+ # Chunk-cat from the temporary to the final all-gather output tensors
312
+ shard_dim = fsdp_param.fsdp_placement.dim
313
+
314
+ with torch.autograd._unsafe_preserve_version_counter(
315
+ tuple(fsdp_param.all_gather_outputs)
316
+ ):
317
+ for param_all_gather_output, target_all_gather_output in zip(
318
+ param_all_gather_outputs, fsdp_param.all_gather_outputs
319
+ ):
320
+ padded_sharded_size = (
321
+ fsdp_param.padded_sharded_param_size
322
+ if fsdp_param.sharded_state == ShardedState.SHARDED
323
+ else cast(
324
+ torch.Tensor, fsdp_param._sharded_post_forward_param_data
325
+ ).size()
326
+ )
327
+ pre_param_size = list(padded_sharded_size)
328
+ pre_param_size[0] *= world_size
329
+ chunks = torch.chunk(
330
+ param_all_gather_output.view(pre_param_size), world_size, dim=0
331
+ )
332
+ post_param_size = list(padded_sharded_size)
333
+ post_param_size[shard_dim] *= world_size
334
+ cat_out = target_all_gather_output.view(post_param_size)
335
+ torch.cat(chunks, dim=shard_dim, out=cat_out)
336
+
337
+
338
+ @torch.no_grad()
339
+ def foreach_reduce(
340
+ fsdp_params: list[FSDPParam],
341
+ unsharded_grads: list[torch.Tensor],
342
+ reduce_scatter_group: dist.ProcessGroup,
343
+ reduce_scatter_stream: torch.Stream,
344
+ orig_dtype: torch.dtype,
345
+ reduce_dtype: Optional[torch.dtype],
346
+ device: torch.device,
347
+ reduce_scatter_reduce_op: Optional[Union[dist.ReduceOp, dist.ReduceOp.RedOpType]],
348
+ all_reduce_group: Optional[dist.ProcessGroup], # not `None` iff HSDP
349
+ all_reduce_stream: torch.Stream,
350
+ all_reduce_grads: bool,
351
+ partial_reduce_output: Optional[torch.Tensor], # only used for HSDP
352
+ all_reduce_hook: Optional[Callable[[torch.Tensor], None]],
353
+ ) -> tuple[
354
+ torch.Tensor,
355
+ torch.Event,
356
+ torch.Event,
357
+ Optional[torch.Tensor],
358
+ Optional[torch.Event],
359
+ Optional[torch.Tensor],
360
+ ]:
361
+ """
362
+ ``unsharded_grads`` owns the references to the gradients computed by
363
+ autograd, so clearing the list frees the gradients.
364
+ """
365
+ grad_dtypes = {grad.dtype for grad in unsharded_grads}
366
+ if len(grad_dtypes) != 1:
367
+ # Check this at runtime since it could be a real runtime error if e.g.
368
+ # fp8 weights do not produce the correct higher precision gradients
369
+ _raise_assert_with_print(
370
+ f"FSDP reduce-scatter expects uniform gradient dtype but got {grad_dtypes}"
371
+ )
372
+ grad_dtype = unsharded_grads[0].dtype
373
+ reduce_dtype = reduce_dtype or grad_dtype
374
+ predivide_factor, postdivide_factor = _get_gradient_divide_factors(
375
+ reduce_scatter_group, all_reduce_group, reduce_dtype, device.type
376
+ )
377
+ world_size = reduce_scatter_group.size()
378
+ for i, (fsdp_param, unsharded_grad) in enumerate(zip(fsdp_params, unsharded_grads)):
379
+ if (shard_dim := fsdp_param.fsdp_placement.dim) == 0:
380
+ continue
381
+ assert unsharded_grad.size(shard_dim) % world_size == 0, (
382
+ f"Shard({shard_dim}) requires even sharding: {unsharded_grad.size()=} {world_size=}"
383
+ )
384
+ chunks = torch.chunk(unsharded_grad, world_size, dim=shard_dim)
385
+ unsharded_grads[i] = torch.cat(chunks, dim=0)
386
+ padded_unsharded_sizes = tuple(
387
+ _get_dim0_padded_size(grad.size(), world_size) for grad in unsharded_grads
388
+ )
389
+ reduce_scatter_input_numel = sum(s.numel() for s in padded_unsharded_sizes)
390
+ reduce_scatter_output_numel = reduce_scatter_input_numel // world_size
391
+ reduce_scatter_input = torch.empty(
392
+ (reduce_scatter_input_numel,), dtype=reduce_dtype, device=device
393
+ )
394
+ device_handle = _get_device_handle(device.type)
395
+ foreach_reduce_scatter_copy_in(unsharded_grads, reduce_scatter_input, world_size)
396
+ current_stream = device_handle.current_stream()
397
+ # Only after the copy-in finishes can we free the gradients
398
+ unsharded_grads.clear()
399
+ reduce_scatter_stream.wait_stream(current_stream)
400
+ all_reduce_input = None
401
+ all_reduce_event = None
402
+ with device_handle.stream(reduce_scatter_stream):
403
+ reduce_output = reduce_scatter_input.new_empty((reduce_scatter_output_numel,))
404
+ _div_if_needed(reduce_scatter_input, predivide_factor)
405
+ if reduce_scatter_reduce_op is None:
406
+ if predivide_factor is None:
407
+ reduce_scatter_reduce_op = ReduceOp.AVG
408
+ else:
409
+ reduce_scatter_reduce_op = ReduceOp.SUM
410
+ dist.reduce_scatter_tensor(
411
+ output=reduce_output,
412
+ input=reduce_scatter_input,
413
+ group=reduce_scatter_group,
414
+ op=reduce_scatter_reduce_op,
415
+ )
416
+ reduce_scatter_event = reduce_scatter_stream.record_event()
417
+ post_reduce_stream = reduce_scatter_stream
418
+ if all_reduce_group is not None: # HSDP
419
+ # Accumulations must run in the reduce-scatter stream
420
+ if not all_reduce_grads:
421
+ if partial_reduce_output is not None:
422
+ partial_reduce_output += reduce_output
423
+ else:
424
+ partial_reduce_output = reduce_output
425
+ return (
426
+ reduce_scatter_input,
427
+ reduce_scatter_event,
428
+ post_reduce_stream.record_event(),
429
+ all_reduce_input,
430
+ all_reduce_event,
431
+ partial_reduce_output,
432
+ )
433
+ if partial_reduce_output is not None:
434
+ reduce_output += partial_reduce_output
435
+ post_reduce_stream = all_reduce_stream
436
+ all_reduce_stream.wait_stream(reduce_scatter_stream)
437
+ with device_handle.stream(all_reduce_stream):
438
+ dist.all_reduce(
439
+ reduce_output,
440
+ group=all_reduce_group,
441
+ op=ReduceOp.AVG if predivide_factor is None else ReduceOp.SUM,
442
+ )
443
+ all_reduce_input = reduce_output
444
+ all_reduce_event = all_reduce_stream.record_event()
445
+ # -- END: ops in reduce_scatter stream
446
+
447
+ if all_reduce_hook is not None:
448
+ # Execute user-specified all reduce hook.
449
+ # If native HSDP is used, this is executed after the HSDP all reduce.
450
+ # If 1-d FSDP is used, this is executed post reduce-scatter.
451
+ post_reduce_stream = all_reduce_stream
452
+ all_reduce_stream.wait_stream(reduce_scatter_stream)
453
+ with device_handle.stream(all_reduce_stream):
454
+ all_reduce_hook(reduce_output)
455
+ # -- END: ops post reduce_scatter
456
+
457
+ with device_handle.stream(post_reduce_stream):
458
+ _div_if_needed(reduce_output, postdivide_factor)
459
+ reduce_output = _to_dtype_if_needed(reduce_output, orig_dtype)
460
+ # View out and accumulate sharded gradients
461
+ flat_grad_offset = 0 # [0, reduce_scatter_output_numel - 1]
462
+ for padded_unsharded_size, fsdp_param in zip(
463
+ padded_unsharded_sizes, fsdp_params
464
+ ):
465
+ # Assume even sharding for Shard(i), i > 0; otherwise would require
466
+ # copy-out for contiguous strides
467
+ new_sharded_grad = torch.as_strided(
468
+ reduce_output,
469
+ size=fsdp_param.sharded_size,
470
+ stride=fsdp_param.contiguous_sharded_stride,
471
+ storage_offset=flat_grad_offset,
472
+ )
473
+ to_accumulate_grad = fsdp_param.sharded_param.grad is not None
474
+ if fsdp_param.offload_to_cpu:
475
+ # Only overlap the D2H copy (copying to pinned memory) if not
476
+ # accumulating gradients since the CPU add kernel depends on
477
+ # the copy result and we cannot run the add as a callback
478
+ non_blocking = fsdp_param.pin_memory and not to_accumulate_grad
479
+ # Since the GPU sharded gradient is allocated in the RS stream,
480
+ # we can free it here by not keeping a ref without waiting for
481
+ # the D2H copy since future RS-stream ops run after the copy
482
+ new_sharded_grad = new_sharded_grad.to(
483
+ torch.device("cpu"), non_blocking=non_blocking
484
+ )
485
+ if non_blocking:
486
+ # Record an event on which to block the CPU thread to
487
+ # ensure that the D2H copy finishes before the optimizer
488
+ fsdp_param.grad_offload_event = reduce_scatter_stream.record_event()
489
+ if to_accumulate_grad:
490
+ assert isinstance(fsdp_param.sharded_param.grad, DTensor)
491
+ fsdp_param.sharded_param.grad._local_tensor += new_sharded_grad
492
+ else:
493
+ new_sharded_dtensor_grad = fsdp_param.to_sharded_dtensor(
494
+ new_sharded_grad
495
+ )
496
+ fsdp_param.sharded_param.grad = new_sharded_dtensor_grad
497
+ if not compiled_autograd_enabled():
498
+ for hook in (
499
+ getattr(fsdp_param.sharded_param, "_post_accumulate_grad_hooks", {})
500
+ or {}
501
+ ).values():
502
+ hook(fsdp_param.sharded_param)
503
+ padded_sharded_numel = padded_unsharded_size.numel() // world_size
504
+ flat_grad_offset += padded_sharded_numel
505
+ post_reduce_event = post_reduce_stream.record_event()
506
+ # The RS output is allocated in the RS stream and used in the default
507
+ # stream (for optimizer). To ensure its memory is not reused for later
508
+ # RSs, we do not need extra synchronization since the sharded parameters
509
+ # hold refs through the end of backward.
510
+ return (
511
+ reduce_scatter_input,
512
+ reduce_scatter_event,
513
+ post_reduce_event,
514
+ all_reduce_input,
515
+ all_reduce_event,
516
+ None,
517
+ )
518
+
519
+
520
+ def foreach_reduce_scatter_copy_in(
521
+ unsharded_grads: list[torch.Tensor],
522
+ reduce_scatter_input: torch.Tensor,
523
+ world_size: int,
524
+ ) -> None:
525
+ reduce_scatter_input = reduce_scatter_input.view(world_size, -1)
526
+ torch.ops.fsdp.chunk_cat(
527
+ unsharded_grads, dim=0, num_chunks=world_size, out=reduce_scatter_input
528
+ )
529
+
530
+
531
+ def _get_all_gather_input_metadatas(
532
+ param_all_gather_inputs: list[list[torch.Tensor]],
533
+ ) -> tuple[list[list[torch.dtype]], list[list[int]], torch.dtype]:
534
+ param_all_gather_input_dtypes: list[list[torch.dtype]] = []
535
+ param_all_gather_input_numels: list[list[int]] = []
536
+ all_gather_dtype = param_all_gather_inputs[0][0].dtype
537
+ for all_gather_inputs in param_all_gather_inputs:
538
+ input_dtypes: list[torch.dtype] = []
539
+ input_numels: list[int] = []
540
+ for all_gather_input in all_gather_inputs:
541
+ if all_gather_input.dtype != all_gather_dtype:
542
+ all_gather_dtype = torch.uint8
543
+ input_dtypes.append(all_gather_input.dtype)
544
+ input_numels.append(all_gather_input.numel())
545
+ param_all_gather_input_dtypes.append(input_dtypes)
546
+ param_all_gather_input_numels.append(input_numels)
547
+ return (
548
+ param_all_gather_input_dtypes,
549
+ param_all_gather_input_numels,
550
+ all_gather_dtype,
551
+ )
552
+
553
+
554
+ def _get_gradient_divide_factors(
555
+ reduce_scatter_group: dist.ProcessGroup,
556
+ all_reduce_group: Optional[dist.ProcessGroup],
557
+ reduce_dtype: torch.dtype,
558
+ device_type: str = "",
559
+ ) -> Union[tuple[None, None], tuple[float, float]]:
560
+ # For fp32/bf16, we do not need to worry about overflow/underflow, so we
561
+ # use NCCL's built-in division to avoid separate div kernels
562
+ if reduce_dtype in (torch.float32, torch.bfloat16) and device_type != "mtia":
563
+ return None, None
564
+ data_parallel_size = reduce_scatter_group.size()
565
+ if all_reduce_group is not None:
566
+ data_parallel_size *= all_reduce_group.size()
567
+ # Since fp16 has smaller dynamic range than fp32/bf16, we want to avoid
568
+ # overflow/underflow. For N data parallel workers, each worker computes
569
+ # g_i, and they collectively reduce (g_1 + ... + g_N) / N. To avoid
570
+ # overflow/underflow, we divide by ~sqrt(N) before/after the reduction.
571
+ factor: int = 1
572
+ while data_parallel_size % factor == 0 and data_parallel_size / factor > factor:
573
+ factor *= 2
574
+ factor = float(factor)
575
+ return (factor, data_parallel_size / factor)
576
+
577
+
578
+ def _div_if_needed(tensor: torch.Tensor, div_factor: Optional[float]) -> None:
579
+ if div_factor is not None and div_factor > 1:
580
+ tensor.div_(div_factor)
_fsdp_common.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import math
3
+ import traceback
4
+ from dataclasses import dataclass
5
+ from enum import auto, Enum
6
+ from typing import Any, Optional
7
+
8
+ import torch
9
+ import torch.distributed as dist
10
+ import torch.nn as nn
11
+ from torch.distributed._composable.contract import _get_registry
12
+ from torch.distributed.tensor import DeviceMesh, DTensor
13
+ from torch.distributed.tensor._dtensor_spec import DTensorSpec
14
+
15
+
16
+ _compiled_autograd_enabled: bool = False
17
+
18
+ if torch._running_with_deploy():
19
+
20
+ def detect_compiled_autograd():
21
+ pass
22
+
23
+ def compiled_autograd_enabled():
24
+ return False
25
+
26
+ else:
27
+
28
+ def detect_compiled_autograd():
29
+ assert not torch.compiler.is_compiling(), (
30
+ "`detect_compiled_autograd()` is designed to be called in eager mode"
31
+ )
32
+ global _compiled_autograd_enabled
33
+ import torch._dynamo.compiled_autograd as ca
34
+
35
+ _compiled_autograd_enabled = (
36
+ ca.compiled_autograd_enabled
37
+ or ca.compiled_autograd_enabled_force_eager
38
+ or ca.in_compiled_autograd_region
39
+ )
40
+
41
+ def compiled_autograd_enabled():
42
+ global _compiled_autograd_enabled
43
+ return _compiled_autograd_enabled
44
+
45
+
46
+ @dataclass
47
+ class DataParallelMeshInfo:
48
+ mesh: DeviceMesh
49
+ shard_mesh_dim: Optional[int] = None
50
+ replicate_mesh_dim: Optional[int] = None
51
+
52
+ def __post_init__(self):
53
+ if self.shard_mesh_dim is None and self.replicate_mesh_dim is None:
54
+ raise AssertionError(
55
+ "At least one of shard_mesh_dim and replicate_mesh_dim must not be None"
56
+ )
57
+
58
+
59
+ @dataclass
60
+ class FSDPMeshInfo(DataParallelMeshInfo):
61
+ def __post_init__(self):
62
+ super().__post_init__()
63
+ if self.shard_mesh_dim is None:
64
+ raise AssertionError("Expects non-None shard_mesh_dim")
65
+ self.shard_mesh_size: int = self.mesh.size(self.shard_mesh_dim)
66
+ self.shard_process_group = self.mesh.get_group(self.shard_mesh_dim)
67
+ self.shard_mesh_rank: int = self.shard_process_group.rank()
68
+
69
+
70
+ @dataclass
71
+ class DDPMeshInfo(DataParallelMeshInfo):
72
+ def __post_init__(self):
73
+ super().__post_init__()
74
+ if self.replicate_mesh_dim is None:
75
+ raise AssertionError("Expects non-None replicate_mesh_dim")
76
+ self.replicate_mesh_size: int = self.mesh.size(self.replicate_mesh_dim)
77
+ self.replicate_process_group = self.mesh.get_group(self.replicate_mesh_dim)
78
+ self.replicate_mesh_rank: int = self.replicate_process_group.rank()
79
+
80
+
81
+ @dataclass
82
+ class HSDPMeshInfo(FSDPMeshInfo, DDPMeshInfo):
83
+ def __post_init__(self):
84
+ # Calls `FSDPMeshInfo` -> `DDPMeshInfo` -> `DataParallelMeshInfo`
85
+ super().__post_init__()
86
+
87
+
88
+ class TrainingState(Enum):
89
+ """Describes the training state of one FSDP state / parameter group."""
90
+
91
+ # Transition to forward starting pre-forward until post-forward
92
+ FORWARD = auto()
93
+ # Transition to pre-backward when unsharding in backward
94
+ PRE_BACKWARD = auto()
95
+ # Transition to post-backward when resharding and reducing gradients
96
+ POST_BACKWARD = auto()
97
+ # Idle before/after forward or before pre-backward/after post-backward
98
+ IDLE = auto()
99
+
100
+
101
+ def _raise_assert_with_print(*args: Any, **kwargs: Any):
102
+ print(f"[Rank {dist.get_rank()}] ", end="")
103
+ print(*args, **kwargs)
104
+ traceback.print_stack()
105
+ raise AssertionError(*args, **kwargs)
106
+
107
+
108
+ def _is_composable_with_fsdp(module: nn.Module) -> bool:
109
+ registry = _get_registry(module)
110
+ if registry is None:
111
+ return True
112
+ # Registry keys by function name
113
+ return "replicate" not in registry
114
+
115
+
116
+ def _get_dim0_padded_size(tensor_size: torch.Size, dim0_factor: int) -> torch.Size:
117
+ padded_dim0 = math.ceil(tensor_size[0] / dim0_factor) * dim0_factor
118
+ return torch.Size([padded_dim0]) + tensor_size[1:]
119
+
120
+
121
+ def _chunk_with_empty(
122
+ tensor: torch.Tensor, num_chunks: int, dim: int
123
+ ) -> list[torch.Tensor]:
124
+ chunks = list(torch.chunk(tensor, num_chunks, dim=dim))
125
+ while len(chunks) < num_chunks:
126
+ chunks.append(chunks[0].new_empty(0))
127
+ return chunks
128
+
129
+
130
+ def _get_dim_chunked_size(
131
+ chunk: torch.Tensor, unchunked_size: torch.Size, dim: int
132
+ ) -> torch.Size:
133
+ if chunk.numel() > 0:
134
+ return chunk.size()
135
+ # For 0 numel, we need to preserve nonzero-sized dims for DTensor APIs
136
+ return unchunked_size[:dim] + torch.Size([0]) + unchunked_size[dim + 1 :]
137
+
138
+
139
+ def _from_local_no_grad(
140
+ local_tensor: torch.Tensor,
141
+ sharding_spec: DTensorSpec,
142
+ ) -> DTensor:
143
+ """
144
+ This method is similar to ``DTensor.from_local()`` except that in eager mode
145
+ it avoids some CPU overhead by avoiding default args and not being differentiable.
146
+ """
147
+
148
+ if not compiled_autograd_enabled():
149
+ return DTensor(
150
+ # Use the local tensor directly instead of constructing a new tensor
151
+ # variable, e.g. with `view_as()`, since this is not differentiable
152
+ local_tensor,
153
+ sharding_spec,
154
+ requires_grad=local_tensor.requires_grad,
155
+ )
156
+ else:
157
+ return DTensor.from_local(
158
+ local_tensor,
159
+ sharding_spec.mesh,
160
+ sharding_spec.placements,
161
+ shape=sharding_spec.shape,
162
+ stride=sharding_spec.stride,
163
+ )
164
+
165
+
166
+ def _to_dtype_if_needed(
167
+ tensor: torch.Tensor, dtype: Optional[torch.dtype]
168
+ ) -> torch.Tensor:
169
+ if dtype is not None and tensor.dtype != dtype:
170
+ return tensor.to(dtype)
171
+ return tensor
172
+
173
+
174
+ def _cast_fp_tensor(dtype: torch.dtype, x: torch.Tensor) -> torch.Tensor:
175
+ if (
176
+ not isinstance(x, torch.Tensor)
177
+ or not torch.is_floating_point(x)
178
+ or x.dtype == dtype
179
+ ):
180
+ return x
181
+ return x.to(dtype)
_fsdp_init.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ from typing import Optional, Union
3
+
4
+ import torch
5
+ import torch.distributed as dist
6
+ import torch.nn as nn
7
+ from torch.distributed.device_mesh import _get_device_handle
8
+ from torch.distributed.tensor import DeviceMesh, DTensor, init_device_mesh
9
+ from torch.utils._python_dispatch import is_traceable_wrapper_subclass
10
+
11
+ from ._fsdp_common import _is_composable_with_fsdp, FSDPMeshInfo, HSDPMeshInfo
12
+ from ._fsdp_state import _get_module_fsdp_state
13
+
14
+
15
+ def _get_post_forward_mesh_info(
16
+ reshard_after_forward: Union[bool, int], mesh_info: FSDPMeshInfo
17
+ ) -> Optional[FSDPMeshInfo]:
18
+ shard_mesh_size = mesh_info.shard_mesh_size
19
+ if not isinstance(reshard_after_forward, (bool, int)):
20
+ raise ValueError(
21
+ "reshard_after_forward should be a bool or an int representing the "
22
+ f"group size to reshard to, not {reshard_after_forward}"
23
+ )
24
+ # NOTE: `isinstance(False, int)` returns `True`.
25
+ if not isinstance(reshard_after_forward, bool) and isinstance(
26
+ reshard_after_forward, int
27
+ ):
28
+ if (
29
+ reshard_after_forward < 1
30
+ or reshard_after_forward > shard_mesh_size
31
+ or shard_mesh_size % reshard_after_forward != 0
32
+ ):
33
+ raise ValueError(
34
+ "If passing reshard_after_forward as an int, it should be a "
35
+ f"factor of {shard_mesh_size}, not {reshard_after_forward}"
36
+ )
37
+ elif reshard_after_forward == 1:
38
+ reshard_after_forward = False
39
+ elif reshard_after_forward == shard_mesh_size:
40
+ reshard_after_forward = True
41
+ post_forward_mesh_info = None
42
+ if reshard_after_forward is True:
43
+ post_forward_mesh_info = mesh_info
44
+ elif reshard_after_forward is not False: # int case
45
+ # For HSDP, we can flatten the two replicate dims into the 0th dim
46
+ post_forward_mesh_tensor = mesh_info.mesh.mesh.view(-1, reshard_after_forward)
47
+ post_forward_mesh = DeviceMesh(
48
+ mesh_info.mesh.device_type, post_forward_mesh_tensor
49
+ )
50
+ post_forward_mesh_info = HSDPMeshInfo(
51
+ post_forward_mesh, shard_mesh_dim=1, replicate_mesh_dim=0
52
+ )
53
+ return post_forward_mesh_info
54
+
55
+
56
+ def _init_default_fully_shard_mesh() -> DeviceMesh:
57
+ """Default to global CUDA mesh if possible else global CPU mesh."""
58
+ if not dist.distributed_c10d.is_initialized():
59
+ dist.distributed_c10d.init_process_group()
60
+ default_pg = dist.distributed_c10d._get_default_group()
61
+ device = torch._C._get_accelerator()
62
+ mesh = init_device_mesh(device.type, mesh_shape=(default_pg.size(),))
63
+ return mesh
64
+
65
+
66
+ def _get_device_from_mesh(mesh: DeviceMesh) -> torch.device:
67
+ if mesh.device_type == "cpu":
68
+ return torch.device("cpu")
69
+ device_handle = _get_device_handle(mesh.device_type)
70
+ return torch.device(mesh.device_type, device_handle.current_device())
71
+
72
+
73
+ def _ignore_module(
74
+ module: nn.Module,
75
+ ignored_params: set[nn.Parameter],
76
+ ignore_decision: dict[nn.Module, bool],
77
+ ) -> bool:
78
+ """
79
+ Decide if it is safe to ignore a module for applying fully_shard.
80
+ """
81
+ if module in ignore_decision:
82
+ return ignore_decision[module]
83
+
84
+ if len(list(module.buffers(recurse=False))) > 0:
85
+ # Cannot ignore a module with any buffer
86
+ ignore_decision[module] = False
87
+ return False
88
+
89
+ for _, param in module.named_parameters(recurse=False):
90
+ if param not in ignored_params:
91
+ # at least one param is not ignored. So this module shouldn't be.
92
+ ignore_decision[module] = False
93
+ return False
94
+
95
+ # Need to consider descendants of module
96
+ for child in list(module.children()):
97
+ ignore_child = _ignore_module(child, ignored_params, ignore_decision)
98
+ if not ignore_child:
99
+ # Cannot ignore module if one of its children is not ignored
100
+ ignore_decision[module] = False
101
+ return False
102
+
103
+ # Safe to ignore module
104
+ ignore_decision[module] = True
105
+ return True
106
+
107
+
108
+ def _adjust_managed_modules(
109
+ modules: list[nn.Module], ignored_params: set[nn.Parameter]
110
+ ) -> list[nn.Module]:
111
+ """
112
+ Adjust the given list of managed modules by removing those with all parameters ignored.
113
+ """
114
+ ignore_decision: dict[nn.Module, bool] = {}
115
+ new_modules = []
116
+ for module in modules:
117
+ ignored = _ignore_module(module, ignored_params, ignore_decision)
118
+ if not ignored:
119
+ new_modules.append(module)
120
+ return new_modules
121
+
122
+
123
+ def _get_managed_modules(
124
+ root_modules: tuple[nn.Module, ...],
125
+ ignored_params: Optional[set[nn.Parameter]] = None,
126
+ ) -> list[nn.Module]:
127
+ modules: list[nn.Module] = []
128
+ root_modules_set = set(root_modules)
129
+ # Track visisted modules to avoid visiting shared modules multiple times
130
+ visited_modules: set[nn.Module] = set()
131
+
132
+ def dfs(module: nn.Module) -> None:
133
+ """
134
+ Runs a DFS to collect managed modules, not recursing into modules with
135
+ a non-composable API or ``fully_shard`` already applied.
136
+ """
137
+ if not _is_composable_with_fsdp(module):
138
+ return
139
+ elif (
140
+ module not in root_modules_set
141
+ and _get_module_fsdp_state(module) is not None
142
+ ):
143
+ return # nested `fully_shard` module
144
+ visited_modules.add(module)
145
+ for submodule in module.children():
146
+ if submodule not in visited_modules:
147
+ dfs(submodule)
148
+ modules.append(module)
149
+
150
+ for root_module in root_modules:
151
+ dfs(root_module)
152
+
153
+ if ignored_params is None:
154
+ return modules
155
+
156
+ adjusted_modules = _adjust_managed_modules(modules, ignored_params)
157
+ return adjusted_modules
158
+
159
+
160
+ def _verify_managed_param(name: str, param: nn.Parameter) -> None:
161
+ """
162
+ Verify if the parameter is accepted by fully_shard. The only restriction now
163
+ is that the parameter cannot be a scalar tensor (param.numel == 0) since we
164
+ need at least one dim to shard.
165
+ """
166
+ if len(param.shape) == 0:
167
+ raise ValueError(
168
+ "fully_shard doesn't support scalar parameters. "
169
+ f"Change {name} to a 1D tensor with numel equal to 1."
170
+ )
171
+
172
+
173
+ def _get_managed_states(
174
+ modules: list[nn.Module], ignored_params: Optional[set[nn.Parameter]] = None
175
+ ) -> tuple[list[nn.Parameter], list[torch.Tensor]]:
176
+ params: list[nn.Parameter] = []
177
+ buffers: list[torch.Tensor] = []
178
+ # Track visited parameters/buffers to avoid visiting shared parameters and
179
+ # buffers multiple times
180
+ visited_params: set[nn.Parameter] = set()
181
+ visited_buffers: set[torch.Tensor] = set()
182
+ if ignored_params is None:
183
+ ignored_params = set()
184
+
185
+ for module in modules:
186
+ for name, param in module.named_parameters(recurse=False):
187
+ if param in ignored_params:
188
+ # do not include an ignored parameters
189
+ continue
190
+ if param not in visited_params:
191
+ _verify_managed_param(name, param)
192
+ params.append(param)
193
+ visited_params.add(param)
194
+ for buffer in module.buffers(recurse=False):
195
+ if buffer not in visited_buffers:
196
+ buffers.append(buffer)
197
+ visited_buffers.add(buffer)
198
+ return params, buffers
199
+
200
+
201
+ def _move_states_to_device(
202
+ params: list[nn.Parameter],
203
+ buffers: list[torch.Tensor],
204
+ device: torch.device,
205
+ ) -> None:
206
+ """
207
+ We have FSDP move states to device for simpler and faster initialization
208
+ since FSDP almost always uses CUDA for training. We move parameters/buffers
209
+ rather than modules since modules to support ignoring parameters/buffers in
210
+ the future.
211
+ """
212
+ # Follow the logic in `nn.Module._apply`
213
+ for tensor in itertools.chain(params, buffers):
214
+ if tensor.device == device or tensor.device.type == "meta":
215
+ # Keep meta-device tensors on meta device for deferred init
216
+ continue
217
+ if isinstance(tensor, DTensor):
218
+ if (dtensor_mesh_type := tensor.device_mesh.device_type) != device.type:
219
+ raise ValueError(
220
+ "Requires DTensor to have mesh of the same type as the FSDP mesh "
221
+ f"but got {dtensor_mesh_type} for DTensor and {device.type} for FSDP"
222
+ )
223
+ raise AssertionError(
224
+ f"Expects DTensor to be moved to {dtensor_mesh_type} but got {tensor.device}"
225
+ )
226
+ tensor_ = tensor
227
+ if is_traceable_wrapper_subclass(tensor_):
228
+ with torch.no_grad(): # avoid autograd increasing C++ refcount by 1
229
+ tensor_on_device = nn.Parameter(tensor.to(device))
230
+ torch.utils.swap_tensors(tensor, tensor_on_device)
231
+ else:
232
+ tensor.data = tensor.to(device)
_fsdp_param.py ADDED
@@ -0,0 +1,906 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import inspect
3
+ import itertools
4
+ from collections.abc import Sequence
5
+ from dataclasses import dataclass, field
6
+ from enum import auto, Enum
7
+ from typing import Any, Callable, cast, Optional
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from torch._prims_common import make_contiguous_strides_for
12
+ from torch.distributed._functional_collectives import AsyncCollectiveTensor
13
+ from torch.distributed.tensor import DTensor, Replicate, Shard
14
+ from torch.distributed.tensor._dtensor_spec import DTensorSpec, TensorMeta
15
+ from torch.distributed.tensor.device_mesh import _mesh_resources
16
+ from torch.distributed.tensor.placement_types import _StridedShard, Placement
17
+
18
+ from ._fsdp_api import CPUOffloadPolicy, MixedPrecisionPolicy, OffloadPolicy
19
+ from ._fsdp_common import (
20
+ _chunk_with_empty,
21
+ _from_local_no_grad,
22
+ _get_dim_chunked_size,
23
+ _raise_assert_with_print,
24
+ _to_dtype_if_needed,
25
+ compiled_autograd_enabled,
26
+ FSDPMeshInfo,
27
+ HSDPMeshInfo,
28
+ )
29
+
30
+
31
+ """
32
+ [Note: FSDP tensors]
33
+ FSDP considers the following tensors:
34
+ - Original parameter: parameter passed to :class:`FSDPParam`, i.e. the one
35
+ on the module when applying FSDP
36
+ - Sharded parameter: sharding the original parameter on dim-0 (or a
37
+ user-specified dim) as a DTensor over the main mesh
38
+ - All-gather inputs: the ``torch.Tensor`` or ``Tensor`` s passed to all-gather,
39
+ derived from the sharded parameter
40
+ - All-gather output: the ``torch.Tensor`` or ``Tensor`` s resulting from
41
+ all-gathering the all-gather inputs
42
+ - Unsharded parameter: parameter used for forward/backward computation, derived
43
+ from the all-gather output; autograd leaf
44
+
45
+ We define these tensors to describe the general framework that can accomodate
46
+ extensions, where:
47
+ - all-gather-inputs = pre-all-gather-transform(sharded-parameter)
48
+ - unsharded-parameter = post-all-gather-transform(all-gather-outputs)
49
+
50
+ For the default ``torch.Tensor`` case, there is only one all-gather input, and
51
+ it shares the same underlying tensor data as the sharded parameter, meaning
52
+ that they can be thought of as the same tensors. The same applies for the
53
+ all-gather output and unsharded parameter. For non-``torch.Tensor`` extensions,
54
+ these equivalences may no longer hold due to the pre/post-all-gather
55
+ transforms, and some may have multiple all-gather inputs/outputs (e.g.
56
+ quantized data and scales).
57
+
58
+ [Note: FSDP and autograd]
59
+ FSDP dynamically frees and allocates the unsharded parameter. Since autograd
60
+ can pack a reference to it or a view to save for backward, we use storage
61
+ resizing to implement the freeing/allocation since that preserves the aliasing.
62
+ This implies that we construct the unsharded parameter object once and write to
63
+ it in-place thereafter. For the default ``torch.Tensor` original parameter
64
+ case, the all-gather output and unsharded parameter share the same
65
+ data, so we use storage resizing on the all-gather output.
66
+ """
67
+
68
+ lib = torch.library.Library("fsdp", "FRAGMENT") # noqa: TOR901
69
+
70
+ lib.define("copy_(Tensor(a!) tensor, Tensor data) -> ()")
71
+
72
+
73
+ @torch.library.impl(lib, "copy_", "Meta")
74
+ @torch.library.impl(lib, "copy_", "CUDA")
75
+ @torch.library.impl(lib, "copy_", "XPU")
76
+ @torch.library.impl(lib, "copy_", "HPU")
77
+ @torch.library.impl(lib, "copy_", "CPU")
78
+ @torch.library.impl(lib, "copy_", "MTIA")
79
+ def copy_(tensor, data):
80
+ tensor.copy_(data)
81
+
82
+
83
+ """
84
+ [Note: Avoiding functionalization for fsdp.copy_ and inductor.resize_storage_bytes_]
85
+
86
+ Currently we don't functionalize `fsdp.copy_` op or `inductor.resize_storage_bytes_` op
87
+ (i.e. they show up as a mutation op in the middle of the AOT joint graph).
88
+
89
+ Reason:
90
+ Traceable FSDP2 compiled autograd BWD graph have the following traits:
91
+ (1) Two inputs of the graph were aliased to each other (one from hook closed-over tensors, one from FWD saved tensors).
92
+ (2) One of them is mutated (copy_ and resize_ to handle the all-gathered param).
93
+ (3) They are both subclasses.
94
+ The combination of these traits is not supported by AOTAutograd (it's difficult to reason about subclass aliasing).
95
+ So this doesn't work at all for Traceable FSDP2.
96
+
97
+ The compromise we use is to avoid functionalization for the FSDP2 copy_ and resize_ ops.
98
+ This avoids the problem above, because from AOTAutograd point-of-view there are no mutations
99
+ that functionalization needs to handle. (Although we need to be careful not to DCE those mutable ops.)
100
+
101
+ We can avoid this functionalization because:
102
+ (1) The nn.Parameter is never used before its .copy_() is called in eager code (i.e. no alias of it is created),
103
+ so it's safe to call .copy_() in the middle of the graph to update its content and start using the nn.Parameter downstream.
104
+ (2) We always re-allocate the buffer for nn.Parameter to store the AllGather output and to be used in downstream user ops.
105
+ So calling resize-to-0 in the middle of the graph to free nn.Parameter memory after use should always be okay
106
+ (since we always allocate anew next time we need it, we strictly don't need to keep the old tensor storage around anymore).
107
+
108
+ Q: Wouldn't the extra resize_ and copy_ ops hurt both memory usage and performance?
109
+ A: Yes it would. As an optimization, we have an Inductor post-grad FX pass to remove those resize_ and copy_ ops
110
+ for unsharded params that have this pattern: resize_(full) -> copy_ -> resize_(0).
111
+
112
+ TODO:
113
+ Now that we are maintaining the invariant of "no aliased + mutated graph inputs" in both the forward and backward,
114
+ it is now more feasible to functionalize all of the mutable FSDP ops. Some of the pros and cons are:
115
+
116
+ Cons (of functionalizing those ops):
117
+ (1) By not functionalizing them as we are today, we are making it more likely that they will run at the "correct" time
118
+ in the generated code. If we start to functionalize them, we will need to make sure that Inductor reinplaces them
119
+ in a way where it properly moves the mutations back to exactly where they should have run, or we risk suffering worse
120
+ peak memory than eager. (We probably already need to do something similar in Inductor's reinplacing for copy_:
121
+ https://github.com/pytorch/pytorch/issues/135305#issuecomment-2334888089)
122
+
123
+ Pros (of functionalizing):
124
+ (1) Better safety, we don't need to worry about the graph passes in inductor/partitioning handling input mutations
125
+ mid-graph quite as much (to be fair we've already done some amount of auditing, but we might have to do some more).
126
+ (2) Better perf: each mutation midway through the graph prevents Inductor from pattern matching across it.
127
+ But maybe there are few enough mutations induced by FSDP for this to matter.
128
+ """
129
+
130
+
131
+ @torch.library.impl(lib, "copy_", "Functionalize")
132
+ def copy__functionalize(tensor, data):
133
+ torch._sync(tensor)
134
+ torch._sync(data)
135
+ tensor_inner = torch._from_functional_tensor(tensor)
136
+ data_inner = torch._from_functional_tensor(data)
137
+ with torch._C._ExcludeDispatchKeyGuard(
138
+ torch._C.DispatchKeySet(torch._C.DispatchKey.Functionalize)
139
+ ):
140
+ torch.ops.fsdp.copy_.default(tensor_inner, data_inner)
141
+
142
+
143
+ if not torch._running_with_deploy():
144
+ torch.fx.node.has_side_effect(torch.ops.fsdp.copy_.default)
145
+
146
+
147
+ class ShardedState(Enum):
148
+ """
149
+ - ``SHARDED``: The sharded parameter is registered to the module. It is the
150
+ only contributor to parameter memory.
151
+ - ``SHARDED_POST_FORWARD``: The unsharded parameter is resharded to a
152
+ smaller world size. Since this data should not be used for computation,
153
+ we do not register it to the module. Users should reshard the module
154
+ before any in-place modifications. Both it and the sharded parameter
155
+ contribute to parameter memory.
156
+ - ``UNSHARDED``: The unsharded parameter is registered to the module. Both
157
+ it and the sharded parameter contribute to parameter memory.
158
+ """
159
+
160
+ SHARDED = auto()
161
+ SHARDED_POST_FORWARD = auto()
162
+ UNSHARDED = auto()
163
+
164
+
165
+ @dataclass
166
+ class ParamModuleInfo:
167
+ """
168
+ For a parameter, this stores the module and the parameter name to be able
169
+ to do a parameter swap via ``setattr(module, param_name, ...)`` or to get
170
+ the parameter via ``getattr(module, param_name)``. We additionally save
171
+ shared modules and shared parameter names to update them accordingly.
172
+ """
173
+
174
+ # Parameter names are unprefixed, e.g. "weight", not "lin.weight"
175
+ module: nn.Module
176
+ param_name: str
177
+ shared_modules: list[nn.Module] = field(default_factory=list)
178
+ shared_param_names: list[str] = field(default_factory=list)
179
+
180
+
181
+ @dataclass
182
+ class ExtensionsData:
183
+ # User-defined metadata passed from pre to post-all-gather
184
+ all_gather_metadata: Optional[Any] = None
185
+ # Save the all-gather input sizes to unflatten the all-gather outputs to ND
186
+ all_gather_input_sizes: Sequence[torch.Size] = () # ND
187
+
188
+ def clear(self):
189
+ self.all_gather_metadata = None
190
+ self.all_gather_input_sizes = ()
191
+
192
+
193
+ class FSDPParam:
194
+ """
195
+ This class manages a parameter with FSDP or FSDP variants applied,
196
+ implementing dim-0 per-parameter sharding.
197
+ """
198
+
199
+ orig_dtype: torch.dtype
200
+ param_dtype: Optional[torch.dtype]
201
+ reduce_dtype: Optional[torch.dtype]
202
+ _orig_size: torch.Size # ND
203
+ sharded_size: torch.Size # ND
204
+ contiguous_sharded_stride: tuple[int, ...]
205
+ padded_sharded_param_size: torch.Size # ND
206
+ sharded_post_forward_size: torch.Size # ND
207
+ contiguous_sharded_post_forward_stride: tuple[int, ...]
208
+ _sharded_param_data: torch.Tensor # 1D
209
+ sharded_param: nn.Parameter # ND
210
+ _sharded_post_forward_param_data: Optional[torch.Tensor] # 1D
211
+ _sharded_post_forward_param: Optional[nn.Parameter] # ND
212
+ _unsharded_param: nn.Parameter # ND
213
+ unsharded_accumulated_grad: Optional[torch.Tensor] # ND
214
+ _sharding_spec: DTensorSpec
215
+ # DTensor attributes (only defined for DTensor `param`):
216
+ _tp_spec: DTensorSpec
217
+ all_gather_outputs: list[torch.Tensor] # 1D
218
+ # All-gather extension attributes
219
+ _extensions_data: ExtensionsData
220
+ _unsharded_inner_tensors: list[torch.Tensor]
221
+
222
+ def __init__(
223
+ self,
224
+ param: nn.Parameter,
225
+ module_info: ParamModuleInfo,
226
+ mesh_info: FSDPMeshInfo,
227
+ post_forward_mesh_info: Optional[FSDPMeshInfo],
228
+ device: torch.device,
229
+ shard_placement_fn: Optional[Callable[[nn.Parameter], Optional[Shard]]],
230
+ mp_policy: MixedPrecisionPolicy,
231
+ offload_policy: OffloadPolicy,
232
+ ):
233
+ self._module_info: ParamModuleInfo = module_info
234
+ self.mesh_info = mesh_info
235
+ self.post_forward_mesh_info = post_forward_mesh_info
236
+ self.device = device
237
+ self.mp_policy = mp_policy
238
+ self.offload_to_cpu: bool = isinstance(offload_policy, CPUOffloadPolicy)
239
+ self.pin_memory = (
240
+ self.offload_to_cpu and cast(CPUOffloadPolicy, offload_policy).pin_memory
241
+ )
242
+ self.grad_offload_event: Optional[torch.Event] = None
243
+ self._init_sharded_param(param, device, shard_placement_fn)
244
+ if self.post_forward_mesh_info:
245
+ self._init_sharded_post_forward_param_metadata(param)
246
+ self._init_extensions()
247
+ self.all_gather_outputs: list[torch.Tensor] = []
248
+ self.unsharded_accumulated_grad = None
249
+ self._param_fqn: Optional[str] = None # prefixed from root module
250
+ # TODO: Remove this padding logic once DTensor pads the local tensor:
251
+ # https://github.com/pytorch/pytorch/issues/113045
252
+ self._post_load_hook_handle = (
253
+ module_info.module.register_load_state_dict_post_hook(
254
+ lambda *args, **kwargs: self.reset_sharded_param()
255
+ )
256
+ )
257
+
258
+ @torch.no_grad()
259
+ def _init_sharded_param(
260
+ self,
261
+ param: nn.Parameter,
262
+ device: torch.device,
263
+ shard_placement_fn: Optional[Callable],
264
+ ):
265
+ if param.device != device and param.device.type != "meta":
266
+ raise AssertionError(
267
+ f"Expects the parameter to already be moved to device {device} but got {param.device}"
268
+ )
269
+ if not param.is_contiguous():
270
+ raise NotImplementedError(
271
+ f"FSDP does not support non-contiguous parameters yet: {param.shape=} {param.stride()=}"
272
+ )
273
+ fsdp_placement = shard_placement_fn(param) if shard_placement_fn else None
274
+ if fsdp_placement is None:
275
+ fsdp_placement = Shard(0)
276
+ elif fsdp_placement.dim < 0:
277
+ fsdp_placement = Shard(fsdp_placement.dim + param.ndim)
278
+ assert isinstance(fsdp_placement, Shard), f"{fsdp_placement}"
279
+ self.fsdp_placement = fsdp_placement
280
+ shard_dim = fsdp_placement.dim
281
+ # TODO: Replace the sharded DTensor parameter construction logic with
282
+ # `distribute_tensor` after https://github.com/pytorch/pytorch/issues/116101
283
+ # TODO: Simplify the following sharded parameter padding logic after
284
+ # https://github.com/pytorch/pytorch/issues/113045
285
+ self.is_dtensor = isinstance(param, DTensor)
286
+ if self.is_dtensor:
287
+ self._tp_spec = cast(DTensor, param)._spec
288
+ dp_mesh, tp_mesh = (self.mesh_info.mesh, self._tp_spec.mesh)
289
+ dp_global_mesh = _mesh_resources.get_root_mesh(dp_mesh)
290
+ tp_global_mesh = _mesh_resources.get_root_mesh(tp_mesh)
291
+ if dp_global_mesh != tp_global_mesh or (
292
+ dp_global_mesh is None or tp_global_mesh is None
293
+ ):
294
+ raise AssertionError(
295
+ "FSDP requires the DP and TP mesh to have the same parent mesh but got: \n"
296
+ f"DP's global mesh: {dp_global_mesh}\nTP's global mesh: {tp_global_mesh}"
297
+ )
298
+ name_dims_error = "FSDP requires named DeviceMesh dims for ND parallelism"
299
+ assert dp_mesh.mesh_dim_names is not None, name_dims_error
300
+ assert tp_mesh.mesh_dim_names is not None, name_dims_error
301
+ submesh_names = dp_mesh.mesh_dim_names + tp_mesh.mesh_dim_names
302
+ self._spmd_mesh = dp_global_mesh[submesh_names]
303
+ if len(self._tp_spec.placements) != 1:
304
+ raise NotImplementedError(
305
+ f"FSDP only supports 1D TP, not {self._tp_spec.placements}"
306
+ )
307
+ split_factor = self._tp_spec.num_shards_map[shard_dim]
308
+ assert 2 <= self._spmd_mesh.ndim <= 3, (
309
+ f"_spmd_mesh.ndim can only be 2 or 3 but got {self._spmd_mesh.ndim}."
310
+ )
311
+ self._spmd_placements: tuple[Placement, ...]
312
+ dp_shard_tp_placement = (
313
+ (
314
+ _StridedShard(shard_dim, split_factor=split_factor)
315
+ if split_factor > 1
316
+ else fsdp_placement
317
+ ),
318
+ self._tp_spec.placements[0],
319
+ )
320
+ if self._spmd_mesh.ndim == 2:
321
+ self._spmd_placements = dp_shard_tp_placement
322
+ else:
323
+ assert self.mesh_info.replicate_mesh_dim == 0
324
+ self._spmd_placements = (Replicate(),) + dp_shard_tp_placement
325
+ self._sharding_spec = DTensorSpec(
326
+ self._spmd_mesh,
327
+ self._spmd_placements,
328
+ tensor_meta=self._tp_spec.tensor_meta,
329
+ )
330
+ # TODO: Enable uneven sharding for FSDP+TP.
331
+ if split_factor > 1: # FSDP has strided sharding on tensor dim 0
332
+ num_shards = self._sharding_spec.num_shards_map[0]
333
+ tensor_size_dim_0 = self._sharding_spec.shape[0]
334
+ if tensor_size_dim_0 % num_shards != 0:
335
+ raise NotImplementedError(
336
+ "FSDP+TP sharding does not support uneven sharding for now: "
337
+ f"tensor dim 0 has size {tensor_size_dim_0} which cannot be "
338
+ f"evenly sharded into {num_shards} shards."
339
+ )
340
+ param_data = cast(DTensor, param)._local_tensor
341
+ else:
342
+ self._spmd_mesh = self.mesh_info.mesh
343
+ if isinstance(self.mesh_info, HSDPMeshInfo):
344
+ self._spmd_placements = (Replicate(), fsdp_placement)
345
+ else:
346
+ self._spmd_placements = (fsdp_placement,)
347
+ self._sharding_spec = DTensorSpec(
348
+ self._spmd_mesh,
349
+ self._spmd_placements,
350
+ tensor_meta=TensorMeta(param.size(), param.stride(), param.dtype),
351
+ )
352
+ param_data = param
353
+ assert param_data.is_contiguous(), f"{param_data.shape=} {param_data.stride()=}"
354
+ shard_dim = fsdp_placement.dim
355
+ if shard_dim >= param_data.ndim:
356
+ raise AssertionError(
357
+ f"Shard dim {shard_dim} is invalid for {param_data.ndim}D tensor: {param.shape}"
358
+ )
359
+ self._orig_size = param_data.size()
360
+ self._contiguous_orig_stride = make_contiguous_strides_for(self._orig_size)
361
+ shard_rank = self.mesh_info.shard_mesh_rank
362
+ shard_world_size = self.mesh_info.shard_mesh_size
363
+ if shard_dim > 0 and param_data.size(shard_dim) % shard_world_size != 0:
364
+ # If sharding on nonzero dim, require even sharding for now because
365
+ # the uneven sharding (1) requires extra copies before/after FSDP
366
+ # collectives and (2) introduces extra complexity to handle padding
367
+ # and unpadding
368
+ raise NotImplementedError(
369
+ f"FSDP does not support uneven sharding on dim {shard_dim}: "
370
+ f"{param_data.size()} (world size: {shard_world_size})"
371
+ )
372
+ chunks = _chunk_with_empty(param_data, shard_world_size, dim=shard_dim)
373
+ sharded_param = chunks[shard_rank]
374
+ self.sharded_size = _get_dim_chunked_size(
375
+ sharded_param, param_data.size(), dim=shard_dim
376
+ )
377
+ self.contiguous_sharded_stride = make_contiguous_strides_for(self.sharded_size)
378
+ padded_sharded_size = chunks[0].size() # 0th always padded
379
+ self.padded_sharded_param_size = padded_sharded_size
380
+ # Pre-pad the sharded parameter to avoid padding before all-gather
381
+ padded_sharded_param = param_data.new_zeros(padded_sharded_size)
382
+ if sharded_param.numel() > 0:
383
+ padded_sharded_param.narrow(
384
+ dim=shard_dim, start=0, length=sharded_param.size(shard_dim)
385
+ ).copy_(sharded_param)
386
+ if self.offload_to_cpu and not padded_sharded_param.is_meta:
387
+ padded_sharded_param = padded_sharded_param.cpu()
388
+ if self.pin_memory:
389
+ padded_sharded_param = padded_sharded_param.pin_memory(
390
+ device=self.device
391
+ )
392
+ self._sharded_param_data = padded_sharded_param.view(-1)
393
+ length = sharded_param.size(shard_dim) if sharded_param.numel() > 0 else 0
394
+ sharded_param = padded_sharded_param.narrow(
395
+ dim=shard_dim, start=0, length=length
396
+ )
397
+ assert sharded_param.is_contiguous(), f"{self.fsdp_placement=}"
398
+ self.sharded_param = nn.Parameter(self.to_sharded_dtensor(sharded_param))
399
+ self.sharded_param.requires_grad_(param.requires_grad)
400
+ # Let `param_data` be freed normally when its ref count reaches 0 when
401
+ # the `fully_shard` call returns to allow provided parameters to alias
402
+ self._setattr_on_modules(self.sharded_param)
403
+ self.sharded_state = ShardedState.SHARDED
404
+
405
+ def _init_sharded_post_forward_param_metadata(self, param: torch.Tensor) -> None:
406
+ mesh_info = self.post_forward_mesh_info
407
+ assert mesh_info is not None # mypy
408
+ param_data = param._local_tensor if isinstance(param, DTensor) else param
409
+ chunks = _chunk_with_empty(param_data, mesh_info.shard_mesh_size, dim=0)
410
+ self.sharded_post_forward_size = _get_dim_chunked_size(
411
+ chunks[mesh_info.shard_mesh_rank],
412
+ param_data.size(),
413
+ dim=self.fsdp_placement.dim,
414
+ )
415
+ self.contiguous_sharded_post_forward_stride = make_contiguous_strides_for(
416
+ self.sharded_post_forward_size
417
+ )
418
+
419
+ def init_dtype_attrs(self, mp_policy: MixedPrecisionPolicy):
420
+ param_dtype, reduce_dtype = (mp_policy.param_dtype, mp_policy.reduce_dtype)
421
+ self.orig_dtype = self.sharded_param.dtype
422
+ # Clamp `reduce_dtype` to `None` if no casting is required: since
423
+ # gradients are computed in `param_dtype`, if `reduce_dtype` matches,
424
+ # then we do not need extra casting
425
+ if reduce_dtype == param_dtype:
426
+ reduce_dtype = None
427
+ # Clamp `param_dtype` to `None` if no casting is required
428
+ if param_dtype == self.orig_dtype:
429
+ param_dtype = None
430
+ self.param_dtype = param_dtype
431
+ self.reduce_dtype = reduce_dtype
432
+ # None indicates that the mixed precision is not enabled
433
+
434
+ def _init_extensions(self) -> None:
435
+ inner_tensor = self._sharded_local_tensor
436
+ has_fsdp_pre_all_gather = hasattr(inner_tensor, "fsdp_pre_all_gather")
437
+ has_fsdp_post_all_gather = hasattr(inner_tensor, "fsdp_post_all_gather")
438
+ if has_fsdp_pre_all_gather != has_fsdp_post_all_gather:
439
+ raise AssertionError(
440
+ "Both fsdp_pre_all_gather and fsdp_post_all_gather should be defined "
441
+ f"if using all-gather extensions: {inner_tensor}"
442
+ )
443
+ if has_fsdp_pre_all_gather:
444
+ self._extensions_data = ExtensionsData()
445
+ self._unsharded_inner_tensors: list[torch.Tensor] = []
446
+
447
+ def init_all_gather_outputs(
448
+ self,
449
+ all_gather_input_numels: list[int],
450
+ all_gather_input_dtypes: list[torch.dtype],
451
+ world_size: int,
452
+ device: torch.device,
453
+ force_recreate: bool = False,
454
+ ):
455
+ if not force_recreate and len(self.all_gather_outputs) > 0:
456
+ return # already initialized
457
+ self.all_gather_outputs = [
458
+ torch.empty(torch.Size([numel * world_size]), dtype=dtype, device=device)
459
+ for numel, dtype in zip(all_gather_input_numels, all_gather_input_dtypes)
460
+ ]
461
+
462
+ def init_unsharded_param(self):
463
+ """
464
+ [Note: Invariants for torch.compile Traceable FSDP2]
465
+ 1. Under compile, we always re-populate the content of `self._unsharded_param`
466
+ per AllGather using the slow path.
467
+ 2. Under compile, we always recreate `self.all_gather_outputs` per AllGather.
468
+ This is to ensure the buffer creation is internal to the graph and
469
+ avoid `self.all_gather_outputs` being captured as a graph input.
470
+ 3. Under compile, at the end of `free_unsharded_param()`, we always clean up
471
+ `self.all_gather_outputs` and `self._unsharded_inner_tensors`,
472
+ to avoid them being captured as graph output.
473
+
474
+ With these invariants, only these tensors will be inputs to the graph:
475
+ - Sharded parameters
476
+ - Placeholders for the `self._unsharded_param` nn.Parameter
477
+ """
478
+ if not compiled_autograd_enabled() and hasattr(
479
+ self, "_unsharded_param"
480
+ ): # after the 1st all-gather
481
+ inner_tensor = self._sharded_local_tensor
482
+ if not hasattr(inner_tensor, "fsdp_post_all_gather"):
483
+ return # already initialized
484
+ for tensor in self._unsharded_inner_tensors:
485
+ alloc_storage(tensor)
486
+ all_gather_outputs = self._unflatten_all_gather_outputs()
487
+ inner_tensor.fsdp_post_all_gather(
488
+ all_gather_outputs,
489
+ self._extensions_data.all_gather_metadata,
490
+ self.param_dtype or self.orig_dtype,
491
+ out=self._unsharded_param,
492
+ )
493
+ self._extensions_data.clear()
494
+ return
495
+ inner_tensor = self._sharded_local_tensor
496
+ if not compiled_autograd_enabled() and hasattr(
497
+ inner_tensor, "fsdp_post_all_gather"
498
+ ):
499
+ all_gather_outputs = self._unflatten_all_gather_outputs()
500
+ (
501
+ unsharded_tensor,
502
+ self._unsharded_inner_tensors,
503
+ ) = inner_tensor.fsdp_post_all_gather(
504
+ all_gather_outputs,
505
+ self._extensions_data.all_gather_metadata,
506
+ self.param_dtype or self.orig_dtype,
507
+ )
508
+ self._extensions_data.clear()
509
+ else:
510
+ # For the default path (no post-all-gather), the all-gather output
511
+ # gives the unsharded parameter data directly
512
+ assert len(self.all_gather_outputs) == 1, f"{len(self.all_gather_outputs)}"
513
+ unsharded_tensor = self.all_gather_outputs[0]
514
+ unsharded_param = torch.as_strided(
515
+ unsharded_tensor,
516
+ self._orig_size,
517
+ self._contiguous_orig_stride,
518
+ storage_offset=0,
519
+ )
520
+ if self.is_dtensor:
521
+ unsharded_param = _from_local_no_grad(unsharded_param, self._tp_spec)
522
+ if hasattr(self, "_unsharded_param"):
523
+ assert compiled_autograd_enabled()
524
+ with (
525
+ torch.no_grad(),
526
+ torch.autograd._unsafe_preserve_version_counter(self._unsharded_param),
527
+ ):
528
+ # NOTE: Under compile, if an unsharded param goes through
529
+ # resize_(full) -> copy_ -> resize_(0) pattern, we will remove those
530
+ # resize_ and copy_ ops in a compiler graph pass
531
+ # `remove_fsdp2_unsharded_param_graph_input_usage` to recover performance.
532
+ self._unsharded_param.untyped_storage().resize_(
533
+ self._unsharded_param.numel() * self._unsharded_param.itemsize
534
+ )
535
+ torch.ops.fsdp.copy_(self._unsharded_param, unsharded_param)
536
+ else:
537
+ self._unsharded_param = nn.Parameter(
538
+ unsharded_param, requires_grad=self.sharded_param.requires_grad
539
+ )
540
+
541
+ def _unflatten_all_gather_outputs(self) -> tuple[torch.Tensor, ...]:
542
+ return tuple(
543
+ t.view(-1, *s[1:])
544
+ for t, s in zip(
545
+ self.all_gather_outputs, self._extensions_data.all_gather_input_sizes
546
+ )
547
+ )
548
+
549
+ def to_sharded(self) -> None:
550
+ self._setattr_on_modules(self.sharded_param)
551
+ self.free_unsharded_param()
552
+ self.sharded_state = ShardedState.SHARDED
553
+
554
+ def to_sharded_post_forward(self) -> None:
555
+ if self.is_dtensor:
556
+ raise NotImplementedError(
557
+ "Resharding to smaller mesh with TP is not supported yet"
558
+ )
559
+ self._assert_in_states(ShardedState.UNSHARDED)
560
+ assert self.post_forward_mesh_info is not None # mypy
561
+ assert len(self.all_gather_outputs) == 1
562
+ shard_world_size = self.post_forward_mesh_info.shard_mesh_size
563
+ if (numel := self.all_gather_outputs[0].numel()) % shard_world_size != 0:
564
+ _raise_assert_with_print(
565
+ f"All-gather output size ({numel}) must be divisible by the shard "
566
+ f"world size ({shard_world_size})"
567
+ )
568
+ shard_rank = self.post_forward_mesh_info.shard_mesh_rank
569
+ sharded_numel = numel // shard_world_size
570
+ self._sharded_post_forward_param_data = (
571
+ self.all_gather_outputs[0].narrow(
572
+ 0, sharded_numel * shard_rank, sharded_numel
573
+ )
574
+ ).clone() # clone to be able to free all-gather output
575
+ sharded_post_forward_tensor = torch.as_strided(
576
+ self._sharded_post_forward_param_data,
577
+ size=self.sharded_post_forward_size,
578
+ stride=self.contiguous_sharded_post_forward_stride,
579
+ storage_offset=0,
580
+ )
581
+ self._sharded_post_forward_param = nn.Parameter(
582
+ self.to_sharded_post_forward_dtensor(sharded_post_forward_tensor)
583
+ )
584
+ self._setattr_on_modules(self._sharded_post_forward_param)
585
+ self.free_unsharded_param()
586
+ self.sharded_state = ShardedState.SHARDED_POST_FORWARD
587
+
588
+ def to_unsharded(self) -> None:
589
+ # Assume that the data has been allocated and all-gathered
590
+ set_requires_grad_if_needed(self.sharded_param, self._unsharded_param)
591
+ self._setattr_on_modules(self._unsharded_param)
592
+ if self.sharded_state == ShardedState.SHARDED_POST_FORWARD:
593
+ # The data is allocated in the default stream via the post-forward
594
+ # reshard and must be kept alive for the next all-gather copy-in.
595
+ # Since we call this method after the copy-out, the data's lifetime
596
+ # is ensured without further synchronization.
597
+ self._sharded_post_forward_param = None
598
+ self._sharded_post_forward_param_data = None # free
599
+ self.sharded_state = ShardedState.UNSHARDED
600
+
601
+ def _setattr_on_modules(self, param: nn.Parameter) -> None:
602
+ unsafe_setattr_param(
603
+ self._module_info.module, self._module_info.param_name, param
604
+ )
605
+ for shared_module, shared_param_name in zip(
606
+ self._module_info.shared_modules, self._module_info.shared_param_names
607
+ ):
608
+ unsafe_setattr_param(shared_module, shared_param_name, param)
609
+
610
+ def to_sharded_dtensor(self, tensor: torch.Tensor) -> DTensor:
611
+ """
612
+ Converts a local tensor representing either the sharded parameter or
613
+ sharded gradient to DTensor.
614
+ """
615
+ if tensor.shape != self.sharded_size:
616
+ _raise_assert_with_print(
617
+ f"Expects size {self.sharded_size} but got {tensor.shape}"
618
+ )
619
+ return _from_local_no_grad(
620
+ tensor,
621
+ self._sharding_spec,
622
+ )
623
+
624
+ def to_sharded_post_forward_dtensor(self, tensor: torch.Tensor) -> DTensor:
625
+ if tensor.shape != self.sharded_post_forward_size:
626
+ _raise_assert_with_print(
627
+ f"Expects size {self.sharded_post_forward_size} but got {tensor.shape}"
628
+ )
629
+ assert isinstance(self.post_forward_mesh_info, HSDPMeshInfo)
630
+ # TODO: Prefer this DTensor to be read-only and generalize the
631
+ # placement once we support TP.
632
+ post_forward_sharding_spec = DTensorSpec(
633
+ self.post_forward_mesh_info.mesh,
634
+ (Replicate(), Shard(0)),
635
+ tensor_meta=self._sharding_spec.tensor_meta,
636
+ )
637
+ return _from_local_no_grad(tensor, post_forward_sharding_spec)
638
+
639
+ def to_accumulated_grad_if_needed(self) -> None:
640
+ # Access `_unsharded_param` to bypass the sharded state check since we
641
+ # prefer to reshard before upcasting the gradient to save memory
642
+ if (
643
+ self.reduce_dtype is None
644
+ or self._unsharded_param.grad is None
645
+ or self._unsharded_param.grad.dtype == self.reduce_dtype
646
+ ):
647
+ return
648
+ unsharded_grad = self._unsharded_param.grad
649
+ self._unsharded_param.grad = None
650
+ self.unsharded_accumulated_grad = unsharded_grad.to(self.reduce_dtype)
651
+
652
+ def accumulate_unsharded_grad_if_needed(self) -> None:
653
+ if (
654
+ self.unsharded_accumulated_grad is not None
655
+ and self.unsharded_param.grad is not None
656
+ ):
657
+ self.unsharded_accumulated_grad += self.unsharded_param.grad
658
+ self.unsharded_param.grad = None
659
+
660
+ def alloc_all_gather_outputs(self) -> None:
661
+ for tensor in self.all_gather_outputs:
662
+ alloc_storage(tensor)
663
+
664
+ def free_unsharded_param(self) -> None:
665
+ if compiled_autograd_enabled():
666
+ """
667
+ Assumptions under compile:
668
+ - `self._unsharded_param` is NOT an alias of `self.all_gather_outputs`.
669
+ Instead, we resize `self._unsharded_param` storage size to full and then
670
+ explicitly *copy* the data from `self.all_gather_outputs` to `self._unsharded_param`
671
+ in `init_unsharded_param()`. (For full-graph FSDP2 case, we will then remove
672
+ the resize_ and copy_ ops in a compiler graph pass to recover performance.)
673
+ - `self.all_gather_outputs` and `self._unsharded_inner_tensors` are NOT
674
+ graph inputs. They are created within the graph and is guaranteed to be freed
675
+ by the end of the graph. They don't leak outside of the graph.
676
+ """
677
+ self._unsharded_param.untyped_storage().resize_(0)
678
+ self.all_gather_outputs = []
679
+ self._unsharded_inner_tensors = []
680
+ else:
681
+ for tensor in itertools.chain(
682
+ self.all_gather_outputs, self._unsharded_inner_tensors
683
+ ):
684
+ free_storage(tensor)
685
+
686
+ @property
687
+ def all_gather_inputs(self) -> list[torch.Tensor]: # 1D
688
+ self._assert_in_states(ShardedState.SHARDED, ShardedState.SHARDED_POST_FORWARD)
689
+ if self.sharded_state == ShardedState.SHARDED:
690
+ if not compiled_autograd_enabled() and hasattr(
691
+ self._sharded_local_tensor, "fsdp_pre_all_gather"
692
+ ):
693
+ sharded_local_tensor = self._sharded_local_tensor
694
+ if self.offload_to_cpu:
695
+ sharded_local_tensor = sharded_local_tensor.to(
696
+ self.device, non_blocking=True
697
+ )
698
+ pre_all_gather_signature = inspect.signature(
699
+ sharded_local_tensor.fsdp_pre_all_gather
700
+ )
701
+ num_fn_params = len(pre_all_gather_signature.parameters)
702
+ # Old signature only passes mesh; keep for BC for now
703
+ assert num_fn_params in (
704
+ 1,
705
+ 5,
706
+ ), (
707
+ f"Invalid fsdp_pre_all_gather: {pre_all_gather_signature}\n"
708
+ "Expects fsdp_pre_all_gather(self, mesh: DeviceMesh, "
709
+ "module: nn.Module, mp_policy: MixedPrecisionPolicy)"
710
+ )
711
+ if num_fn_params == 1:
712
+ (
713
+ all_gather_inputs,
714
+ self._extensions_data.all_gather_metadata,
715
+ ) = sharded_local_tensor.fsdp_pre_all_gather(
716
+ self.shard_mesh_from_root
717
+ )
718
+ else:
719
+ (
720
+ all_gather_inputs,
721
+ self._extensions_data.all_gather_metadata,
722
+ ) = sharded_local_tensor.fsdp_pre_all_gather(
723
+ self.shard_mesh_from_root,
724
+ self._orig_size,
725
+ self._contiguous_orig_stride,
726
+ self._module_info.module,
727
+ self.mp_policy,
728
+ )
729
+ if (
730
+ sharded_local_tensor.size() != self.padded_sharded_param_size
731
+ and any(
732
+ all_gather_input.size() != self.padded_sharded_param_size
733
+ for all_gather_input in all_gather_inputs
734
+ )
735
+ ):
736
+ # NOTE: Since this error can only be raised on the
737
+ # ranks that have padding, this can manifest as a NCCL
738
+ # watchdog timeout, as the other ranks will not error.
739
+ raise AssertionError(
740
+ "When a parameter is unevenly sharded by FSDP "
741
+ f"(orig size={self._orig_size}, FSDP world size={self.mesh_info.mesh.size()}), "
742
+ "fsdp_pre_all_gather must return all-gather inputs with the padded sharded size "
743
+ f"{self.padded_sharded_param_size} but got {[t.size() for t in all_gather_inputs]}"
744
+ )
745
+ self._extensions_data.all_gather_input_sizes = [
746
+ t.size() for t in all_gather_inputs
747
+ ]
748
+ return [t.view(-1) for t in all_gather_inputs]
749
+ sharded_param_data = self._sharded_param_data
750
+ if self.offload_to_cpu:
751
+ sharded_param_data = sharded_param_data.to(
752
+ self.device, non_blocking=True
753
+ )
754
+ return [_to_dtype_if_needed(sharded_param_data, self.param_dtype)]
755
+ elif self.sharded_state == ShardedState.SHARDED_POST_FORWARD:
756
+ if not compiled_autograd_enabled() and hasattr(
757
+ self._sharded_local_tensor, "fsdp_pre_all_gather"
758
+ ):
759
+ raise NotImplementedError
760
+ all_gather_input = _to_dtype_if_needed(
761
+ cast(torch.Tensor, self._sharded_post_forward_param_data),
762
+ self.param_dtype,
763
+ )
764
+ return [all_gather_input]
765
+ return [torch.empty(0)] # mypy
766
+
767
+ @property
768
+ def unsharded_param(self) -> nn.Parameter: # ND
769
+ return self._unsharded_param
770
+
771
+ @property
772
+ def unsharded_grad_data(self) -> torch.Tensor:
773
+ grad = self.unsharded_param.grad
774
+ assert grad is not None, "Expects unsharded_param.grad to not be None"
775
+ return self._get_grad_inner_tensor(grad)
776
+
777
+ @property
778
+ def unsharded_accumulated_grad_data(self) -> torch.Tensor:
779
+ grad = self.unsharded_accumulated_grad
780
+ assert grad is not None, "Expects unsharded_accumulated_grad to not be None"
781
+ return self._get_grad_inner_tensor(grad)
782
+
783
+ def _get_grad_inner_tensor(self, grad: torch.Tensor) -> torch.Tensor:
784
+ if self.is_dtensor:
785
+ if isinstance(grad, AsyncCollectiveTensor):
786
+ grad = grad.wait()
787
+ assert isinstance(grad, DTensor), f"{type(grad)}"
788
+ placements = self._tp_spec.placements
789
+ if placements != grad.placements:
790
+ assert len(self._tp_spec.placements) == len(grad.placements), (
791
+ f"{self._tp_spec=} {grad.placements=}"
792
+ )
793
+ grad = grad.redistribute(placements=placements)
794
+ grad = grad._local_tensor
795
+ return grad
796
+
797
+ @property
798
+ def _sharded_local_tensor(self) -> torch.Tensor:
799
+ return cast(DTensor, self.sharded_param)._local_tensor
800
+
801
+ @property
802
+ def shard_mesh(self):
803
+ mesh = self.mesh_info.mesh
804
+ if mesh.ndim == 1:
805
+ return mesh
806
+ elif mesh.ndim == 2:
807
+ assert mesh.mesh_dim_names is not None
808
+ return mesh[mesh.mesh_dim_names[-1]]
809
+ raise ValueError(f"Invalid mesh: {mesh}")
810
+
811
+ @property
812
+ def shard_mesh_from_root(self):
813
+ mesh = self.mesh_info.mesh
814
+
815
+ if mesh.ndim == 1:
816
+ return mesh
817
+ else:
818
+ assert mesh.mesh_dim_names is not None
819
+ shard_dim_name = mesh.mesh_dim_names[-1]
820
+
821
+ root_mesh = _mesh_resources.get_root_mesh(mesh)
822
+ return root_mesh[shard_dim_name]
823
+
824
+ def _assert_in_states(self, *states: ShardedState) -> None:
825
+ if self.sharded_state not in states:
826
+ _raise_assert_with_print(
827
+ f"Expects to be in one of {states}, not {self.sharded_state}"
828
+ )
829
+
830
+ def reset_sharded_param(self):
831
+ # For ops like `nn.Module._apply` or `load_state_dict(assign=True)`
832
+ # that change the sharded parameter tensor, we may need to re-pad the
833
+ # sharded local tensor and re-save the reference.
834
+ module_info = self._module_info
835
+ new_param = getattr(module_info.module, module_info.param_name)
836
+ if new_param is not self.sharded_param:
837
+ if torch.__future__.get_swap_module_params_on_conversion():
838
+ raise AssertionError(
839
+ f"Expects swap_tensors to preserve object but got {new_param} "
840
+ f"instead of {self.sharded_param}"
841
+ )
842
+ self.sharded_param = new_param
843
+ local_tensor = new_param._local_tensor
844
+ if local_tensor.is_meta:
845
+ return
846
+ updated_local_tensor = False
847
+ padded_sharded_size = self.padded_sharded_param_size
848
+ shard_dim = self.fsdp_placement.dim
849
+ length = local_tensor.size(shard_dim) if local_tensor.numel() > 0 else 0
850
+ if local_tensor.size() != padded_sharded_size:
851
+ assert shard_dim == 0, (
852
+ f"Shard({shard_dim}) requires even sharding: {local_tensor.size()=}"
853
+ )
854
+ padded_local_tensor = local_tensor.new_zeros(padded_sharded_size)
855
+ padded_local_tensor.narrow(dim=shard_dim, start=0, length=length).copy_(
856
+ local_tensor
857
+ )
858
+ local_tensor = padded_local_tensor
859
+ updated_local_tensor = True
860
+ if self.pin_memory and not local_tensor.is_pinned():
861
+ local_tensor = local_tensor.cpu().pin_memory(device=self.device)
862
+ updated_local_tensor = True
863
+ self._sharded_param_data = local_tensor.view(-1)
864
+ assert isinstance(self.sharded_param, DTensor) # mypy
865
+ if updated_local_tensor:
866
+ # Only change the local tensor object if needed
867
+ self.sharded_param._local_tensor = local_tensor.narrow(
868
+ dim=shard_dim, start=0, length=length
869
+ )
870
+ assert self.sharded_param._local_tensor.is_contiguous()
871
+ self._sharding_spec = self.sharded_param._spec
872
+
873
+ def __repr__(self):
874
+ return f"FSDPParam(fqn={self._param_fqn}, orig_size={self._orig_size})"
875
+
876
+
877
+ def alloc_storage(tensor: torch.Tensor) -> None:
878
+ size = tensor.numel() * tensor.itemsize
879
+ if (storage := tensor.untyped_storage()).size() != size:
880
+ storage.resize_(size)
881
+
882
+
883
+ def free_storage(tensor: torch.Tensor) -> None:
884
+ if (storage := tensor.untyped_storage()).size() != 0:
885
+ storage.resize_(0)
886
+
887
+
888
+ # NOTE: These bypass `nn.Module.__setattr__` checks, which incur non-trivial
889
+ # CPU overhead, if the module did not override it. For FSDP, we know we do not
890
+ # need those checks when transitioning between sharded/unsharded parameters.
891
+ def unsafe_setattr_param(
892
+ module: nn.Module, param_name: str, param: nn.Parameter
893
+ ) -> None:
894
+ if getattr(module.__setattr__, "__func__", None) is nn.Module.__setattr__:
895
+ module._parameters[param_name] = param
896
+ else: # slow path
897
+ setattr(module, param_name, param)
898
+
899
+
900
+ def set_requires_grad_if_needed(
901
+ src_tensor: torch.Tensor, dst_tensor: torch.Tensor
902
+ ) -> None:
903
+ # Only call `requires_grad_` if needed to avoid the Python <> C++ context
904
+ # switch overhead
905
+ if src_tensor.requires_grad != dst_tensor.requires_grad:
906
+ dst_tensor.requires_grad_(src_tensor.requires_grad)
_fsdp_param_group.py ADDED
@@ -0,0 +1,748 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import contextlib
3
+ import logging
4
+ from typing import Any, Callable, cast, NamedTuple, Optional
5
+
6
+ import torch
7
+ import torch.distributed as dist
8
+ import torch.nn as nn
9
+ from torch.distributed.device_mesh import _get_device_handle
10
+ from torch.distributed.fsdp._common_utils import _named_parameters_with_duplicates
11
+ from torch.distributed.tensor import Shard
12
+ from torch.profiler import record_function
13
+ from torch.utils._pytree import tree_flatten, tree_unflatten
14
+ from torch.utils.hooks import RemovableHandle
15
+
16
+ from ._fsdp_api import CPUOffloadPolicy, MixedPrecisionPolicy, OffloadPolicy
17
+ from ._fsdp_collectives import (
18
+ AllGatherResult,
19
+ foreach_all_gather,
20
+ foreach_all_gather_copy_out,
21
+ foreach_reduce,
22
+ )
23
+ from ._fsdp_common import (
24
+ compiled_autograd_enabled,
25
+ FSDPMeshInfo,
26
+ HSDPMeshInfo,
27
+ TrainingState,
28
+ )
29
+ from ._fsdp_param import FSDPParam, ParamModuleInfo, ShardedState
30
+
31
+
32
+ logger = logging.getLogger("torch.distributed.fsdp.fully_shard")
33
+
34
+ _ModuleToHandleDict = dict[nn.Module, RemovableHandle] # for state dict
35
+
36
+
37
+ """
38
+ [Note: Overlapping all-gather copy-in and all-gather]
39
+ For implicit forward prefetching, we want to overlap the next copy-in with the
40
+ current all-gather. We do so using a separate copy-in stream. However, since
41
+ we have the all-gather input as a view into the output, we must make sure to
42
+ copy into different memory from the current all-gather's output. Thus, we keep
43
+ a reference to the current all-gather's output and have the next FSDP parameter
44
+ group free it after its copy-in. Finally, we have the last FSDP state flush the
45
+ reference to avoid holding onto memory after forward.
46
+ """
47
+
48
+
49
+ class FSDPCommContext:
50
+ """This has the communication state shared across FSDP states/parameter groups."""
51
+
52
+ def lazy_init(self, device: torch.device):
53
+ self.device_handle = _get_device_handle(device.type)
54
+ # Setting the all-gather/reduce-scatter streams to be higher priority
55
+ # can help avoid some issues where their copies in/out are delayed and
56
+ # block computation (this is different from high-pri NCCL streams)
57
+ high_priority = -1
58
+ # All-gather state and copy-in stream allow overlapping the next
59
+ # copy-in with the current all-gather in forward; copy-in overlaps with
60
+ # reduce-scatter in backward without the separate copy-in stream
61
+ self.all_gather_copy_in_stream = self.device_handle.Stream(
62
+ priority=high_priority
63
+ )
64
+ # All-gather stream allows overlapping next all-gather with current
65
+ # forward compute
66
+ self.all_gather_stream = self.device_handle.Stream(priority=high_priority)
67
+ # Reduce-scatter stream gives separate execution "thread" for post-
68
+ # backward logic like pre/post-gradient division and reduce-scatter
69
+ self.reduce_scatter_stream = self.device_handle.Stream(priority=high_priority)
70
+ # Run the HSDP all-reduces concurrently with all-gather/reduce-scatter
71
+ # since collectives use different network resources and can overlap
72
+ # in the typical intra-node sharding / inter-node replication case
73
+ self.all_reduce_stream = self.device_handle.Stream()
74
+ # All-gather/reduce-scatter states keep references to collective
75
+ # tensors produced in one stream and used in another and accompanying
76
+ # CUDA events for synchronization
77
+ self.all_gather_state: Optional[AllGatherState] = None
78
+ self.reduce_scatter_state: Optional[ReduceScatterState] = None
79
+ # Post-forward order for explicit backward prefetching
80
+ self.post_forward_order: list[FSDPParamGroup] = [] # will cause ref cycles
81
+
82
+ def get_all_gather_streams(
83
+ self, async_op: bool, training_state: TrainingState
84
+ ) -> tuple[torch.Stream, torch.Stream]:
85
+ if not async_op and training_state in (
86
+ TrainingState.FORWARD,
87
+ TrainingState.PRE_BACKWARD,
88
+ ):
89
+ # Use separate streams for implicit prefetching
90
+ return self.all_gather_copy_in_stream, self.all_gather_stream
91
+ current_stream = self.device_handle.current_stream()
92
+ return current_stream, current_stream
93
+
94
+
95
+ # See [Note: Overlapping all-gather copy-in and all-gather]
96
+ class AllGatherState(NamedTuple):
97
+ all_gather_result: AllGatherResult
98
+ event: torch.Event # all-gather copy-out
99
+
100
+
101
+ class ReduceScatterState(NamedTuple):
102
+ reduce_scatter_input: torch.Tensor
103
+ event: torch.Event # reduce-scatter event
104
+
105
+
106
+ class AllReduceState(NamedTuple):
107
+ all_reduce_input: torch.Tensor
108
+ event: torch.Event # all-reduce event
109
+
110
+
111
+ class FSDPParamGroup:
112
+ """This class represents a parameter group to communicate together."""
113
+
114
+ _orig_dtype: torch.dtype
115
+ _reduce_dtype: Optional[torch.dtype]
116
+
117
+ def __init__(
118
+ self,
119
+ params: list[nn.Parameter],
120
+ modules: tuple[nn.Module, ...],
121
+ mesh_info: FSDPMeshInfo,
122
+ post_forward_mesh_info: Optional[FSDPMeshInfo],
123
+ device: torch.device,
124
+ shard_placement_fn: Optional[Callable[[nn.Parameter], Optional[Shard]]],
125
+ mp_policy: MixedPrecisionPolicy,
126
+ offload_policy: OffloadPolicy,
127
+ ):
128
+ self.modules = modules # permit ref cycle because 1:1 lifetime
129
+ param_module_infos = _get_param_module_infos(params, modules)
130
+
131
+ self.fsdp_params = [
132
+ FSDPParam(
133
+ param,
134
+ module_info,
135
+ mesh_info,
136
+ post_forward_mesh_info,
137
+ device,
138
+ shard_placement_fn,
139
+ mp_policy,
140
+ offload_policy,
141
+ )
142
+ for param, module_info in zip(params, param_module_infos)
143
+ ]
144
+ self.mesh_info = mesh_info
145
+ self.post_forward_mesh_info = post_forward_mesh_info
146
+ self.device = device
147
+ self.device_handle = _get_device_handle(device.type)
148
+ self.mp_policy = mp_policy
149
+ self.offload_policy = offload_policy
150
+ self._training_state = TrainingState.IDLE
151
+ # Group's sharded state always matches its parameters' sharded states
152
+ self._sharded_state = ShardedState.SHARDED
153
+ self._module_fqn: Optional[str] = None # prefixed from root module
154
+ # Only consider resetting sharded parameters once in lazy init since it
155
+ # can incur nontrivial overhead to reset them
156
+ self._reset_sharded_params: bool = False
157
+
158
+ # - Hook state
159
+ self._module_to_pre_save_state_dict_hook_handle: _ModuleToHandleDict = {}
160
+ self._module_to_pre_load_state_dict_hook_handle: _ModuleToHandleDict = {}
161
+ self._all_reduce_hook: Optional[Callable[[torch.Tensor], None]] = None
162
+ # Optional stream to run the user-defined all-reduce hook in
163
+ # Saved here and not in the comm. context because we allow the user to
164
+ # specify it, possibly at construction time before lazy init
165
+ self._all_reduce_hook_stream: Optional[torch.cuda.Stream] = None
166
+
167
+ # - Communication and communication/computation overlap
168
+ self.comm_ctx = FSDPCommContext()
169
+ # Group's indices in the shared post-forward order
170
+ self._post_forward_indices: list[int] = []
171
+ # Whether to reduce gradients at all (whether for FSDP or HSDP)
172
+ self.reduce_grads: bool = True
173
+ # Whether to all-reduce gradients for HSDP; only used if
174
+ # `self.reduce_grads` is true, in which case setting this to false
175
+ # means reduce-scatter but no all-reduce
176
+ self.all_reduce_grads: bool = True
177
+ # Whether to reshard parameters after backward (only useful for
178
+ # gradient accumulation)
179
+ self.reshard_after_backward: bool = True
180
+ # Optional custom reduce-scatter reduce op (e.g. to divide by a
181
+ # factor other than the shard world size)
182
+ self.reduce_scatter_reduce_op: Optional[dist.ReduceOp] = None
183
+ # `async_op` arg used for pre-forward/pre-backward unshard; can be
184
+ # overridden to only do explicit prefetching and avoid inter-stream
185
+ # fragmentation from using separate unshard streams
186
+ self.unshard_async_op: bool = False
187
+ # Whether to unshard in backward: can be overridden by the user if the
188
+ # parameters in this group are not needed for backward (e.g. embedding)
189
+ self.unshard_in_backward: bool = True
190
+
191
+ # - CUDA events for stream synchronization
192
+ # Holds the all-gather output buffer, sync objects, and metadata
193
+ self._all_gather_result: Optional[AllGatherResult] = None
194
+ # Holds the reduce-scatter/all-reduce view-out CUDA event that marks the end of
195
+ # the group's post-backward (e.g. reduce-scatter, all-reduce and div), which
196
+ # should be waited on at the end of backward
197
+ self._post_reduce_event: Optional[torch.Event] = None
198
+ # Holds the reshard-after-forward CUDA event when resharding to a
199
+ # different world size, which should be waited on in the next unshard
200
+ self._reshard_after_forward_event: Optional[torch.Event] = None
201
+
202
+ # Only for HSDP, if accumulating gradients without all-reduce, save the
203
+ # partial reduce output (only reduce-scattered but not all-reduced)
204
+ self._partial_reduce_output: Optional[torch.Tensor] = None
205
+ # Holds the all-reduce input and all-reduce event to keep it alive
206
+ # until the end of backward (critical when doing bf16 reduction with
207
+ # fp32 parameters since the all-reduce input is allocated in the RS
208
+ # stream and will have no refs to it after being upcast to fp32)
209
+ self._all_reduce_state: Optional[AllReduceState] = None
210
+
211
+ # Initialization #
212
+ def _init_mp_dtypes(self) -> None:
213
+ for fsdp_param in self.fsdp_params:
214
+ fsdp_param.init_dtype_attrs(self.mp_policy)
215
+ orig_dtypes = {fsdp_param.orig_dtype for fsdp_param in self.fsdp_params}
216
+ if len(orig_dtypes) != 1:
217
+ # This can be relaxed if we copy-out for the reduce-scatter
218
+ raise AssertionError(
219
+ f"FSDP expects uniform original parameter dtype but got {orig_dtypes}"
220
+ )
221
+ self._orig_dtype = next(iter(orig_dtypes))
222
+ reduce_dtypes = {fsdp_param.reduce_dtype for fsdp_param in self.fsdp_params}
223
+ if len(reduce_dtypes) != 1:
224
+ # This can be relaxed if we issue one reduce-scatter per reduce
225
+ # dtype (but we would need a way for users to specify multiple
226
+ # reduce dtypes)
227
+ raise AssertionError(
228
+ f"FSDP expects uniform reduce dtype but got {reduce_dtypes}"
229
+ )
230
+ self._reduce_dtype = next(iter(reduce_dtypes))
231
+
232
+ def lazy_init(self):
233
+ # Lazy init should be idempotent
234
+ # Users may change or register parameters after construction time.
235
+ # For example, DoRA (https://arxiv.org/abs/2402.09353) initializes linear magnitudes based on
236
+ # other parameters (e.g. loaded from the state dict).
237
+ if not hasattr(self.comm_ctx, "device_handle"):
238
+ self.comm_ctx.device_handle = _get_device_handle(self.device.type)
239
+ if self.is_sharded and not self._reset_sharded_params:
240
+ for fsdp_param in self.fsdp_params:
241
+ fsdp_param.reset_sharded_param()
242
+ fsdp_param._init_extensions() # allow monkey patch after init
243
+ self._reset_sharded_params = True
244
+ self._validate_no_meta_params()
245
+ self._validate_cpu_offload_params()
246
+ # Initialize mixed precision attributes lazily in case the user changes
247
+ # the parameter dtypes after construction time but before forward
248
+ self._init_mp_dtypes()
249
+ self._register_state_dict_hooks()
250
+
251
+ # Runtime #
252
+ def unshard(self, async_op: bool = False):
253
+ if self._all_gather_result is not None: # already called, pending wait
254
+ return
255
+ if self.is_unsharded:
256
+ return # no-op
257
+ if (
258
+ not self.unshard_in_backward
259
+ and self._training_state == TrainingState.PRE_BACKWARD
260
+ ):
261
+ return
262
+ if self._reshard_after_forward_event is not None:
263
+ # Resharded parameter data is allocated in the default stream and
264
+ # used in the all-gather streams
265
+ self._wait_all_gather_streams_on_event(self._reshard_after_forward_event)
266
+ self._reshard_after_forward_event = None
267
+ with record_function(self._with_fqn("FSDP::all_gather")):
268
+ self._all_gather_result = foreach_all_gather(
269
+ self.fsdp_params,
270
+ self._all_gather_process_group,
271
+ async_op,
272
+ *self.comm_ctx.get_all_gather_streams(async_op, self._training_state),
273
+ self.device,
274
+ )
275
+
276
+ def wait_for_unshard(self):
277
+ """
278
+ 1. In forward with implict prefetching, to overlap the current copy-out
279
+ with the next all-gather, we save a reference to the current all-gather
280
+ result to free after the next copy-out.
281
+ 2. Otherwise (explicit prefetching or in backward), we free the
282
+ all-gather result immediately after the current copy-out since we can
283
+ already overlap the current copy-out with the previous reduce-scatter.
284
+ """
285
+ if not self._all_gather_result:
286
+ return # no preceding unshard
287
+ async_op = self._all_gather_result.all_gather_work is not None
288
+ if self._training_state == TrainingState.FORWARD: # implicit prefetch
289
+ if prev_all_gather_state := self.comm_ctx.all_gather_state:
290
+ self._wait_all_gather_streams_on_event(prev_all_gather_state.event)
291
+ self.comm_ctx.all_gather_state = None # free the all-gather result
292
+ with record_function(self._with_fqn("FSDP::all_gather_copy_out")):
293
+ foreach_all_gather_copy_out(
294
+ self._all_gather_result,
295
+ self.fsdp_params,
296
+ self._all_gather_process_group,
297
+ )
298
+ for fsdp_param in self.fsdp_params:
299
+ fsdp_param.init_unsharded_param()
300
+ self._to_unsharded()
301
+ all_gather_copy_out_event = self.device_handle.Event()
302
+ all_gather_copy_out_event.record()
303
+ if not async_op and self._training_state == TrainingState.FORWARD:
304
+ # Defer free to allow for overlap of this copy-out with next
305
+ # all-gather collective
306
+ self.comm_ctx.all_gather_state = AllGatherState(
307
+ self._all_gather_result, all_gather_copy_out_event
308
+ )
309
+ else:
310
+ self._wait_all_gather_streams_on_event(all_gather_copy_out_event)
311
+ self._all_gather_result = None # free unless saved in `all_gather_state`
312
+
313
+ def _wait_all_gather_streams_on_event(self, event: torch.Event):
314
+ # Calling `unshard` before lazy init means streams are not initialized
315
+ if hasattr(self.comm_ctx, "all_gather_copy_in_stream"):
316
+ self.comm_ctx.all_gather_copy_in_stream.wait_event(event)
317
+ if hasattr(self.comm_ctx, "all_gather_stream"):
318
+ self.comm_ctx.all_gather_stream.wait_event(event)
319
+
320
+ def reshard(self):
321
+ if self._training_state == TrainingState.FORWARD:
322
+ if not self._reshard_after_forward:
323
+ return
324
+ if self._use_post_forward_mesh:
325
+ self._to_sharded_post_forward()
326
+ self._reshard_after_forward_event = self.device_handle.Event()
327
+ if self._reshard_after_forward_event is not None:
328
+ self._reshard_after_forward_event.record()
329
+ return
330
+ self._to_sharded()
331
+
332
+ def pre_forward(
333
+ self, module: nn.Module, args: tuple[Any, ...], kwargs: dict[str, Any]
334
+ ) -> tuple[tuple[Any, ...], dict[str, Any]]:
335
+ if not compiled_autograd_enabled():
336
+ logger.debug("%s", self._with_fqn("FSDP::pre_forward"))
337
+ with record_function(self._with_fqn("FSDP::pre_forward")):
338
+ self._training_state = TrainingState.FORWARD
339
+ self.unshard(self.unshard_async_op)
340
+ self.wait_for_unshard()
341
+ args, kwargs = self._register_post_backward_hook(args, kwargs)
342
+ return args, kwargs
343
+
344
+ def post_forward(self, module: nn.Module, input: Any, output: Any):
345
+ if not compiled_autograd_enabled():
346
+ logger.debug("%s", self._with_fqn("FSDP::post_forward"))
347
+ with record_function(self._with_fqn("FSDP::post_forward")):
348
+ self.reshard()
349
+ self._record_post_forward()
350
+ self._training_state = TrainingState.IDLE
351
+ return output
352
+
353
+ def _record_post_forward(self) -> None:
354
+ # Since a group has one pre-backward unshard for each forward call
355
+ # before the backward, we record each usage (with multiplicity)
356
+ post_forward_index = len(self.comm_ctx.post_forward_order)
357
+ self.comm_ctx.post_forward_order.append(self)
358
+ self._post_forward_indices.append(post_forward_index)
359
+
360
+ def pre_backward(self, default_prefetch: bool, *unused: Any):
361
+ if (
362
+ compiled_autograd_enabled()
363
+ and self._training_state == TrainingState.PRE_BACKWARD
364
+ ):
365
+ # Traceable FSDP2 cannot trigger the param group's `post_backward` immediately after param usage;
366
+ # instead it relies on this to trigger the previously unexecuted `post_backward`.
367
+ self.post_backward()
368
+ if self._training_state == TrainingState.PRE_BACKWARD:
369
+ return
370
+ if not compiled_autograd_enabled():
371
+ logger.debug("%s", self._with_fqn("FSDP::pre_backward"))
372
+ with record_function(self._with_fqn("FSDP::pre_backward")):
373
+ self._training_state = TrainingState.PRE_BACKWARD
374
+ self.unshard(self.unshard_async_op) # no-op if prefetched
375
+ self.wait_for_unshard()
376
+ if default_prefetch and not compiled_autograd_enabled():
377
+ self._backward_prefetch()
378
+
379
+ def post_backward(self, *unused: Any):
380
+ # This method should be idempotent and safe to call even when this
381
+ # FSDP parameter group was not used in backward (should be a no-op)
382
+ if not compiled_autograd_enabled():
383
+ logger.debug("%s", self._with_fqn("FSDP::post_backward"))
384
+ self._training_state = TrainingState.POST_BACKWARD
385
+ with record_function(self._with_fqn("FSDP::post_backward_accumulate")):
386
+ for fsdp_param in self.fsdp_params:
387
+ fsdp_param.accumulate_unsharded_grad_if_needed()
388
+ with record_function(self._with_fqn("FSDP::post_backward_reshard")):
389
+ if not self.reduce_grads:
390
+ if self.reshard_after_backward:
391
+ self.reshard()
392
+ for fsdp_param in self.fsdp_params:
393
+ fsdp_param.to_accumulated_grad_if_needed()
394
+ return
395
+ # Save the autograd-computed gradients before resharding to only
396
+ # access the unsharded parameters when their data is present
397
+ fsdp_params_with_grad: list[FSDPParam] = []
398
+ unsharded_grads: list[torch.Tensor] = []
399
+ for fsdp_param in self.fsdp_params:
400
+ if not hasattr(fsdp_param, "_unsharded_param"):
401
+ continue
402
+ # May have an accumulated gradient of the reduce dtype if the
403
+ # previous backward did not reduce-scatter
404
+ if fsdp_param.unsharded_accumulated_grad is not None:
405
+ fsdp_params_with_grad.append(fsdp_param)
406
+ unsharded_grads.append(fsdp_param.unsharded_accumulated_grad_data)
407
+ fsdp_param.unsharded_accumulated_grad = None
408
+ elif fsdp_param.unsharded_param.grad is not None:
409
+ fsdp_params_with_grad.append(fsdp_param)
410
+ unsharded_grads.append(fsdp_param.unsharded_grad_data)
411
+ fsdp_param.unsharded_param.grad = None
412
+ if self.reshard_after_backward:
413
+ self.reshard()
414
+ if len(fsdp_params_with_grad) == 0:
415
+ return
416
+ with record_function(self._with_fqn("FSDP::post_backward_reduce")):
417
+ if self.comm_ctx.reduce_scatter_state is not None:
418
+ self.device_handle.current_stream().wait_event(
419
+ self.comm_ctx.reduce_scatter_state.event
420
+ )
421
+ self.comm_ctx.reduce_scatter_state = None
422
+ all_reduce_pg = self._all_reduce_process_group if self._is_hsdp else None
423
+ all_reduce_stream: torch.cuda.Stream
424
+ if all_reduce_pg is None and self._all_reduce_hook_stream is not None:
425
+ # this means the native HSDP is not enabled,
426
+ # but user may want to have a custom HSDP setup
427
+ assert self._all_reduce_hook is not None, (
428
+ "all reduce hook stream is specified but hook itself is missing."
429
+ )
430
+ all_reduce_stream = self._all_reduce_hook_stream
431
+ else:
432
+ all_reduce_stream = self.comm_ctx.all_reduce_stream
433
+
434
+ self._wait_for_post_backward()
435
+ (
436
+ reduce_scatter_input,
437
+ reduce_scatter_event,
438
+ self._post_reduce_event,
439
+ all_reduce_input,
440
+ all_reduce_event,
441
+ self._partial_reduce_output,
442
+ ) = foreach_reduce(
443
+ fsdp_params_with_grad,
444
+ unsharded_grads,
445
+ self._reduce_scatter_process_group,
446
+ self.comm_ctx.reduce_scatter_stream,
447
+ self._orig_dtype,
448
+ self._reduce_dtype,
449
+ self.device,
450
+ self.reduce_scatter_reduce_op,
451
+ self._all_reduce_process_group if self._is_hsdp else None,
452
+ all_reduce_stream,
453
+ self.all_reduce_grads,
454
+ self._partial_reduce_output,
455
+ self._all_reduce_hook,
456
+ )
457
+ self.comm_ctx.reduce_scatter_state = ReduceScatterState(
458
+ reduce_scatter_input, reduce_scatter_event
459
+ )
460
+ if all_reduce_input is not None:
461
+ assert all_reduce_event is not None
462
+ self._all_reduce_state = AllReduceState(
463
+ all_reduce_input, all_reduce_event
464
+ )
465
+
466
+ def finalize_backward(self):
467
+ self._wait_for_post_backward()
468
+ for fsdp_param in self.fsdp_params:
469
+ if fsdp_param.grad_offload_event is not None:
470
+ fsdp_param.grad_offload_event.synchronize()
471
+ fsdp_param.grad_offload_event = None
472
+ if self._all_gather_result is not None:
473
+ # If there was a mistargeted unshard without a corresponding wait,
474
+ # then we wait here and clear the unshard
475
+ if (event := self._all_gather_result.all_gather_event) is not None:
476
+ torch.accelerator.current_stream().wait_event(event)
477
+ work = self._all_gather_result.all_gather_work
478
+ if isinstance(work, dist.distributed_c10d.Work):
479
+ work.wait()
480
+ self._all_gather_result = None
481
+ self._post_forward_indices.clear()
482
+
483
+ def _wait_for_post_backward(self):
484
+ if self._post_reduce_event is not None:
485
+ self.device_handle.current_stream().wait_event(self._post_reduce_event)
486
+ self._post_reduce_event = None
487
+ if self._all_reduce_state is not None:
488
+ self.device_handle.current_stream().wait_event(self._all_reduce_state.event)
489
+ self._all_reduce_state = None
490
+
491
+ def _backward_prefetch(self) -> None:
492
+ if self._training_state == TrainingState.PRE_BACKWARD:
493
+ if not self._post_forward_indices:
494
+ # Can be cleared if running multiple `backward`s
495
+ return
496
+ curr_index = self._post_forward_indices.pop()
497
+ if (target_index := curr_index - 1) < 0:
498
+ return
499
+ # Prefetch naively using the reverse post-forward order, which may
500
+ # have mistargeted prefetches if not all modules used in forward
501
+ # are used in this backward
502
+ target_fsdp_param_group = self.comm_ctx.post_forward_order[target_index]
503
+ self._prefetch_unshard(target_fsdp_param_group, "backward")
504
+
505
+ @staticmethod
506
+ def _prefetch_unshard(
507
+ target_fsdp_param_group: "FSDPParamGroup", pass_type: str
508
+ ) -> None:
509
+ if pass_type == "backward":
510
+ training_state = TrainingState.PRE_BACKWARD
511
+ elif pass_type == "forward":
512
+ training_state = TrainingState.FORWARD
513
+ else:
514
+ raise ValueError(f"Unknown pass type: {pass_type}")
515
+ target_fqn = target_fsdp_param_group._module_fqn
516
+ with (
517
+ record_function(f"FSDP::{pass_type}_prefetch for {target_fqn}"),
518
+ target_fsdp_param_group.use_training_state(training_state),
519
+ ):
520
+ async_op = target_fsdp_param_group.unshard_async_op
521
+ target_fsdp_param_group.unshard(async_op)
522
+
523
+ # Utilities #
524
+ def _to_sharded(self):
525
+ if not self.is_sharded:
526
+ for fsdp_param in self.fsdp_params:
527
+ fsdp_param.to_sharded()
528
+ self._sharded_state = ShardedState.SHARDED
529
+
530
+ def _to_sharded_post_forward(self):
531
+ if not self.is_sharded_post_forward:
532
+ for fsdp_param in self.fsdp_params:
533
+ fsdp_param.to_sharded_post_forward()
534
+ self._sharded_state = ShardedState.SHARDED_POST_FORWARD
535
+
536
+ def _to_unsharded(self):
537
+ if not self.is_unsharded:
538
+ for fsdp_param in self.fsdp_params:
539
+ fsdp_param.to_unsharded()
540
+ self._sharded_state = ShardedState.UNSHARDED
541
+
542
+ @property
543
+ def is_sharded(self) -> bool:
544
+ return self._sharded_state == ShardedState.SHARDED
545
+
546
+ @property
547
+ def is_sharded_post_forward(self) -> bool:
548
+ return self._sharded_state == ShardedState.SHARDED_POST_FORWARD
549
+
550
+ @property
551
+ def is_unsharded(self) -> bool:
552
+ return self._sharded_state == ShardedState.UNSHARDED
553
+
554
+ @contextlib.contextmanager
555
+ def use_training_state(self, training_state: TrainingState):
556
+ old_training_state = self._training_state
557
+ self._training_state = training_state
558
+ try:
559
+ yield
560
+ finally:
561
+ self._training_state = old_training_state
562
+
563
+ # Hook Registration #
564
+ def _register_post_backward_hook(
565
+ self, args: tuple[Any, ...], kwargs: dict[str, Any]
566
+ ) -> tuple[tuple[Any, ...], dict[str, Any]]:
567
+ # Traceable FSDP2 relies on `root_post_backward_callback` to call each
568
+ # `FSDPParamGroup.post_backward`
569
+ if (not torch._dynamo.config.skip_fsdp_hooks) or compiled_autograd_enabled():
570
+ return args, kwargs
571
+ if not torch.is_grad_enabled():
572
+ return args, kwargs
573
+ args_list, args_spec = tree_flatten(args)
574
+ kwargs_list, kwargs_spec = tree_flatten(kwargs)
575
+ args_kwargs_list = list(args_list) + list(kwargs_list)
576
+ inp_tensor_indices: list[int] = []
577
+ inp_tensors: list[torch.Tensor] = []
578
+ for i, obj in enumerate(args_kwargs_list):
579
+ if torch.is_tensor(obj) and obj.requires_grad:
580
+ inp_tensor_indices.append(i)
581
+ inp_tensors.append(obj)
582
+ if len(inp_tensors) == 0:
583
+ return args, kwargs # no tensors that require gradients
584
+ inp_tensors = RegisterPostBackwardFunction.apply(self, *inp_tensors)
585
+ for inp_tensor_idx, inp_tensor in zip(inp_tensor_indices, inp_tensors):
586
+ args_kwargs_list[inp_tensor_idx] = inp_tensor
587
+ args_list = args_kwargs_list[: len(args_list)]
588
+ kwargs_list = args_kwargs_list[len(args_list) :]
589
+ args = tree_unflatten(args_list, args_spec)
590
+ kwargs = tree_unflatten(kwargs_list, kwargs_spec)
591
+ return args, kwargs
592
+
593
+ def _register_state_dict_hooks(self) -> None:
594
+ num_pre_save_hooks = len(self._module_to_pre_save_state_dict_hook_handle)
595
+ num_pre_load_hooks = len(self._module_to_pre_load_state_dict_hook_handle)
596
+ assert num_pre_save_hooks == num_pre_load_hooks, (
597
+ f"Pre-save: {num_pre_save_hooks} pre-load: {num_pre_load_hooks}"
598
+ )
599
+ if num_pre_save_hooks > 0:
600
+ return # already registered
601
+ modules_with_fsdp_params: set[nn.Module] = {
602
+ fsdp_param._module_info.module for fsdp_param in self.fsdp_params
603
+ }
604
+
605
+ def to_sharded_hook(*args: Any, **kwargs: Any) -> None:
606
+ self._to_sharded()
607
+
608
+ for module in modules_with_fsdp_params:
609
+ self._module_to_pre_save_state_dict_hook_handle[module] = (
610
+ module.register_state_dict_pre_hook(to_sharded_hook)
611
+ )
612
+ self._module_to_pre_load_state_dict_hook_handle[module] = (
613
+ module._register_load_state_dict_pre_hook(to_sharded_hook)
614
+ )
615
+
616
+ # Properties #
617
+ @property
618
+ def _reshard_after_forward(self) -> bool:
619
+ return self.post_forward_mesh_info is not None
620
+
621
+ @property
622
+ def _use_post_forward_mesh(self) -> bool:
623
+ return (
624
+ self._reshard_after_forward
625
+ and self.mesh_info != self.post_forward_mesh_info
626
+ )
627
+
628
+ @property
629
+ def _is_hsdp(self) -> bool:
630
+ return isinstance(self.mesh_info, HSDPMeshInfo)
631
+
632
+ @property
633
+ def _all_gather_process_group(self) -> dist.ProcessGroup:
634
+ mesh_info = (
635
+ cast(FSDPMeshInfo, self.post_forward_mesh_info)
636
+ if self.is_sharded_post_forward
637
+ else self.mesh_info
638
+ )
639
+ assert isinstance(mesh_info, FSDPMeshInfo)
640
+ return mesh_info.shard_process_group
641
+
642
+ @property
643
+ def _reduce_scatter_process_group(self) -> dist.ProcessGroup:
644
+ assert isinstance(self.mesh_info, FSDPMeshInfo)
645
+ return self.mesh_info.shard_process_group
646
+
647
+ @property
648
+ def _all_reduce_process_group(self) -> dist.ProcessGroup:
649
+ assert isinstance(self.mesh_info, HSDPMeshInfo)
650
+ return self.mesh_info.replicate_process_group
651
+
652
+ def _with_fqn(self, label: str) -> str:
653
+ if self._module_fqn:
654
+ return f"{label} ({self._module_fqn})"
655
+ return label
656
+
657
+ def __repr__(self):
658
+ return f"FSDPParamGroup(fqn={self._module_fqn})"
659
+
660
+ def _validate_no_meta_params(self):
661
+ param_names_on_meta = [
662
+ fsdp_param._param_fqn
663
+ for fsdp_param in self.fsdp_params
664
+ if fsdp_param.sharded_param.device.type == "meta"
665
+ ]
666
+ if param_names_on_meta:
667
+ raise RuntimeError(
668
+ "FSDP parameters should be materialized from meta device before training, "
669
+ f"but the following were still on meta device: {param_names_on_meta}\n"
670
+ "For example, call module.to_empty(device) to materialize to device and "
671
+ "call module.reset_parameters() on each module to initialize values."
672
+ )
673
+
674
+ def _validate_cpu_offload_params(self):
675
+ if not isinstance(self.offload_policy, CPUOffloadPolicy):
676
+ return
677
+ fsdp_params_not_on_cpu = [
678
+ fsdp_param
679
+ for fsdp_param in self.fsdp_params
680
+ if fsdp_param.sharded_param.device.type != "cpu"
681
+ ]
682
+ if fsdp_params_not_on_cpu:
683
+ raise RuntimeError(
684
+ "FSDP parameters should be materialized on CPU when enabling CPU offloading. "
685
+ 'For example, load a CPU state dict or call module.to_empty(device="cpu"). '
686
+ "Found following parameters on non-CPU device: "
687
+ f"{[(fsdp_param._param_fqn, fsdp_param.sharded_param.device) for fsdp_param in fsdp_params_not_on_cpu]}\n"
688
+ )
689
+
690
+
691
+ def _get_param_module_infos(
692
+ params: list[nn.Parameter], modules: tuple[nn.Module, ...]
693
+ ) -> list[ParamModuleInfo]:
694
+ """
695
+ Shared parameter: lin1.weight = lin2.weight
696
+ Shared module: mlp.lin1 = mlp.lin2
697
+ We do not remove duplicates when traversing both modules and parameters to
698
+ find shared modules' parameters and shared parameters within a module.
699
+ """
700
+ params_set = set(params)
701
+ param_to_module_info: dict[nn.Parameter, ParamModuleInfo] = {}
702
+ for module in modules:
703
+ for _, submodule in module.named_modules(remove_duplicate=False):
704
+ for param_name, param in _named_parameters_with_duplicates(
705
+ submodule, recurse=False
706
+ ):
707
+ if param in params_set:
708
+ if param not in param_to_module_info:
709
+ param_to_module_info[param] = ParamModuleInfo(
710
+ submodule, param_name
711
+ )
712
+ else:
713
+ param_to_module_info[param].shared_modules.append(submodule)
714
+ param_to_module_info[param].shared_param_names.append(
715
+ param_name
716
+ )
717
+ if len(param_to_module_info) != len(params):
718
+ raise AssertionError(f"Some parameters are not in the module tree of {module}")
719
+ return [param_to_module_info[param] for param in params]
720
+
721
+
722
+ class RegisterPostBackwardFunction(torch.autograd.Function):
723
+ @staticmethod
724
+ def _assert_not_tracing_fsdp():
725
+ if compiled_autograd_enabled():
726
+ # TODO: Find a way to print the offending FSDP2 module.
727
+ msg = """\
728
+ When Traceable FSDP2 is enabled, we should not be calling into `RegisterPostBackwardFunction`.
729
+ Instead, we rely on the param group's next `pre_backward` hook to trigger its previously unexecuted
730
+ `post_backward`, and we rely on FSDPState's `root_post_backward_callback` to trigger the resharding
731
+ of any leftover unsharded param groups.
732
+ If you are here, it means the forward part of this FSDP2 instance is not compiled, and you must also
733
+ compile the forward part if you want to use Traceable FSDP2."""
734
+ torch._dynamo.comptime.comptime.print(msg)
735
+ raise RuntimeError(msg)
736
+
737
+ @staticmethod
738
+ def forward(ctx, param_group: FSDPParamGroup, *inputs: torch.Tensor):
739
+ # All tensors in `inputs` should require gradient
740
+ RegisterPostBackwardFunction._assert_not_tracing_fsdp()
741
+ ctx.param_group = param_group
742
+ return inputs
743
+
744
+ @staticmethod
745
+ def backward(ctx, *grads: torch.Tensor):
746
+ RegisterPostBackwardFunction._assert_not_tracing_fsdp()
747
+ ctx.param_group.post_backward()
748
+ return (None,) + grads
_fsdp_state.py ADDED
@@ -0,0 +1,385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-decorators
2
+ # mypy: allow-untyped-defs
3
+ import functools
4
+ import logging
5
+ from collections.abc import Sequence
6
+ from typing import Any, Callable, Optional, TYPE_CHECKING
7
+
8
+ import torch
9
+ import torch.nn as nn
10
+ from torch._logging import warning_once
11
+ from torch.autograd import Variable
12
+ from torch.autograd.graph import _MultiHandle
13
+ from torch.distributed._composable_state import (
14
+ _get_module_state,
15
+ _insert_module_state,
16
+ _State,
17
+ )
18
+ from torch.distributed.device_mesh import _get_device_handle
19
+ from torch.distributed.utils import _to_kwargs
20
+ from torch.utils._pytree import tree_flatten, tree_map
21
+
22
+ from ._fsdp_api import MixedPrecisionPolicy
23
+ from ._fsdp_common import (
24
+ _cast_fp_tensor,
25
+ compiled_autograd_enabled,
26
+ detect_compiled_autograd,
27
+ TrainingState,
28
+ )
29
+ from ._fsdp_param_group import FSDPCommContext, FSDPParamGroup
30
+
31
+
32
+ if TYPE_CHECKING:
33
+ from ._fsdp_param import FSDPParam
34
+
35
+
36
+ logger = logging.getLogger("torch.distributed.fsdp.fully_shard")
37
+
38
+
39
+ class FSDPStateContext:
40
+ """This has state shared across FSDP states."""
41
+
42
+ def __init__(self) -> None:
43
+ # All FSDP states in the root state's module tree
44
+ self.all_states: list[FSDPState] = []
45
+ # Iteration's forward root runs the once-per-forward logic; this root
46
+ # may not be the overall root set by lazy initialization in cases where
47
+ # only a submodule runs forward (e.g. encoder-only for eval)
48
+ self.iter_forward_root: Optional[FSDPState] = None
49
+ # Final callback should only be queued once per backward
50
+ self.post_backward_final_callback_queued: bool = False
51
+ # Whether to finalize backward in this backward's final callback
52
+ self.is_last_backward: bool = True
53
+ # Optional user-provided event recorded after optimizer for the
54
+ # all-gather streams to wait on in the root pre-forward
55
+ self.post_optim_event: Optional[torch.Event] = None
56
+
57
+
58
+ def disable_if_config_true(func):
59
+ @functools.wraps(func)
60
+ def fsdp_hook_wrapper(*args, **kwargs):
61
+ if torch._dynamo.config.skip_fsdp_hooks:
62
+ return torch._dynamo.disable(func, recursive=True)(*args, **kwargs)
63
+ else:
64
+ return func(*args, **kwargs)
65
+
66
+ return fsdp_hook_wrapper
67
+
68
+
69
+ class FSDPState(_State):
70
+ def __init__(self) -> None:
71
+ super().__init__()
72
+ self._fsdp_param_group: Optional[FSDPParamGroup] = None
73
+ self._is_root: Optional[bool] = None # root set during lazy init
74
+ self._state_ctx = FSDPStateContext()
75
+ self._comm_ctx = FSDPCommContext()
76
+ self._training_state: TrainingState = TrainingState.IDLE
77
+ self._states_to_forward_prefetch: list[FSDPState] = []
78
+ self._states_to_backward_prefetch: list[FSDPState] = []
79
+ self._modules_to_run_forward: set[nn.Module] = set()
80
+
81
+ # Define a separate init since `__init__` is called in the contract
82
+ def init(
83
+ self,
84
+ modules: tuple[nn.Module, ...],
85
+ device: torch.device,
86
+ mp_policy: MixedPrecisionPolicy,
87
+ ) -> None:
88
+ for module in modules:
89
+ _insert_module_state(module, self)
90
+ self._modules = modules
91
+ self._device = device
92
+ self._device_handle = _get_device_handle(device.type)
93
+ self._mp_policy = mp_policy
94
+ if len(modules) == 1:
95
+ self._pre_forward_hook_handle = modules[0].register_forward_pre_hook(
96
+ self._pre_forward, prepend=True, with_kwargs=True
97
+ )
98
+ self._post_forward_hook_handle = modules[0].register_forward_hook(
99
+ self._post_forward, prepend=False
100
+ )
101
+ else:
102
+ hook_handle = _register_group_forward_hooks(
103
+ modules,
104
+ self._pre_forward,
105
+ self._post_forward,
106
+ self._modules_to_run_forward,
107
+ )
108
+ self._pre_forward_hook_handle = hook_handle
109
+ self._post_forward_hook_handle = hook_handle
110
+
111
+ def _root_pre_forward(
112
+ self, module: nn.Module, args: tuple[Any, ...], kwargs: dict[str, Any]
113
+ ) -> tuple[tuple[Any, ...], dict[str, Any]]:
114
+ self._lazy_init()
115
+ if self._state_ctx.iter_forward_root is not None:
116
+ return args, kwargs
117
+ if not compiled_autograd_enabled():
118
+ logger.debug("FSDP::root_pre_forward")
119
+ self._state_ctx.iter_forward_root = self
120
+ with torch.profiler.record_function("FSDP::root_pre_forward"):
121
+ # Wait for optimizer before implicitly prefetched all-gathers
122
+ if (event := self._state_ctx.post_optim_event) is not None:
123
+ self._comm_ctx.all_gather_copy_in_stream.wait_event(event)
124
+ self._comm_ctx.all_gather_stream.wait_event(event)
125
+ self._state_ctx.post_optim_event = None
126
+ else:
127
+ current_stream = self._device_handle.current_stream()
128
+ self._comm_ctx.all_gather_copy_in_stream.wait_stream(current_stream)
129
+ self._comm_ctx.all_gather_stream.wait_stream(current_stream)
130
+ if self._device.type in ["cuda", "hpu", "xpu", "mtia"]:
131
+ with torch.profiler.record_function("FSDP::inputs_to_device"):
132
+ args_tuple, kwargs_tuple = _to_kwargs(
133
+ args, kwargs, self._device, False
134
+ ) # same as DDP
135
+ args, kwargs = args_tuple[0], kwargs_tuple[0]
136
+ return args, kwargs
137
+
138
+ def _lazy_init(self) -> None:
139
+ """
140
+ Lazy initialization represents when all modules' parallelisms have
141
+ finalized (e.g. FSDP has been applied to all desired modules). This
142
+ means that we can determine which state is the root, and we do so by
143
+ the 1st state to run forward.
144
+ """
145
+ if self._is_root is not None:
146
+ return # no-op: already initialized
147
+ self._is_root = True
148
+ if len(self._modules) > 1:
149
+ raise RuntimeError(
150
+ f"FSDP requires a single root module but got {self._modules}"
151
+ )
152
+ detect_compiled_autograd()
153
+ root_module = self._modules[0]
154
+ visited_states: set[FSDPState] = set()
155
+ for module_name, module in root_module.named_modules():
156
+ if (state := _get_module_fsdp_state(module)) is None:
157
+ continue
158
+ if module is not root_module:
159
+ if state not in visited_states and state._is_root is not None:
160
+ raise RuntimeError(
161
+ "FSDP state has already been lazily initialized for "
162
+ f"{module_name}\nFSDP requires running forward through "
163
+ "the root module first"
164
+ )
165
+ state._is_root = False
166
+ self._state_ctx.all_states.append(state)
167
+ visited_states.add(state)
168
+ if self._fsdp_param_group:
169
+ # For the root, do not reshard after forward since for training,
170
+ # the parameters would be freed and all-gathered immediately
171
+ self._fsdp_param_group.post_forward_mesh_info = None
172
+ self._init_fqns()
173
+ self._init_shared_state()
174
+ # Run parameter group lazy inits after initializing FQNs for improved
175
+ # error messages
176
+ for state in self._state_ctx.all_states:
177
+ if state._fsdp_param_group:
178
+ state._fsdp_param_group.lazy_init()
179
+
180
+ def _init_shared_state(self) -> None:
181
+ self._comm_ctx.lazy_init(self._device)
182
+ for state in self._state_ctx.all_states:
183
+ state._state_ctx = self._state_ctx
184
+ state._comm_ctx = self._comm_ctx
185
+ if fsdp_param_group := state._fsdp_param_group:
186
+ fsdp_param_group.comm_ctx = self._comm_ctx
187
+
188
+ def _init_fqns(self) -> None:
189
+ """Sets module and parameter FQN attributes for debugging."""
190
+ assert self._is_root
191
+ root_module = self._modules[0]
192
+ param_to_fsdp_param: dict[nn.Parameter, FSDPParam] = {}
193
+ module_to_fsdp_param_group: dict[nn.Module, FSDPParamGroup] = {}
194
+ for state in self._state_ctx.all_states:
195
+ if fsdp_param_group := state._fsdp_param_group:
196
+ for fsdp_param in fsdp_param_group.fsdp_params:
197
+ param_to_fsdp_param[fsdp_param.sharded_param] = fsdp_param
198
+ for module in fsdp_param_group.modules:
199
+ module_to_fsdp_param_group[module] = fsdp_param_group
200
+ for param_name, param in root_module.named_parameters():
201
+ if param in param_to_fsdp_param:
202
+ param_to_fsdp_param[param]._param_fqn = param_name
203
+ for module_name, module in root_module.named_modules():
204
+ if module in module_to_fsdp_param_group:
205
+ module_fqn = module_to_fsdp_param_group[module]._module_fqn
206
+ if module_fqn is None:
207
+ module_to_fsdp_param_group[module]._module_fqn = module_name
208
+ else:
209
+ assert isinstance(module_fqn, str), f"{module_fqn}"
210
+ module_fqn += f", {module_name}"
211
+ module_to_fsdp_param_group[module]._module_fqn = module_fqn
212
+
213
+ @disable_if_config_true
214
+ def _pre_forward(
215
+ self, module: nn.Module, args: tuple[Any, ...], kwargs: dict[str, Any]
216
+ ) -> tuple[tuple[Any, ...], dict[str, Any]]:
217
+ # When composing with module-hook-based activation checkpointing, the
218
+ # the pre-backward hook is responsible for the unshard
219
+ if self._training_state == TrainingState.PRE_BACKWARD:
220
+ return args, kwargs
221
+ self._training_state = TrainingState.FORWARD
222
+ args, kwargs = self._root_pre_forward(module, args, kwargs)
223
+ if self._mp_policy.cast_forward_inputs and self._mp_policy.param_dtype:
224
+ with torch.profiler.record_function("FSDP::cast_forward_inputs"):
225
+ cast_fn = functools.partial(
226
+ _cast_fp_tensor, self._mp_policy.param_dtype
227
+ )
228
+ args, kwargs = tree_map(cast_fn, args), tree_map(cast_fn, kwargs)
229
+ if self._fsdp_param_group:
230
+ args, kwargs = self._fsdp_param_group.pre_forward(module, args, kwargs)
231
+ for fsdp_state in self._states_to_forward_prefetch:
232
+ if (target_param_group := fsdp_state._fsdp_param_group) is not None:
233
+ FSDPParamGroup._prefetch_unshard(target_param_group, "forward")
234
+ return args, kwargs
235
+
236
+ @disable_if_config_true
237
+ def _post_forward(self, module: nn.Module, input: Any, output: Any) -> Any:
238
+ # When composing with module-hook-based activation checkpointing, the
239
+ # post-backward hook is responsible for the reshard
240
+ if self._training_state == TrainingState.PRE_BACKWARD:
241
+ return output
242
+ if self._fsdp_param_group:
243
+ output = self._fsdp_param_group.post_forward(module, input, output)
244
+ output = self._register_pre_backward_hook(output)
245
+ self._training_state = TrainingState.IDLE
246
+ if self._state_ctx.iter_forward_root is self:
247
+ if all_gather_state := self._comm_ctx.all_gather_state:
248
+ # Free the last all-gather result if needed; refer to
249
+ # [Note: Overlapping all-gather copy-in and all-gather]
250
+ self._comm_ctx.all_gather_copy_in_stream.wait_event(
251
+ all_gather_state.event
252
+ )
253
+ self._comm_ctx.all_gather_stream.wait_event(all_gather_state.event)
254
+ self._comm_ctx.all_gather_state = None # free the all-gather result
255
+ self._state_ctx.iter_forward_root = None
256
+ if self._mp_policy.output_dtype is not None:
257
+ with torch.profiler.record_function("FSDP::cast_forward_outputs"):
258
+ output = tree_map(
259
+ functools.partial(_cast_fp_tensor, self._mp_policy.output_dtype),
260
+ output,
261
+ )
262
+ return output
263
+
264
+ def _pre_backward(self, grad: torch.Tensor) -> torch.Tensor:
265
+ self._training_state = TrainingState.PRE_BACKWARD
266
+ self._register_root_post_backward_final_callback()
267
+ if self._fsdp_param_group:
268
+ default_prefetch = len(self._states_to_backward_prefetch) == 0
269
+ self._fsdp_param_group.pre_backward(default_prefetch)
270
+ for fsdp_state in self._states_to_backward_prefetch:
271
+ if (target_param_group := fsdp_state._fsdp_param_group) is not None:
272
+ FSDPParamGroup._prefetch_unshard(target_param_group, "backward")
273
+ return grad
274
+
275
+ def _root_post_backward_final_callback(self) -> None:
276
+ if not compiled_autograd_enabled():
277
+ logger.debug("FSDP::root_post_backward")
278
+ with torch.profiler.record_function("FSDP::root_post_backward_callback"):
279
+ for state in self._state_ctx.all_states:
280
+ fsdp_param_group = state._fsdp_param_group
281
+ if (
282
+ fsdp_param_group
283
+ and fsdp_param_group._training_state != TrainingState.POST_BACKWARD
284
+ ):
285
+ # Run post-backward in case forward inputs did not require
286
+ # gradient so the autograd backward did not run
287
+ fsdp_param_group.post_backward()
288
+ state._training_state = TrainingState.IDLE
289
+ if fsdp_param_group:
290
+ fsdp_param_group._training_state = TrainingState.IDLE
291
+ if self._state_ctx.is_last_backward:
292
+ state._finalize_backward()
293
+ if self._state_ctx.is_last_backward:
294
+ self._comm_ctx.post_forward_order.clear()
295
+ if self._comm_ctx.reduce_scatter_state is not None:
296
+ self._device_handle.current_stream().wait_event(
297
+ self._comm_ctx.reduce_scatter_state.event
298
+ )
299
+ self._comm_ctx.reduce_scatter_state = None
300
+ self._state_ctx.post_backward_final_callback_queued = False
301
+
302
+ def _finalize_backward(self) -> None:
303
+ if self._modules_to_run_forward:
304
+ msg = (
305
+ f"{len(self._modules_to_run_forward)} of the {len(self._modules)} "
306
+ f"modules passed to fully_shard did not run forward before backward, "
307
+ "which is error-prone since FSDP post-forward/pre-backward logic "
308
+ "will not run for these modules. We recommend passing only modules "
309
+ "that run forward together. Modules that did not run forward: "
310
+ f"{list(self._modules_to_run_forward)}"
311
+ )
312
+ warning_once(logger, msg, stacklevel=2)
313
+ # Clear since we want the next forward to run
314
+ self._modules_to_run_forward.clear()
315
+ if self._fsdp_param_group:
316
+ self._fsdp_param_group.finalize_backward()
317
+
318
+ def _register_pre_backward_hook(self, output: Any) -> Any:
319
+ if not torch.is_grad_enabled():
320
+ return output
321
+ flat_outputs, _ = tree_flatten(output)
322
+ for t in flat_outputs:
323
+ if torch.is_tensor(t) and t.requires_grad:
324
+ t.register_hook(self._pre_backward)
325
+ return output
326
+
327
+ def _register_root_post_backward_final_callback(self):
328
+ if self._state_ctx.post_backward_final_callback_queued:
329
+ return
330
+ self._state_ctx.post_backward_final_callback_queued = True
331
+ Variable._execution_engine.queue_callback(
332
+ self._root_post_backward_final_callback
333
+ )
334
+
335
+
336
+ def _get_module_fsdp_state(module: nn.Module) -> Optional[FSDPState]:
337
+ state = _get_module_state(module)
338
+ if isinstance(state, FSDPState):
339
+ return state
340
+ return None
341
+
342
+
343
+ def _register_group_forward_hooks(
344
+ modules: Sequence[nn.Module],
345
+ pre_hook: Callable,
346
+ post_hook: Callable,
347
+ modules_to_run: set[nn.Module],
348
+ ):
349
+ """
350
+ Registers group forward pre and post-hooks. The pre-hook runs upon the
351
+ first module pre-forward, and the post-hook runs upon the last. If at least
352
+ one module does not run forward, then the post-hook does not run.
353
+ """
354
+ modules_set = set(modules)
355
+
356
+ @disable_if_config_true
357
+ @functools.wraps(pre_hook)
358
+ def wrapped_pre_hook(*args: Any, **kwargs: Any):
359
+ if len(modules_to_run) == 0: # first to run
360
+ modules_to_run.update(modules_set)
361
+ return pre_hook(*args, **kwargs)
362
+
363
+ @disable_if_config_true
364
+ def get_wrapped_post_hook(module: nn.Module):
365
+ @functools.wraps(post_hook)
366
+ def wrapped_post_hook(*args: Any, **kwargs: Any):
367
+ modules_to_run.discard(module)
368
+ if len(modules_to_run) == 0:
369
+ return post_hook(*args, **kwargs)
370
+
371
+ return wrapped_post_hook
372
+
373
+ pre_handles = [
374
+ module.register_forward_pre_hook(
375
+ wrapped_pre_hook, prepend=True, with_kwargs=True
376
+ )
377
+ for module in modules
378
+ ]
379
+ post_handles = [
380
+ module.register_forward_hook(
381
+ get_wrapped_post_hook(module), prepend=False, always_call=True
382
+ )
383
+ for module in modules
384
+ ]
385
+ return _MultiHandle(tuple(pre_handles + post_handles))
_fully_shard.py ADDED
@@ -0,0 +1,590 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-decorators
2
+ # mypy: allow-untyped-defs
3
+
4
+ from __future__ import annotations
5
+
6
+ import functools
7
+ from typing import (
8
+ Any,
9
+ Callable,
10
+ cast,
11
+ NoReturn,
12
+ Optional,
13
+ overload,
14
+ TYPE_CHECKING,
15
+ Union,
16
+ )
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ from torch.distributed._composable import contract
21
+ from torch.distributed.utils import _get_root_modules
22
+
23
+ from ._fsdp_api import MixedPrecisionPolicy, OffloadPolicy
24
+ from ._fsdp_common import FSDPMeshInfo, HSDPMeshInfo
25
+ from ._fsdp_init import (
26
+ _get_device_from_mesh,
27
+ _get_managed_modules,
28
+ _get_managed_states,
29
+ _get_post_forward_mesh_info,
30
+ _init_default_fully_shard_mesh,
31
+ _move_states_to_device,
32
+ )
33
+ from ._fsdp_param_group import FSDPParamGroup
34
+ from ._fsdp_state import _get_module_fsdp_state, FSDPState
35
+
36
+
37
+ if TYPE_CHECKING:
38
+ from collections.abc import Iterable
39
+
40
+ from torch.distributed.tensor import DeviceMesh, Shard
41
+
42
+ __all__ = [
43
+ "fully_shard",
44
+ "FSDPModule",
45
+ "UnshardHandle",
46
+ "register_fsdp_forward_method",
47
+ ]
48
+
49
+
50
+ cls_to_fsdp_cls: dict[type, type] = {}
51
+
52
+
53
+ @overload
54
+ def fully_shard(
55
+ module: nn.Module,
56
+ *,
57
+ mesh: Optional[DeviceMesh] = ...,
58
+ reshard_after_forward: Union[bool, int] = ...,
59
+ shard_placement_fn: Optional[Callable[[nn.Parameter], Optional[Shard]]] = ...,
60
+ mp_policy: MixedPrecisionPolicy = ...,
61
+ offload_policy: OffloadPolicy = ...,
62
+ ignored_params: Optional[set[nn.Parameter]] = ...,
63
+ ) -> FSDPModule: ...
64
+
65
+
66
+ @overload
67
+ def fully_shard(
68
+ module: list[nn.Module],
69
+ *,
70
+ mesh: Optional[DeviceMesh] = ...,
71
+ reshard_after_forward: Union[bool, int] = ...,
72
+ shard_placement_fn: Optional[Callable[[nn.Parameter], Optional[Shard]]] = ...,
73
+ mp_policy: MixedPrecisionPolicy = ...,
74
+ offload_policy: OffloadPolicy = ...,
75
+ ignored_params: Optional[set[nn.Parameter]] = ...,
76
+ ) -> list[FSDPModule]: ...
77
+
78
+
79
+ # The decorator adds a state object to `module` that can be accessed via
80
+ # `fully_shard.state(module)`. The state object and module are 1:1.
81
+ # [1] Python runtime decorator does not play well with static type checking
82
+ # so suppressing some type checks to support type overloads
83
+ # such that caller can still get correct return types based on input type
84
+ @contract(state_cls=FSDPState) # type: ignore[misc] # see [1]
85
+ def fully_shard(
86
+ module,
87
+ *,
88
+ mesh: Optional[DeviceMesh] = None,
89
+ reshard_after_forward: Union[bool, int] = True,
90
+ shard_placement_fn: Optional[Callable[[nn.Parameter], Optional[Shard]]] = None,
91
+ mp_policy: MixedPrecisionPolicy = MixedPrecisionPolicy(),
92
+ offload_policy: OffloadPolicy = OffloadPolicy(),
93
+ ignored_params: Optional[set[nn.Parameter]] = None,
94
+ ):
95
+ """
96
+ Apply fully sharded data parallelism (FSDP) to ``module``, where FSDP
97
+ shards module parameters, gradients, and optimizer states across data
98
+ parallel workers to save memory at the cost of communication.
99
+
100
+ At initialization, FSDP shards the module's parameters across the data
101
+ parallel workers given by ``mesh``. Before forward, FSDP all-gathers the
102
+ sharded parameters across the data-parallel workers to get the unsharded
103
+ parameters for forward computation. If ``reshard_after_forward`` is
104
+ ``True``, then FSDP frees the unsharded parameters after forward and
105
+ re-all-gathers them in backward before gradient computation. After gradient
106
+ computation, FSDP frees the unsharded parameters and reduce-scatters the
107
+ unsharded gradients across data-parallel workers.
108
+
109
+ This implementation represents the sharded parameters as :class:`DTensor` s
110
+ sharded on dim-0, while the unsharded parameters will be like the original
111
+ parameters on ``module`` (e.g. :class:`torch.Tensor` if originally
112
+ :class:`torch.Tensor`). A module
113
+ `forward pre-hook <https://pytorch.org/docs/main/generated/torch.nn.Module.html#torch.nn.Module.register_forward_pre_hook>`_
114
+ on ``module`` all-gathers the parameters, and a module
115
+ `forward hook <https://pytorch.org/docs/main/generated/torch.nn.Module.html#torch.nn.Module.register_forward_hook>`_
116
+ on ``module`` frees them (if needed). Similar backward hooks all-gather
117
+ parameters and later free parameters and reduce-scatter gradients.
118
+
119
+ Since grouping multiple tensors together for one collective is critical for
120
+ communication efficiency, this implementation makes this grouping first
121
+ class. Calling :meth:`fully_shard` on ``module`` constructs one group that
122
+ includes the parameters in ``module.parameters()`` except those already
123
+ assigned to a group from an earlier call on a submodule. This means that
124
+ :meth:`fully_shard` should be called bottom-up on your model. Each group's
125
+ parameters are all-gathered in one collective, and its gradients are
126
+ reduce-scattered in one collective. Partitioning the model into multiple
127
+ groups ("layer by layer") allows for peak memory savings and communication/computation
128
+ overlap. Users generally should *not* call :meth:`fully_shard` only on the
129
+ topmost root module.
130
+
131
+ Args:
132
+ module (Union[nn.Module, List[nn.Module]): The module or modules to
133
+ shard with FSDP and group together for communication.
134
+ mesh (Optional[DeviceMesh]): This data parallel mesh defines the
135
+ sharding and device. If 1D, then parameters are fully sharded
136
+ across the 1D mesh (FSDP) with ``(Shard(0),)`` placement. If 2D,
137
+ then parameters are sharded across the 1st dim and replicated
138
+ across the 0th dim (HSDP) with ``(Replicate(), Shard(0))``
139
+ placement. The mesh's device type gives the device type used for
140
+ communication; if a CUDA or CUDA-like device type, then we use the
141
+ current device.
142
+ reshard_after_forward (Union[bool, int]): This controls the parameter
143
+ behavior after forward and can trade off memory and communication:
144
+
145
+ - If ``True``, then this reshards parameters after forward and
146
+ re-all-gathers in backward.
147
+ - If ``False``, then this keeps the unsharded parameters in memory
148
+ after forward and avoids the all-gather in backward.
149
+ - If an ``int``, then this represents the world size to reshard to
150
+ after forward. It should be a non-trivial divisor of the ``mesh``
151
+ shard dim size (i.e. excluding 1 and the dim size itself). A
152
+ choice may be the intra-node size (e.g. ``torch.cuda.device_count()``).
153
+ This allows the all-gather in backward to be over a smaller world
154
+ size at the cost of higher memory usage than setting to ``True``.
155
+ - The root FSDP state has its value specially set to ``False`` as a
156
+ heuristic since its parameters would typically be immediately
157
+ all-gathered for backward.
158
+ - After forward, the parameters registered to the module depend on
159
+ to this: The registered parameters are the sharded parameters if
160
+ ``True``; unsharded parameters if ``False``; and the paramters
161
+ resharded to the smaller mesh otherwise. To modify the parameters
162
+ between forward and backward, the registered parameters must be
163
+ the sharded parameters. For ``False`` or an ``int``, this can be
164
+ done by manually resharding via :meth:`reshard`.
165
+ shard_placement_fn (Optional[Callable[[nn.Parameter], Optional[Shard]]]):
166
+ This callable can be used to override the sharding placement for a
167
+ parameter to shard a parameter on a dimension other than dim-0. If
168
+ this callable returns a :class:`Shard` placement (not ``None``),
169
+ then FSDP will shard according to that placement (e.g. ``Shard(1)``).
170
+ If sharding on a nonzero dim, we currently require even sharding,
171
+ i.e. the tensor dim size on that dim must be divisible by the FSDP
172
+ shard mesh size.
173
+ mp_policy (MixedPrecisionPolicy): This controls the mixed precision
174
+ policy, which offers parameter/reduction mixed precision for this
175
+ module. See :class:`MixedPrecisionPolicy` for details.
176
+ offload_policy (OffloadPolicy): This controls the offloading policy,
177
+ which offers parameter/gradient/optimizer state offloading. See
178
+ :class:`OffloadPolicy` and its subclasses for details.
179
+ ignored_params: Optional(Set[nn.Parameter]): The set of parameters that we
180
+ don't want to shard with FSDP.
181
+
182
+ Returns:
183
+ FSDPModule: The module with FSDP applied (in-place).
184
+ """
185
+ if isinstance(module, (nn.ModuleList, nn.ModuleDict)):
186
+ raise ValueError(
187
+ f"fully_shard does not support containers that do not implement forward: {module}"
188
+ )
189
+ mesh = mesh or _init_default_fully_shard_mesh()
190
+ if mesh.ndim not in (1, 2):
191
+ raise ValueError(f"fully_shard expects a 1D or 2D DeviceMesh but got {mesh}")
192
+ elif mesh.ndim == 1:
193
+ mesh_info = FSDPMeshInfo(mesh, shard_mesh_dim=0)
194
+ else:
195
+ if mesh.mesh_dim_names is None:
196
+ raise AssertionError(
197
+ "Please init the 2D mesh for HSDP with mesh_dim_names specified"
198
+ )
199
+ mesh_info = HSDPMeshInfo(mesh, shard_mesh_dim=1, replicate_mesh_dim=0)
200
+ device = _get_device_from_mesh(mesh)
201
+ post_forward_mesh_info = _get_post_forward_mesh_info(
202
+ reshard_after_forward, mesh_info
203
+ )
204
+
205
+ arg_module = module
206
+ modules = (
207
+ (module,) if isinstance(module, nn.Module) else tuple(_get_root_modules(module))
208
+ )
209
+ state = fully_shard.state(modules[0]) # type: ignore[attr-defined] # see [1]
210
+ state.init(modules, device, mp_policy)
211
+
212
+ managed_modules = _get_managed_modules(modules, ignored_params)
213
+ params, buffers = _get_managed_states(managed_modules, ignored_params)
214
+
215
+ _move_states_to_device(params, buffers, device)
216
+ if params:
217
+ state._fsdp_param_group = FSDPParamGroup(
218
+ params,
219
+ modules,
220
+ mesh_info,
221
+ post_forward_mesh_info,
222
+ device,
223
+ shard_placement_fn,
224
+ mp_policy,
225
+ offload_policy,
226
+ )
227
+
228
+ # For Dynamo
229
+ for managed_module in managed_modules:
230
+ managed_module._is_fsdp_managed_module = True # type: ignore[assignment]
231
+ managed_module._fsdp_use_orig_params = True # type: ignore[assignment]
232
+
233
+ # Place FSDP leftmost for highest priority in the method resolution order
234
+ for module in modules:
235
+ cls = module.__class__
236
+ new_cls = cls_to_fsdp_cls.get(cls, None)
237
+ if not new_cls:
238
+ dct = {"__deepcopy__": _unimplemented_deepcopy}
239
+ new_cls = type(f"FSDP{cls.__name__}", (FSDPModule, cls), dct)
240
+ cls_to_fsdp_cls[cls] = new_cls
241
+ module.__class__ = new_cls
242
+ return arg_module
243
+
244
+
245
+ def _unimplemented_deepcopy(*args: Any, **kwargs: Any) -> NoReturn:
246
+ raise AssertionError(
247
+ "FSDP does not support deepcopy. Please use state dict for serialization."
248
+ )
249
+
250
+
251
+ class FSDPModule:
252
+ def __new__(cls, *args, **kwargs):
253
+ """
254
+ Override ``__new__`` to remove the FSDP class and directly construct
255
+ the original class for cases like indexing into a container module.
256
+ """
257
+ # Use index 2 since 0 is the dynamically constructed `FSDP<...>` class
258
+ # and index 1 is the `FSDPModule` class itself
259
+ orig_cls = cls.__mro__[2]
260
+ self = orig_cls.__new__(orig_cls, *args, **kwargs)
261
+ self.__init__(*args, **kwargs)
262
+ return self
263
+
264
+ def reshard(self) -> None:
265
+ """
266
+ Reshards the module's parameters, freeing the unsharded parameters if
267
+ they are allocated and registering the sharded parameters to the
268
+ module. This method is *not* recursive.
269
+ """
270
+ state = self._get_fsdp_state()
271
+ if fsdp_param_group := state._fsdp_param_group:
272
+ fsdp_param_group.reshard()
273
+
274
+ def unshard(self, async_op: bool = False) -> Optional[UnshardHandle]:
275
+ """
276
+ Unshards the module's parameters by allocating memory and all-gathering
277
+ the parameters. This method is *not* recursive. The unshard follows the
278
+ :class:`MixedPrecisionPolicy`, so it will all-gather following
279
+ ``param_dtype`` if set.
280
+
281
+ Args:
282
+ async_op (bool): If ``True``, then returns a :class:`UnshardHandle`
283
+ that has a :meth:`wait` method to wait on the unshard op. If
284
+ ``False``, then returns ``None`` and waits on the handle inside
285
+ this function.
286
+
287
+ .. note:: If ``async_op=True``, then FSDP will wait on the pending
288
+ unshard in the module's pre-forward for the user. The user only
289
+ needs to call :meth:`wait` explicitly if the wait should happen
290
+ before pre-forward.
291
+ """
292
+ state = self._get_fsdp_state()
293
+ fsdp_param_group = state._fsdp_param_group
294
+ if fsdp_param_group is not None:
295
+ fsdp_param_group.lazy_init()
296
+ fsdp_param_group.unshard(async_op=async_op)
297
+ handle = _UnshardHandleImpl(fsdp_param_group)
298
+ if async_op:
299
+ return handle
300
+ handle.wait()
301
+ return None
302
+
303
+ def set_is_last_backward(self, is_last_backward: bool) -> None:
304
+ """
305
+ Sets whether the next backward is the last one. On the last backward,
306
+ FSDP waits on pending gradient reduction and clears internal data
307
+ data structures for backward prefetching. This can be useful for
308
+ microbatching.
309
+ """
310
+ state = self._get_fsdp_state()
311
+ state._state_ctx.is_last_backward = is_last_backward
312
+
313
+ def set_requires_gradient_sync(
314
+ self, requires_gradient_sync: bool, *, recurse: bool = True
315
+ ) -> None:
316
+ """
317
+ Sets if the module should sync gradients. This can be used to implement
318
+ gradient accumulation *without communication*. For HSDP, this controls
319
+ both reduce-scatter and all-reduce together. This is the equivalence of
320
+ `no_sync` in FSDP1.
321
+
322
+ Args:
323
+ requires_gradient_sync (bool): Whether to reduce gradients for the
324
+ module's parameters.
325
+ recurse (bool): Whether to set for all FSDP submodules or just the
326
+ passed-in module.
327
+ """
328
+ self_module = cast(nn.Module, self)
329
+ modules = list(self_module.modules()) if recurse else [self_module]
330
+ for module in modules:
331
+ if isinstance(module, FSDPModule):
332
+ state = module._get_fsdp_state()
333
+ if fsdp_param_group := state._fsdp_param_group:
334
+ fsdp_param_group.reduce_grads = requires_gradient_sync
335
+ fsdp_param_group.all_reduce_grads = requires_gradient_sync
336
+
337
+ def set_requires_all_reduce(
338
+ self, requires_all_reduce: bool, *, recurse: bool = True
339
+ ) -> None:
340
+ """
341
+ Sets if the module should all-reduce gradients. This can be used to
342
+ implement gradient accumulation with only reduce-scatter but not
343
+ all-reduce for HSDP.
344
+ """
345
+ self_module = cast(nn.Module, self)
346
+ modules = list(self_module.modules()) if recurse else [self_module]
347
+ for module in modules:
348
+ if isinstance(module, FSDPModule):
349
+ state = module._get_fsdp_state()
350
+ if fsdp_param_group := state._fsdp_param_group:
351
+ fsdp_param_group.all_reduce_grads = requires_all_reduce
352
+
353
+ def set_reshard_after_backward(
354
+ self, reshard_after_backward: bool, *, recurse: bool = True
355
+ ) -> None:
356
+ """
357
+ Sets if the module should reshard parameters after backward. This can
358
+ be used during gradient accumulation to trade off higher memory for
359
+ reduced communication since the unsharded parameters do not need to be
360
+ re-all-gathered before the next forward.
361
+
362
+ Args:
363
+ reshard_after_backward (bool): Whether to reshard parameters after
364
+ backward.
365
+ recurse (bool): Whether to set for all FSDP submodules or just the
366
+ passed-in module.
367
+ """
368
+ self_module = cast(nn.Module, self)
369
+ modules = list(self_module.modules()) if recurse else [self_module]
370
+ for module in modules:
371
+ if isinstance(module, FSDPModule):
372
+ state = module._get_fsdp_state()
373
+ if fsdp_param_group := state._fsdp_param_group:
374
+ fsdp_param_group.reshard_after_backward = reshard_after_backward
375
+
376
+ def set_modules_to_forward_prefetch(self, modules: list[FSDPModule]) -> None:
377
+ """
378
+ Sets the FSDP modules for which this FSDP module should explicitly
379
+ prefetch all-gathers in forward. The prefetching runs after this
380
+ module's all-gather copy-out.
381
+
382
+ Passing a singleton list containing the next FSDP module gives the same
383
+ all-gather overlap behavior as the default overlap behavior, except the
384
+ prefetched all-gather is issued earlier from the CPU. Passing a list
385
+ with at least length two is required for more aggressive overlap and
386
+ will use more reserved memory.
387
+
388
+ Args:
389
+ modules (List[FSDPModule]): FSDP modules to prefetch.
390
+ """
391
+ _assert_all_fsdp_modules(modules)
392
+ self._get_fsdp_state()._states_to_forward_prefetch = [
393
+ module._get_fsdp_state() for module in modules
394
+ ]
395
+
396
+ def set_modules_to_backward_prefetch(self, modules: list[FSDPModule]) -> None:
397
+ """
398
+ Sets the FSDP modules for which this FSDP module should explicitly
399
+ prefetch all-gathers in backward. This overrides the default backward
400
+ pretching implementation that prefetches the next FSDP module based on
401
+ the reverse post-forward order.
402
+
403
+ Passing a singleton list containing the previous FSDP module gives the
404
+ same all-gather overlap behavior as the default overlap behavior.
405
+ Passing a list with at least length two is required for more aggressive
406
+ overlap and will use more reserved memory.
407
+
408
+ Args:
409
+ modules (List[FSDPModule]): FSDP modules to prefetch.
410
+ """
411
+ _assert_all_fsdp_modules(modules)
412
+ self._get_fsdp_state()._states_to_backward_prefetch = [
413
+ module._get_fsdp_state() for module in modules
414
+ ]
415
+
416
+ def set_all_reduce_hook(
417
+ self,
418
+ hook: Callable[[torch.Tensor], None],
419
+ *,
420
+ stream: Optional[torch.cuda.Stream] = None,
421
+ ):
422
+ """
423
+ Args:
424
+ hook (Callable[[torch.Tensor], None]): User-defined all-reduce hook
425
+ with expected signature ``hook(reduce_output: torch.Tensor) -> None``
426
+ where ``reduce_output`` is the reduce-scatter output if only
427
+ using FSDP or the all-reduce output if using native HSDP.
428
+ stream (Optional[torch.cuda.Stream]): Stream to run the all-reduce
429
+ hook in. This should only be set if not using native HSDP. If
430
+ using native HSDP, the hook will run in the internally defined
431
+ all-reduce stream used by the native HSDP all-reduce.
432
+ """
433
+ state = self._get_fsdp_state()
434
+ if (fsdp_param_group := state._fsdp_param_group) is not None:
435
+ fsdp_param_group._all_reduce_hook = hook
436
+ if stream is not None:
437
+ if fsdp_param_group._is_hsdp:
438
+ raise ValueError("stream cannot be set when using native HSDP")
439
+ fsdp_param_group._all_reduce_hook_stream = stream
440
+
441
+ def set_post_optim_event(self, event: torch.Event) -> None:
442
+ """
443
+ Sets a post-optimizer-step event for the root FSDP module to wait the
444
+ all-gather streams on.
445
+
446
+ By default, the root FSDP module waits the all-gather streams on the
447
+ current stream to ensure that the optimizer step has finished before
448
+ all-gathering. However, this may introduce false dependencies if
449
+ there is unrelated computation after the optimizer step. This API
450
+ allows the user to provide their own event to wait on. After the root
451
+ waits on the event, the event is discarded, so this API should be
452
+ called with a new event each iteration.
453
+
454
+ Args:
455
+ event (torch.Event): Event recorded after the optimizer step
456
+ to wait all-gather streams on.
457
+ """
458
+ self._get_fsdp_state()._state_ctx.post_optim_event = event
459
+
460
+ def set_reduce_scatter_divide_factor(self, factor: float) -> None:
461
+ """
462
+ Sets a custom divide factor for the reduce-scatter. This becomes a
463
+ custom reduce op using NCCL's PreMulSum, which allows multiplying by
464
+ the factor before reduction.
465
+
466
+ Args:
467
+ factor (float): Custom divide factor.
468
+ """
469
+ state = self._get_fsdp_state()
470
+ if (fsdp_param_group := state._fsdp_param_group) is not None:
471
+ mul_factor = 1.0 / float(factor)
472
+ reduce_op = torch.distributed._make_nccl_premul_sum(mul_factor)
473
+ fsdp_param_group.reduce_scatter_reduce_op = reduce_op
474
+
475
+ def set_unshard_in_backward(self, unshard_in_backward: bool) -> None:
476
+ """
477
+ Sets whether the FSDP module's parameters need to be unsharded in
478
+ backward. This can be used in expert cases when the user knows that all
479
+ parameters in this FSDP module's parameter group are not needed for
480
+ backward computation (e.g. embedding).
481
+ """
482
+ state = self._get_fsdp_state()
483
+ if (fsdp_param_group := state._fsdp_param_group) is not None:
484
+ fsdp_param_group.unshard_in_backward = unshard_in_backward
485
+
486
+ def _set_unshard_async_op(self, async_op: bool):
487
+ """
488
+ Sets whether to use ``async_op=True`` or ``False`` for the pre-forward
489
+ and pre-backward unshard op. This defaults to ``False`` but can be set
490
+ to ``True`` with this method.
491
+
492
+ Setting this to ``True`` allows the all-gather allocations to happen in
493
+ the default stream, avoiding inter-stream memory fragmentation.
494
+ However, you must use explicit prefetching (e.g. via :meth:`unshard`)
495
+ in forward to still get overlap, and the pre-all-gather ops like dtype
496
+ casting and copy-in will not overlap with compute.
497
+ """
498
+ self_module = cast(nn.Module, self)
499
+ for module in self_module.modules():
500
+ if isinstance(module, FSDPModule):
501
+ state = module._get_fsdp_state()
502
+ if fsdp_param_group := state._fsdp_param_group:
503
+ fsdp_param_group.unshard_async_op = async_op
504
+
505
+ def _get_fsdp_state(self) -> FSDPState:
506
+ if (state := _get_module_fsdp_state(cast(nn.Module, self))) is None:
507
+ raise AssertionError(f"No FSDP state found on {self}")
508
+ return state
509
+
510
+ def _apply(self, *args: Any, **kwargs: Any) -> Any:
511
+ # Reshard to ensure that sharded parameters are registered
512
+ self.reshard()
513
+ ret = super()._apply(*args, **kwargs) # type: ignore[misc]
514
+ state = self._get_fsdp_state()
515
+ if not (fsdp_param_group := state._fsdp_param_group):
516
+ return ret
517
+ # TODO: Remove this padding logic once DTensor pads the local tensor:
518
+ # https://github.com/pytorch/pytorch/issues/113045
519
+ with torch.no_grad():
520
+ for fsdp_param in fsdp_param_group.fsdp_params:
521
+ fsdp_param.reset_sharded_param()
522
+ return ret
523
+
524
+
525
+ class UnshardHandle:
526
+ """
527
+ A handle to wait on a :meth:`FSDPModule.unshard` op.
528
+ """
529
+
530
+ def wait(self) -> None:
531
+ """
532
+ Waits on the unshard op. This ensures that the current stream can use
533
+ the unsharded parameters, which are now registered to the module.
534
+ """
535
+ return
536
+
537
+
538
+ class _UnshardHandleImpl(UnshardHandle):
539
+ def __init__(self, fsdp_param_group: Optional[FSDPParamGroup]):
540
+ self._fsdp_param_group = fsdp_param_group
541
+
542
+ def wait(self):
543
+ if self._fsdp_param_group is not None:
544
+ self._fsdp_param_group.wait_for_unshard()
545
+ # Avoid keeping a reference
546
+ self._fsdp_param_group = None
547
+
548
+
549
+ def register_fsdp_forward_method(module: nn.Module, method_name: str) -> None:
550
+ """
551
+ Registers a method on ``module`` to be considered a forward method for
552
+ FSDP.
553
+
554
+ FSDP all-gathers parameters pre-forward and optionally frees parameters
555
+ post-forward (depending on ``reshard_after_forward``). FSDP only knows to
556
+ do this for :meth:`nn.Module.forward` by default. This function patches a
557
+ user-specified method to run the pre/post-forward hooks before/after the
558
+ method, respectively. If ``module`` is not an :class:`FSDPModule`, then
559
+ this is a no-op.
560
+
561
+ Args:
562
+ module (nn.Module): Module to register the forward method on.
563
+ method_name (str): Name of the forward method.
564
+ """
565
+ if not isinstance(module, FSDPModule):
566
+ # Make no-op to allow including both when using/not using FSDP
567
+ return
568
+ if not hasattr(module, method_name):
569
+ raise ValueError(f"{type(module)} does not have a method {method_name}")
570
+ orig_method = getattr(module, method_name)
571
+
572
+ @functools.wraps(orig_method)
573
+ def wrapped_method(self, *args, **kwargs):
574
+ fsdp_state = self._get_fsdp_state()
575
+ args, kwargs = fsdp_state._pre_forward(self, args, kwargs)
576
+ out = orig_method(*args, **kwargs)
577
+ return fsdp_state._post_forward(self, args, out)
578
+
579
+ # Use `__get__` to make `wrapped_method` an instance method
580
+ setattr(
581
+ module,
582
+ method_name,
583
+ wrapped_method.__get__(module, type(module)), # type:ignore[attr-defined]
584
+ )
585
+
586
+
587
+ def _assert_all_fsdp_modules(modules: Iterable[Any]) -> None:
588
+ for module in modules:
589
+ if not isinstance(module, FSDPModule):
590
+ raise ValueError(f"Expects FSDPModule but got {type(module)}: {module}")
chat_template.jinja ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {%- set ns = namespace(enable_thinking=true) %}{%- for message in messages -%}{%- set content = message['content'] -%}{%- if message['role'] == 'user' or message['role'] == 'system' -%}{%- if '/think' in content -%}{%- set ns.enable_thinking = true -%}{%- elif '/no_think' in content -%}{%- set ns.enable_thinking = false -%}{%- endif -%}{%- endif -%}{%- endfor -%}{%- if messages[0]['role'] != 'system' -%}{%- set ns.non_tool_system_content = '' -%}{{- '<SPECIAL_10>System
2
+ ' -}}{%- else -%}{%- set ns.non_tool_system_content = messages[0]['content'].replace('/think', '').replace('/no_think', '').strip() -%}{{- '<SPECIAL_10>System
3
+ ' + ns.non_tool_system_content }}{%- endif -%}{%- if tools -%}{%- if ns.non_tool_system_content is defined and ns.non_tool_system_content != '' -%}{{- '
4
+
5
+ ' -}}{%- endif -%}{{- 'You can use the following tools to assist the user if required:' -}}{{- '
6
+ <AVAILABLE_TOOLS>[' -}}{%- for tool in tools -%}{{- (tool.function if tool.function is defined else tool) | tojson -}}{{- ', ' if not loop.last else '' -}}{%- endfor -%}{{- ']</AVAILABLE_TOOLS>
7
+
8
+ ' -}}{{- 'If you decide to call any tool(s), use the following format:
9
+ ' -}}{{- '<TOOLCALL>[{{"name": "tool_name1", "arguments": "tool_args1"}}, ' -}}{{- '{{"name": "tool_name2", "arguments": "tool_args2"}}]</TOOLCALL>
10
+
11
+ ' -}}{{- 'The user will execute tool-calls and return responses from tool(s) in this format:
12
+ ' -}}{{- '<TOOL_RESPONSE>[{{"tool_response1"}}, {{"tool_response2"}}]</TOOL_RESPONSE>
13
+
14
+ ' -}}{{- 'Based on the tool responses, you can call additional tools if needed, correct tool calls if any errors are found, or just respond to the user.' -}}{%- endif -%}{{- '
15
+ ' -}}{%- set messages = messages[1:] if messages[0]['role'] == 'system' else messages -%}{%- if messages[-1]['role'] == 'assistant' -%}{%- set ns.last_turn_assistant_content = messages[-1]['content'].strip() -%}{%- set messages = messages[:-1] -%}{%- endif -%}{%- for message in messages %}{%- set content = message['content'] %}{%- if message['role'] == 'user' -%}{{- '<SPECIAL_11>User
16
+ ' + content.replace('/think', '').replace('/no_think', '').strip() + '
17
+ ' }}{%- elif message['role'] == 'tool' -%}{%- if loop.first or (messages[loop.index0 - 1].role != 'tool') -%}{{- '<SPECIAL_11>User
18
+ ' + '<TOOL_RESPONSE>[' }}{%- endif -%}{{- message['content'] -}}{{- ', ' if not loop.last and (messages[loop.index0 + 1].role == 'tool') else '' -}}{%- if loop.last or (messages[loop.index0 + 1].role != 'tool') -%}{{- ']</TOOL_RESPONSE>
19
+ ' -}}{%- endif -%}{%- elif message['role'] == 'assistant' -%}{%- if '</think>' in content -%}{%- set content = content.split('</think>')[1].strip() %}{%- endif -%}{{- '<SPECIAL_11>Assistant
20
+ ' + content.strip() }}{%- if message.tool_calls -%}{%- if content.strip() != '' -%}{{- '
21
+
22
+ ' -}}{%- endif -%}{{- '<TOOLCALL>[' -}}{%- for call in message.tool_calls -%}{%- set fn = call.function if call.function is defined else call -%}{{- '{"name": "' + fn.name + '", "arguments": ' -}}{%- if fn.arguments is string -%}{{- fn.arguments -}}{%- else -%}{{- fn.arguments | tojson -}}{%- endif -%}{{- '}' + (', ' if not loop.last else '') -}}{%- endfor -%}{{- ']</TOOLCALL>' -}}{%- endif -%}{{- '
23
+ <SPECIAL_12>
24
+ ' -}}{%- endif -%}{%- endfor -%}{%- if add_generation_prompt -%}{{- '<SPECIAL_11>Assistant
25
+ ' -}}{%- if ns.enable_thinking is defined and ns.enable_thinking is false -%}{{- '<think></think>' -}}{%- else -%}{{- '<think>
26
+ ' -}}{%- endif -%}{%- if ns.last_turn_assistant_content is defined and ns.last_turn_assistant_content != '' -%}{{- ns.last_turn_assistant_content -}}{%- endif -%}{%- else -%}{%- if ns.last_turn_assistant_content is defined and ns.last_turn_assistant_content != '' -%}{{- '<SPECIAL_11>Assistant
27
+ ' -}}{%- if ns.enable_thinking is defined and ns.enable_thinking is false -%}{{- '<think></think>' -}}{%- else -%}{{- '<think>
28
+ ' -}}{%- endif -%}{{- ns.last_turn_assistant_content -}}{%- if continue_final_message is defined -%}{%- if continue_final_message is false -%}{{- '
29
+ <SPECIAL_12>
30
+ ' -}}{%- endif -%}{%- else -%}{{- '
31
+ <SPECIAL_12>
32
+ ' -}}{%- endif -%}{%- endif -%}{%- endif -%}
config.json ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "NemotronHForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "auto_map": {
8
+ "AutoConfig": "configuration_nemotron_h.NemotronHConfig",
9
+ "AutoModelForCausalLM": "modeling_nemotron_h.NemotronHForCausalLM"
10
+ },
11
+ "bos_token_id": 1,
12
+ "chunk_size": 128,
13
+ "conv_kernel": 4,
14
+ "eos_token_id": 12,
15
+ "expand": 2,
16
+ "head_dim": 128,
17
+ "hidden_dropout": 0.0,
18
+ "hidden_size": 5120,
19
+ "hybrid_override_pattern": "M-M-M-M*-M-M-M-M*-M-M-M-M*-M-M-M-M*-M-M-M-M*-M-M-M-M*-M-M-M-M-",
20
+ "initializer_range": 0.02,
21
+ "intermediate_size": 20480,
22
+ "layer_norm_epsilon": 1e-05,
23
+ "mamba_head_dim": 80,
24
+ "mamba_hidden_act": "silu",
25
+ "mamba_num_heads": 128,
26
+ "mamba_proj_bias": false,
27
+ "max_position_embeddings": 131072,
28
+ "mlp_bias": false,
29
+ "mlp_hidden_act": "relu2",
30
+ "model_type": "nemotron_h",
31
+ "n_groups": 8,
32
+ "num_attention_heads": 40,
33
+ "num_hidden_layers": 62,
34
+ "num_key_value_heads": 8,
35
+ "num_logits_to_keep": 1,
36
+ "pad_token_id": 0,
37
+ "rescale_prenorm_residual": true,
38
+ "residual_in_fp32": false,
39
+ "rms_norm_eps": 1e-05,
40
+ "sliding_window": null,
41
+ "ssm_state_size": 128,
42
+ "tie_word_embeddings": false,
43
+ "time_step_floor": 0.0001,
44
+ "time_step_limit": [
45
+ 0.0,
46
+ Infinity
47
+ ],
48
+ "time_step_max": 0.1,
49
+ "time_step_min": 0.001,
50
+ "time_step_rank": 256,
51
+ "torch_dtype": "bfloat16",
52
+ "transformers_version": "4.55.2",
53
+ "use_bias": false,
54
+ "use_cache": false,
55
+ "use_conv_bias": true,
56
+ "use_mamba_kernels": true,
57
+ "vocab_size": 131072
58
+ }
configuration_nemotron_h.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 AI21 Labs Ltd. and the HuggingFace Inc. team. All rights reserved.
3
+ # Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """NemotronH model configuration"""
17
+
18
+ import re
19
+
20
+ from transformers.configuration_utils import PretrainedConfig
21
+ from transformers.utils import logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ class NemotronHConfig(PretrainedConfig):
28
+ r"""
29
+ This is the configuration class to store the configuration of a [`NemotronHModel`]. It is used to instantiate a
30
+ NemotronH model according to the specified arguments, defining the model architecture. Instantiating a configuration
31
+ with the defaults will yield a similar configuration to that of the NemotronH-v0.1 model.
32
+
33
+ [todo](todo)
34
+
35
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
36
+ documentation from [`PretrainedConfig`] for more information.
37
+
38
+
39
+ Args:
40
+ vocab_size (`int`, *optional*, defaults to 131072):
41
+ Vocabulary size of the NemotronH model. Defines the number of different tokens that can be represented by the
42
+ `inputs_ids` passed when calling [`NemotronHModel`]
43
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
44
+ Whether the model's input and output word embeddings should be tied. Note that this is only relevant if the
45
+ model has a output word embedding layer.
46
+ hidden_size (`int`, *optional*, defaults to 4096):
47
+ Dimension of the hidden representations.
48
+ intermediate_size (`int`, *optional*, defaults to 21504):
49
+ Dimension of the MLP representations.
50
+ num_hidden_layers (`int`, *optional*, defaults to 52):
51
+ Number of hidden layers in the Transformer encoder.
52
+ hybrid_override_pattern (`str`, *optional*, defaults to `"M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M-"`):
53
+ The pattern of the hybrid model. The pattern is a string of characters where each character represents M: Mamba2, *: Attention, -: MLP
54
+ num_attention_heads (`int`, *optional*, defaults to 32):
55
+ Number of attention heads for each attention layer in the Transformer encoder.
56
+ attention_head_dim (`int`, *optional*, defaults to 128):
57
+ Dimension of each attention head.
58
+ num_key_value_heads (`int`, *optional*, defaults to 8):
59
+ This is the number of key_value heads that should be used to implement Grouped Query Attention. If
60
+ `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if
61
+ `num_key_value_heads=1` the model will use Multi Query Attention (MQA) otherwise GQA is used.
62
+ mlp_hidden_act (`str`, *optional*, defaults to "relu2"):
63
+ The non-linear activation function in the MLP layers.
64
+ attention_bias (`bool`, *optional*, defaults to `False`):
65
+ Whether to use bias in attention layers.
66
+ mlp_bias (`bool`, *optional*, defaults to `False`):
67
+ Whether to use bias in MLP layers.
68
+ use_bias (`bool`, *optional*, defaults to `False`):
69
+ Whether to use bias in the model.
70
+ initializer_range (`float`, *optional*, defaults to 0.02):
71
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
72
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-5):
73
+ The epsilon used by the layer normalization layers.
74
+ residual_in_fp32 (`bool`, *optional*, defaults to `False`):
75
+ Whether or not residuals should be in `float32`. If set to `False` residuals will keep the same `dtype` as the rest of the model.
76
+ use_cache (`bool`, *optional*, defaults to `True`):
77
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
78
+ relevant if `config.is_decoder=True`.
79
+ num_logits_to_keep (`int` or `None`, *optional*, defaults to 1):
80
+ Number of prompt logits to calculate during generation. If `None`, all logits will be calculated. If an
81
+ integer value, only last `num_logits_to_keep` logits will be calculated.
82
+ pad_token_id (`int`, *optional*, defaults to 0):
83
+ The id of the padding token.
84
+ bos_token_id (`int`, *optional*, defaults to 1):
85
+ The id of the "beginning-of-sequence" token.
86
+ eos_token_id (`int`, *optional*, defaults to 2):
87
+ The id of the "end-of-sequence" token.
88
+ sliding_window (`int`, *optional*, defaults to None):
89
+ Sliding window attention window size.
90
+ max_position_embeddings (`int`, *optional*, defaults to 4096):
91
+ The maximum sequence length that this model might ever be used with.
92
+ attention_dropout (`float`, *optional*, defaults to 0.0):
93
+ The dropout ratio for the attention probabilities.
94
+ hidden_dropout (`float`, *optional*, defaults to 0.0):
95
+ The dropout ratio for the hidden states.
96
+ use_mamba_kernels (`bool`, *optional*, defaults to `True`):
97
+ Flag indicating whether or not to use the fast mamba kernels. These are available only if `mamba-ssm` and
98
+ `causal-conv1d` are installed, and the mamba modules are running on a CUDA device.
99
+ ssm_state_size (`int`, *optional*, defaults to 128):
100
+ The dimension of the mamba state space latents.
101
+ mamba_num_heads (`int`, *optional*, defaults to 128):
102
+ Number of heads in Mamba layers.
103
+ mamba_n_groups (`int`, *optional*, defaults to 8):
104
+ Number of groups in Mamba layers.
105
+ mamba_head_dim (`int`, *optional*, defaults to 64):
106
+ Dimension of each Mamba head.
107
+ mamba_d_conv (`int`, *optional*, defaults to 4):
108
+ The size of the mamba convolution kernel.
109
+ mamba_expand (`int`, *optional*, defaults to 2):
110
+ Expanding factor used to determine the mamba intermediate size.
111
+ mamba_hidden_act (`str`, *optional*, defaults to "silu"):
112
+ The non-linear activation function in the Mamba layers.
113
+ mamba_dt_min (`float`, *optional*, defaults to 0.001):
114
+ Minimum value for the time step in Mamba.
115
+ mamba_dt_max (`float`, *optional*, defaults to 0.1):
116
+ Maximum value for the time step in Mamba.
117
+ mamba_dt_limit (`tuple`, *optional*, defaults to (0.0, float("inf"))):
118
+ Limits for the time step in Mamba.
119
+ mamba_dt_init_floor (`float`, *optional*, defaults to 1e-4):
120
+ Floor value for time step initialization in Mamba.
121
+ mamba_conv_bias (`bool`, *optional*, defaults to `True`):
122
+ Whether to use bias in the convolution layer of the mamba mixer block.
123
+ mamba_proj_bias (`bool`, *optional*, defaults to `False`):
124
+ Whether to use bias in the input and output projections of the mamba mixer block.
125
+ mamba_chunk_size (`int`, *optional*, defaults to 256):
126
+ Size of chunks for Mamba processing.
127
+ rescale_prenorm_residual (`bool`, *optional*, defaults to `True`):
128
+ Whether to rescale the pre-normalization residual connections.
129
+ """
130
+
131
+ model_type = "nemotron_h"
132
+ keys_to_ignore_at_inference = ["past_key_values"]
133
+
134
+ def __init__(
135
+ self,
136
+ vocab_size=131072,
137
+ tie_word_embeddings=False,
138
+ hidden_size=4096,
139
+ intermediate_size=21504,
140
+ num_hidden_layers=52,
141
+ hybrid_override_pattern="M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M*-M-M-M-M-M-",
142
+ num_attention_heads=32,
143
+ #attention_head_dim=128,
144
+ head_dim=128,
145
+ num_key_value_heads=8, # nemo: num_query_groups
146
+ mlp_hidden_act="relu2",
147
+ attention_bias=False,
148
+ mlp_bias=False,
149
+ use_bias=False,
150
+ initializer_range=0.02, # nemo: init_method_std
151
+ layer_norm_epsilon=1e-5, # nemo: layernorm_epsilon
152
+ residual_in_fp32=False, # Megatron Core default value
153
+ use_cache=True,
154
+ num_logits_to_keep=1,
155
+ pad_token_id=0,
156
+ bos_token_id=1,
157
+ eos_token_id=2,
158
+ sliding_window=None,
159
+ max_position_embeddings=4096,
160
+ attention_dropout=0.0,
161
+ hidden_dropout=0.0, # * ADDED
162
+ use_mamba_kernels=True,
163
+ ssm_state_size=128, # mamba_state_size
164
+ mamba_num_heads=128,
165
+ mamba_n_groups=8, # nemo: mamba_ssm_ngroups = num_heads
166
+ mamba_head_dim=64,
167
+ mamba_d_conv=4,
168
+ mamba_expand=2,
169
+ mamba_hidden_act="silu",
170
+ mamba_dt_min=0.001,
171
+ mamba_dt_max=0.1,
172
+ mamba_dt_limit=(0.0, float("inf")),
173
+ mamba_dt_init_floor=1e-4,
174
+ mamba_conv_bias=True,
175
+ mamba_proj_bias=False,
176
+ mamba_chunk_size=256,
177
+ rescale_prenorm_residual=True,
178
+ **kwargs,
179
+ ):
180
+ self.vocab_size = vocab_size
181
+ self.tie_word_embeddings = tie_word_embeddings
182
+ self.hidden_size = hidden_size
183
+ self.intermediate_size = intermediate_size
184
+ self.num_hidden_layers = num_hidden_layers
185
+ self.hybrid_override_pattern = hybrid_override_pattern
186
+ self.num_attention_heads = num_attention_heads
187
+ #self.attention_head_dim = attention_head_dim
188
+ self.head_dim = head_dim
189
+ self.sliding_window = sliding_window
190
+ self.max_position_embeddings = max_position_embeddings
191
+ self.attention_dropout = attention_dropout
192
+ self.hidden_dropout = hidden_dropout
193
+
194
+ # Validate hybrid_override_pattern
195
+ # M: Mamba2, *: Attention, -: MLP
196
+ assert len(self.hybrid_override_pattern) == self.num_hidden_layers, "hybrid_override_pattern must have the same length as num_hidden_layers"
197
+ assert re.match(r"^[*-M]+$", self.hybrid_override_pattern), "hybrid_override_pattern must only contain characters 'M', '*', or '-'"
198
+
199
+ # for backward compatibility
200
+ if num_key_value_heads is None:
201
+ num_key_value_heads = num_attention_heads
202
+
203
+ self.num_key_value_heads = num_key_value_heads
204
+ self.mlp_hidden_act = mlp_hidden_act
205
+ self.attention_bias = attention_bias
206
+ self.mlp_bias = mlp_bias
207
+ self.use_bias = use_bias
208
+ self.initializer_range = initializer_range
209
+ self.layer_norm_epsilon = layer_norm_epsilon
210
+ self.residual_in_fp32 = residual_in_fp32
211
+
212
+ self.use_cache = use_cache
213
+ self.num_logits_to_keep = num_logits_to_keep
214
+
215
+ self.use_mamba_kernels = use_mamba_kernels
216
+ self.n_groups = mamba_n_groups
217
+ self.mamba_head_dim = mamba_head_dim
218
+ self.ssm_state_size = ssm_state_size
219
+ self.mamba_num_heads = mamba_num_heads
220
+ self.conv_kernel = mamba_d_conv
221
+ self.expand = mamba_expand
222
+ self.mamba_hidden_act = mamba_hidden_act
223
+ self.time_step_min = mamba_dt_min
224
+ self.time_step_max = mamba_dt_max
225
+ self.time_step_limit = mamba_dt_limit
226
+ self.time_step_floor = mamba_dt_init_floor
227
+ self.use_conv_bias = mamba_conv_bias
228
+ self.mamba_proj_bias = mamba_proj_bias
229
+ self.chunk_size = mamba_chunk_size
230
+ self.rescale_prenorm_residual = rescale_prenorm_residual
231
+
232
+ super().__init__(
233
+ pad_token_id=pad_token_id,
234
+ bos_token_id=bos_token_id,
235
+ eos_token_id=eos_token_id,
236
+ tie_word_embeddings=tie_word_embeddings,
237
+ **kwargs,
238
+ )
239
+
240
+ @property
241
+ def layers_block_type(self):
242
+ return [
243
+ "mamba" if self.hybrid_override_pattern[i] == "M" else
244
+ "attention" if self.hybrid_override_pattern[i] == "*" else "mlp"
245
+ for i in range(self.num_hidden_layers)]
generation_config.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "do_sample": true,
5
+ "eos_token_id": [
6
+ 2,
7
+ 11,
8
+ 12
9
+ ],
10
+ "pad_token_id": 0,
11
+ "transformers_version": "4.55.2"
12
+ }
model-00001-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aa84c378f1908d1ab7cb573b2fd9d1caf40f3802ddc5cd946bfdf25a23771d35
3
+ size 4830843560
model-00002-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d730a1ef91b417ee7b2174f8102ed50cd045a97db052c2135fe3f7e2dc73e3ce
3
+ size 4874263544
model-00003-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bec6336ca7e0a9e71616622ce57c8d5a67f445d072809ed2e7a081e2e3601be4
3
+ size 4790388152
model-00004-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c4dd39daf43d4b0a412723a8fd5c6ddc357d101912ecd448fad319f81064fcb0
3
+ size 4874398064
model-00005-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b619bb890e939d47be214e23f52f5136df742e50e1b7fc01494e99a67f49e61e
3
+ size 3907972648
model-00006-of-00006.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:87097fe14cd8c5c50268ea9177900d2ff8cad8422fbc9d7b239a4ce6e3b220f5
3
+ size 1342177408
model.safetensors.index.json ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "metadata": {
3
+ "total_parameters": 12310001152,
4
+ "total_size": 24620002304
5
+ },
6
+ "weight_map": {
7
+ "backbone.embeddings.weight": "model-00001-of-00006.safetensors",
8
+ "backbone.layers.0.mixer.A_log": "model-00001-of-00006.safetensors",
9
+ "backbone.layers.0.mixer.D": "model-00001-of-00006.safetensors",
10
+ "backbone.layers.0.mixer.conv1d.bias": "model-00001-of-00006.safetensors",
11
+ "backbone.layers.0.mixer.conv1d.weight": "model-00001-of-00006.safetensors",
12
+ "backbone.layers.0.mixer.dt_bias": "model-00001-of-00006.safetensors",
13
+ "backbone.layers.0.mixer.in_proj.weight": "model-00001-of-00006.safetensors",
14
+ "backbone.layers.0.mixer.norm.weight": "model-00001-of-00006.safetensors",
15
+ "backbone.layers.0.mixer.out_proj.weight": "model-00001-of-00006.safetensors",
16
+ "backbone.layers.0.norm.weight": "model-00001-of-00006.safetensors",
17
+ "backbone.layers.1.mixer.down_proj.weight": "model-00001-of-00006.safetensors",
18
+ "backbone.layers.1.mixer.up_proj.weight": "model-00001-of-00006.safetensors",
19
+ "backbone.layers.1.norm.weight": "model-00001-of-00006.safetensors",
20
+ "backbone.layers.10.mixer.down_proj.weight": "model-00002-of-00006.safetensors",
21
+ "backbone.layers.10.mixer.up_proj.weight": "model-00002-of-00006.safetensors",
22
+ "backbone.layers.10.norm.weight": "model-00001-of-00006.safetensors",
23
+ "backbone.layers.11.mixer.A_log": "model-00002-of-00006.safetensors",
24
+ "backbone.layers.11.mixer.D": "model-00002-of-00006.safetensors",
25
+ "backbone.layers.11.mixer.conv1d.bias": "model-00002-of-00006.safetensors",
26
+ "backbone.layers.11.mixer.conv1d.weight": "model-00002-of-00006.safetensors",
27
+ "backbone.layers.11.mixer.dt_bias": "model-00002-of-00006.safetensors",
28
+ "backbone.layers.11.mixer.in_proj.weight": "model-00002-of-00006.safetensors",
29
+ "backbone.layers.11.mixer.norm.weight": "model-00002-of-00006.safetensors",
30
+ "backbone.layers.11.mixer.out_proj.weight": "model-00002-of-00006.safetensors",
31
+ "backbone.layers.11.norm.weight": "model-00002-of-00006.safetensors",
32
+ "backbone.layers.12.mixer.down_proj.weight": "model-00002-of-00006.safetensors",
33
+ "backbone.layers.12.mixer.up_proj.weight": "model-00002-of-00006.safetensors",
34
+ "backbone.layers.12.norm.weight": "model-00002-of-00006.safetensors",
35
+ "backbone.layers.13.mixer.A_log": "model-00002-of-00006.safetensors",
36
+ "backbone.layers.13.mixer.D": "model-00002-of-00006.safetensors",
37
+ "backbone.layers.13.mixer.conv1d.bias": "model-00002-of-00006.safetensors",
38
+ "backbone.layers.13.mixer.conv1d.weight": "model-00002-of-00006.safetensors",
39
+ "backbone.layers.13.mixer.dt_bias": "model-00002-of-00006.safetensors",
40
+ "backbone.layers.13.mixer.in_proj.weight": "model-00002-of-00006.safetensors",
41
+ "backbone.layers.13.mixer.norm.weight": "model-00002-of-00006.safetensors",
42
+ "backbone.layers.13.mixer.out_proj.weight": "model-00002-of-00006.safetensors",
43
+ "backbone.layers.13.norm.weight": "model-00002-of-00006.safetensors",
44
+ "backbone.layers.14.mixer.down_proj.weight": "model-00002-of-00006.safetensors",
45
+ "backbone.layers.14.mixer.up_proj.weight": "model-00002-of-00006.safetensors",
46
+ "backbone.layers.14.norm.weight": "model-00002-of-00006.safetensors",
47
+ "backbone.layers.15.mixer.A_log": "model-00002-of-00006.safetensors",
48
+ "backbone.layers.15.mixer.D": "model-00002-of-00006.safetensors",
49
+ "backbone.layers.15.mixer.conv1d.bias": "model-00002-of-00006.safetensors",
50
+ "backbone.layers.15.mixer.conv1d.weight": "model-00002-of-00006.safetensors",
51
+ "backbone.layers.15.mixer.dt_bias": "model-00002-of-00006.safetensors",
52
+ "backbone.layers.15.mixer.in_proj.weight": "model-00002-of-00006.safetensors",
53
+ "backbone.layers.15.mixer.norm.weight": "model-00002-of-00006.safetensors",
54
+ "backbone.layers.15.mixer.out_proj.weight": "model-00002-of-00006.safetensors",
55
+ "backbone.layers.15.norm.weight": "model-00002-of-00006.safetensors",
56
+ "backbone.layers.16.mixer.k_proj.weight": "model-00002-of-00006.safetensors",
57
+ "backbone.layers.16.mixer.o_proj.weight": "model-00002-of-00006.safetensors",
58
+ "backbone.layers.16.mixer.q_proj.weight": "model-00002-of-00006.safetensors",
59
+ "backbone.layers.16.mixer.v_proj.weight": "model-00002-of-00006.safetensors",
60
+ "backbone.layers.16.norm.weight": "model-00002-of-00006.safetensors",
61
+ "backbone.layers.17.mixer.down_proj.weight": "model-00002-of-00006.safetensors",
62
+ "backbone.layers.17.mixer.up_proj.weight": "model-00002-of-00006.safetensors",
63
+ "backbone.layers.17.norm.weight": "model-00002-of-00006.safetensors",
64
+ "backbone.layers.18.mixer.A_log": "model-00002-of-00006.safetensors",
65
+ "backbone.layers.18.mixer.D": "model-00002-of-00006.safetensors",
66
+ "backbone.layers.18.mixer.conv1d.bias": "model-00002-of-00006.safetensors",
67
+ "backbone.layers.18.mixer.conv1d.weight": "model-00002-of-00006.safetensors",
68
+ "backbone.layers.18.mixer.dt_bias": "model-00002-of-00006.safetensors",
69
+ "backbone.layers.18.mixer.in_proj.weight": "model-00002-of-00006.safetensors",
70
+ "backbone.layers.18.mixer.norm.weight": "model-00002-of-00006.safetensors",
71
+ "backbone.layers.18.mixer.out_proj.weight": "model-00002-of-00006.safetensors",
72
+ "backbone.layers.18.norm.weight": "model-00002-of-00006.safetensors",
73
+ "backbone.layers.19.mixer.down_proj.weight": "model-00002-of-00006.safetensors",
74
+ "backbone.layers.19.mixer.up_proj.weight": "model-00002-of-00006.safetensors",
75
+ "backbone.layers.19.norm.weight": "model-00002-of-00006.safetensors",
76
+ "backbone.layers.2.mixer.A_log": "model-00001-of-00006.safetensors",
77
+ "backbone.layers.2.mixer.D": "model-00001-of-00006.safetensors",
78
+ "backbone.layers.2.mixer.conv1d.bias": "model-00001-of-00006.safetensors",
79
+ "backbone.layers.2.mixer.conv1d.weight": "model-00001-of-00006.safetensors",
80
+ "backbone.layers.2.mixer.dt_bias": "model-00001-of-00006.safetensors",
81
+ "backbone.layers.2.mixer.in_proj.weight": "model-00001-of-00006.safetensors",
82
+ "backbone.layers.2.mixer.norm.weight": "model-00001-of-00006.safetensors",
83
+ "backbone.layers.2.mixer.out_proj.weight": "model-00001-of-00006.safetensors",
84
+ "backbone.layers.2.norm.weight": "model-00001-of-00006.safetensors",
85
+ "backbone.layers.20.mixer.A_log": "model-00002-of-00006.safetensors",
86
+ "backbone.layers.20.mixer.D": "model-00002-of-00006.safetensors",
87
+ "backbone.layers.20.mixer.conv1d.bias": "model-00002-of-00006.safetensors",
88
+ "backbone.layers.20.mixer.conv1d.weight": "model-00002-of-00006.safetensors",
89
+ "backbone.layers.20.mixer.dt_bias": "model-00002-of-00006.safetensors",
90
+ "backbone.layers.20.mixer.in_proj.weight": "model-00002-of-00006.safetensors",
91
+ "backbone.layers.20.mixer.norm.weight": "model-00002-of-00006.safetensors",
92
+ "backbone.layers.20.mixer.out_proj.weight": "model-00002-of-00006.safetensors",
93
+ "backbone.layers.20.norm.weight": "model-00002-of-00006.safetensors",
94
+ "backbone.layers.21.mixer.down_proj.weight": "model-00002-of-00006.safetensors",
95
+ "backbone.layers.21.mixer.up_proj.weight": "model-00002-of-00006.safetensors",
96
+ "backbone.layers.21.norm.weight": "model-00002-of-00006.safetensors",
97
+ "backbone.layers.22.mixer.A_log": "model-00002-of-00006.safetensors",
98
+ "backbone.layers.22.mixer.D": "model-00002-of-00006.safetensors",
99
+ "backbone.layers.22.mixer.conv1d.bias": "model-00002-of-00006.safetensors",
100
+ "backbone.layers.22.mixer.conv1d.weight": "model-00002-of-00006.safetensors",
101
+ "backbone.layers.22.mixer.dt_bias": "model-00002-of-00006.safetensors",
102
+ "backbone.layers.22.mixer.in_proj.weight": "model-00002-of-00006.safetensors",
103
+ "backbone.layers.22.mixer.norm.weight": "model-00002-of-00006.safetensors",
104
+ "backbone.layers.22.mixer.out_proj.weight": "model-00002-of-00006.safetensors",
105
+ "backbone.layers.22.norm.weight": "model-00002-of-00006.safetensors",
106
+ "backbone.layers.23.mixer.down_proj.weight": "model-00003-of-00006.safetensors",
107
+ "backbone.layers.23.mixer.up_proj.weight": "model-00002-of-00006.safetensors",
108
+ "backbone.layers.23.norm.weight": "model-00002-of-00006.safetensors",
109
+ "backbone.layers.24.mixer.A_log": "model-00003-of-00006.safetensors",
110
+ "backbone.layers.24.mixer.D": "model-00003-of-00006.safetensors",
111
+ "backbone.layers.24.mixer.conv1d.bias": "model-00003-of-00006.safetensors",
112
+ "backbone.layers.24.mixer.conv1d.weight": "model-00003-of-00006.safetensors",
113
+ "backbone.layers.24.mixer.dt_bias": "model-00003-of-00006.safetensors",
114
+ "backbone.layers.24.mixer.in_proj.weight": "model-00003-of-00006.safetensors",
115
+ "backbone.layers.24.mixer.norm.weight": "model-00003-of-00006.safetensors",
116
+ "backbone.layers.24.mixer.out_proj.weight": "model-00003-of-00006.safetensors",
117
+ "backbone.layers.24.norm.weight": "model-00003-of-00006.safetensors",
118
+ "backbone.layers.25.mixer.k_proj.weight": "model-00003-of-00006.safetensors",
119
+ "backbone.layers.25.mixer.o_proj.weight": "model-00003-of-00006.safetensors",
120
+ "backbone.layers.25.mixer.q_proj.weight": "model-00003-of-00006.safetensors",
121
+ "backbone.layers.25.mixer.v_proj.weight": "model-00003-of-00006.safetensors",
122
+ "backbone.layers.25.norm.weight": "model-00003-of-00006.safetensors",
123
+ "backbone.layers.26.mixer.down_proj.weight": "model-00003-of-00006.safetensors",
124
+ "backbone.layers.26.mixer.up_proj.weight": "model-00003-of-00006.safetensors",
125
+ "backbone.layers.26.norm.weight": "model-00003-of-00006.safetensors",
126
+ "backbone.layers.27.mixer.A_log": "model-00003-of-00006.safetensors",
127
+ "backbone.layers.27.mixer.D": "model-00003-of-00006.safetensors",
128
+ "backbone.layers.27.mixer.conv1d.bias": "model-00003-of-00006.safetensors",
129
+ "backbone.layers.27.mixer.conv1d.weight": "model-00003-of-00006.safetensors",
130
+ "backbone.layers.27.mixer.dt_bias": "model-00003-of-00006.safetensors",
131
+ "backbone.layers.27.mixer.in_proj.weight": "model-00003-of-00006.safetensors",
132
+ "backbone.layers.27.mixer.norm.weight": "model-00003-of-00006.safetensors",
133
+ "backbone.layers.27.mixer.out_proj.weight": "model-00003-of-00006.safetensors",
134
+ "backbone.layers.27.norm.weight": "model-00003-of-00006.safetensors",
135
+ "backbone.layers.28.mixer.down_proj.weight": "model-00003-of-00006.safetensors",
136
+ "backbone.layers.28.mixer.up_proj.weight": "model-00003-of-00006.safetensors",
137
+ "backbone.layers.28.norm.weight": "model-00003-of-00006.safetensors",
138
+ "backbone.layers.29.mixer.A_log": "model-00003-of-00006.safetensors",
139
+ "backbone.layers.29.mixer.D": "model-00003-of-00006.safetensors",
140
+ "backbone.layers.29.mixer.conv1d.bias": "model-00003-of-00006.safetensors",
141
+ "backbone.layers.29.mixer.conv1d.weight": "model-00003-of-00006.safetensors",
142
+ "backbone.layers.29.mixer.dt_bias": "model-00003-of-00006.safetensors",
143
+ "backbone.layers.29.mixer.in_proj.weight": "model-00003-of-00006.safetensors",
144
+ "backbone.layers.29.mixer.norm.weight": "model-00003-of-00006.safetensors",
145
+ "backbone.layers.29.mixer.out_proj.weight": "model-00003-of-00006.safetensors",
146
+ "backbone.layers.29.norm.weight": "model-00003-of-00006.safetensors",
147
+ "backbone.layers.3.mixer.down_proj.weight": "model-00001-of-00006.safetensors",
148
+ "backbone.layers.3.mixer.up_proj.weight": "model-00001-of-00006.safetensors",
149
+ "backbone.layers.3.norm.weight": "model-00001-of-00006.safetensors",
150
+ "backbone.layers.30.mixer.down_proj.weight": "model-00003-of-00006.safetensors",
151
+ "backbone.layers.30.mixer.up_proj.weight": "model-00003-of-00006.safetensors",
152
+ "backbone.layers.30.norm.weight": "model-00003-of-00006.safetensors",
153
+ "backbone.layers.31.mixer.A_log": "model-00003-of-00006.safetensors",
154
+ "backbone.layers.31.mixer.D": "model-00003-of-00006.safetensors",
155
+ "backbone.layers.31.mixer.conv1d.bias": "model-00003-of-00006.safetensors",
156
+ "backbone.layers.31.mixer.conv1d.weight": "model-00003-of-00006.safetensors",
157
+ "backbone.layers.31.mixer.dt_bias": "model-00003-of-00006.safetensors",
158
+ "backbone.layers.31.mixer.in_proj.weight": "model-00003-of-00006.safetensors",
159
+ "backbone.layers.31.mixer.norm.weight": "model-00003-of-00006.safetensors",
160
+ "backbone.layers.31.mixer.out_proj.weight": "model-00003-of-00006.safetensors",
161
+ "backbone.layers.31.norm.weight": "model-00003-of-00006.safetensors",
162
+ "backbone.layers.32.mixer.down_proj.weight": "model-00003-of-00006.safetensors",
163
+ "backbone.layers.32.mixer.up_proj.weight": "model-00003-of-00006.safetensors",
164
+ "backbone.layers.32.norm.weight": "model-00003-of-00006.safetensors",
165
+ "backbone.layers.33.mixer.A_log": "model-00003-of-00006.safetensors",
166
+ "backbone.layers.33.mixer.D": "model-00003-of-00006.safetensors",
167
+ "backbone.layers.33.mixer.conv1d.bias": "model-00003-of-00006.safetensors",
168
+ "backbone.layers.33.mixer.conv1d.weight": "model-00003-of-00006.safetensors",
169
+ "backbone.layers.33.mixer.dt_bias": "model-00003-of-00006.safetensors",
170
+ "backbone.layers.33.mixer.in_proj.weight": "model-00003-of-00006.safetensors",
171
+ "backbone.layers.33.mixer.norm.weight": "model-00003-of-00006.safetensors",
172
+ "backbone.layers.33.mixer.out_proj.weight": "model-00003-of-00006.safetensors",
173
+ "backbone.layers.33.norm.weight": "model-00003-of-00006.safetensors",
174
+ "backbone.layers.34.mixer.k_proj.weight": "model-00003-of-00006.safetensors",
175
+ "backbone.layers.34.mixer.o_proj.weight": "model-00003-of-00006.safetensors",
176
+ "backbone.layers.34.mixer.q_proj.weight": "model-00003-of-00006.safetensors",
177
+ "backbone.layers.34.mixer.v_proj.weight": "model-00003-of-00006.safetensors",
178
+ "backbone.layers.34.norm.weight": "model-00003-of-00006.safetensors",
179
+ "backbone.layers.35.mixer.down_proj.weight": "model-00003-of-00006.safetensors",
180
+ "backbone.layers.35.mixer.up_proj.weight": "model-00003-of-00006.safetensors",
181
+ "backbone.layers.35.norm.weight": "model-00003-of-00006.safetensors",
182
+ "backbone.layers.36.mixer.A_log": "model-00003-of-00006.safetensors",
183
+ "backbone.layers.36.mixer.D": "model-00003-of-00006.safetensors",
184
+ "backbone.layers.36.mixer.conv1d.bias": "model-00003-of-00006.safetensors",
185
+ "backbone.layers.36.mixer.conv1d.weight": "model-00003-of-00006.safetensors",
186
+ "backbone.layers.36.mixer.dt_bias": "model-00003-of-00006.safetensors",
187
+ "backbone.layers.36.mixer.in_proj.weight": "model-00003-of-00006.safetensors",
188
+ "backbone.layers.36.mixer.norm.weight": "model-00003-of-00006.safetensors",
189
+ "backbone.layers.36.mixer.out_proj.weight": "model-00003-of-00006.safetensors",
190
+ "backbone.layers.36.norm.weight": "model-00003-of-00006.safetensors",
191
+ "backbone.layers.37.mixer.down_proj.weight": "model-00004-of-00006.safetensors",
192
+ "backbone.layers.37.mixer.up_proj.weight": "model-00003-of-00006.safetensors",
193
+ "backbone.layers.37.norm.weight": "model-00003-of-00006.safetensors",
194
+ "backbone.layers.38.mixer.A_log": "model-00004-of-00006.safetensors",
195
+ "backbone.layers.38.mixer.D": "model-00004-of-00006.safetensors",
196
+ "backbone.layers.38.mixer.conv1d.bias": "model-00004-of-00006.safetensors",
197
+ "backbone.layers.38.mixer.conv1d.weight": "model-00004-of-00006.safetensors",
198
+ "backbone.layers.38.mixer.dt_bias": "model-00004-of-00006.safetensors",
199
+ "backbone.layers.38.mixer.in_proj.weight": "model-00004-of-00006.safetensors",
200
+ "backbone.layers.38.mixer.norm.weight": "model-00004-of-00006.safetensors",
201
+ "backbone.layers.38.mixer.out_proj.weight": "model-00004-of-00006.safetensors",
202
+ "backbone.layers.38.norm.weight": "model-00004-of-00006.safetensors",
203
+ "backbone.layers.39.mixer.down_proj.weight": "model-00004-of-00006.safetensors",
204
+ "backbone.layers.39.mixer.up_proj.weight": "model-00004-of-00006.safetensors",
205
+ "backbone.layers.39.norm.weight": "model-00004-of-00006.safetensors",
206
+ "backbone.layers.4.mixer.A_log": "model-00001-of-00006.safetensors",
207
+ "backbone.layers.4.mixer.D": "model-00001-of-00006.safetensors",
208
+ "backbone.layers.4.mixer.conv1d.bias": "model-00001-of-00006.safetensors",
209
+ "backbone.layers.4.mixer.conv1d.weight": "model-00001-of-00006.safetensors",
210
+ "backbone.layers.4.mixer.dt_bias": "model-00001-of-00006.safetensors",
211
+ "backbone.layers.4.mixer.in_proj.weight": "model-00001-of-00006.safetensors",
212
+ "backbone.layers.4.mixer.norm.weight": "model-00001-of-00006.safetensors",
213
+ "backbone.layers.4.mixer.out_proj.weight": "model-00001-of-00006.safetensors",
214
+ "backbone.layers.4.norm.weight": "model-00001-of-00006.safetensors",
215
+ "backbone.layers.40.mixer.A_log": "model-00004-of-00006.safetensors",
216
+ "backbone.layers.40.mixer.D": "model-00004-of-00006.safetensors",
217
+ "backbone.layers.40.mixer.conv1d.bias": "model-00004-of-00006.safetensors",
218
+ "backbone.layers.40.mixer.conv1d.weight": "model-00004-of-00006.safetensors",
219
+ "backbone.layers.40.mixer.dt_bias": "model-00004-of-00006.safetensors",
220
+ "backbone.layers.40.mixer.in_proj.weight": "model-00004-of-00006.safetensors",
221
+ "backbone.layers.40.mixer.norm.weight": "model-00004-of-00006.safetensors",
222
+ "backbone.layers.40.mixer.out_proj.weight": "model-00004-of-00006.safetensors",
223
+ "backbone.layers.40.norm.weight": "model-00004-of-00006.safetensors",
224
+ "backbone.layers.41.mixer.down_proj.weight": "model-00004-of-00006.safetensors",
225
+ "backbone.layers.41.mixer.up_proj.weight": "model-00004-of-00006.safetensors",
226
+ "backbone.layers.41.norm.weight": "model-00004-of-00006.safetensors",
227
+ "backbone.layers.42.mixer.A_log": "model-00004-of-00006.safetensors",
228
+ "backbone.layers.42.mixer.D": "model-00004-of-00006.safetensors",
229
+ "backbone.layers.42.mixer.conv1d.bias": "model-00004-of-00006.safetensors",
230
+ "backbone.layers.42.mixer.conv1d.weight": "model-00004-of-00006.safetensors",
231
+ "backbone.layers.42.mixer.dt_bias": "model-00004-of-00006.safetensors",
232
+ "backbone.layers.42.mixer.in_proj.weight": "model-00004-of-00006.safetensors",
233
+ "backbone.layers.42.mixer.norm.weight": "model-00004-of-00006.safetensors",
234
+ "backbone.layers.42.mixer.out_proj.weight": "model-00004-of-00006.safetensors",
235
+ "backbone.layers.42.norm.weight": "model-00004-of-00006.safetensors",
236
+ "backbone.layers.43.mixer.k_proj.weight": "model-00004-of-00006.safetensors",
237
+ "backbone.layers.43.mixer.o_proj.weight": "model-00004-of-00006.safetensors",
238
+ "backbone.layers.43.mixer.q_proj.weight": "model-00004-of-00006.safetensors",
239
+ "backbone.layers.43.mixer.v_proj.weight": "model-00004-of-00006.safetensors",
240
+ "backbone.layers.43.norm.weight": "model-00004-of-00006.safetensors",
241
+ "backbone.layers.44.mixer.down_proj.weight": "model-00004-of-00006.safetensors",
242
+ "backbone.layers.44.mixer.up_proj.weight": "model-00004-of-00006.safetensors",
243
+ "backbone.layers.44.norm.weight": "model-00004-of-00006.safetensors",
244
+ "backbone.layers.45.mixer.A_log": "model-00004-of-00006.safetensors",
245
+ "backbone.layers.45.mixer.D": "model-00004-of-00006.safetensors",
246
+ "backbone.layers.45.mixer.conv1d.bias": "model-00004-of-00006.safetensors",
247
+ "backbone.layers.45.mixer.conv1d.weight": "model-00004-of-00006.safetensors",
248
+ "backbone.layers.45.mixer.dt_bias": "model-00004-of-00006.safetensors",
249
+ "backbone.layers.45.mixer.in_proj.weight": "model-00004-of-00006.safetensors",
250
+ "backbone.layers.45.mixer.norm.weight": "model-00004-of-00006.safetensors",
251
+ "backbone.layers.45.mixer.out_proj.weight": "model-00004-of-00006.safetensors",
252
+ "backbone.layers.45.norm.weight": "model-00004-of-00006.safetensors",
253
+ "backbone.layers.46.mixer.down_proj.weight": "model-00004-of-00006.safetensors",
254
+ "backbone.layers.46.mixer.up_proj.weight": "model-00004-of-00006.safetensors",
255
+ "backbone.layers.46.norm.weight": "model-00004-of-00006.safetensors",
256
+ "backbone.layers.47.mixer.A_log": "model-00004-of-00006.safetensors",
257
+ "backbone.layers.47.mixer.D": "model-00004-of-00006.safetensors",
258
+ "backbone.layers.47.mixer.conv1d.bias": "model-00004-of-00006.safetensors",
259
+ "backbone.layers.47.mixer.conv1d.weight": "model-00004-of-00006.safetensors",
260
+ "backbone.layers.47.mixer.dt_bias": "model-00004-of-00006.safetensors",
261
+ "backbone.layers.47.mixer.in_proj.weight": "model-00004-of-00006.safetensors",
262
+ "backbone.layers.47.mixer.norm.weight": "model-00004-of-00006.safetensors",
263
+ "backbone.layers.47.mixer.out_proj.weight": "model-00004-of-00006.safetensors",
264
+ "backbone.layers.47.norm.weight": "model-00004-of-00006.safetensors",
265
+ "backbone.layers.48.mixer.down_proj.weight": "model-00004-of-00006.safetensors",
266
+ "backbone.layers.48.mixer.up_proj.weight": "model-00004-of-00006.safetensors",
267
+ "backbone.layers.48.norm.weight": "model-00004-of-00006.safetensors",
268
+ "backbone.layers.49.mixer.A_log": "model-00004-of-00006.safetensors",
269
+ "backbone.layers.49.mixer.D": "model-00004-of-00006.safetensors",
270
+ "backbone.layers.49.mixer.conv1d.bias": "model-00004-of-00006.safetensors",
271
+ "backbone.layers.49.mixer.conv1d.weight": "model-00004-of-00006.safetensors",
272
+ "backbone.layers.49.mixer.dt_bias": "model-00004-of-00006.safetensors",
273
+ "backbone.layers.49.mixer.in_proj.weight": "model-00004-of-00006.safetensors",
274
+ "backbone.layers.49.mixer.norm.weight": "model-00004-of-00006.safetensors",
275
+ "backbone.layers.49.mixer.out_proj.weight": "model-00004-of-00006.safetensors",
276
+ "backbone.layers.49.norm.weight": "model-00004-of-00006.safetensors",
277
+ "backbone.layers.5.mixer.down_proj.weight": "model-00001-of-00006.safetensors",
278
+ "backbone.layers.5.mixer.up_proj.weight": "model-00001-of-00006.safetensors",
279
+ "backbone.layers.5.norm.weight": "model-00001-of-00006.safetensors",
280
+ "backbone.layers.50.mixer.down_proj.weight": "model-00004-of-00006.safetensors",
281
+ "backbone.layers.50.mixer.up_proj.weight": "model-00004-of-00006.safetensors",
282
+ "backbone.layers.50.norm.weight": "model-00004-of-00006.safetensors",
283
+ "backbone.layers.51.mixer.A_log": "model-00004-of-00006.safetensors",
284
+ "backbone.layers.51.mixer.D": "model-00004-of-00006.safetensors",
285
+ "backbone.layers.51.mixer.conv1d.bias": "model-00004-of-00006.safetensors",
286
+ "backbone.layers.51.mixer.conv1d.weight": "model-00004-of-00006.safetensors",
287
+ "backbone.layers.51.mixer.dt_bias": "model-00004-of-00006.safetensors",
288
+ "backbone.layers.51.mixer.in_proj.weight": "model-00005-of-00006.safetensors",
289
+ "backbone.layers.51.mixer.norm.weight": "model-00005-of-00006.safetensors",
290
+ "backbone.layers.51.mixer.out_proj.weight": "model-00005-of-00006.safetensors",
291
+ "backbone.layers.51.norm.weight": "model-00004-of-00006.safetensors",
292
+ "backbone.layers.52.mixer.k_proj.weight": "model-00005-of-00006.safetensors",
293
+ "backbone.layers.52.mixer.o_proj.weight": "model-00005-of-00006.safetensors",
294
+ "backbone.layers.52.mixer.q_proj.weight": "model-00005-of-00006.safetensors",
295
+ "backbone.layers.52.mixer.v_proj.weight": "model-00005-of-00006.safetensors",
296
+ "backbone.layers.52.norm.weight": "model-00005-of-00006.safetensors",
297
+ "backbone.layers.53.mixer.down_proj.weight": "model-00005-of-00006.safetensors",
298
+ "backbone.layers.53.mixer.up_proj.weight": "model-00005-of-00006.safetensors",
299
+ "backbone.layers.53.norm.weight": "model-00005-of-00006.safetensors",
300
+ "backbone.layers.54.mixer.A_log": "model-00005-of-00006.safetensors",
301
+ "backbone.layers.54.mixer.D": "model-00005-of-00006.safetensors",
302
+ "backbone.layers.54.mixer.conv1d.bias": "model-00005-of-00006.safetensors",
303
+ "backbone.layers.54.mixer.conv1d.weight": "model-00005-of-00006.safetensors",
304
+ "backbone.layers.54.mixer.dt_bias": "model-00005-of-00006.safetensors",
305
+ "backbone.layers.54.mixer.in_proj.weight": "model-00005-of-00006.safetensors",
306
+ "backbone.layers.54.mixer.norm.weight": "model-00005-of-00006.safetensors",
307
+ "backbone.layers.54.mixer.out_proj.weight": "model-00005-of-00006.safetensors",
308
+ "backbone.layers.54.norm.weight": "model-00005-of-00006.safetensors",
309
+ "backbone.layers.55.mixer.down_proj.weight": "model-00005-of-00006.safetensors",
310
+ "backbone.layers.55.mixer.up_proj.weight": "model-00005-of-00006.safetensors",
311
+ "backbone.layers.55.norm.weight": "model-00005-of-00006.safetensors",
312
+ "backbone.layers.56.mixer.A_log": "model-00005-of-00006.safetensors",
313
+ "backbone.layers.56.mixer.D": "model-00005-of-00006.safetensors",
314
+ "backbone.layers.56.mixer.conv1d.bias": "model-00005-of-00006.safetensors",
315
+ "backbone.layers.56.mixer.conv1d.weight": "model-00005-of-00006.safetensors",
316
+ "backbone.layers.56.mixer.dt_bias": "model-00005-of-00006.safetensors",
317
+ "backbone.layers.56.mixer.in_proj.weight": "model-00005-of-00006.safetensors",
318
+ "backbone.layers.56.mixer.norm.weight": "model-00005-of-00006.safetensors",
319
+ "backbone.layers.56.mixer.out_proj.weight": "model-00005-of-00006.safetensors",
320
+ "backbone.layers.56.norm.weight": "model-00005-of-00006.safetensors",
321
+ "backbone.layers.57.mixer.down_proj.weight": "model-00005-of-00006.safetensors",
322
+ "backbone.layers.57.mixer.up_proj.weight": "model-00005-of-00006.safetensors",
323
+ "backbone.layers.57.norm.weight": "model-00005-of-00006.safetensors",
324
+ "backbone.layers.58.mixer.A_log": "model-00005-of-00006.safetensors",
325
+ "backbone.layers.58.mixer.D": "model-00005-of-00006.safetensors",
326
+ "backbone.layers.58.mixer.conv1d.bias": "model-00005-of-00006.safetensors",
327
+ "backbone.layers.58.mixer.conv1d.weight": "model-00005-of-00006.safetensors",
328
+ "backbone.layers.58.mixer.dt_bias": "model-00005-of-00006.safetensors",
329
+ "backbone.layers.58.mixer.in_proj.weight": "model-00005-of-00006.safetensors",
330
+ "backbone.layers.58.mixer.norm.weight": "model-00005-of-00006.safetensors",
331
+ "backbone.layers.58.mixer.out_proj.weight": "model-00005-of-00006.safetensors",
332
+ "backbone.layers.58.norm.weight": "model-00005-of-00006.safetensors",
333
+ "backbone.layers.59.mixer.down_proj.weight": "model-00005-of-00006.safetensors",
334
+ "backbone.layers.59.mixer.up_proj.weight": "model-00005-of-00006.safetensors",
335
+ "backbone.layers.59.norm.weight": "model-00005-of-00006.safetensors",
336
+ "backbone.layers.6.mixer.A_log": "model-00001-of-00006.safetensors",
337
+ "backbone.layers.6.mixer.D": "model-00001-of-00006.safetensors",
338
+ "backbone.layers.6.mixer.conv1d.bias": "model-00001-of-00006.safetensors",
339
+ "backbone.layers.6.mixer.conv1d.weight": "model-00001-of-00006.safetensors",
340
+ "backbone.layers.6.mixer.dt_bias": "model-00001-of-00006.safetensors",
341
+ "backbone.layers.6.mixer.in_proj.weight": "model-00001-of-00006.safetensors",
342
+ "backbone.layers.6.mixer.norm.weight": "model-00001-of-00006.safetensors",
343
+ "backbone.layers.6.mixer.out_proj.weight": "model-00001-of-00006.safetensors",
344
+ "backbone.layers.6.norm.weight": "model-00001-of-00006.safetensors",
345
+ "backbone.layers.60.mixer.A_log": "model-00005-of-00006.safetensors",
346
+ "backbone.layers.60.mixer.D": "model-00005-of-00006.safetensors",
347
+ "backbone.layers.60.mixer.conv1d.bias": "model-00005-of-00006.safetensors",
348
+ "backbone.layers.60.mixer.conv1d.weight": "model-00005-of-00006.safetensors",
349
+ "backbone.layers.60.mixer.dt_bias": "model-00005-of-00006.safetensors",
350
+ "backbone.layers.60.mixer.in_proj.weight": "model-00005-of-00006.safetensors",
351
+ "backbone.layers.60.mixer.norm.weight": "model-00005-of-00006.safetensors",
352
+ "backbone.layers.60.mixer.out_proj.weight": "model-00005-of-00006.safetensors",
353
+ "backbone.layers.60.norm.weight": "model-00005-of-00006.safetensors",
354
+ "backbone.layers.61.mixer.down_proj.weight": "model-00005-of-00006.safetensors",
355
+ "backbone.layers.61.mixer.up_proj.weight": "model-00005-of-00006.safetensors",
356
+ "backbone.layers.61.norm.weight": "model-00005-of-00006.safetensors",
357
+ "backbone.layers.7.mixer.k_proj.weight": "model-00001-of-00006.safetensors",
358
+ "backbone.layers.7.mixer.o_proj.weight": "model-00001-of-00006.safetensors",
359
+ "backbone.layers.7.mixer.q_proj.weight": "model-00001-of-00006.safetensors",
360
+ "backbone.layers.7.mixer.v_proj.weight": "model-00001-of-00006.safetensors",
361
+ "backbone.layers.7.norm.weight": "model-00001-of-00006.safetensors",
362
+ "backbone.layers.8.mixer.down_proj.weight": "model-00001-of-00006.safetensors",
363
+ "backbone.layers.8.mixer.up_proj.weight": "model-00001-of-00006.safetensors",
364
+ "backbone.layers.8.norm.weight": "model-00001-of-00006.safetensors",
365
+ "backbone.layers.9.mixer.A_log": "model-00001-of-00006.safetensors",
366
+ "backbone.layers.9.mixer.D": "model-00001-of-00006.safetensors",
367
+ "backbone.layers.9.mixer.conv1d.bias": "model-00001-of-00006.safetensors",
368
+ "backbone.layers.9.mixer.conv1d.weight": "model-00001-of-00006.safetensors",
369
+ "backbone.layers.9.mixer.dt_bias": "model-00001-of-00006.safetensors",
370
+ "backbone.layers.9.mixer.in_proj.weight": "model-00001-of-00006.safetensors",
371
+ "backbone.layers.9.mixer.norm.weight": "model-00001-of-00006.safetensors",
372
+ "backbone.layers.9.mixer.out_proj.weight": "model-00001-of-00006.safetensors",
373
+ "backbone.layers.9.norm.weight": "model-00001-of-00006.safetensors",
374
+ "backbone.norm_f.weight": "model-00005-of-00006.safetensors",
375
+ "lm_head.weight": "model-00006-of-00006.safetensors"
376
+ }
377
+ }
modeling_nemotron_h.py ADDED
The diff for this file is too large to render. See raw diff
 
optimizer.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:264c8650bb948fcb5b86d9bafc4d68957db9ff1111ae5dfb8633a330623f1bfe
3
+ size 49240333014
pytorch_model_fsdp.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:260c989b1933fa7579b855219e59358a48e113f87467320d5c4f639dbba4d2bd
3
+ size 24620125662
rng_state_0.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cc7a5d9ca652a5bd1d04349d77fd0f56f8f1775e1b00b5cc5176468e017ac92a
3
+ size 16389
rng_state_1.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3bd450366f4274a04e6d5dd0754dcf816f88f65b85ed9c88a1d081c89aada859
3
+ size 16389
rng_state_2.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0a77d0583487d8cfff2e76df0532730c5485b42767b1ed8f4969f22094d840e3
3
+ size 16389
rng_state_3.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dfc063696020bbba4af73e5ff59ec7700b0b1cdad96c500dc21ee7ad1944a49f
3
+ size 16389
rng_state_4.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d6eef58bc47946544af1ba531a8c236e1942654ee216ea13ace82cce27989f69
3
+ size 16389
rng_state_5.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d1817a933eaa47c02483f98f317c6922afa277826ec0331b0e7b317b1a450ede
3
+ size 16389
rng_state_6.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9879f2fc500918bc865d70f89366cd6d137a38668bd679637ef9fb550fc7ed7a
3
+ size 16389
rng_state_7.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6dbd587ebbf015d1ccd7042d123702b4ff325bb586cf67ebe78a6992b029aa9a
3
+ size 16389
scheduler.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7a407fb2a9c82a7ab4e6f47bc2a056635b39725faf37e6b3c33db559bf5b5cd1
3
+ size 1465
special_tokens_map.json ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<s>",
4
+ "lstrip": false,
5
+ "normalized": false,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<SPECIAL_12>",
11
+ "lstrip": false,
12
+ "normalized": false,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": {
17
+ "content": "<SPECIAL_12>",
18
+ "lstrip": false,
19
+ "normalized": false,
20
+ "rstrip": false,
21
+ "single_word": false
22
+ },
23
+ "unk_token": {
24
+ "content": "<unk>",
25
+ "lstrip": false,
26
+ "normalized": false,
27
+ "rstrip": false,
28
+ "single_word": false
29
+ }
30
+ }
tokenizer.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3277c00fe5fb3963b3cb7c07b7f183722d2af4d775a4aea7cfb3684d7cccbc2f
3
+ size 17078330
tokenizer_config.json ADDED
The diff for this file is too large to render. See raw diff
 
trainer_state.json ADDED
The diff for this file is too large to render. See raw diff
 
training_args.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:85e9b8e9cc91d745e0d21eb1a3b65a163ce4453fa741397e511251ef3b7b9118
3
+ size 11921