Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / compile / passes / parallel / fsdp_pass.py: 93%
727 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""
16FSDP / DDP / HSDP Pass - Data Parallel Partitioning Pass
18Operates on the joint fwd+bwd graph produced by the tracer, where
19parameters/buffers are **static inputs** (leading placeholders), not get_attr
20nodes. The data-parallel mode comes from ``PassConfig.dp_mode`` and mirrors
21simplefsdp's ``data_parallel`` modes:
23- ``"fsdp"`` (fully_shard): parameters sharded on dim 0; forward all_gather,
24 backward reduce_scatter.
25- ``"ddp"`` (replicate): parameters stay replicated; no all_gather, gradients
26 are all-reduced on the ``dp_replicate`` axis.
27- ``"hsdp"`` (hybrid_shard): parameters replicated on ``dp_replicate`` and
28 sharded on ``fsdp``; forward all_gather on ``fsdp``, backward reduce_scatter
29 on ``fsdp`` then all_reduce on ``dp_replicate``.
31``FsdpParamSpec`` may override the shard and replicate axes per parameter.
32This is how expert parameters use their own EDP topology: shard on
33``edp_shard`` and, when ``edp_replicate > 1``, all-reduce the local shard on
34``edp_replicate`` — the same chain as HSDP but on expert-only groups.
36Responsibilities:
371. Identify parameter placeholders belonging to DP-wrapped modules
38 (via GraphParallelPlan, exact FQN or pattern)
392. Insert AllGather after each such placeholder (Shard -> Replicate), so the
40 computation body operates on full parameters while the graph input stays
41 sharded (skipped for ``"ddp"``)
423. Insert gradient reduction on the gradient outputs of DP parameters —
43 reduce_scatter (FSDP/HSDP) and/or all_reduce (DDP/HSDP)
444. Physically shard the *live model's* parameters in place (dim 0, by FSDP
45 rank) for FSDP/HSDP, so ``model.parameters()`` already holds the local
46 shard and the trainer / optimizer need no DP awareness at all
475. Reshard (``fsdp_reshard_after_forward``): sink each AllGather to its first
48 forward use, free the replicated parameter after its last forward read,
49 and, for parameters the backward still needs, re-gather plus rematerialize
50 the saved view chain just before the first backward consumer. Peak memory
51 tracks the forward working set instead of every replicated parameter.
53All DP logic (which parameters, the collectives, and the sharding itself)
54lives in this pass; the trainer simply feeds ``model.parameters()``.
55"""
57__all__ = ["FSDPPass", "FsdpParamSpec", "FsdpPlan"]
59import logging
60import operator
61from contextlib import contextmanager
62from dataclasses import dataclass, field
63from typing import Any, Dict, Iterator, List, Mapping, Optional, Set, Tuple
65import torch
66import torch.distributed as dist
67from torch import fx, nn
68from torch._subclasses import FakeTensor
69from torch.distributed.distributed_c10d import _resolve_process_group
70from torch.fx.node import _side_effectful_functions
71from torch.ops import _c10d_functional, prims
73from ...graph_parallel_plan import GraphParallelPlan
74from ...pass_config import GradientReduction, PassConfig, normalize_dp_mode
75from ..base import GraphPass
76from ..overlap.utils import rs_layout_preparation
78_LOG = logging.getLogger(__name__)
80_GETITEM = operator.getitem
81_DEFAULT_GRADIENT_REDUCTION = GradientReduction()
84@dataclass(frozen=True)
85class FsdpParamSpec:
86 """How ``FSDPPass`` handles one parameter.
88 ``mode`` selects the top-level policy; ``pad_policy`` only applies when
89 ``mode == "shard"`` and dim 0 is not divisible by ``degree``.
91 ``replicate_group_name`` / ``replicate_degree`` add a second, orthogonal
92 data-parallel axis (HSDP's ``dp_replicate`` or EDP's ``edp_replicate``).
93 The primary axis (``group_name`` / ``degree``) is reduced first, then the
94 replicate axis: a sharded parameter reduce-scatters on the shard group and
95 all-reduces the local shard on the replicate group; a replicated parameter
96 all-reduces on the replicate group only.
97 """
99 group_name: str
100 degree: int
101 mode: str = "shard"
102 pad_policy: str = "pad"
103 replicate_group_name: Optional[str] = None
104 replicate_degree: int = 1
106 def __post_init__(self) -> None:
107 if self.mode not in ("shard", "replicate", "skip"):
108 raise ValueError(f"Invalid FSDP shard mode: {self.mode!r}")
109 if self.pad_policy not in ("pad", "error", "replicate"):
110 raise ValueError(f"Invalid FSDP pad policy: {self.pad_policy!r}")
111 if isinstance(self.degree, bool) or not isinstance(self.degree, int) or self.degree < 1:
112 raise ValueError(f"FSDP shard degree must be a positive integer, got {self.degree!r}")
113 if (
114 isinstance(self.replicate_degree, bool)
115 or not isinstance(self.replicate_degree, int)
116 or self.replicate_degree < 1
117 ):
118 raise ValueError(
119 "FSDP replicate degree must be a positive integer, got "
120 f"{self.replicate_degree!r}"
121 )
122 if self.replicate_degree > 1 and not self.replicate_group_name:
123 raise ValueError("A replicate degree > 1 requires replicate_group_name")
126@dataclass(frozen=True)
127class FsdpPlan:
128 """Per-parameter overrides; unlisted parameters use the pass default."""
130 params: Mapping[str, FsdpParamSpec] = field(default_factory=dict)
132 def spec(self, fqn: str) -> Optional[FsdpParamSpec]:
133 """Return the override for ``fqn`` or ``None`` when unlisted."""
134 return self.params.get(fqn)
137def tag_gradient_identity(wait: fx.Node, param_name: str, state_idx: int) -> None:
138 """Attach the known output-to-parameter identity to a reduction chain.
140 Args:
141 wait: Final waited gradient returned by FSDPPass.
142 param_name: Canonical traced parameter FQN.
143 state_idx: Position in the traced state inputs.
144 """
145 node = wait
146 while node.op == "call_function" and str(node.target).startswith(
147 "_c10d_functional."
148 ):
149 node.meta.update(param_name=param_name, state_idx=state_idx)
150 if not node.args or not isinstance(node.args[0], fx.Node):
151 break
152 node = node.args[0]
155def _annotate_rs_spec(node: fx.Node, degree: int) -> None:
156 """Attach packed input/output shapes to one reduce-scatter node."""
157 source = node.args[0]
158 preparation = rs_layout_preparation(node)
159 if preparation:
160 # Contiguous changes strides, not the padded shape/dtype/device.
161 source = preparation[0].args[0]
162 value = source.meta.get("val")
163 spec = source.meta.get("fsdp_padded_input_spec")
164 if spec is None and value is not None and hasattr(value, "shape"):
165 spec = {
166 "shape": tuple(value.shape),
167 "dtype": value.dtype,
168 "device": str(value.device),
169 }
170 if spec is None:
171 return
172 shape = spec["shape"]
173 static = shape and all(
174 isinstance(dim, int) and not isinstance(dim, bool) and dim > 0 for dim in shape
175 )
176 if not static or shape[0] % degree:
177 return
178 node.meta["fsdp_bucket_spec"] = {
179 "input_shape": tuple(shape),
180 "output_shape": (shape[0] // degree, *shape[1:]),
181 "dtype": spec["dtype"],
182 "device": spec["device"],
183 }
186def _annotate_ag_spec(node: fx.Node, degree: int, params: dict) -> None:
187 """Attach shard/full shapes of one all-gather node from its parameter."""
188 param = params.get(node.meta.get("param_name"))
189 if param is None:
190 return
191 shape = tuple(param.shape)
192 if not shape or any(
193 not isinstance(dim, int) or isinstance(dim, bool) or dim <= 0 for dim in shape
194 ):
195 return
196 node.meta["fsdp_bucket_spec"] = {
197 "input_shape": shape,
198 "output_shape": (shape[0] * degree, *shape[1:]),
199 "dtype": node.meta.get("fsdp_compute_dtype", param.dtype),
200 "device": str(param.device),
201 }
204def annotate_fsdp_bucket_specs(graph_module: fx.GraphModule, model: nn.Module) -> None:
205 """Record actual padded shard shapes after the live model has been sharded.
207 Args:
208 graph_module: Graph transformed by FSDPPass.
209 model: Live model whose parameters now have their rank-local shard shapes.
210 """
211 params = dict(model.named_parameters())
212 for node in graph_module.graph.nodes:
213 kind = node.meta.get("comm_type")
214 if kind not in (
215 "fsdp_all_gather",
216 "fsdp_all_gather_backward",
217 "fsdp_reduce_scatter",
218 ):
219 continue
220 degree = node.meta.get("fsdp_degree")
221 if (not isinstance(degree, int) or isinstance(degree, bool)) or degree <= 1:
222 continue
223 if kind == "fsdp_reduce_scatter":
224 _annotate_rs_spec(node, degree)
225 else:
226 _annotate_ag_spec(node, degree, params)
229def _is_redundant_param_cast(node: fx.Node, parameter: fx.Node) -> bool:
230 """Match the exact dtype-only copy that AllGather already performs."""
231 dtype = parameter.meta.get("fsdp_compute_dtype")
232 if dtype is None or node.op != "call_function" or node.args != (parameter,):
233 return False
234 schema = getattr(node.target, "_schema", None)
235 return (
236 getattr(schema, "name", None) == "aten::_to_copy"
237 and getattr(schema, "overload_name", None) == ""
238 and node.kwargs == {"dtype": dtype}
239 )
242def _gather_input(graph: fx.Graph, parameter: fx.Node) -> fx.Node:
243 """Cast the local shard before gathering it in the compute dtype."""
244 dtype = parameter.meta.get("fsdp_compute_dtype")
245 if dtype is None:
246 return parameter
247 # The prefetch pass can move this functional cast with its AllGather.
248 result = graph.call_function(prims.convert_element_type.default, args=(parameter, dtype))
249 value = parameter.meta.get("val")
250 if value is not None:
251 result.meta["val"] = value.to(dtype)
252 return result
255def _free_tensor_storage(tensor: torch.Tensor) -> None:
256 """Release ``tensor``'s storage in place (FSDP reshard free step).
258 Inserted as a side-effecting FX node between an unsharded parameter's last
259 forward reader and its backward re-gather, so the replicated full
260 parameter (and every view aliasing it) does not stay resident for the
261 whole joint graph. Returns ``None``; the node exists only for its effect.
262 Mirrors ``fully_shard``'s ``free_unsharded_param`` storage release.
263 """
264 # FakeTensorProp (InductorPass shape propagation) executes this node on
265 # fake values whose storage cannot be resized; there is nothing to free.
266 if isinstance(tensor, FakeTensor):
267 return
268 # Replay handles borrow graph-pool storage. Resizing their non-owning
269 # Storage would only invalidate the address needed by the next replay.
270 if getattr(tensor, "_aclgraph_non_owning", False):
271 return
272 if isinstance(tensor, torch.Tensor) and tensor.untyped_storage().size() > 0:
273 tensor.untyped_storage().resize_(0)
276# FX dead-code elimination drops call_function nodes it judges pure; our free
277# op is pure to FX but has a real side effect. Register it so a later
278# ``eliminate_dead_code`` (a future pass, or a user) cannot delete the free.
279_side_effectful_functions.add(_free_tensor_storage)
282@dataclass
283class _UnshardedParam:
284 """Forward all_gather that materializes one FSDP parameter.
286 ``param_node`` is the sharded placeholder (graph input); ``ag_node`` /
287 ``wait_node`` produce and expose the replicated (unsharded) full parameter
288 the forward — and, after a reshard re-gather, the backward — read.
289 """
291 param_node: fx.Node
292 ag_node: fx.Node
293 wait_node: fx.Node
296@dataclass
297class _DpParamClassification:
298 """How DP handles each trainable parameter's gradient.
300 Produced by ``_classify_dp_params``:
302 - ``sharded_nodes``: marked, trainable parameter placeholders that get an
303 AllGather (Shard -> Replicate) and a reduce_scatter gradient, and are
304 physically sharded in the live model. Dim-0-divisible params are chunked
305 directly; non-divisible ones are pad-sharded (see ``_PaddedParam``).
306 - ``replicated_indices``: state indices of parameters kept replicated (never
307 chunked) whose gradient is averaged over the DP group with ``all_reduce``
308 instead of reduce-scattered — a marked 0-dim scalar (cannot be sharded), or
309 a partial-plan leftover that falls back to DDP.
310 - ``unmarked_trainable``: ``(state_idx, fqn)`` for the partial-plan leftovers
311 (a subset of ``replicated_indices``), kept only so the caller can log that
312 the plan did not cover them.
313 """
315 sharded_nodes: List[fx.Node]
316 replicated_indices: Set[int]
317 unmarked_trainable: List[Tuple[int, str]]
320@dataclass
321class _PaddedParam:
322 """A marked parameter that cannot be sharded evenly, pad-sharded instead.
324 Mirrors eager ``fully_shard`` (``core/fully_shard/hsdp_param.py``): dim 0 of
325 ``n`` elements is zero-padded to ``n_pad = ceil(n / degree) * degree`` so
326 every rank owns a uniform ``n_pad / degree``-element shard. The graph
327 narrows the gathered ``[n_pad, ...]`` back to ``[n, ...]`` for the compute,
328 and the backward pads the ``[n, ...]`` gradient back to ``[n_pad, ...]``
329 before reduce_scatter, so the returned local gradient matches the padded
330 shard (the padding region gets an all-zero gradient, hence never moves).
331 """
333 n: int
334 n_pad: int
335 dim0_pad: int
336 ndim: int
339@dataclass(frozen=True)
340class _GradReductionInfo:
341 """A parameter's selected mesh view and independent normalization policy."""
343 group_name: str
344 degree: int
345 reduction: GradientReduction
346 replicate_group_name: Optional[str] = None
347 replicate_degree: int = 1
350def _iter_arg_nodes(node: fx.Node) -> Iterator[fx.Node]:
351 """Yield every ``fx.Node`` in ``node.args`` / ``node.kwargs`` (nested)."""
352 stack: List[Any] = list(node.args) + list(node.kwargs.values())
353 while stack:
354 item = stack.pop()
355 if isinstance(item, fx.Node):
356 yield item
357 elif isinstance(item, (tuple, list)):
358 stack.extend(item)
359 elif isinstance(item, dict):
360 stack.extend(item.values())
363@contextmanager
364def _insertion_point(
365 graph: fx.Graph, anchor: Optional[fx.Node], fallback: fx.Node
366) -> Iterator[None]:
367 """Yield a graph insertion context.
369 Owns the ``anchor``-vs-``fallback`` choice so the gather-insertion body
370 stays a single code path: when ``anchor`` is given, new nodes land right
371 before it; otherwise they land right after ``fallback``.
372 """
373 if anchor is None:
374 with graph.inserting_after(fallback):
375 yield
376 else:
377 with graph.inserting_before(anchor):
378 yield
381class FSDPPass(GraphPass):
382 """
383 FSDP Partitioning Pass (Module-Level, static-input graph)
385 Responsibilities:
386 1. Only shard parameters in modules marked for FSDP wrapping
387 2. Insert AllGather after each FSDP parameter placeholder
388 (Shard -> Replicate)
389 3. Insert ReduceScatter after Backward (Replicate -> Shard)
390 4. Physically shard the live model's parameters in place so the
391 trainer / optimizer stay FSDP-agnostic
393 Key Difference from Old Implementation:
394 - Old: shard all parameters via get_attr nodes and physically rewrite the
395 GraphModule's stored tensors
396 - New: parameters are static graph inputs; the pass inserts collectives
397 into the graph and shards the live model's parameters in place
398 """
400 name = "fsdp_parallel"
402 def __init__(
403 self,
404 fsdp_group_name: Optional[str] = None,
405 parallel_plan: Optional[GraphParallelPlan] = None,
406 ) -> None:
407 """Initialize FSDP pass state.
409 Args:
410 fsdp_group_name: Process-group name registered for FSDP
411 collectives. Defaults to ``"fsdp"``. May be overridden
412 per-run via the ``fsdp_group_name`` kwarg in ``run``.
413 parallel_plan: Declarative plan identifying which modules to
414 shard. When ``None``, all parameters are sharded.
415 """
416 super().__init__()
417 self._fsdp_group_name = fsdp_group_name or "fsdp"
418 self._parallel_plan = parallel_plan
419 # Resolved from ``pass_config.fsdp_degree`` (or world_size) at
420 # ``run`` entry; left as ``None`` here so a stray access before
421 # ``run`` fails loudly instead of silently using a wrong default.
422 self._fsdp_degree: Optional[int] = None
423 self._fsdp_plan: Optional[FsdpPlan] = None
424 self._default_spec: Optional[FsdpParamSpec] = None
425 self._gradient_reductions: Dict[str, GradientReduction] = {}
426 self._source_gradient_groups: Dict[str, str] = {}
427 # Data-parallel mode ("fsdp" | "ddp" | "hsdp") and the replicate-axis
428 # group/degree used by DDP / HSDP gradient reduction.
429 self._dp_mode = "fsdp"
430 self._dp_replicate_group_name = "dp_replicate"
431 self._dp_replicate_degree: Optional[int] = None
432 self._processed_params: Set[str] = set()
433 self._fsdp_modules: Set[str] = set()
434 # Per-param forward all_gather record (the unsharded parameter),
435 # populated by ``_insert_all_gather_for_params`` and consumed by the
436 # reshard step.
437 self._unsharded_params: Dict[str, _UnshardedParam] = {}
438 # Non-divisible marked params keyed by FQN; populated by
439 # ``_classify_dp_params`` and consumed by the all_gather / grad-reduce /
440 # live-shard steps so they are pad-sharded like eager ``fully_shard``.
441 self._padded_params: Dict[str, _PaddedParam] = {}
443 def run(
444 self,
445 graph_module: fx.GraphModule,
446 pass_config: PassConfig,
447 **kwargs: Any,
448 ) -> fx.GraphModule:
449 """Insert AllGather/ReduceScatter and shard the live model.
451 Args:
452 graph_module: Joint fwd+bwd FX graph from the tracer.
453 pass_config: Parallel configuration. ``fsdp_degree`` is
454 read directly; ``None`` falls back to ``world_size`` (the
455 FSDP-only path). A ``TypeError`` here means a non-Protocol
456 config was passed — fix at the caller, do not paper over.
457 **kwargs: Must include ``model`` (the live ``nn.Module``) and
458 ``fsdp_group_name`` / ``parallel_plan`` as needed.
460 Returns:
461 The transformed graph module.
462 """
463 if not dist.is_initialized() or dist.get_world_size() == 1:
464 _LOG.info("Skipped: distributed not initialized or world_size=1")
465 return graph_module
467 model = self._setup_dp_config(pass_config, kwargs)
469 # Identify DP parameter placeholders. The joint graph's
470 # parameters/buffers are static inputs (leading placeholders, not
471 # get_attr nodes): locate them by position via the state layout the
472 # tracer attached, then keep only those in DP-marked modules. For
473 # FSDP/HSDP a marked param whose leading dim is not divisible by the
474 # shard degree is pad-sharded (like eager fully_shard) so it is still
475 # sharded and gradient-reduced; scalars stay replicated. DDP has no
476 # shard axis so every marked parameter is reduced.
477 state_fqns = getattr(graph_module, "state_fqns", [])
478 num_state_inputs = getattr(graph_module, "num_state_inputs", 0)
479 # Param-vs-buffer flag per leading state input. Absent on graphs
480 # traced before this flag existed; default to all-params so old
481 # traces keep the previous (parameter-only) behaviour.
482 state_is_param = getattr(graph_module, "state_is_param", None)
484 self._reset_run_state()
485 classification = self._classify_dp_params(
486 graph_module, state_fqns, num_state_inputs, state_is_param, model
487 )
488 param_nodes = classification.sharded_nodes
489 graph_module.fsdp_sharded_param_names = frozenset(
490 node.meta["param_name"] for node in param_nodes
491 )
492 graph_module.fsdp_padded_params = {
493 name: (info.n, info.n_pad) for name, info in self._padded_params.items()
494 }
496 _LOG.info(
497 "Identified %d sharded (incl. %d pad-sharded) + %d replicated DP "
498 "parameter nodes out of %d total state inputs",
499 len(param_nodes),
500 len(self._padded_params),
501 len(classification.replicated_indices),
502 num_state_inputs,
503 )
505 # A partial plan that leaves trainable params unmarked keeps their local
506 # gradient (never reduced) — a silent divergence source across DP ranks,
507 # so warn loudly before continuing.
508 if classification.unmarked_trainable:
509 self._warn_unmarked_trainable(classification.unmarked_trainable)
511 if not param_nodes and not classification.replicated_indices and not self._gradient_reductions:
512 _LOG.warning(
513 "No DP parameters found, check GraphParallelPlan or model structure"
514 )
515 return graph_module
517 graph_module = self._apply_dp_transforms(
518 graph_module,
519 model,
520 classification,
521 pass_config,
522 state_fqns,
523 num_state_inputs,
524 state_is_param,
525 )
527 _LOG.info(
528 "Completed dp_mode=%s, processed %d parameters",
529 self._dp_mode,
530 len(param_nodes),
531 )
533 graph_module.recompile()
534 return graph_module
536 def _setup_dp_config(
537 self, pass_config: PassConfig, kwargs: Dict[str, Any]
538 ) -> nn.Module:
539 """Resolve run-time DP config, stash it on ``self``, return the model.
541 Reads ``dp_mode`` / ``fsdp_degree`` / ``dp_replicate_degree`` off
542 ``pass_config`` (the last two fall back to ``world_size`` when unset)
543 and the group names / ``parallel_plan`` / ``model`` off ``kwargs``.
545 Returns:
546 The live ``nn.Module`` to physically shard.
548 Raises:
549 ValueError: If ``model`` is missing from ``kwargs``.
550 """
551 self._dp_mode = normalize_dp_mode(getattr(pass_config, "dp_mode", "fsdp"))
552 # FSDP shard-axis group size: use the explicitly configured degree when
553 # present (required for TP+FSDP / HSDP, where the FSDP group is a
554 # proper sub-group of the world — using world_size would over-shard
555 # along the TP axis).
556 configured = pass_config.fsdp_degree
557 self._fsdp_degree = configured if configured else dist.get_world_size()
558 self._fsdp_group_name = kwargs.get("fsdp_group_name", self._fsdp_group_name)
559 self._fsdp_plan = kwargs.get("fsdp_plan")
560 self._gradient_reductions = dict(kwargs.get("gradient_reductions", {}))
561 self._source_gradient_groups = dict(kwargs.get("source_gradient_groups", {}))
562 self._dp_replicate_group_name = kwargs.get(
563 "dp_replicate_group_name", self._dp_replicate_group_name
564 )
565 # Replicate-axis degree used by DDP / HSDP gradient reduction.
566 replicate_degree = getattr(pass_config, "dp_replicate_degree", None)
567 if self._dp_mode == "ddp":
568 self._dp_replicate_degree = replicate_degree or dist.get_world_size()
569 elif self._dp_mode == "hsdp":
570 self._dp_replicate_degree = replicate_degree or (
571 dist.get_world_size() // self._fsdp_degree
572 )
573 else:
574 self._dp_replicate_degree = replicate_degree
575 if self._dp_mode == "ddp":
576 self._default_spec = FsdpParamSpec(
577 self._dp_replicate_group_name,
578 self._dp_replicate_degree,
579 mode="replicate",
580 )
581 elif self._dp_mode == "hsdp":
582 self._default_spec = FsdpParamSpec(
583 self._fsdp_group_name,
584 self._fsdp_degree,
585 replicate_group_name=self._dp_replicate_group_name,
586 replicate_degree=self._dp_replicate_degree,
587 )
588 else:
589 self._default_spec = FsdpParamSpec(
590 self._fsdp_group_name,
591 self._fsdp_degree,
592 )
593 self._parallel_plan = kwargs.get("parallel_plan", self._parallel_plan)
594 model = kwargs.get("model")
595 if model is None:
596 raise ValueError(
597 "FSDPPass requires the live model via kwargs (model=...) so it "
598 "can physically shard parameters; the trainer passes it through "
599 "in compile()"
600 )
602 _LOG.info(
603 "Running dp_mode=%s fsdp_degree=%s dp_replicate_degree=%s world_size=%s",
604 self._dp_mode,
605 self._fsdp_degree,
606 self._dp_replicate_degree,
607 dist.get_world_size(),
608 )
609 return model
611 def _reset_run_state(self) -> None:
612 """Clear per-run state so a reused pass does not carry names across graphs."""
613 self._processed_params = set()
614 self._fsdp_modules = set()
615 self._unsharded_params = {}
616 self._padded_params = {}
618 def _apply_dp_transforms(
619 self,
620 graph_module: fx.GraphModule,
621 model: nn.Module,
622 classification: _DpParamClassification,
623 pass_config: PassConfig,
624 state_fqns: List[str],
625 num_state_inputs: int,
626 state_is_param: Optional[List[bool]],
627 ) -> fx.GraphModule:
628 """Insert gather / grad-reduce / reshard and shard the live model.
630 Parameters whose spec shards on a real axis (FSDP/HSDP/EDP) also
631 all_gather for the forward and are pad/sharded in the live model.
632 Parameters whose spec only reduces a replicate axis (DDP, or a
633 singleton expert shard) keep their full storage.
634 """
635 param_nodes = classification.sharded_nodes
636 if param_nodes:
637 graph_module = self._insert_all_gather_for_params(
638 graph_module, param_nodes, pass_config
639 )
641 sharded_param_indices = frozenset(
642 node.meta["state_idx"] for node in param_nodes
643 )
644 graph_module = self._insert_grad_reduction(
645 graph_module,
646 sharded_param_indices,
647 classification.replicated_indices,
648 state_fqns,
649 num_state_inputs,
650 state_is_param,
651 model,
652 )
654 if param_nodes:
655 # Reshard: free each replicated parameter once forward is done and
656 # re-gather + rematerialize it for the backward. Runs after the
657 # grad reduction so the grad path is untouched; no-op when disabled.
658 graph_module = self._insert_reshard_logic(
659 graph_module, param_nodes, pass_config
660 )
662 # Shard the live model's parameters in place (dim 0, by this rank's
663 # index in the FSDP group). ``model.parameters()`` then yields the
664 # shards, so the trainer's optimizer / grad accumulation stay
665 # DP-agnostic; the graph re-gathers each step.
666 self._shard_live_model_params(model)
667 annotate_fsdp_bucket_specs(graph_module, model)
669 return graph_module
671 def _param_spec(self, name: str) -> FsdpParamSpec:
672 """Return the shard policy for one parameter."""
673 if self._fsdp_plan is not None:
674 spec = self._fsdp_plan.spec(name)
675 if spec is not None:
676 return spec
677 if self._default_spec is None:
678 raise RuntimeError("FSDPPass default shard spec is not initialized")
679 return self._default_spec
681 def _param_group(self, name: str) -> tuple[str, int]:
682 """Choose the shard group and degree for one parameter."""
683 spec = self._param_spec(name)
684 return spec.group_name, spec.degree
686 def _classify_dp_params(
687 self,
688 graph_module: fx.GraphModule,
689 state_fqns: List[str],
690 num_state_inputs: int,
691 state_is_param: Optional[List[bool]] = None,
692 model: Optional[nn.Module] = None,
693 ) -> _DpParamClassification:
694 """Classify parameter placeholders by how DP handles their gradient.
696 Parameters are the leading ``num_state_inputs`` placeholders of the
697 joint graph, in ``state_fqns`` order. A parameter is DP-marked when any
698 ancestor module FQN (e.g. ``layers.0.attention.wq`` for
699 ``layers.0.attention.wq.weight``) is marked in the GraphParallelPlan —
700 either exactly or via pattern (e.g. ``layers.*``).
702 Buffers (e.g. RoPE's non-persistent ``cache``) and frozen parameters
703 are skipped: the tracer omits them from the gradient list and the
704 live-model sharder leaves them full-size. The pad-shard and unmarked-
705 fallback decisions are delegated to ``_marked_param_stays_replicated``
706 and ``_unmarked_disposition``.
708 Returns:
709 A ``_DpParamClassification`` (see its docstring).
710 """
711 sharded_nodes: List[fx.Node] = []
712 replicated_indices: Set[int] = set()
713 unmarked_trainable: List[Tuple[int, str]] = []
715 placeholders = [n for n in graph_module.graph.nodes if n.op == "placeholder"]
716 if len(placeholders) < num_state_inputs:
717 return _DpParamClassification(
718 sharded_nodes, replicated_indices, unmarked_trainable
719 )
721 # Build a FQN -> Parameter lookup so the divisibility gate uses the
722 # same source of truth as ``_shard_live_model_params`` (which iterates
723 # ``model.named_parameters``). ``state_fqns`` covers both parameters
724 # and buffers; only parameters are reachable here because buffers are
725 # filtered out by ``state_is_param`` above.
726 param_lookup: Dict[str, nn.Parameter] = (
727 dict(model.named_parameters(remove_duplicate=False))
728 if model is not None
729 else {}
730 )
732 for idx in range(num_state_inputs):
733 fqn, param, skip = self._resolve_dp_param(
734 idx, state_fqns, state_is_param, param_lookup, model
735 )
736 if skip:
737 continue
739 spec = self._param_spec(fqn)
740 if spec.mode == "skip":
741 continue
742 _, degree = self._param_group(fqn)
743 if spec.mode == "replicate":
744 replicated_indices.add(idx)
745 continue
747 fallback = self._unmarked_disposition(fqn, param, model)
748 if fallback is not None:
749 if fallback:
750 replicated_indices.add(idx)
751 unmarked_trainable.append((idx, fqn))
752 continue
754 if self._marked_param_stays_replicated(fqn, param):
755 replicated_indices.add(idx)
756 continue
758 sharded_nodes.append(
759 self._mark_sharded_param(idx, fqn, degree, placeholders[idx], param)
760 )
762 return _DpParamClassification(
763 sharded_nodes, replicated_indices, unmarked_trainable
764 )
766 def _resolve_dp_param(
767 self,
768 idx: int,
769 state_fqns: List[str],
770 state_is_param: Optional[List[bool]],
771 param_lookup: Dict[str, nn.Parameter],
772 model: Optional[nn.Module],
773 ) -> Tuple[Optional[str], Optional[nn.Parameter], bool]:
774 """Resolve one state placeholder to ``(fqn, param, skip)``.
776 Buffers and frozen parameters are skipped: the tracer omits them from
777 the gradient list and the live-model sharder leaves them full-size.
778 """
779 if state_is_param is not None and not state_is_param[idx]:
780 # Buffer, not a parameter -> never FSDP-sharded.
781 return None, None, True
783 fqn = state_fqns[idx]
784 param = param_lookup.get(fqn)
785 if model is not None and param is None:
786 return None, None, True
788 if param is not None and not param.requires_grad:
789 _LOG.info("Skip %s: requires_grad=False (frozen)", fqn)
790 return None, None, True
791 return fqn, param, False
793 def _mark_sharded_param(
794 self,
795 idx: int,
796 fqn: str,
797 degree: int,
798 node: fx.Node,
799 param: Optional[nn.Parameter],
800 ) -> fx.Node:
801 """Tag a DP-sharded placeholder and record its live-model shard size."""
802 node.meta["state_idx"] = idx
803 node.meta["param_name"] = fqn
804 node.meta["fsdp_degree"] = degree
805 node.meta["is_param"] = True
806 # Record the TP-local, unsharded size before live-model FSDP slicing.
807 # Newly inserted collective nodes have no shape-propagated ``val``.
808 value = param if param is not None else node.meta.get("val")
809 if isinstance(value, torch.Tensor) and isinstance(value.numel(), int):
810 dtype = node.meta.get("fsdp_compute_dtype", value.dtype)
811 node.meta["fsdp_unsharded_nbytes"] = value.numel() * dtype.itemsize
812 self._fsdp_modules.add(self._get_parent_module_fqn(fqn))
813 return node
815 def _unmarked_disposition(
816 self,
817 fqn: str,
818 param: Optional[nn.Parameter],
819 model: Optional[nn.Module],
820 ) -> Optional[bool]:
821 """Decide how a trainable param a partial plan left unmarked is handled.
823 Rather than leave it with a local, unreduced gradient (silent
824 divergence across DP ranks), fall it back to DDP: keep it replicated
825 and average its gradient over the DP group.
827 Returns:
828 ``True`` to replicate it and warn the caller, ``False`` to skip it
829 silently (``param is None`` with a live model means a buffer, only
830 reachable when an old trace lacks ``state_is_param``), or ``None``
831 when the param is marked and the caller should shard it normally.
832 """
833 if self._parallel_plan is None or self._param_belongs_to_fsdp_module(fqn):
834 return None
835 return model is None or param is not None
837 def _marked_param_stays_replicated(
838 self, fqn: str, param: Optional[nn.Parameter]
839 ) -> bool:
840 """Decide whether a marked param is kept replicated instead of sharded.
842 A marked param whose dim 0 is not divisible by its shard degree cannot
843 be chunked evenly. A 0-dim scalar cannot be padded along dim 0, so it
844 stays replicated and its gradient is averaged over the shard axis.
845 Every other non-divisible param is recorded for pad-sharding (mirroring
846 eager ``fully_shard``): dim 0 is zero-padded to a multiple of the
847 degree, so it is still sharded and gradient-reduced. The divisibility
848 decision is driven by the param's own spec (dense ``fsdp``/``hsdp`` or
849 expert ``fsdp_expert``), not the dense ``dp_mode``: a replicated-only
850 dense mode (``ddp``) may still shard expert params on ``fsdp_expert``.
851 """
852 if param is None:
853 return False
854 spec = self._param_spec(fqn)
855 _, degree = self._param_group(fqn)
856 shape = param.shape
857 if spec.pad_policy == "replicate":
858 return True
859 if not shape:
860 if spec.pad_policy == "error":
861 raise ValueError(
862 f"Parameter {fqn} with shape {tuple(shape)} cannot be sharded "
863 f"across group {spec.group_name!r} degree {degree}"
864 )
865 _LOG.info(
866 "Scalar param %s stays replicated: 0-dim cannot be "
867 "pad-sharded; its gradient will be all-reduced",
868 fqn,
869 )
870 return True
871 if shape[0] % degree == 0:
872 return False
873 if spec.pad_policy == "error":
874 raise ValueError(
875 f"Parameter {fqn} with shape {tuple(shape)} cannot be sharded "
876 f"across group {spec.group_name!r} degree {degree}"
877 )
878 n = int(shape[0])
879 n_pad = -(-n // degree) * degree
880 self._padded_params[fqn] = _PaddedParam(
881 n=n, n_pad=n_pad, dim0_pad=n_pad - n, ndim=param.ndim
882 )
883 _LOG.info(
884 "Param %s pad-sharded: dim 0 %d -> %d (fsdp_degree %d)",
885 fqn,
886 n,
887 n_pad,
888 degree,
889 )
890 return False
892 @staticmethod
893 def _warn_unmarked_trainable(entries: List[Tuple[int, str]]) -> None:
894 """Report trainable params a partial plan left unmarked.
896 They are not FSDP-sharded, so they fall back to DDP: kept replicated and
897 their gradient averaged over the DP group. The warning is informational —
898 the plan simply did not cover them, and they cost no sharded memory but a
899 replicated gradient all-reduce.
900 """
901 shown = [fqn for _, fqn in entries[:10]]
902 remaining = len(entries) - len(shown)
903 _LOG.warning(
904 "%d trainable parameter(s) are not marked for DP; falling back to "
905 "DDP (kept replicated, gradient all-reduced over the DP group): "
906 "%s%s. Mark them via GraphParallelPlan.fsdp_mark()/"
907 "fsdp_mark_pattern() to FSDP-shard them instead.",
908 len(entries),
909 ", ".join(shown),
910 f" (+{remaining} more)" if remaining > 0 else "",
911 )
913 def _shard_live_model_params(self, model: nn.Module) -> None:
914 """
915 Physically shard the live model's parameters in place (dim 0).
917 After this, model.parameters() yields the local shards.
918 """
919 # Use each param's own group's local rank (NOT the global rank) as the
920 # chunk index — when a shard degree < world_size (TP+FSDP, EDP), the
921 # global rank exceeds the chunk count and causes IndexError. Resolved
922 # lazily per distinct group so a replicated-only mode (DDP) never
923 # touches the dense "fsdp" group, which is not registered in that mode.
924 group_ranks = {}
925 sharded_count = 0
927 for name, param in model.named_parameters():
928 if not param.requires_grad:
929 continue
931 spec = self._param_spec(name)
932 if spec.mode != "shard" or spec.pad_policy == "replicate":
933 continue
934 group_name, degree = spec.group_name, spec.degree
936 # Same plan gate as ``_classify_dp_params``: only parameters inside
937 # FSDP-marked modules are sharded. Skipping the gate here would
938 # shard params the graph still expects full-rank
939 # (no AllGather inserted), causing a shape mismatch at
940 # ``run_traced_graph`` time on any non-``*`` plan.
941 if (
942 self._parallel_plan is not None
943 and not self._param_belongs_to_fsdp_module(name)
944 ):
945 _LOG.info(
946 "Skip %s: not in an FSDP-wrapped module",
947 name,
948 )
949 continue
951 if group_name not in group_ranks:
952 group_ranks[group_name] = dist.get_rank(
953 group=_resolve_process_group(group_name)
954 )
955 rank = group_ranks[group_name]
957 # Pad-shard a non-divisible param (recorded by
958 # ``_classify_dp_params``): zero-pad dim 0 to a multiple of the
959 # degree, then take this rank's equal-size chunk — exactly what
960 # eager ``fully_shard`` does. A 0-dim scalar cannot be padded and
961 # stays replicated.
962 pad_info = self._padded_params.get(name)
963 if pad_info is not None:
964 original_shape = param.shape
965 full = param.detach()
966 if pad_info.dim0_pad:
967 full = torch.cat(
968 [full, full.new_zeros((pad_info.dim0_pad, *full.shape[1:]))],
969 dim=0,
970 )
971 param.data = full.chunk(degree, dim=0)[rank].clone()
972 sharded_count += 1
973 _LOG.info(
974 "Pad-sharded %s: %s -> %s",
975 name,
976 list(original_shape),
977 list(param.shape),
978 )
979 continue
981 # Mirror ``_classify_dp_params``: a 0-dim scalar stays replicated.
982 if not param.shape or param.shape[0] % degree != 0:
983 _LOG.info(
984 "Skip %s: dim 0 (%s) not divisible by fsdp_degree (%s)",
985 name,
986 param.shape[0] if param.shape else "scalar",
987 degree,
988 )
989 continue
991 original_shape = param.shape
992 param.data = param.detach().chunk(degree, dim=0)[rank].clone()
993 sharded_count += 1
994 _LOG.info(
995 "Sharded %s: %s -> %s",
996 name,
997 list(original_shape),
998 list(param.shape),
999 )
1001 _LOG.info("Total sharded parameters: %d", sharded_count)
1003 def _param_belongs_to_fsdp_module(self, param_fqn: str) -> bool:
1004 """Check if a parameter FQN belongs to an FSDP-wrapped module.
1006 The parameter's own module FQN (``layers.0.attention.wq.weight`` ->
1007 ``layers.0.attention.wq``) plus every ancestor (``layers.0``, ...) is
1008 tested, so both ``fsdp_mark("layers.0.attention.wq")`` and
1009 ``fsdp_mark_pattern("layers.*")`` match.
1011 A parameter directly on the root (``weight``) has no module ancestor;
1012 its own FQN is still tested first so it can be marked by its name
1013 (``fsdp_mark("weight")``) or by a ``*`` pattern.
1014 """
1015 if self._parallel_plan.is_marked_for_fsdp(param_fqn):
1016 return True
1018 parts = param_fqn.split(".")
1019 for i in range(len(parts) - 1, 0, -1):
1020 module_fqn = ".".join(parts[:i])
1021 if self._parallel_plan.is_marked_for_fsdp(module_fqn):
1022 return True
1023 return False
1025 def _get_parent_module_fqn(self, param_fqn: str) -> str:
1026 """
1027 Get parent module FQN from parameter FQN.
1029 e.g., "layers.0.attention.wq.weight" -> "layers.0.attention.wq"
1030 """
1031 parts = param_fqn.split(".")
1032 return ".".join(parts[:-1]) if len(parts) > 1 else param_fqn
1034 def _insert_all_gather_for_params(
1035 self,
1036 graph_module: fx.GraphModule,
1037 param_nodes: List[fx.Node],
1038 pass_config: PassConfig,
1039 ) -> fx.GraphModule:
1040 """
1041 Insert AllGather for each FSDP parameter placeholder.
1043 Parameter state: Shard -> Replicate. All subsequent uses of the
1044 placeholder are rewired to the unsharded (replicated) tensor, so the
1045 computation body keeps operating on full parameters while the graph
1046 input stays sharded. The gather is placed after the placeholder, or
1047 sunk to just before the first consumer when reshard is enabled.
1049 When reshard is enabled the gather is **sunk** to just before the
1050 parameter's first consumer instead of sitting next to the placeholder.
1051 All state placeholders lead the graph, so an unsunk gather would
1052 materialize every full parameter before any compute runs, leaving the
1053 reshard free step nothing to reclaim; sinking is what makes peak
1054 memory track the forward working set.
1055 """
1056 graph = graph_module.graph
1058 for param_node in param_nodes:
1059 if param_node.name in self._processed_params:
1060 continue
1062 sink = pass_config.fsdp_reshard_after_forward
1063 if sink and not param_node.users:
1064 # Dead parameter: a gather would materialize a full replica
1065 # nobody reads, and reshard would never free it. Leave the
1066 # placeholder sharded.
1067 self._processed_params.add(param_node.name)
1068 continue
1069 anchor = self._first_user(param_node) if sink else None
1071 group_name, degree = self._param_group(
1072 param_node.meta.get("param_name", "")
1073 )
1075 # AllGather + immediate wait for correctness; FsdpOverlapPass may
1076 # sink the wait past independent compute later.
1077 with _insertion_point(graph, anchor, param_node):
1078 gather_input = _gather_input(graph, param_node)
1079 with _insertion_point(graph, anchor, gather_input):
1080 ag_node = graph.call_function(
1081 _c10d_functional.all_gather_into_tensor,
1082 args=(gather_input, degree, group_name),
1083 )
1084 dtype = param_node.meta.get("fsdp_compute_dtype")
1085 if dtype is not None:
1086 ag_node.meta["fsdp_compute_dtype"] = dtype
1087 ag_node.meta["comm_type"] = "fsdp_all_gather"
1088 ag_node.meta["comm_group"] = group_name
1089 ag_node.meta["param_node"] = param_node.name
1090 ag_node.meta["param_name"] = param_node.meta.get("param_name")
1091 ag_node.meta["state_idx"] = param_node.meta.get("state_idx")
1092 ag_node.meta["fsdp_degree"] = degree
1093 ag_node.meta["fsdp_unsharded_nbytes"] = param_node.meta.get(
1094 "fsdp_unsharded_nbytes"
1095 )
1097 # Insert the wait in its own block: a wait placed in the same block
1098 # as the gather would land *before* the gather it depends on (the
1099 # first insert inside ``inserting_after(X)`` lands right after
1100 # ``X``), and codegen would emit
1101 # ``wait_tensor(all_gather_into_tensor)`` before that variable is
1102 # assigned.
1103 with graph.inserting_after(ag_node):
1104 wait_node = graph.call_function(
1105 _c10d_functional.wait_tensor,
1106 args=(ag_node,),
1107 )
1108 wait_node.meta["wait_for"] = ag_node.name
1110 param_node.meta["fsdp_sharded"] = True
1111 param_node.meta["fsdp_ag_node"] = ag_node.name
1112 self._unsharded_params[param_node.name] = _UnshardedParam(
1113 param_node=param_node, ag_node=ag_node, wait_node=wait_node
1114 )
1116 # Pad-sharded parameter: the gather produced the padded full tensor
1117 # ``[n_pad, ...]``; narrow it back to the real ``[n, ...]`` and route
1118 # every consumer to that view. Use the ``aten`` overload (not the
1119 # ``torch.narrow`` builtin) so its schema's ``alias_info`` marks it a
1120 # view: ``_propagates_alias`` keys off that schema, so the reshard
1121 # alias walk (free / rematerialize) tracks the narrow and does not
1122 # free the padded gather out from under its forward consumers.
1123 replacement = wait_node
1124 pad_info = self._padded_params.get(param_node.meta.get("param_name"))
1125 if pad_info is not None:
1126 with graph.inserting_after(wait_node):
1127 replacement = graph.call_function(
1128 torch.ops.aten.narrow.default,
1129 args=(wait_node, 0, 0, pad_info.n),
1130 )
1131 replacement.meta["param_name"] = param_node.meta.get("param_name")
1132 replacement.meta["state_idx"] = param_node.meta.get("state_idx")
1134 for user in list(param_node.users):
1135 if user in (gather_input, ag_node, wait_node):
1136 continue
1137 if _is_redundant_param_cast(user, param_node):
1138 # Preserve reshard's last-reader tracking without a second full-size copy.
1139 user.replace_all_uses_with(replacement)
1140 graph.erase_node(user)
1141 else:
1142 user.replace_input_with(param_node, replacement)
1144 self._processed_params.add(param_node.name)
1146 return graph_module
1148 @staticmethod
1149 def _first_user(param_node: fx.Node) -> Optional[fx.Node]:
1150 """Earliest (in graph order) consumer of ``param_node``.
1152 Placeholders are all at the top; their consumers are spread through
1153 the forward. Returning the earliest consumer lets the gather sink
1154 next to the first real use. ``None`` when the placeholder is unused
1155 (then the gather stays next to the placeholder).
1156 """
1157 # A cast removed by this pass must not pin the gather to the graph entry.
1158 users = {
1159 consumer
1160 for user in param_node.users
1161 for consumer in (user.users if _is_redundant_param_cast(user, param_node) else (user,))
1162 if consumer.op != "output"
1163 }
1164 if not users:
1165 return None
1166 forward_users = [u for u in users if not u.meta.get("autograd_backward", False)]
1167 candidates = forward_users or users
1168 order = {n: i for i, n in enumerate(param_node.graph.nodes)}
1169 return min(candidates, key=lambda u: order.get(u, len(order)))
1171 def _insert_grad_reduction( # pylint: disable=too-many-locals
1172 self,
1173 graph_module: fx.GraphModule,
1174 sharded_param_indices: Set[int],
1175 replicated_param_indices: Set[int],
1176 state_fqns: List[str],
1177 num_state_inputs: int,
1178 state_is_param: Optional[List[bool]] = None,
1179 model: Optional[nn.Module] = None,
1180 ) -> fx.GraphModule:
1181 """Insert gradient reduction on the gradient outputs of DP parameters.
1183 The joint graph returns ``[loss, grad0, grad1, ...]`` from the fwd+bwd
1184 function; gradient ``i`` (output index ``i+1``) corresponds to the
1185 ``i``-th trainable parameter (``state_fqns`` order, buffers and frozen
1186 params skipped, mirrored by ``_build_trainable_state_indices``). For a
1187 parameter in ``sharded_param_indices`` (a real shard axis) the per-spec
1188 chain applies: reduce_scatter on the spec's primary ``group_name``
1189 (Replicate -> Shard), then, when the spec carries a
1190 ``replicate_group_name`` with degree > 1 (HSDP / EDP), all_reduce on
1191 that replicate axis (shard axis first, so the cross-axis message is
1192 already sharded). Pad-sharded params (``_padded_params``) zero-pad their
1193 ``[n, ...]`` gradient back to ``[n_pad, ...]`` first so the local
1194 gradient matches the padded shard.
1196 For a parameter in ``replicated_param_indices`` (a marked 0-dim scalar,
1197 or a partial-plan leftover that fell back to DDP) no shard axis exists,
1198 so the gradient is reduced with all_reduce instead. Ordinary parameters
1199 average over the DP axes; source-layout parameters use their explicit
1200 reduction policy. Gradients outside the DP modules stay full.
1201 """
1202 graph = graph_module.graph
1204 output_node = next((n for n in graph.nodes if n.op == "output"), None)
1205 if output_node is None:
1206 return graph_module
1208 returned = output_node.args[0]
1209 if not isinstance(returned, (list, tuple)):
1210 # Model returned a single value (e.g. just loss) -> no grads.
1211 return graph_module
1213 trainable_state_indices = self._build_trainable_state_indices(
1214 state_fqns, num_state_inputs, state_is_param, model
1215 )
1217 new_returned = list(returned)
1218 # ``train_fn`` may append the traced ``loss_dict`` outputs AFTER the
1219 # gradients (see ``trace_model_graph``); those are not gradients and
1220 # must stay outside the reduce_scatter range.
1221 num_loss_outputs = len(getattr(graph_module, "loss_dict_keys", []))
1222 num_grads = len(new_returned) - 1 - num_loss_outputs # index 0 is the loss
1223 if num_grads != len(trainable_state_indices):
1224 raise ValueError(
1225 f"Gradient count ({num_grads}) does not match trainable "
1226 f"parameter count ({len(trainable_state_indices)}). The "
1227 f"traced graph and the live model disagree on which "
1228 f"parameters are trainable; refusing to insert gradient "
1229 f"reduction to avoid silent gradient/state misalignment."
1230 )
1232 # Index 0 is the loss; gradients start at index 1. Gradient i+1
1233 # corresponds to trainable parameter i, whose state_idx is
1234 # trainable_state_indices[i]. The trailing loss_dict outputs are
1235 # named loss values, not gradients.
1236 for i in range(1, len(new_returned) - num_loss_outputs):
1237 grad_node = new_returned[i]
1238 if not isinstance(grad_node, fx.Node):
1239 continue
1241 state_idx = trainable_state_indices[i - 1]
1242 fqn = state_fqns[state_idx]
1243 spec = self._param_spec(fqn)
1244 if spec.mode == "skip":
1245 continue
1246 group_name, degree = spec.group_name, spec.degree
1247 if state_idx in sharded_param_indices:
1248 replicated = False
1249 pad_info = self._padded_params.get(fqn)
1250 elif state_idx in replicated_param_indices:
1251 replicated = True
1252 pad_info = None
1253 elif spec.mode == "replicate":
1254 replicated = True
1255 pad_info = None
1256 elif degree == 1 and fqn in self._gradient_reductions:
1257 replicated = True
1258 pad_info = None
1259 else:
1260 continue
1262 reduction_info = _GradReductionInfo(
1263 group_name, degree, self._gradient_reductions.get(fqn, _DEFAULT_GRADIENT_REDUCTION),
1264 replicate_group_name=spec.replicate_group_name,
1265 replicate_degree=spec.replicate_degree,
1266 )
1267 with graph.inserting_before(output_node):
1268 new_returned[i] = self._build_grad_reduction_nodes(
1269 graph,
1270 grad_node,
1271 reduction_info,
1272 replicated=replicated,
1273 pad_info=pad_info,
1274 )
1275 tag_gradient_identity(new_returned[i], fqn, state_idx)
1276 source_group = self._source_gradient_groups.get(fqn)
1277 if source_group is not None:
1278 new_returned[i] = self._insert_source_gradient_reduction(
1279 graph, new_returned[i], source_group
1280 )
1281 tag_gradient_identity(new_returned[i], state_fqns[state_idx], state_idx)
1283 output_node.args = (type(returned)(new_returned),) + tuple(output_node.args[1:])
1285 return graph_module
1287 @staticmethod
1288 def _insert_source_gradient_reduction(
1289 graph: fx.Graph, gradient: fx.Node, group_name: str
1290 ) -> fx.Node:
1291 """Sum replicated source-layout contributions after completed DP reduction."""
1292 contiguous = graph.call_function(torch.ops.aten.contiguous.default, args=(gradient,))
1293 reduced = graph.call_function(
1294 _c10d_functional.all_reduce, args=(contiguous, "sum", group_name)
1295 )
1296 reduced.meta.update(comm_type="source_all_reduce", comm_group=group_name, autograd_backward=True)
1297 return FSDPPass._insert_wait(graph, reduced)
1299 @staticmethod
1300 def _pad_gradient(graph: fx.Graph, gradient: fx.Node, source: fx.Node, pad_info: _PaddedParam) -> fx.Node:
1301 """Pad the gradient and retain the physical layout expected by collective lowering."""
1302 # Pad tuples address dimensions from last to first; only dim 0 grows.
1303 pad_tuple = tuple([0, 0] * (pad_info.ndim - 1) + [0, pad_info.dim0_pad])
1304 padded = graph.call_function(torch.ops.aten.constant_pad_nd.default, args=(gradient, pad_tuple))
1305 padded.meta["comm_type"] = "fsdp_grad_pad"
1306 value = source.meta.get("val")
1307 if value is not None and hasattr(value, "shape"):
1308 padded.meta["fsdp_padded_input_spec"] = {
1309 "shape": (pad_info.n_pad, *value.shape[1:]),
1310 "dtype": value.dtype,
1311 "device": str(value.device),
1312 }
1313 return padded
1315 def _build_grad_reduction_nodes(
1316 self,
1317 graph: fx.Graph,
1318 grad_node: fx.Node,
1319 info: _GradReductionInfo,
1320 replicated: bool = False,
1321 pad_info: Optional[_PaddedParam] = None,
1322 ) -> fx.Node:
1323 """Build and return the waited gradient-reduction node for ``grad_node``.
1325 The returned (wait) node replaces ``grad_node`` in the graph output.
1326 Emits the per-spec reduction chain: the primary axis (shard
1327 ``reduce_scatter`` or replicate ``all_reduce``) followed by the optional
1328 replicate axis (HSDP ``dp_replicate`` / EDP ``edp_replicate``). When
1329 ``pad_info`` is given the parameter is pad-sharded: the real ``[n, ...]``
1330 gradient is zero-padded on dim 0 to ``[n_pad, ...]`` before the
1331 reduce_scatter, so the scattered local gradient matches the padded live
1332 shard (mirrors eager ``fully_shard``'s padded grad buffer). When
1333 ``replicated`` is True the parameter stays full, so its gradient is
1334 reduced over the primary group with ``all_reduce`` instead of
1335 reduce-scattered — a reduce_scatter would change the shape and desync
1336 the graph from the live model.
1338 Every collective is waited on before its result is consumed. A chained
1339 collective runs on a different process-group stream (HSDP's
1340 reduce_scatter is on ``fsdp`` while the all_reduce is on
1341 ``dp_replicate``), so without the intermediate wait the all_reduce could
1342 read a partially written shard. This mirrors eager ``fully_shard``,
1343 which orders the all_reduce stream after the reduce_scatter stream.
1344 """
1345 group_name, degree = info.group_name, info.degree
1346 replicate_group = info.replicate_group_name
1347 replicate_degree = info.replicate_degree
1348 has_replicate = bool(replicate_group) and replicate_degree > 1
1349 emitted = False
1350 reduced = grad_node
1351 if info.reduction.scale is not None:
1352 reduced = graph.call_function(torch.ops.aten.mul.Tensor, args=(reduced, info.reduction.scale))
1353 if pad_info is not None:
1354 reduced = self._pad_gradient(graph, reduced, grad_node, pad_info)
1355 if replicated and degree > 1:
1356 # Replicated parameter (a 0-dim scalar, a DDP parameter, or a
1357 # partial-plan leftover): average the full gradient over the primary
1358 # group so every replica takes the same optimizer step. DDP's
1359 # primary group *is* the replicate axis, so tag it as such.
1360 ar_node = graph.call_function(
1361 _c10d_functional.all_reduce,
1362 args=(reduced, info.reduction.reduce_op, group_name),
1363 )
1364 if group_name == self._dp_replicate_group_name:
1365 ar_node.meta["comm_type"] = "dp_all_reduce"
1366 ar_node.meta["dp_replicate_degree"] = degree
1367 ar_node.meta["autograd_backward"] = True
1368 else:
1369 ar_node.meta["comm_type"] = "fsdp_all_reduce"
1370 ar_node.meta["fsdp_degree"] = degree
1371 ar_node.meta["autograd_backward"] = True
1372 ar_node.meta["comm_group"] = group_name
1373 reduced = ar_node
1374 emitted = True
1375 if has_replicate:
1376 reduced = self._insert_wait(graph, reduced)
1377 elif not replicated and degree > 1:
1378 # Matmul backward can return a transposed view on NPU, including dense router weights.
1379 reduced = graph.call_function(torch.ops.aten.contiguous.default, args=(reduced,))
1380 rs_node = graph.call_function(
1381 _c10d_functional.reduce_scatter_tensor,
1382 args=(
1383 reduced,
1384 info.reduction.reduce_op,
1385 degree,
1386 group_name,
1387 ),
1388 )
1389 # Native contiguous needs an owner so schedulers can move it with this RS.
1390 reduced.meta.update(autograd_backward=True, fsdp_reduce_scatter_prepare=rs_node.name)
1391 rs_node.meta["comm_type"] = "fsdp_reduce_scatter"
1392 rs_node.meta["comm_group"] = group_name
1393 rs_node.meta["fsdp_degree"] = degree
1394 rs_node.meta["autograd_backward"] = True
1395 reduced = rs_node
1396 emitted = True
1397 # A following replicate-axis all_reduce runs on another stream, so
1398 # wait first; otherwise only the final node is waited on below.
1399 if has_replicate:
1400 reduced = self._insert_wait(graph, reduced)
1402 if has_replicate:
1403 ar_node = graph.call_function(
1404 _c10d_functional.all_reduce,
1405 args=(reduced, info.reduction.reduce_op, replicate_group),
1406 )
1407 ar_node.meta["comm_type"] = "dp_all_reduce"
1408 ar_node.meta["comm_group"] = replicate_group
1409 ar_node.meta["dp_replicate_degree"] = replicate_degree
1410 ar_node.meta["autograd_backward"] = True
1411 reduced = ar_node
1412 emitted = True
1414 return self._insert_wait(graph, reduced) if emitted else reduced
1416 @staticmethod
1417 def _insert_wait(graph: fx.Graph, tensor_node: fx.Node) -> fx.Node:
1418 """Append ``wait_tensor(tensor_node)`` and return the waited node."""
1419 wait_node = graph.call_function(
1420 _c10d_functional.wait_tensor,
1421 args=(tensor_node,),
1422 )
1423 wait_node.meta["wait_for"] = tensor_node.name
1424 wait_node.meta["autograd_backward"] = True
1425 return wait_node
1427 def _build_trainable_state_indices(
1428 self,
1429 state_fqns: List[str],
1430 num_state_inputs: int,
1431 state_is_param: Optional[List[bool]],
1432 model: Optional[nn.Module],
1433 ) -> List[int]:
1434 """
1435 Return state indices of trainable parameters, in ``state_fqns`` order.
1437 Mirrors the tracer's ``params`` list construction (skip buffers via
1438 ``state_is_param``, skip frozen params via ``requires_grad``) so
1439 gradient ``i`` maps to ``trainable_state_indices[i]``. Reproducing this
1440 filter here is what keeps reduce_scatter aligned for models with
1441 buffers or frozen params.
1442 """
1443 if model is None:
1444 # Without the model we cannot inspect requires_grad; fall back to
1445 # the all-trainable assumption. The grad-count check in the caller
1446 # raises if that assumption is wrong, so misalignment is not silent.
1447 return list(range(num_state_inputs))
1449 param_lookup = dict(model.named_parameters(remove_duplicate=False))
1450 trainable: List[int] = []
1451 for idx in range(num_state_inputs):
1452 if state_is_param is not None and not state_is_param[idx]:
1453 continue
1454 param = param_lookup.get(state_fqns[idx])
1455 if param is not None and param.requires_grad:
1456 trainable.append(idx)
1457 return trainable
1459 def _insert_reshard_logic(
1460 self,
1461 graph_module: fx.GraphModule,
1462 param_nodes: List[fx.Node],
1463 pass_config: PassConfig,
1464 ) -> fx.GraphModule:
1465 """Reshard each FSDP parameter after forward (FSDP release).
1467 For every FSDP parameter whose all_gather was inserted by
1468 ``_insert_all_gather_for_params``:
1470 1. Free the replicated full parameter once its last forward reader —
1471 including forward views aliasing it — has run.
1472 2. If the backward still needs the parameter (directly or through a
1473 saved forward view), insert a fresh all_gather just before the
1474 first backward consumer and rematerialize the saved view chain, so
1475 the backward computes the exact same values from the re-gathered
1476 (unsharded) parameter.
1477 3. Free that backward re-gather once its last backward reader runs.
1479 Steps 1-3 keep only the forward working set resident during forward and
1480 only the active layer's parameter resident during backward, instead of
1481 every replicated parameter for the whole joint graph.
1483 No-op when ``fsdp_reshard_after_forward`` is disabled.
1484 """
1485 if not pass_config.fsdp_reshard_after_forward:
1486 return graph_module
1488 for param_node in param_nodes:
1489 record = self._unsharded_params.get(param_node.name)
1490 if record is None:
1491 continue
1492 self._reshard_param(graph_module.graph, record)
1493 return graph_module
1495 def _reshard_param(self, graph: fx.Graph, record: _UnshardedParam) -> None:
1496 """Reshard one FSDP parameter (free + backward re-gather/remat)."""
1497 wait = record.wait_node
1498 alias_nodes = self._alias_descendants(wait)
1499 order = {n: i for i, n in enumerate(graph.nodes)}
1501 # Alias (view) descendants the backward reads must be rematerialized
1502 # from the re-gathered parameter; the unsharded tensor itself may be
1503 # consumed directly by the backward in some models.
1504 needed = [
1505 n for n in [wait, *alias_nodes] if self._feeds_backward(n, alias_nodes)
1506 ]
1508 # Remat plan first: the forward free is only safe once every backward
1509 # consumer has been rewired onto fresh (re-gathered) storage. If the
1510 # view chain cannot be cloned, keep the previous resident-for-the-graph
1511 # behavior — a missed free costs memory, a misordered one is unsound.
1512 if self._rematerialize_for_backward(graph, record, needed, order):
1513 # 1. Free after the last forward data read of the unsharded storage.
1514 self._insert_reshard_free(graph, wait, record, order, backward=False)
1516 def _rematerialize_for_backward(
1517 self,
1518 graph: fx.Graph,
1519 record: _UnshardedParam,
1520 needed: List[fx.Node],
1521 order: Dict[fx.Node, int],
1522 ) -> bool:
1523 """Re-gather ahead of the first backward consumer and remat views.
1525 The saved forward view chain is cloned against the re-gathered
1526 parameter so the backward reads identical values from a fresh,
1527 correctly-sized tensor.
1529 Returns:
1530 ``True`` when the free may proceed — no backward consumer exists,
1531 or every one of them was rewired onto rematerialized storage.
1532 ``False`` when a needed view cannot be cloned; the caller must
1533 keep the unsharded parameter resident.
1534 """
1535 backward_users = [
1536 u for n in needed for u in n.users if u.meta.get("autograd_backward", False)
1537 ]
1538 if not backward_users:
1539 return True
1541 wait = record.wait_node
1542 uncloneable = [n for n in needed if n is not wait and not self._cloneable(n)]
1543 if uncloneable:
1544 _LOG.warning(
1545 "FSDP reshard: cannot rematerialize %s for '%s'; keeping the "
1546 "unsharded parameter resident",
1547 [n.format_node() for n in uncloneable],
1548 record.param_node.meta.get("param_name"),
1549 )
1550 return False
1552 anchor = min(backward_users, key=lambda u: order.get(u, len(order)))
1553 wait2 = self._insert_backward_gather(graph, record, anchor)
1555 recreate: Dict[fx.Node, fx.Node] = {wait: wait2}
1556 last_inserted = wait2
1557 for node in sorted(
1558 (n for n in needed if n is not wait), key=lambda n: order[n]
1559 ):
1560 last_inserted = self._clone_with_remap(
1561 graph, node, recreate, wait, wait2, last_inserted
1562 )
1564 self._rewire_backward_users(recreate)
1565 self._insert_reshard_free(graph, wait2, record, order, backward=True)
1566 return True
1568 @staticmethod
1569 def _cloneable(node: fx.Node) -> bool:
1570 """Whether ``node`` can be cloned as a rematerialized view op."""
1571 return node.op == "call_function" and callable(node.target)
1573 def _insert_backward_gather(
1574 self, graph: fx.Graph, record: _UnshardedParam, anchor: fx.Node
1575 ) -> fx.Node:
1576 """Insert the backward all_gather + wait pair before ``anchor``."""
1577 group_name, degree = self._param_group(
1578 record.param_node.meta.get("param_name", "")
1579 )
1580 with graph.inserting_before(anchor):
1581 gather_input = _gather_input(graph, record.param_node)
1582 if gather_input is not record.param_node:
1583 gather_input.meta["autograd_backward"] = True
1584 ag_node = graph.call_function(
1585 _c10d_functional.all_gather_into_tensor,
1586 args=(gather_input, degree, group_name),
1587 )
1588 dtype = record.param_node.meta.get("fsdp_compute_dtype")
1589 if dtype is not None:
1590 ag_node.meta["fsdp_compute_dtype"] = dtype
1591 ag_node.meta["comm_type"] = "fsdp_all_gather_backward"
1592 ag_node.meta["comm_group"] = group_name
1593 ag_node.meta["param_node"] = record.param_node.name
1594 ag_node.meta["param_name"] = record.param_node.meta.get("param_name")
1595 ag_node.meta["state_idx"] = record.param_node.meta.get("state_idx")
1596 ag_node.meta["fsdp_degree"] = degree
1597 ag_node.meta["fsdp_unsharded_nbytes"] = record.param_node.meta.get(
1598 "fsdp_unsharded_nbytes"
1599 )
1600 # This gather lives in the backward half; tag it so downstream
1601 # passes (e.g. PpPass phase classification) do not mistake it and
1602 # its remat clones for forward nodes — their only arg is a forward
1603 # state placeholder, which would otherwise imply the forward phase.
1604 ag_node.meta["autograd_backward"] = True
1605 with graph.inserting_before(anchor):
1606 wait_node = graph.call_function(
1607 _c10d_functional.wait_tensor, args=(ag_node,)
1608 )
1609 wait_node.meta["wait_for"] = ag_node.name
1610 wait_node.meta["autograd_backward"] = True
1611 return wait_node
1613 def _clone_with_remap(
1614 self,
1615 graph: fx.Graph,
1616 node: fx.Node,
1617 recreate: Dict[fx.Node, fx.Node],
1618 wait: fx.Node,
1619 wait2: fx.Node,
1620 insert_after: fx.Node,
1621 ) -> fx.Node:
1622 """Clone ``node`` after ``insert_after``, remapping args to re-gathers."""
1623 args = tuple(self._remap_arg(a, recreate, wait, wait2) for a in node.args)
1624 kwargs = {
1625 k: self._remap_arg(v, recreate, wait, wait2) for k, v in node.kwargs.items()
1626 }
1627 with graph.inserting_after(insert_after):
1628 clone = graph.call_function(node.target, args=args, kwargs=kwargs)
1629 self._copy_recreated_meta(node, clone)
1630 # Rematerialized views serve the backward half, so they carry the
1631 # backward phase (see ``_insert_backward_gather``).
1632 clone.meta["autograd_backward"] = True
1633 recreate[node] = clone
1634 return clone
1636 @staticmethod
1637 def _rewire_backward_users(recreate: Dict[fx.Node, fx.Node]) -> None:
1638 """Point every backward consumer of an original node at its clone."""
1639 for original, clone in recreate.items():
1640 for user in list(original.users):
1641 if user.meta.get("autograd_backward", False):
1642 user.replace_input_with(original, clone)
1644 def _insert_reshard_free(
1645 self,
1646 graph: fx.Graph,
1647 tensor: fx.Node,
1648 record: _UnshardedParam,
1649 order: Dict[fx.Node, int],
1650 backward: bool,
1651 ) -> None:
1652 """Free ``tensor``'s storage after its last reader in the phase."""
1653 last_reader = self._last_data_reader(tensor, order, backward=backward)
1654 if last_reader is None:
1655 return
1656 comm_type = "fsdp_reshard_free_backward" if backward else "fsdp_reshard_free"
1657 with graph.inserting_after(last_reader):
1658 free_node = graph.call_function(_free_tensor_storage, args=(tensor,))
1659 free_node.meta["comm_type"] = comm_type
1660 free_node.meta["param_name"] = record.param_node.meta.get("param_name")
1661 if backward:
1662 free_node.meta["autograd_backward"] = True
1664 def _alias_descendants(self, root: fx.Node) -> Set[fx.Node]:
1665 """Forward view descendants of ``root`` (nodes aliasing its storage).
1667 Only aliasing ops propagate: an op that allocates a new tensor
1668 (``mm``, ``addmm``, ``relu``, ...) copies the data out, so freeing
1669 ``root``'s storage does not invalidate it and it need not be
1670 rematerialized. Backward nodes terminate the walk.
1671 """
1672 alias: Set[fx.Node] = set()
1673 stack = [root]
1674 while stack:
1675 current = stack.pop()
1676 for user in current.users:
1677 if user is root or user in alias:
1678 continue
1679 if user.meta.get("autograd_backward", False):
1680 continue
1681 if current not in set(_iter_arg_nodes(user)):
1682 continue
1683 if not self._propagates_alias(user):
1684 continue
1685 alias.add(user)
1686 stack.append(user)
1687 return alias
1689 @staticmethod
1690 def _propagates_alias(node: fx.Node) -> bool:
1691 """Whether ``node``'s output aliases its already-aliasing input.
1693 Two forms propagate. Schema-declared view returns (``aten.t``,
1694 ``aten.slice``, ...), and ``operator.getitem`` picking one output of a
1695 multi-output view op such as ``aten.chunk`` / ``aten.split`` /
1696 ``aten.unbind`` — getitem itself has no schema, so the alias must be
1697 inherited from the indexed producer (which the caller has already
1698 established is in the alias closure).
1699 """
1700 if node.op != "call_function":
1701 return False
1702 if node.target is _GETITEM:
1703 return True
1704 schema = getattr(node.target, "_schema", None)
1705 if schema is None:
1706 return False
1707 return any(ret.alias_info is not None for ret in schema.returns)
1709 def _feeds_backward(self, node: fx.Node, alias_nodes: Set[fx.Node]) -> bool:
1710 """Whether ``node`` (or an aliasing descendant) is read by backward."""
1711 memo: Dict[fx.Node, bool] = {}
1713 def visit(current: fx.Node) -> bool:
1714 """Whether ``current`` or an aliasing descendant reaches backward.
1716 Args:
1717 current: Node to test.
1719 Returns:
1720 True when a backward node consumes the node or its aliases.
1721 """
1722 if current in memo:
1723 return memo[current]
1724 memo[current] = False # cycle guard (aliasing is a DAG)
1725 result = False
1726 for user in current.users:
1727 if user.meta.get("autograd_backward", False):
1728 result = True
1729 break
1730 if user in alias_nodes and visit(user):
1731 result = True
1732 break
1733 memo[current] = result
1734 return result
1736 return visit(node)
1738 def _last_data_reader(
1739 self, root: fx.Node, order: Dict[fx.Node, int], backward: bool
1740 ) -> Optional[fx.Node]:
1741 """Latest, in graph order, op that reads ``root``'s storage data.
1743 Walks the alias (view) chain so a free is not placed after a view
1744 *creation* but before the non-view op that actually reads it: freeing
1745 between ``t_2 = t(w)`` and ``mm(grad, t_2)`` would invalidate ``t_2``.
1746 Multi-output views reach their consumers through ``getitem``, so the
1747 walk continues through those picks instead of mistaking them for the
1748 final reader. ``backward=False`` picks the last forward read (free
1749 point for the unsharded parameter); ``backward=True`` the last
1750 backward read (free point for the backward re-gather).
1751 """
1752 last: Optional[fx.Node] = None
1753 last_pos = -1
1754 seen: Set[fx.Node] = set()
1755 stack = [root]
1756 while stack:
1757 current = stack.pop()
1758 if current in seen:
1759 continue
1760 seen.add(current)
1761 for user in current.users:
1762 if user.op == "output":
1763 continue
1764 if self._propagates_alias(user) and current in set(
1765 _iter_arg_nodes(user)
1766 ):
1767 stack.append(user)
1768 continue
1769 if bool(user.meta.get("autograd_backward", False)) != backward:
1770 continue
1771 pos = order.get(user, -1)
1772 if pos > last_pos:
1773 last_pos = pos
1774 last = user
1775 return last
1777 @classmethod
1778 def _remap_arg(
1779 cls,
1780 arg: Any,
1781 recreate: Dict[fx.Node, fx.Node],
1782 wait: fx.Node,
1783 wait2: fx.Node,
1784 ) -> Any:
1785 """Rewrite an op arg for a rematerialized clone (nested containers)."""
1786 if arg is wait:
1787 return wait2
1788 if isinstance(arg, fx.Node):
1789 return recreate.get(arg, arg)
1790 if isinstance(arg, tuple):
1791 return tuple(cls._remap_arg(a, recreate, wait, wait2) for a in arg)
1792 if isinstance(arg, list):
1793 return [cls._remap_arg(a, recreate, wait, wait2) for a in arg]
1794 if isinstance(arg, dict):
1795 return {k: cls._remap_arg(v, recreate, wait, wait2) for k, v in arg.items()}
1796 return arg
1798 @staticmethod
1799 def _copy_recreated_meta(original: fx.Node, clone: fx.Node) -> None:
1800 """Copy the module/stack/shape metadata a remat clone needs."""
1801 for key in (
1802 "nn_module_stack",
1803 "custom",
1804 "stack_trace",
1805 "tensor_meta",
1806 "val",
1807 ):
1808 value = original.meta.get(key)
1809 if value is not None:
1810 clone.meta[key] = value