Skip to content

[graph_trainer] Trace forward loss backward step with make_fx - #2561

Merged
yiming0416 merged 1 commit into
mainfrom
yiming/fwd_loss_bwd
Mar 25, 2026
Merged

yiming0416 merged 1 commit into
mainfrom
yiming/fwd_loss_bwd

Conversation

@yiming0416

@yiming0416 yiming0416 commented Mar 12, 2026 •

Copy link
Copy Markdown
Contributor

This PR adds a new aot_fx_trace compilation mode to the graph_trainer experiment that uses make_fx_tracer to trace the entire forward pass, loss computation, and backward pass as a single unified graph.

It introduces FwdBwdStepModule that composes model(inputs) → loss_fn(pred, labels) → autograd.grad(loss, params) into a single traceable forward. Overrides forward_backward_step in GraphTrainer to use this path when compile.mode == "aot_fx_trace", with lazy tracing on the first step.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Mar 12, 2026
@yiming0416
yiming0416 force-pushed the yiming/fwd_loss_bwd branch 9 times, most recently from 3a54326 to ed0f024 Compare March 17, 2026 22:08
@yiming0416
yiming0416 marked this pull request as ready for review March 17, 2026 22:14
self._train_step_module: TrainStepModule | None = None
self._traced_step: TracedResult | None = None

def forward_backward_step(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this trainer work for other models?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It works on existing llama3 and dsv3 models in graph_trainer.
Added integration tests and numerics tests

fsdp_reshard_after_forward,
joint_passes=[],
)
elif mode == "make_fx":

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you think of better name?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we might still want to mention aot in this mode.

What about aot_step or aot_fx_trace

self.model = model
self.loss_fn = loss_fn

def forward(self, inputs, labels, global_valid_tokens, extra_inputs, extra_kwargs):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this forward func's signature is not general.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It matches the caller-side contract used by Trainer.forward_backward_step (in torchtitan/trainer.py).

All Decoder-based models (Llama3, Llama4, Qwen3, DeepSeekV3, GptOss) and the VLM model accept this pattern.


def forward(self, inputs, labels, global_valid_tokens, extra_inputs, extra_kwargs):
pred = self.model(inputs, **extra_inputs, **extra_kwargs)
loss = self.loss_fn(pred, labels) / global_valid_tokens

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this loss pattern apply to all the models?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes. It follows the same pattern in torchtitan/trainer.py, which is used for all models in torchtitan

@yiming0416 yiming0416 Mar 18, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, all LLM models follow this pattern. The only exception is FLUX model which has its own customized trainer.

labels: torch.Tensor,
global_valid_tokens: torch.Tensor,
) -> torch.Tensor:
if self.config.compile.mode != "make_fx":

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it should raise here.
non-make-fx code shouldn't reach here

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In graph_trainer experiment, we'll always use GraphTrainer which inherits the original Trainer.

The forward_backward_step is overridden so that when we are in non-make-fx mode, we just fallback to super().forward_backward_step

train_context=self.train_context,
)

params_and_buffers = {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is params_and_buffers available from tracedresult, I feel it should? @ydwu4

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right now the separation of parameters/buffers and execution (the gm and metadata) feels OK. But if we want to follow something like exported program, packaging them together in traced result (e.g. one single object that gets serded) seems reasonable. So whatever that's easy to understand.

@SherlockNoMad

Copy link
Copy Markdown
Contributor

@claude review this.

Think about generality, this path should be applicable for all models in the repo.
Look for opportunity for better API and abstraction.

@claude

claude Bot commented Mar 17, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @SherlockNoMad's task in 4m 12s —— View job


Review of PR #2561: [graph_trainer] Trace forward loss backward step with make_fx

  • Read all changed files and gather context
  • Review existing models to assess generality
  • Analyze API design and abstractions
  • Post detailed review feedback

I reviewed all 6 changed files and cross-referenced against the base Trainer.forward_backward_step, all model forward signatures (Llama3, Llama4, Qwen3, DeepSeek V3, GPT-OSS, Flux), loss patterns, and the existing make_fx_tracer API. Here are my findings, organized by severity.

Critical: Generality Issues

1. TrainStepModule.forward signature is not general (trainer.py:34-38)

The forward signature (inputs, labels, global_valid_tokens, extra_inputs, extra_kwargs) is tightly coupled to the Trainer.post_dataloading_process return shape. This works for standard LLMs (Llama3, Qwen3, DeepSeek V3, etc.) because they all follow the model(inputs, **extra_inputs, **extra_kwargs) calling convention. However:

  • Flux completely overrides forward_backward_step with a different data pipeline (preprocessing through autoencoder, CLIP, T5 encoders, explicit named arguments like img, img_ids, txt, txt_ids, timesteps, y). This module cannot handle Flux.
  • The loss = self.loss_fn(pred, labels) / global_valid_tokens pattern (line 36) also doesn't generalize — Flux recomputes global_valid_tokens internally and uses MSE loss with different normalization.

Suggestion: Rather than trying to make one TrainStepModule work for all models, consider making TrainStepModule (or rather FwdBwdStepModule per the naming feedback) accept a generic callable or accept *args, **kwargs and have the caller (or a model-specific factory) define the composition of model + loss + backward. Alternatively, since this lives in experiments, accept that it's Llama/LLM-specific for now and document that limitation explicitly.

2. train_context added to trace_module API (make_fx_tracer.py:165)

I agree with @SherlockNoMad's existing comment — adding train_context as a parameter to trace_module hurts the API's generality. trace_module is a general-purpose tracing utility that should eventually move upstream to PyTorch. The caller should handle entering the context. This can be done at the callsite:

with self.train_context():
    self._traced_step = trace_module(
        self._train_step_module,
        (inputs, labels, global_valid_tokens, extra_inputs, extra_kwargs),
    )

However, note that trace_module already enters fake_mode and preserve_node_meta() internally, so the train_context needs to be active during make_fx tracing (inside fake_mode). This means simply wrapping the trace_module call won't work — you'd need to pass a context or restructure the tracing to allow external contexts to be composed. Consider providing a contexts: list[Callable[[], AbstractContextManager]] parameter if you must, or refactoring trace_module to accept a pre-entered context stack.

Naming Issues

3. TrainStepModule should be FwdBwdStepModule (trainer.py:23)

As @SherlockNoMad noted, "train_step" conventionally means fwd + loss + bwd + optimizer.step(). Since this module only covers fwd + loss + bwd (no optimizer step), FwdBwdStepModule is more accurate.

4. Variable name wrapped is unclear (trainer.py:119)

wrapped is the return value of run_traced_module — it's the rewrapped outputs (loss + grads). Consider outputs or traced_outputs.

Logic Issues

5. Should raise instead of falling through (trainer.py:62)

Currently, forward_backward_step calls super() when mode is not make_fx. This means non-make-fx code paths go through this override (which does nothing extra). The override should only be entered for make_fx, and non-make-fx code should never reach here. Since forward_backward_step is overridden, it catches all calls. Two options:

  • Keep the current structure with the super() delegation (acceptable but add a comment explaining why)
  • Only override when mode is make_fx (e.g., dynamically swap the method in __init__)

Given the existing review comment asking for a raise, I think the right approach is: keep the super() delegation for non-make-fx modes (since the override is always installed), but add an assert or raise specifically if mode == "make_fx" fails to trace (i.e., defensive check inside the make_fx path itself).

6. params_and_buffers reconstruction (trainer.py:115-118)

@SherlockNoMad asked whether params_and_buffers is available from TracedResult. Currently, TracedResult stores params_len and params_spec but not the actual dict of params. The current approach of reconstructing it from self._train_step_module.named_parameters() and named_buffers() works correctly because _train_step_module wraps the real model, so these are live references. However, this is somewhat fragile — if the module's parameter set changes between tracing and execution, it would silently break. Consider storing a reference or documenting that the module's parameter set must not change after tracing.

7. Missing maybe_enable_amp context (trainer.py:34-38)

The base Trainer.forward_backward_step wraps the forward+loss in both self.train_context() and self.maybe_enable_amp (see torchtitan/trainer.py:670-671). The make_fx path passes train_context to trace_module, but maybe_enable_amp (autocast) is not included. This could produce different numerics when mixed precision is used without FSDP. This should at minimum be documented as a known limitation or handled.

Minor Issues

8. params computed twice (trainer.py:37, 79)

params = [p for p in model.parameters() if p.requires_grad] is computed once in forward_backward_step (line 79) and again inside TrainStepModule.forward (line 37). The one in forward is used during tracing to determine which params to differentiate. The one in forward_backward_step is used to assign gradients back. These should always match, but it's worth noting the coupling.

9. Gradient accumulation semantics (trainer.py:127-131)

if param.grad is None:
    param.grad = grad
else:
    param.grad += grad

This += grad path handles gradient accumulation across microbatches correctly. Good.

10. Loss function unwrapping (trainer.py:103-106)

orig = getattr(loss_fn, "_torchdynamo_orig_callable", None)
if orig is not None:
    loss_fn = orig

This is fragile — it relies on a private Dynamo attribute. If this attribute is renamed or removed in a future PyTorch version, it will silently fail (the compiled loss_fn would be passed to make_fx, which would then fail). Add a comment explaining why this is necessary and consider a more robust approach.

11. Test coverage is Llama3-only

Both test_numerics.py and integration_tests.py only add Llama3 tests. To validate generality, DeepSeek V3 tests should also be added (similar to how other modes have both _build_llama3_tests and _build_deepseek_v3_tests).

Summary

The core idea of tracing fwd+loss+bwd as a single graph via make_fx is sound. The main concerns are:

  1. Generality: The TrainStepModule forward signature and loss pattern are specific to standard LLMs. This won't work for Flux or models with non-standard forward/loss patterns. Either generalize the abstraction or explicitly scope it.
  2. API pollution: train_context should not be added to trace_module — handle it at the callsite or via a more general contexts parameter.
  3. Naming: TrainStepModule → FwdBwdStepModule, wrapped → traced_outputs.
  4. Missing AMP context: The maybe_enable_amp autocast is not included in the tracing context.

| Branch: yiming/fwd_loss_bwd

@yiming0416
yiming0416 force-pushed the yiming/fwd_loss_bwd branch 11 times, most recently from 699f3ea to bc8f822 Compare March 20, 2026 18:37
@yiming0416
yiming0416 force-pushed the yiming/fwd_loss_bwd branch from 52ce35d to f437d42 Compare March 24, 2026 19:45
loss = outputs[0]
grads = outputs[1:]

for param, grad in zip(params, grads):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not always the case that we can directly += the grad i think? There is an optimizer step.

Since we're not tracing into optimizer at the moment, the other options is to return the loss and grads and do the gradient accumulation outside. Don't have to do in this pr though

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is already doing outside the non-strict region?

@yiming0416
yiming0416 merged commit 62da83c into main Mar 25, 2026
19 of 27 checks passed
pytorch-bot Bot pushed a commit that referenced this pull request Mar 27, 2026
This PR adds a new `aot_fx_trace` compilation mode to the graph_trainer
experiment that uses `make_fx_tracer` to trace the entire forward pass,
loss computation, and backward pass as a single unified graph.

It introduces `FwdBwdStepModule` that composes `model(inputs)` →
`loss_fn(pred, labels)` → `autograd.grad(loss, params)` into a single
traceable forward. Overrides `forward_backward_step` in `GraphTrainer`
to use this path when `compile.mode == "aot_fx_trace"`, with lazy
tracing on the first step.
acisseJZhong pushed a commit that referenced this pull request Mar 31, 2026
This PR adds a new `aot_fx_trace` compilation mode to the graph_trainer
experiment that uses `make_fx_tracer` to trace the entire forward pass,
loss computation, and backward pass as a single unified graph.

It introduces `FwdBwdStepModule` that composes `model(inputs)` →
`loss_fn(pred, labels)` → `autograd.grad(loss, params)` into a single
traceable forward. Overrides `forward_backward_step` in `GraphTrainer`
to use this path when `compile.mode == "aot_fx_trace"`, with lazy
tracing on the first step.
TXacs pushed a commit to McmillanTAC/torchtitan that referenced this pull request Apr 13, 2026
…h#2561)

This PR adds a new `aot_fx_trace` compilation mode to the graph_trainer
experiment that uses `make_fx_tracer` to trace the entire forward pass,
loss computation, and backward pass as a single unified graph.

It introduces `FwdBwdStepModule` that composes `model(inputs)` →
`loss_fn(pred, labels)` → `autograd.grad(loss, params)` into a single
traceable forward. Overrides `forward_backward_step` in `GraphTrainer`
to use this path when `compile.mode == "aot_fx_trace"`, with lazy
tracing on the first step.
ACharacterInASimulation pushed a commit to ACharacterInASimulation/torchtitan that referenced this pull request Apr 21, 2026
…h#2561)

This PR adds a new `aot_fx_trace` compilation mode to the graph_trainer
experiment that uses `make_fx_tracer` to trace the entire forward pass,
loss computation, and backward pass as a single unified graph.

It introduces `FwdBwdStepModule` that composes `model(inputs)` →
`loss_fn(pred, labels)` → `autograd.grad(loss, params)` into a single
traceable forward. Overrides `forward_backward_step` in `GraphTrainer`
to use this path when `compile.mode == "aot_fx_trace"`, with lazy
tracing on the first step.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/8gpu CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants