Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / compile / tracer / graph_tracer.py: 94%
278 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# Portions copyright (c) Meta Platforms, Inc. and affiliates.
2# Licensed under the BSD-3-Clause license; see
3# Third_Party_Open_Source_Software_Notice.
4# Copyright 2026 Huawei Technologies Co., Ltd
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17# ============================================================================
18# Tracer reaches into torch internals (torch._dynamo, torch.nn.utils.stateless,
19# torch.utils._pytree) for joint-graph capture; these have no public API.
20# pylint: disable=E1136,E1129,W0212
21"""
22Graph Tracer - Model Graph Tracer (make_fx + autograd.grad)
24Traces a model into a joint Forward + Backward FX graph, following
25the design of torchtitan's ``experiments/graph_trainer/minimal_fx_tracer``:
271. Module parameters/buffers are extracted from the live model into flat
28 tensors and threaded through the graph as **static inputs** (leading
29 placeholders) instead of ``get_attr`` nodes, via
30 ``torch.nn.utils.stateless._reparametrize_module``. The graph therefore
31 contains no parameter ``get_attr`` nodes, and passes can split the graph by
32 reshaping the static-input placeholders.
342. The forward pass runs ``torch.autograd.grad(loss, params)`` *inside* the
35 traced function body. For that to be traceable the engine backward must be
36 patched (``torch.compiler._patch_engine_backward()``) and backward must run
37 on the calling thread (``torch.autograd.set_multithreading_enabled(False)``),
38 otherwise the C++ autograd engine dispatches backward to a worker thread
39 with a fresh ``contextvars.Context`` and the tracing context is lost.
413. The whole trace runs under ``FakeTensorMode(allow_non_fake_inputs=True)``
42 plus a non-strict tracing context, ``preserve_node_meta()`` and
43 ``_skip_nested_compile()``, mirroring the torchtitan tracer.
45The joint graph is executed with ``torch.no_grad()`` at runtime: it already
46contains the explicit backward ops, and a redundant autograd graph on top
47would keep every forward intermediate alive via ``grad_fn`` references.
48"""
50from __future__ import annotations
52__all__ = [
53 "JointGraph",
54 "trace_model_graph",
55 "run_traced_graph",
56 "extract_module_state",
57]
59import contextlib
60import copy
61import inspect
62import warnings
63from collections.abc import Callable, Generator
64from collections import deque
65from contextlib import contextmanager
66from dataclasses import dataclass
67from typing import Any, Dict, List
69import torch
70from torch import nn
71from torch._decomp import get_decompositions
72from torch._guards import tracing, TracingContext
73from torch._subclasses import FakeTensorMode
74from torch.fx.experimental.proxy_tensor import make_fx
75from torch.fx.experimental.symbolic_shapes import ShapeEnv
76from torch.fx.passes.runtime_assert import insert_deferred_runtime_asserts
77from torch.fx.traceback import preserve_node_meta
78from torch.nn.utils import stateless
80from ..mixed_precision import GraphMixedPrecision
81from .dynamic_shapes import InputGuards, build_symbolic_inputs
83# Older torch's make_fx predates record_stack_traces / record_module_stack
84# and rejects unknown kwargs; forward only the kwargs this torch supports.
85# The joint graph still captures without record_stack_traces -- the fwd->bw
86# metadata copy skips a missing stack_trace instead of failing.
87try:
88 _MAKE_FX_PARAMS = inspect.signature(make_fx).parameters
89except (ValueError, TypeError):
90 _MAKE_FX_PARAMS = {}
91_MAKE_FX_KWARGS: Dict[str, Any] = {
92 kw: val
93 for kw, val in (("record_stack_traces", True), ("record_module_stack", True))
94 if kw in _MAKE_FX_PARAMS
95}
97# Tensors and make_fx-safe primitives are allowed as graph leaves.
98# Everything else (callables, custom objects) must be captured in the
99# train_fn closure or registered as pytree constants.
100_ALLOWED_LEAF_TYPES = (torch.Tensor, int, float, bool, str, type(None))
103@contextmanager
104def _skip_nested_compile() -> Generator[None, None, None]:
105 """Tell dynamo to inline ``torch.compile``'d functions during make_fx tracing.
107 make_fx cannot trace through torch.compile'd functions (e.g. compiled
108 attention kernels). Setting ``error_on_nested_fx_trace`` to False makes
109 dynamo silently inline the wrapped function instead of raising.
110 """
111 prev = torch._dynamo.config.error_on_nested_fx_trace
112 torch._dynamo.config.error_on_nested_fx_trace = False
113 try:
114 yield
115 finally:
116 torch._dynamo.config.error_on_nested_fx_trace = prev
119@contextmanager
120def _patch_engine_backward() -> Generator[None, None, None]:
121 """No-op fallback for torch versions without the patched autograd engine.
123 ``torch.compiler._patch_engine_backward`` makes ``torch.autograd.grad``
124 inside a make_fx-traced function emit backward ops as FX nodes instead of
125 running a real autograd backward. Present in torchtitan's patched torch;
126 absent in stock torch, where joint-graph capture of ``autograd.grad`` is
127 not supported at all.
128 """
129 patcher = getattr(torch.compiler, "_patch_engine_backward", None)
130 if patcher is None:
131 warnings.warn(
132 "torch.compiler._patch_engine_backward not available. "
133 "Joint-graph capture of autograd.grad may not work correctly. "
134 "Consider using torchtitan's patched torch or a newer torch version.",
135 RuntimeWarning,
136 stacklevel=2,
137 )
138 yield
139 else:
140 with patcher():
141 yield
144@contextmanager
145def _non_strict_tracing_context() -> Generator[None, None, None]:
146 """Mark this make_fx pass as the non-strict tracing flow.
148 Required by ``_patch_engine_backward``; no-op fallback on stock torch.
149 """
150 ctx = getattr(torch.compiler, "_non_strict_tracing_context", None)
151 if ctx is None:
152 yield
153 else:
154 with ctx():
155 yield
158@dataclass
159class JointGraph:
160 """
161 Joint forward-backward computation graph
163 Features:
164 - No parallel information
165 - Parameters, activations, gradients are all complete tensors
166 - Forward + Loss + Backward complete joint graph
167 - Parameters/buffers are static graph inputs (leading placeholders),
168 not ``get_attr`` nodes
169 """
171 graph_module: torch.fx.GraphModule
172 # Storage-free descriptors of the tracing-time user inputs (shape/dtype
173 # for tensors) via ``_input_meta``. Real sample tensors are deliberately
174 # not kept: they would pin their storage for the whole training run. The
175 # FakeTensor counterparts live in ``example_inputs``.
176 inputs: List[Any]
177 outputs: List[Any]
178 param_names: List[str]
179 param_shapes: Dict[str, tuple]
180 num_layers: int
181 # Trace-time parameter/buffer values (flat, in graph placeholder order)
182 # and their FQNs. ``state_fqns`` is the authoritative order for feeding
183 # runtime parameter state into the graph.
184 state_fqns: List[str]
185 example_inputs: tuple
186 input_guards: InputGuards | None = None
189def extract_module_state(mod: nn.Module) -> Dict[str, torch.Tensor]:
190 """Return a merged dict of the module's named parameters and buffers.
192 Tied tensors (e.g. an ``lm_head.weight`` sharing storage with
193 ``embed_tokens.weight``) are DEDUPLICATED to a single entry: the graph
194 threads each unique tensor as one static input, so emitting one entry per
195 alias would double the placeholder count, duplicate every FSDP collective,
196 and make ``torch.autograd.grad`` return (and the compiler add) the same
197 gradient once per alias. The missing aliases are re-materialized only for
198 tracing, via ``_reparametrize_train_state``'s ``tie_weights=True``.
199 """
200 return {
201 **dict(mod.named_parameters(remove_duplicate=True)),
202 **dict(mod.named_buffers(remove_duplicate=True)),
203 }
206@contextlib.contextmanager
207def _reparametrize_train_state(
208 module: nn.Module,
209 model_state: Dict[str, torch.Tensor],
210):
211 """Rebind ``module``'s parameters/buffers to explicit trace-time tensors.
213 Inside the traced function this swaps in the fake/static tensors so every
214 parameter access in the model goes through the graph's static inputs.
216 ``tie_weights=True`` re-adds, for the duration of the trace, the alias
217 keys that ``extract_module_state`` deduplicated — mapping each alias to
218 the SAME static tensor. Both tied uses then reference one ``fx.Node``, so
219 the traced graph keeps a single placeholder (and a single gradient) for
220 the shared tensor instead of a baked-in ``get_attr`` constant.
221 """
222 with contextlib.ExitStack() as stack:
223 stack.enter_context(
224 stateless._reparametrize_module(module, model_state, tie_weights=True)
225 )
226 yield
229def _iter_node_args(node: torch.fx.Node):
230 """Yield every ``fx.Node`` among ``node.args`` (unwrapping nested lists)."""
231 for a in node.args:
232 if isinstance(a, torch.fx.Node):
233 yield a
234 elif isinstance(a, (tuple, list)):
235 for x in a:
236 if isinstance(x, torch.fx.Node):
237 yield x
240def _output_args(fx_g: torch.fx.GraphModule) -> List[torch.fx.Node]:
241 """Return the flattened forward arg list of the graph's ``output`` node."""
242 out_node = next((n for n in fx_g.graph.nodes if n.op == "output"), None)
243 if out_node is None:
244 return []
245 args: List[torch.fx.Node] = []
246 for a in out_node.args:
247 if isinstance(a, torch.fx.Node):
248 args.append(a)
249 elif isinstance(a, (tuple, list)):
250 for x in a:
251 if isinstance(x, torch.fx.Node):
252 args.append(x)
253 return args
256def _ancestors_of(node: torch.fx.Node) -> set:
257 """Return the transitive producers of ``node`` (excluding ``node``)."""
258 ancestors = set()
259 dq = deque([node])
260 while dq:
261 cur = dq.popleft()
262 for a in _iter_node_args(cur):
263 if a.op == "placeholder" or a in ancestors:
264 continue
265 ancestors.add(a)
266 dq.append(a)
267 return ancestors
270def _has_module_stack(node: torch.fx.Node) -> bool:
271 """True if the node carries any ``nn_module_stack`` entry.
273 make_fx leaves stack-less nodes (e.g. autograd engine output) with an
274 *empty* ``OrderedDict`` rather than ``None``, so a truthiness check is
275 the robust test.
276 """
277 return bool(node.meta.get("nn_module_stack"))
280def _annotate_autograd_backward(fx_g: torch.fx.GraphModule) -> None:
281 """Tag backward nodes with ``meta['autograd_backward'] = True``.
283 Stock torch's make_fx (without the torchtitan ``_patch_engine_backward``
284 hook) never attaches the autograd engine's ``autograd_backward`` tag, so
285 passes that split the joint graph into fwd/bwd halves get nothing to key
286 on. This reconstructs the tag structurally.
288 The joint graph's ``output`` returns ``[loss, grad_0, ... grad_n]``. The
289 loss and the nodes feeding it (logits, loss reduction, ``getitem`` of the
290 loss value) are forward even though they live outside any module and so
291 carry no ``nn_module_stack``. Every other output is a parameter gradient
292 produced by ``torch.autograd.grad``.
294 Two pre-computed sets separate the halves:
296 - ``fwd_loss_nodes``: the transitive producers of ``loss`` — the logits,
297 the shift/reshape that makes the loss target, and the loss reduction
298 itself. These are forward (they are the loss *source*); backward is
299 computed *from* them.
300 - ``bwd_nodes``: ``call_function`` nodes reachable from the parameter
301 gradients (``output[1:]``) that carry no ``nn_module_stack`` and are
302 not in ``fwd_loss_nodes``. The module stack is only recorded while a
303 traced module ``forward`` runs, so autograd-engine nodes have none.
304 Walking backward and stopping at forward boundaries (stack-bearing
305 nodes or the loss source) spans exactly the backward half.
306 """
307 output = _output_args(fx_g)
308 if not output:
309 return
310 loss_node = output[0]
311 grad_seeds = output[1:]
313 # Forward loss chain: everything that flows INTO the loss. Backward is
314 # computed from the loss, so these are forward regardless of whether any
315 # module recorded them (they may sit in ``train_fn``, outside modules).
316 fwd_loss_nodes = _ancestors_of(loss_node)
317 fwd_loss_nodes.add(loss_node)
319 # BFS backward over dataflow from the gradient outputs, marking every
320 # stack-less, non-loss-source node as backward. Stack-bearing nodes are
321 # forward (module boundaries); loss-source nodes are forward (the loss is
322 # the backward's *source*, not part of it).
323 bwd_nodes = set()
324 dq = deque()
325 for seed in grad_seeds:
326 if (
327 not _has_module_stack(seed)
328 and seed.op != "placeholder"
329 and seed not in fwd_loss_nodes
330 ):
331 bwd_nodes.add(seed)
332 dq.append(seed)
333 while dq:
334 n = dq.popleft()
335 for a in _iter_node_args(n):
336 if a.op == "placeholder" or a in bwd_nodes:
337 continue
338 if a in fwd_loss_nodes:
339 continue # forward loss source; do not expand
340 if _has_module_stack(a):
341 continue # forward module boundary; do not expand
342 bwd_nodes.add(a)
343 dq.append(a)
345 for node in bwd_nodes:
346 node.meta["autograd_backward"] = True
349def _copy_fwd_metadata_to_bw_nodes(fx_g: torch.fx.GraphModule) -> None:
350 """Copy forward metadata to backward nodes across all nested FX subgraphs.
352 Uses a two-pass approach over all submodule graphs (including HOP
353 subgraphs). Pass 1 collects forward nodes by ``seq_nr``; pass 2 copies
354 ``custom``/``nn_module_stack``/``stack_trace`` from the matching forward
355 node to each backward node. Backward nodes are identified by the autograd
356 engine's ``autograd_backward`` tag on ``node.meta``.
357 """
358 seq_nr_to_fwd_node: Dict[int, torch.fx.Node] = {}
359 for node in _iter_seq_nr_nodes(fx_g, backward=False):
360 seq_nr_to_fwd_node.setdefault(node.meta["seq_nr"], node)
362 for node in _iter_seq_nr_nodes(fx_g, backward=True):
363 fwd_node = seq_nr_to_fwd_node.get(node.meta["seq_nr"])
364 if fwd_node is None or fwd_node is node:
365 continue
366 _copy_fwd_meta(fwd_node, node)
369def _iter_seq_nr_nodes(fx_g: torch.fx.GraphModule, backward: bool):
370 """Yield ``seq_nr``-bearing call/get_attr nodes across all subgraphs.
372 ``backward=False`` yields forward nodes, ``backward=True`` backward ones
373 (tagged by the autograd engine's ``autograd_backward`` meta).
374 """
375 for submod in fx_g.modules():
376 if not isinstance(submod, torch.fx.GraphModule):
377 continue
378 for node in submod.graph.nodes:
379 if (
380 node.op not in ("call_function", "get_attr")
381 or "seq_nr" not in node.meta
382 or node.meta.get("autograd_backward", False) != backward
383 ):
384 continue
385 yield node
388def _copy_fwd_meta(fwd_node: torch.fx.Node, node: torch.fx.Node) -> None:
389 """Copy ``custom``/``nn_module_stack``/``stack_trace`` from fwd to bwd."""
390 custom = fwd_node.meta.get("custom")
391 if custom:
392 node.meta.setdefault("custom", {}).update(copy.deepcopy(custom))
393 nn_module_stack = fwd_node.meta.get("nn_module_stack")
394 if nn_module_stack is not None:
395 node.meta["nn_module_stack"] = nn_module_stack.copy()
396 stack_trace = fwd_node.meta.get("stack_trace")
397 if stack_trace is not None:
398 node.meta["stack_trace"] = stack_trace
401def _fakeify_input(fake_mode: FakeTensorMode, x: Any) -> Any:
402 """Convert a real tensor input into its fake counterpart."""
403 if not isinstance(x, torch.Tensor):
404 return x
405 return fake_mode.from_tensor(x, static_shapes=True)
408def _input_meta(x: Any) -> Any:
409 """Return a storage-free descriptor of a traced user input.
411 Tensors become shape/dtype metadata; primitives pass through; pytree
412 containers (list/tuple/dict) are converted recursively. Used for
413 ``JointGraph.inputs`` so the joint graph never pins the real sample
414 tensors' storage for the lifetime of training.
415 """
416 if isinstance(x, torch.Tensor):
417 return {"shape": tuple(x.shape), "dtype": str(x.dtype)}
418 if isinstance(x, tuple):
419 return tuple(_input_meta(v) for v in x)
420 if isinstance(x, list):
421 return [_input_meta(v) for v in x]
422 if isinstance(x, dict):
423 return {k: _input_meta(v) for k, v in x.items()}
424 return x
427def _validate_trace_leaves(leaves: list[Any]) -> None:
428 """Reject state or input objects that cannot become explicit FX inputs."""
429 for leaf in leaves:
430 if isinstance(leaf, nn.Module):
431 raise ValueError(
432 "trace_model_graph requires explicit tensor state, not "
433 "nn.Module instances. Capture nn.Modules in train_fn's closure."
434 )
435 if not isinstance(leaf, _ALLOWED_LEAF_TYPES):
436 raise ValueError(
437 "trace_model_graph requires all pytree leaves in "
438 f"state/args to be tensors or primitives (int/float/bool/str), "
439 f"got {type(leaf).__name__}."
440 )
443def _make_fwd_bwd_fn(
444 model: nn.Module,
445 train_fn: Callable,
446 state_fqns: list[str],
447 state_is_param: list[bool],
448 state_spec: Any,
449 user_inputs_spec: Any,
450 mixed_precision: GraphMixedPrecision | None = None,
451) -> tuple[Callable, list[str]]:
452 """Build the joint callable and its named-loss output metadata."""
453 num_state_inputs = len(state_fqns)
454 # ``_fwd_bwd_fn`` communicates the traced ``loss_dict`` key order to the
455 # enclosing scope through this box (plain closure writes cannot escape
456 # the nested ``def``); the keys are attached to the GraphModule below.
457 loss_dict_keys_box: list[str] = []
459 def _fwd_bwd_fn(*plain_args):
460 state_wrapped = plain_args[:num_state_inputs]
461 user_wrapped = plain_args[num_state_inputs:]
462 state_t = torch.utils._pytree.tree_unflatten(list(state_wrapped), state_spec)
463 user_args = torch.utils._pytree.tree_unflatten(
464 list(user_wrapped), user_inputs_spec
465 )
466 model_state = state_t["model"]
467 if mixed_precision is not None:
468 model_state = mixed_precision.cast_state(model_state)
470 with (
471 _reparametrize_train_state(model, model_state),
472 _patch_engine_backward(),
473 ):
474 out = train_fn(model, **user_args)
476 # ``train_fn`` may return either a bare loss tensor or the
477 # ``(loss, loss_dict)`` pair produced by the trainer's
478 # ``postforward``. The named loss_dict values are emitted as
479 # graph outputs AFTER the gradients so passes that assume
480 # ``output[0] == loss`` and ``output[1:] == grads`` keep working
481 # once they trim the trailing loss_dict outputs.
482 if (
483 isinstance(out, tuple)
484 and len(out) == 2
485 and isinstance(out[1], dict)
486 ):
487 loss, loss_dict = out
488 loss_dict_keys = list(loss_dict.keys())
489 loss_dict_keys_box.extend(loss_dict_keys)
490 loss_dict_values = [loss_dict[key] for key in loss_dict_keys]
491 else:
492 loss, loss_dict_keys, loss_dict_values = out, [], []
494 # Differentiate compute weights. An autograd cast back to the storage
495 # dtype here would round the gradient before the reduction cast.
496 params = {fqn: model_state[fqn] for fqn, is_param in zip(state_fqns, state_is_param)
497 if is_param and model_state[fqn].requires_grad}
498 grads = torch.autograd.grad(loss, tuple(params.values()), allow_unused=True)
500 # Replace None grads with zeros so the output arity is stable.
501 processed_grads = []
502 for (name, param), grad in zip(params.items(), grads):
503 if grad is None:
504 grad = torch.zeros_like(param)
505 if mixed_precision is not None:
506 grad = mixed_precision.cast_gradient(name, grad)
507 processed_grads.append(grad)
509 return [loss] + processed_grads + loss_dict_values
511 return _fwd_bwd_fn, loss_dict_keys_box
514def _annotate_fsdp_compute_dtypes(
515 graph_module: torch.fx.GraphModule,
516 model_state: dict[str, torch.Tensor],
517 mixed_precision: GraphMixedPrecision,
518 num_inputs: int,
519) -> None:
520 """Record the compute dtype on state placeholders for the FSDP pass."""
521 placeholders = graph_module.graph.find_nodes(op="placeholder")
522 if len(placeholders) != num_inputs:
523 raise ValueError(f"Expected {num_inputs} graph input placeholders, got {len(placeholders)}")
524 for (name, value), node in zip(model_state.items(), placeholders):
525 dtype, _ = mixed_precision.parameter_dtypes.get(name, (None, None))
526 if dtype is not None and value.is_floating_point():
527 node.meta["fsdp_compute_dtype"] = dtype
530def trace_model_graph( # pylint: disable=too-many-locals
531 model: torch.nn.Module,
532 train_fn: Callable,
533 inputs: Dict[str, Any],
534 *,
535 dynamic: bool = False,
536 dynamic_arg_dims: dict[str, int | list[int]] | None = None,
537 mixed_precision: GraphMixedPrecision | None = None,
538) -> JointGraph:
539 """
540 Trace model to generate complete forward + backward graph
542 Args:
543 model: Model (no parallel wrapping)
544 train_fn: Training function signature:
545 ``train_fn(model, **inputs) -> loss``
546 inputs: Model inputs, forwarded to ``train_fn`` as keyword arguments
547 dynamic: Symbolize all user tensor dimensions when no explicit mapping is supplied.
548 dynamic_arg_dims: Dotted input paths to dynamic dimensions (supports negative indices).
549 Providing a mapping enables selective symbolic tracing, even when dynamic is False.
550 Parameters and buffers always remain static.
551 mixed_precision: Resolved FSDP policy for capture without eager HSDP hooks.
553 Returns:
554 JointGraph: Joint forward-backward computation graph
556 Note:
557 Static tracing remains the default. Dynamic traces retain shape guards;
558 incompatible shapes or shape-dependent branches raise before execution.
559 """
560 # Extract module state (parameters/buffers) into flat tensors threaded
561 # through the graph as static inputs (leading placeholders).
562 model_state = extract_module_state(model)
563 state_fqns = list(model_state.keys())
564 # Which leading state inputs are parameters (vs buffers). FSDP shards
565 # parameters only: buffers -- e.g. the non-persistent RoPE ``cache`` --
566 # are full-rank by nature and must flow through as plain inputs, never
567 # all-gathered. ``state_is_param`` is indexed by state position, aligned
568 # with ``state_fqns``.
569 param_fqns = set(dict(model.named_parameters(remove_duplicate=False)).keys())
570 state_is_param = [fqn in param_fqns for fqn in state_fqns]
571 state_flat, state_spec = torch.utils._pytree.tree_flatten({"model": model_state})
573 # user_inputs is a plain dict so the traced closure unpacks it back into
574 # train_fn's keyword arguments.
575 user_inputs = inputs
576 user_inputs_flat, user_inputs_spec = torch.utils._pytree.tree_flatten(user_inputs)
578 _validate_trace_leaves([*state_flat, *user_inputs_flat])
580 full_args = list(state_flat) + list(user_inputs_flat)
582 if not isinstance(dynamic, bool):
583 raise ValueError("dynamic must be a bool")
584 symbolic = dynamic or dynamic_arg_dims is not None
585 if symbolic:
586 fake_mode, fake_args = build_symbolic_inputs(state_flat, inputs, dynamic_arg_dims)
587 else:
588 fake_mode = FakeTensorMode(allow_non_fake_inputs=True, shape_env=ShapeEnv(), static_shapes=True)
589 fake_args = tuple(_fakeify_input(fake_mode, value) for value in full_args)
590 num_state_inputs = len(state_flat)
592 _fwd_bwd_fn, loss_dict_keys_box = _make_fwd_bwd_fn( # pylint: disable=C0103
593 model, train_fn, state_fqns, state_is_param, state_spec, user_inputs_spec, mixed_precision
594 )
596 # make_fx only records ``nn_module_stack`` when the traced callable
597 # carries ``_orig_mod``: its ``_init_modes_from_inputs`` then installs a
598 # ``_ModuleStackTracer`` that captures which module's ``forward`` was
599 # executing as each node is created. Forward nodes thereby gain the
600 # module-stack metadata ``PpPass._stage_from_stack`` needs to map a node
601 # to its pipeline stage. Backward nodes are annotated separately (see
602 # ``_annotate_autograd_backward``), after tracing.
603 _fwd_bwd_fn._orig_mod = model # type: ignore[attr-defined]
605 ctx = TracingContext(fake_mode)
606 with (
607 fake_mode,
608 tracing(ctx),
609 preserve_node_meta(),
610 _skip_nested_compile(),
611 torch.autograd.set_multithreading_enabled(False),
612 _non_strict_tracing_context(),
613 mixed_precision.module_casts() if mixed_precision is not None else contextlib.nullcontext(),
614 ):
615 # Native constant padding can specialize SymInt sizes (notably on
616 # NPU). Its upstream decomposition preserves causal-LM label lengths.
617 decompositions = get_decompositions([torch.ops.aten.constant_pad_nd.default]) if symbolic else None
618 traced_graph = make_fx(
619 _fwd_bwd_fn, decomposition_table=decompositions, **_MAKE_FX_KWARGS
620 )(*fake_args)
622 # EP receive lengths depend on routing values even when input shapes are fixed.
623 insert_deferred_runtime_asserts(traced_graph, fake_mode.shape_env, "joint_graph")
624 traced_graph.recompile()
626 # Stock torch's make_fx does not tag backward nodes (no torchtitan
627 # ``_patch_engine_backward`` hook), so the joint graph splits into
628 # fwd/bwd halves with no ``autograd_backward`` meta to key on.
629 # ``_annotate_autograd_backward`` reconstructs the tag structurally so
630 # ``PpPass`` can classify both halves.
631 _annotate_autograd_backward(traced_graph)
633 # Copy forward metadata (nn_module_stack/stack_trace) to backward nodes so
634 # passes can match nodes by module FQN on both halves of the joint graph.
635 # On torchtitan's patched torch this is the primary source (the engine
636 # already tagged backward nodes); on stock torch it is a no-op because
637 # backward nodes carry no ``seq_nr`` that collides with a forward one.
638 _copy_fwd_metadata_to_bw_nodes(traced_graph)
640 # Expose the state layout on the GraphModule so downstream passes can
641 # identify which leading placeholders are parameters/buffers, and the
642 # trainer can feed runtime state in the same order.
643 traced_graph.state_fqns = state_fqns
644 traced_graph.state_is_param = state_is_param
645 traced_graph.num_state_inputs = num_state_inputs
646 if mixed_precision is not None:
647 _annotate_fsdp_compute_dtypes(traced_graph, model_state, mixed_precision, len(fake_args))
648 # Kept for ``run_traced_graph`` to validate the runtime inputs' pytree
649 # structure against the traced one.
650 traced_graph.user_inputs_spec = user_inputs_spec
651 # Key order of the traced ``loss_dict``: its values are emitted as
652 # graph outputs AFTER the gradients, so ``run_traced_graph`` can split
653 # (loss, grads, loss_dict) and passes can trim the trailing loss_dict
654 # outputs off the gradient range.
655 traced_graph.loss_dict_keys = list(loss_dict_keys_box)
657 param_names = [name for name, _ in model.named_parameters() if _.requires_grad]
658 param_shapes = {
659 name: tuple(param.shape) for name, param in model.named_parameters()
660 }
662 num_layers = 0
663 if hasattr(model, "layers"):
664 num_layers = len(model.layers)
666 return JointGraph(
667 graph_module=traced_graph,
668 inputs=[_input_meta(v) for v in inputs.values()],
669 outputs=[],
670 param_names=param_names,
671 param_shapes=param_shapes,
672 num_layers=num_layers,
673 state_fqns=state_fqns,
674 example_inputs=fake_args,
675 input_guards=(
676 InputGuards(user_inputs_flat, fake_args[num_state_inputs:], fake_mode.shape_env)
677 if symbolic else None
678 ),
679 )
682def run_traced_graph(
683 joint_graph: JointGraph,
684 model: torch.nn.Module,
685 inputs: Dict[str, Any],
686) -> tuple:
687 """
688 Execute a traced joint graph against the live model state.
690 Parameters/buffers are sampled from ``model`` at call time and fed to the
691 graph as static inputs (in ``joint_graph.state_fqns`` order). ``inputs``
692 is flattened with the same pytree structure used at trace time (checked
693 against the stored spec) and appended after the state. Runs under
694 ``torch.no_grad()`` because the graph already contains the explicit
695 backward ops traced by ``torch.autograd.grad``.
697 FSDP is invisible here: FSDPPass shards ``model``'s parameters in place,
698 so ``model.parameters()`` yields the shards the graph expects as its
699 leading static inputs (the graph re-gathers them via AllGather each step).
701 Returns:
702 tuple: (loss, grads, loss_dict) where ``grads`` aligns with the
703 model's trainable parameter list and ``loss_dict`` maps the traced
704 loss names to their graph outputs (empty when ``train_fn`` returned
705 a bare loss tensor).
706 """
707 model_state = extract_module_state(model)
708 if list(model_state.keys()) != joint_graph.state_fqns:
709 raise ValueError(
710 "model has different parameter/buffer names than during tracing.\n"
711 f" Traced: {joint_graph.state_fqns}\n"
712 f" Got: {list(model_state.keys())}"
713 )
715 user_flat, user_spec = torch.utils._pytree.tree_flatten(inputs)
716 traced_spec = getattr(joint_graph.graph_module, "user_inputs_spec", None)
717 if traced_spec is not None and user_spec != traced_spec:
718 raise ValueError(
719 "model inputs have a different pytree structure than during "
720 "tracing (keys, nesting, or leaf types changed).\n"
721 f" Traced spec: {traced_spec}\n"
722 f" Got spec: {user_spec}"
723 )
725 state_flat, _ = torch.utils._pytree.tree_flatten({"model": model_state})
727 if joint_graph.input_guards is not None:
728 joint_graph.input_guards.validate(user_flat)
730 flat_inputs = list(state_flat) + list(user_flat)
732 with torch.no_grad():
733 outputs = joint_graph.graph_module(*flat_inputs)
735 loss_dict_keys = getattr(joint_graph.graph_module, "loss_dict_keys", [])
736 num_loss_outputs = len(loss_dict_keys)
737 if isinstance(outputs, (list, tuple)):
738 loss = outputs[0]
739 loss_dict = (
740 dict(zip(loss_dict_keys, outputs[len(outputs) - num_loss_outputs:]))
741 if num_loss_outputs
742 else {}
743 )
744 grads = (
745 list(outputs[1:len(outputs) - num_loss_outputs])
746 if num_loss_outputs
747 else list(outputs[1:])
748 )
749 else:
750 loss, grads, loss_dict = outputs, [], {}
751 return loss, grads, loss_dict