Skip to content

[graph_trainer] Add preserve_ops_order utility for shielding regions from graph passes - #3246

Closed
ydwu4 wants to merge 18 commits into
gh/ydwu4/3/basefrom
gh/ydwu4/3/head
Closed

ydwu4 wants to merge 18 commits into
gh/ydwu4/3/basefrom
gh/ydwu4/3/head

Conversation

@ydwu4

@ydwu4 ydwu4 commented May 6, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Problem:
We don't functionalize the graph so the implicit read-after-write dependency is
invisible to graph passes
.

The joint_transformer_block_bucketing_reordering_pass moving readers of ChunkedCELoss's
grad-accumulator buffer past the in-place aten.copy_ writes that fill it.

Implementation:
Add skip_module(fqns) decorator that wraps a graph pass so it cannot
reorder or restructure nodes whose module_fqn annotation is in
fqns. Mechanically:

  1. Before the wrapped pass runs, _pin_ops_order walks the
    graph and pairs consecutive nodes in the listed modules with
    preserve_node_ordering from
    torch._inductor.fx_passes.control_dependencies. Each anchored
    node ends up wrapped in a control_deps HOP whose first arg
    points to the previous anchored node, so any pass that does
    topological scheduling against arg edges sees the region as a
    single linear chain that cannot be split.
  2. The wrapped pass runs against the shielded graph.
  3. _unpin_ops_order unwraps every control_deps HOP back
    to the original op so subsequent passes see the unmodified graph.

…aph passes

skip_module(fqns) is a decorator that wraps a graph pass so it cannot
reorder or restructure nodes whose ``module_fqn`` annotation is in
``fqns``. Mechanically:

  1. Before the wrapped pass runs, ``_anchor_module_region`` walks the
     graph and pairs consecutive nodes in the listed modules with
     ``preserve_node_ordering`` from
     ``torch._inductor.fx_passes.control_dependencies``. Each anchored
     node ends up wrapped in a ``control_deps`` HOP whose first arg
     points to the previous anchored node, so any pass that does
     topological scheduling against arg edges sees the region as a
     single linear chain that cannot be split.
  2. The wrapped pass runs against the shielded graph.
  3. ``_inline_control_deps`` unwraps every ``control_deps`` HOP back
     to the original op so subsequent passes see the unmodified graph.

The motivating consumer (separate commit) is the bucketing reorder
pass moving readers of ChunkedCELoss's grad-accumulator buffer past
the in-place ``aten.copy_`` writes that fill it. Bucketing-style
passes don't track tensor aliasing, so the implicit read-after-write
dependency is invisible to them; opaque HOP wrapping makes it
explicit. The same shielding pattern can be applied to any future
pass that misbehaves on a region.

Tests (CPU only; no E2E coverage in this commit — the consumer's
commit exercises the integration):

  - tests/test_skip_module.py: 9 unit tests covering anchor / inline
    / decorator behaviors. Includes exception-safe inlining
    (control_deps wrappers are cleaned up even if the wrapped pass
    raises) and a structural check that the wrapped pass observes
    HOPs in place of the original ops while non-anchored nodes
    remain visible.

[ghstack-poisoned]
…ons from graph passes"

skip_module(fqns) is a decorator that wraps a graph pass so it cannot
reorder or restructure nodes whose ``module_fqn`` annotation is in
``fqns``. Mechanically:

  1. Before the wrapped pass runs, ``_anchor_module_region`` walks the
     graph and pairs consecutive nodes in the listed modules with
     ``preserve_node_ordering`` from
     ``torch._inductor.fx_passes.control_dependencies``. Each anchored
     node ends up wrapped in a ``control_deps`` HOP whose first arg
     points to the previous anchored node, so any pass that does
     topological scheduling against arg edges sees the region as a
     single linear chain that cannot be split.
  2. The wrapped pass runs against the shielded graph.
  3. ``_inline_control_deps`` unwraps every ``control_deps`` HOP back
     to the original op so subsequent passes see the unmodified graph.

The motivating consumer (separate commit) is the bucketing reorder
pass moving readers of ChunkedCELoss's grad-accumulator buffer past
the in-place ``aten.copy_`` writes that fill it. Bucketing-style
passes don't track tensor aliasing, so the implicit read-after-write
dependency is invisible to them; opaque HOP wrapping makes it
explicit. The same shielding pattern can be applied to any future
pass that misbehaves on a region.

Tests (CPU only; no E2E coverage in this commit — the consumer's
commit exercises the integration):

  - tests/test_skip_module.py: 9 unit tests covering anchor / inline
    / decorator behaviors. Includes exception-safe inlining
    (control_deps wrappers are cleaned up even if the wrapped pass
    raises) and a structural check that the wrapped pass observes
    HOPs in place of the original ops while non-anchored nodes
    remain visible.

[ghstack-poisoned]
ydwu4 added 5 commits May 6, 2026 13:30
…ons from graph passes"

skip_module(fqns) is a decorator that wraps a graph pass so it cannot
reorder or restructure nodes whose ``module_fqn`` annotation is in
``fqns``. Mechanically:

  1. Before the wrapped pass runs, ``_anchor_module_region`` walks the
     graph and pairs consecutive nodes in the listed modules with
     ``preserve_node_ordering`` from
     ``torch._inductor.fx_passes.control_dependencies``. Each anchored
     node ends up wrapped in a ``control_deps`` HOP whose first arg
     points to the previous anchored node, so any pass that does
     topological scheduling against arg edges sees the region as a
     single linear chain that cannot be split.
  2. The wrapped pass runs against the shielded graph.
  3. ``_inline_control_deps`` unwraps every ``control_deps`` HOP back
     to the original op so subsequent passes see the unmodified graph.

The motivating consumer (separate commit) is the bucketing reorder
pass moving readers of ChunkedCELoss's grad-accumulator buffer past
the in-place ``aten.copy_`` writes that fill it. Bucketing-style
passes don't track tensor aliasing, so the implicit read-after-write
dependency is invisible to them; opaque HOP wrapping makes it
explicit. The same shielding pattern can be applied to any future
pass that misbehaves on a region.

Tests (CPU only; no E2E coverage in this commit — the consumer's
commit exercises the integration):

  - tests/test_skip_module.py: 9 unit tests covering anchor / inline
    / decorator behaviors. Includes exception-safe inlining
    (control_deps wrappers are cleaned up even if the wrapped pass
    raises) and a structural check that the wrapped pass observes
    HOPs in place of the original ops while non-anchored nodes
    remain visible.

[ghstack-poisoned]
…ons from graph passes"

skip_module(fqns) is a decorator that wraps a graph pass so it cannot
reorder or restructure nodes whose ``module_fqn`` annotation is in
``fqns``. Mechanically:

  1. Before the wrapped pass runs, ``_anchor_module_region`` walks the
     graph and pairs consecutive nodes in the listed modules with
     ``preserve_node_ordering`` from
     ``torch._inductor.fx_passes.control_dependencies``. Each anchored
     node ends up wrapped in a ``control_deps`` HOP whose first arg
     points to the previous anchored node, so any pass that does
     topological scheduling against arg edges sees the region as a
     single linear chain that cannot be split.
  2. The wrapped pass runs against the shielded graph.
  3. ``_inline_control_deps`` unwraps every ``control_deps`` HOP back
     to the original op so subsequent passes see the unmodified graph.

The motivating consumer (separate commit) is the bucketing reorder
pass moving readers of ChunkedCELoss's grad-accumulator buffer past
the in-place ``aten.copy_`` writes that fill it. Bucketing-style
passes don't track tensor aliasing, so the implicit read-after-write
dependency is invisible to them; opaque HOP wrapping makes it
explicit. The same shielding pattern can be applied to any future
pass that misbehaves on a region.

Tests (CPU only; no E2E coverage in this commit — the consumer's
commit exercises the integration):

  - tests/test_skip_module.py: 9 unit tests covering anchor / inline
    / decorator behaviors. Includes exception-safe inlining
    (control_deps wrappers are cleaned up even if the wrapped pass
    raises) and a structural check that the wrapped pass observes
    HOPs in place of the original ops while non-anchored nodes
    remain visible.

[ghstack-poisoned]
…ons from graph passes"



**Problem:**
We don't functionalize the graph so **the implicit read-after-write dependency is
invisible to graph passes**. 

The **joint_transformer_block_bucketing_reordering_pass** moving readers of ChunkedCELoss's 
grad-accumulator buffer past the in-place ``aten.copy_`` writes that fill it.

**Implementation:**
Add skip_module(fqns) decorator that wraps a graph pass so it **cannot**
reorder or restructure nodes whose ``module_fqn`` annotation is in
``fqns``. Mechanically:

  1. Before the wrapped pass runs, ``_anchor_module_region`` walks the
     graph and pairs consecutive nodes in the listed modules with
     ``preserve_node_ordering`` from
     ``torch._inductor.fx_passes.control_dependencies``. Each anchored
     node ends up wrapped in a ``control_deps`` HOP whose first arg
     points to the previous anchored node, so any pass that does
     topological scheduling against arg edges sees the region as a
     single linear chain that cannot be split.
  2. The wrapped pass runs against the shielded graph.
  3. ``_inline_control_deps`` unwraps every ``control_deps`` HOP back
     to the original op so subsequent passes see the unmodified graph.


[ghstack-poisoned]
…ons from graph passes"



**Problem:**
We don't functionalize the graph so **the implicit read-after-write dependency is
invisible to graph passes**. 

The **joint_transformer_block_bucketing_reordering_pass** moving readers of ChunkedCELoss's 
grad-accumulator buffer past the in-place ``aten.copy_`` writes that fill it.

**Implementation:**
Add skip_module(fqns) decorator that wraps a graph pass so it **cannot**
reorder or restructure nodes whose ``module_fqn`` annotation is in
``fqns``. Mechanically:

  1. Before the wrapped pass runs, ``_anchor_module_region`` walks the
     graph and pairs consecutive nodes in the listed modules with
     ``preserve_node_ordering`` from
     ``torch._inductor.fx_passes.control_dependencies``. Each anchored
     node ends up wrapped in a ``control_deps`` HOP whose first arg
     points to the previous anchored node, so any pass that does
     topological scheduling against arg edges sees the region as a
     single linear chain that cannot be split.
  2. The wrapped pass runs against the shielded graph.
  3. ``_inline_control_deps`` unwraps every ``control_deps`` HOP back
     to the original op so subsequent passes see the unmodified graph.


[ghstack-poisoned]
…ons from graph passes"



**Problem:**
We don't functionalize the graph so **the implicit read-after-write dependency is
invisible to graph passes**. 

The **joint_transformer_block_bucketing_reordering_pass** moving readers of ChunkedCELoss's 
grad-accumulator buffer past the in-place ``aten.copy_`` writes that fill it.

**Implementation:**
Add skip_module(fqns) decorator that wraps a graph pass so it **cannot**
reorder or restructure nodes whose ``module_fqn`` annotation is in
``fqns``. Mechanically:

  1. Before the wrapped pass runs, ``_anchor_module_region`` walks the
     graph and pairs consecutive nodes in the listed modules with
     ``preserve_node_ordering`` from
     ``torch._inductor.fx_passes.control_dependencies``. Each anchored
     node ends up wrapped in a ``control_deps`` HOP whose first arg
     points to the previous anchored node, so any pass that does
     topological scheduling against arg edges sees the region as a
     single linear chain that cannot be split.
  2. The wrapped pass runs against the shielded graph.
  3. ``_inline_control_deps`` unwraps every ``control_deps`` HOP back
     to the original op so subsequent passes see the unmodified graph.


[ghstack-poisoned]
@xmfan

xmfan commented May 6, 2026

Copy link
Copy Markdown
Contributor

what if we did a graph pass to insert node dependencies instead?

@ydwu4

ydwu4 commented May 6, 2026 •

Copy link
Copy Markdown
Contributor Author

That would also work, If we want the dependencies to be always in the graph, could call the _pin_ops_order without _unpin_ops_order.

I want to do the dependency preserving in a local per-pass manner (kind of like a pass modifier, higher order pass lol). Many passes don't reorder things anyway. Keeping the control deps hop in graph seems a bit overshooting for them.

check the usage in https://github.com/pytorch/torchtitan/pull/3247/changes!

…ons from graph passes"



**Problem:**
We don't functionalize the graph so **the implicit read-after-write dependency is
invisible to graph passes**. 

The **joint_transformer_block_bucketing_reordering_pass** moving readers of ChunkedCELoss's 
grad-accumulator buffer past the in-place ``aten.copy_`` writes that fill it.

**Implementation:**
Add skip_module(fqns) decorator that wraps a graph pass so it **cannot**
reorder or restructure nodes whose ``module_fqn`` annotation is in
``fqns``. Mechanically:

  1. Before the wrapped pass runs, ``_anchor_module_region`` walks the
     graph and pairs consecutive nodes in the listed modules with
     ``preserve_node_ordering`` from
     ``torch._inductor.fx_passes.control_dependencies``. Each anchored
     node ends up wrapped in a ``control_deps`` HOP whose first arg
     points to the previous anchored node, so any pass that does
     topological scheduling against arg edges sees the region as a
     single linear chain that cannot be split.
  2. The wrapped pass runs against the shielded graph.
  3. ``_inline_control_deps`` unwraps every ``control_deps`` HOP back
     to the original op so subsequent passes see the unmodified graph.


[ghstack-poisoned]
@ydwu4 ydwu4 changed the title [graph_trainer] Add skip_module utility for shielding regions from graph passes [graph_trainer] Add preserve_ops_order utility for shielding regions from graph passes May 6, 2026
gm.recompile()


def preserve_ops_order(fqns: list[str]) -> Callable[[Callable], Callable]:

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 an interesting generic solution to prevent nodes from moving around...

but I see this as a stop-bleed solution that would come handy when someone need a quick and dirty fix.

My worry is that its existence will encourage irresponsible use of topo_sort, and passes should still try best to avoid global manipulation of the graph.

so we should still land this, but as an stop-gap quick fix pass.

@ydwu4 ydwu4 May 6, 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.

Agree global transformation is hard to get right for a non-functional graph. But I also don't want to restrict us to only local transformations: isn't global transformation the main magic we get out of full graph tracing (compared with eager/ partial graph)? Topo-sorting and partial ordering are very generic concepts in graph algorithms and we could provide utilities for users to easily do that IMO.

@ydwu4 ydwu4 May 6, 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.

Having said that, I'm not sure what pass would actually benefit from a global topo-sort!

ydwu4 added 4 commits May 6, 2026 21:50
…ng regions from graph passes"



**Problem:**
We don't functionalize the graph so **the implicit read-after-write dependency is
invisible to graph passes**. 

The **joint_transformer_block_bucketing_reordering_pass** moving readers of ChunkedCELoss's 
grad-accumulator buffer past the in-place ``aten.copy_`` writes that fill it.

**Implementation:**
Add skip_module(fqns) decorator that wraps a graph pass so it **cannot**
reorder or restructure nodes whose ``module_fqn`` annotation is in
``fqns``. Mechanically:

  1. Before the wrapped pass runs, ``_pin_ops_order`` walks the
     graph and pairs consecutive nodes in the listed modules with
     ``preserve_node_ordering`` from
     ``torch._inductor.fx_passes.control_dependencies``. Each anchored
     node ends up wrapped in a ``control_deps`` HOP whose first arg
     points to the previous anchored node, so any pass that does
     topological scheduling against arg edges sees the region as a
     single linear chain that cannot be split.
  2. The wrapped pass runs against the shielded graph.
  3. ``_unpin_ops_order`` unwraps every ``control_deps`` HOP back
     to the original op so subsequent passes see the unmodified graph.


[ghstack-poisoned]
…ng regions from graph passes"



**Problem:**
We don't functionalize the graph so **the implicit read-after-write dependency is
invisible to graph passes**. 

The **joint_transformer_block_bucketing_reordering_pass** moving readers of ChunkedCELoss's 
grad-accumulator buffer past the in-place ``aten.copy_`` writes that fill it.

**Implementation:**
Add skip_module(fqns) decorator that wraps a graph pass so it **cannot**
reorder or restructure nodes whose ``module_fqn`` annotation is in
``fqns``. Mechanically:

  1. Before the wrapped pass runs, ``_pin_ops_order`` walks the
     graph and pairs consecutive nodes in the listed modules with
     ``preserve_node_ordering`` from
     ``torch._inductor.fx_passes.control_dependencies``. Each anchored
     node ends up wrapped in a ``control_deps`` HOP whose first arg
     points to the previous anchored node, so any pass that does
     topological scheduling against arg edges sees the region as a
     single linear chain that cannot be split.
  2. The wrapped pass runs against the shielded graph.
  3. ``_unpin_ops_order`` unwraps every ``control_deps`` HOP back
     to the original op so subsequent passes see the unmodified graph.


[ghstack-poisoned]
…ng regions from graph passes"



**Problem:**
We don't functionalize the graph so **the implicit read-after-write dependency is
invisible to graph passes**. 

The **joint_transformer_block_bucketing_reordering_pass** moving readers of ChunkedCELoss's 
grad-accumulator buffer past the in-place ``aten.copy_`` writes that fill it.

**Implementation:**
Add skip_module(fqns) decorator that wraps a graph pass so it **cannot**
reorder or restructure nodes whose ``module_fqn`` annotation is in
``fqns``. Mechanically:

  1. Before the wrapped pass runs, ``_pin_ops_order`` walks the
     graph and pairs consecutive nodes in the listed modules with
     ``preserve_node_ordering`` from
     ``torch._inductor.fx_passes.control_dependencies``. Each anchored
     node ends up wrapped in a ``control_deps`` HOP whose first arg
     points to the previous anchored node, so any pass that does
     topological scheduling against arg edges sees the region as a
     single linear chain that cannot be split.
  2. The wrapped pass runs against the shielded graph.
  3. ``_unpin_ops_order`` unwraps every ``control_deps`` HOP back
     to the original op so subsequent passes see the unmodified graph.


[ghstack-poisoned]
…ng regions from graph passes"



**Problem:**
We don't functionalize the graph so **the implicit read-after-write dependency is
invisible to graph passes**. 

The **joint_transformer_block_bucketing_reordering_pass** moving readers of ChunkedCELoss's 
grad-accumulator buffer past the in-place ``aten.copy_`` writes that fill it.

**Implementation:**
Add skip_module(fqns) decorator that wraps a graph pass so it **cannot**
reorder or restructure nodes whose ``module_fqn`` annotation is in
``fqns``. Mechanically:

  1. Before the wrapped pass runs, ``_pin_ops_order`` walks the
     graph and pairs consecutive nodes in the listed modules with
     ``preserve_node_ordering`` from
     ``torch._inductor.fx_passes.control_dependencies``. Each anchored
     node ends up wrapped in a ``control_deps`` HOP whose first arg
     points to the previous anchored node, so any pass that does
     topological scheduling against arg edges sees the region as a
     single linear chain that cannot be split.
  2. The wrapped pass runs against the shielded graph.
  3. ``_unpin_ops_order`` unwraps every ``control_deps`` HOP back
     to the original op so subsequent passes see the unmodified graph.


[ghstack-poisoned]
ydwu4 added 5 commits May 7, 2026 13:26
…ng regions from graph passes"



**Problem:**
We don't functionalize the graph so **the implicit read-after-write dependency is
invisible to graph passes**. 

The **joint_transformer_block_bucketing_reordering_pass** moving readers of ChunkedCELoss's 
grad-accumulator buffer past the in-place ``aten.copy_`` writes that fill it.

**Implementation:**
Add skip_module(fqns) decorator that wraps a graph pass so it **cannot**
reorder or restructure nodes whose ``module_fqn`` annotation is in
``fqns``. Mechanically:

  1. Before the wrapped pass runs, ``_pin_ops_order`` walks the
     graph and pairs consecutive nodes in the listed modules with
     ``preserve_node_ordering`` from
     ``torch._inductor.fx_passes.control_dependencies``. Each anchored
     node ends up wrapped in a ``control_deps`` HOP whose first arg
     points to the previous anchored node, so any pass that does
     topological scheduling against arg edges sees the region as a
     single linear chain that cannot be split.
  2. The wrapped pass runs against the shielded graph.
  3. ``_unpin_ops_order`` unwraps every ``control_deps`` HOP back
     to the original op so subsequent passes see the unmodified graph.


[ghstack-poisoned]
…ng regions from graph passes"



**Problem:**
We don't functionalize the graph so **the implicit read-after-write dependency is
invisible to graph passes**. 

The **joint_transformer_block_bucketing_reordering_pass** moving readers of ChunkedCELoss's 
grad-accumulator buffer past the in-place ``aten.copy_`` writes that fill it.

**Implementation:**
Add skip_module(fqns) decorator that wraps a graph pass so it **cannot**
reorder or restructure nodes whose ``module_fqn`` annotation is in
``fqns``. Mechanically:

  1. Before the wrapped pass runs, ``_pin_ops_order`` walks the
     graph and pairs consecutive nodes in the listed modules with
     ``preserve_node_ordering`` from
     ``torch._inductor.fx_passes.control_dependencies``. Each anchored
     node ends up wrapped in a ``control_deps`` HOP whose first arg
     points to the previous anchored node, so any pass that does
     topological scheduling against arg edges sees the region as a
     single linear chain that cannot be split.
  2. The wrapped pass runs against the shielded graph.
  3. ``_unpin_ops_order`` unwraps every ``control_deps`` HOP back
     to the original op so subsequent passes see the unmodified graph.


[ghstack-poisoned]
…ng regions from graph passes"



**Problem:**
We don't functionalize the graph so **the implicit read-after-write dependency is
invisible to graph passes**. 

The **joint_transformer_block_bucketing_reordering_pass** moving readers of ChunkedCELoss's 
grad-accumulator buffer past the in-place ``aten.copy_`` writes that fill it.

**Implementation:**
Add skip_module(fqns) decorator that wraps a graph pass so it **cannot**
reorder or restructure nodes whose ``module_fqn`` annotation is in
``fqns``. Mechanically:

  1. Before the wrapped pass runs, ``_pin_ops_order`` walks the
     graph and pairs consecutive nodes in the listed modules with
     ``preserve_node_ordering`` from
     ``torch._inductor.fx_passes.control_dependencies``. Each anchored
     node ends up wrapped in a ``control_deps`` HOP whose first arg
     points to the previous anchored node, so any pass that does
     topological scheduling against arg edges sees the region as a
     single linear chain that cannot be split.
  2. The wrapped pass runs against the shielded graph.
  3. ``_unpin_ops_order`` unwraps every ``control_deps`` HOP back
     to the original op so subsequent passes see the unmodified graph.


[ghstack-poisoned]
…ng regions from graph passes"



**Problem:**
We don't functionalize the graph so **the implicit read-after-write dependency is
invisible to graph passes**. 

The **joint_transformer_block_bucketing_reordering_pass** moving readers of ChunkedCELoss's 
grad-accumulator buffer past the in-place ``aten.copy_`` writes that fill it.

**Implementation:**
Add skip_module(fqns) decorator that wraps a graph pass so it **cannot**
reorder or restructure nodes whose ``module_fqn`` annotation is in
``fqns``. Mechanically:

  1. Before the wrapped pass runs, ``_pin_ops_order`` walks the
     graph and pairs consecutive nodes in the listed modules with
     ``preserve_node_ordering`` from
     ``torch._inductor.fx_passes.control_dependencies``. Each anchored
     node ends up wrapped in a ``control_deps`` HOP whose first arg
     points to the previous anchored node, so any pass that does
     topological scheduling against arg edges sees the region as a
     single linear chain that cannot be split.
  2. The wrapped pass runs against the shielded graph.
  3. ``_unpin_ops_order`` unwraps every ``control_deps`` HOP back
     to the original op so subsequent passes see the unmodified graph.


[ghstack-poisoned]
…ng regions from graph passes"



**Problem:**
We don't functionalize the graph so **the implicit read-after-write dependency is
invisible to graph passes**. 

The **joint_transformer_block_bucketing_reordering_pass** moving readers of ChunkedCELoss's 
grad-accumulator buffer past the in-place ``aten.copy_`` writes that fill it.

**Implementation:**
Add skip_module(fqns) decorator that wraps a graph pass so it **cannot**
reorder or restructure nodes whose ``module_fqn`` annotation is in
``fqns``. Mechanically:

  1. Before the wrapped pass runs, ``_pin_ops_order`` walks the
     graph and pairs consecutive nodes in the listed modules with
     ``preserve_node_ordering`` from
     ``torch._inductor.fx_passes.control_dependencies``. Each anchored
     node ends up wrapped in a ``control_deps`` HOP whose first arg
     points to the previous anchored node, so any pass that does
     topological scheduling against arg edges sees the region as a
     single linear chain that cannot be split.
  2. The wrapped pass runs against the shielded graph.
  3. ``_unpin_ops_order`` unwraps every ``control_deps`` HOP back
     to the original op so subsequent passes see the unmodified graph.


[ghstack-poisoned]
ydwu4 added a commit that referenced this pull request May 8, 2026
…ding externally (#3244)

Stack from [ghstack](https://github.com/ezyang/ghstack) (oldest at
bottom):
* #3250
* #3248
* #3247
* #3246
* #3249
* __->__ #3244

graph_trainer's compute_loss previously did
``loss_fn(pred, labels) / global_valid_tokens`` — calling the loss
without
gvt, then dividing the result. This breaks the "loss is the autograd
endpoint" mental model and forces every loss-side autograd.Function
backward
to chain-rule the external division through grad_output, which interacts
poorly with custom Functions whose returned grads live on a different
DeviceMesh than the loss output (e.g. lm_head params on (fsdp, tp) vs
loss
on (tp), as we'd hit with chunked CE plumbing).

global_valid_tokens is already part of the BaseLoss.__call__ contract —
``CrossEntropyLoss``, ``MSELoss``, and ``ChunkedCELoss`` all accept it
and
divide internally if provided. Passing gvt through restores "loss is the
endpoint": no external scaling on the autograd path, downstream
grad_output
is trivially 1.0, and the loss tensor lands on a single mesh determined
by
the loss computation rather than the gvt operand's mesh.

Numerically equivalent: BaseLoss.__call__ does
``loss = self.fn(...); if gvt: loss = loss / gvt`` — identical to the
prior
external divide for the existing CrossEntropyLoss path that
to_graph_trainer_config swaps to.
…ng regions from graph passes"



**Problem:**
We don't functionalize the graph so **the implicit read-after-write dependency is
invisible to graph passes**. 

The **joint_transformer_block_bucketing_reordering_pass** moving readers of ChunkedCELoss's 
grad-accumulator buffer past the in-place ``aten.copy_`` writes that fill it.

**Implementation:**
Add skip_module(fqns) decorator that wraps a graph pass so it **cannot**
reorder or restructure nodes whose ``module_fqn`` annotation is in
``fqns``. Mechanically:

  1. Before the wrapped pass runs, ``_pin_ops_order`` walks the
     graph and pairs consecutive nodes in the listed modules with
     ``preserve_node_ordering`` from
     ``torch._inductor.fx_passes.control_dependencies``. Each anchored
     node ends up wrapped in a ``control_deps`` HOP whose first arg
     points to the previous anchored node, so any pass that does
     topological scheduling against arg edges sees the region as a
     single linear chain that cannot be split.
  2. The wrapped pass runs against the shielded graph.
  3. ``_unpin_ops_order`` unwraps every ``control_deps`` HOP back
     to the original op so subsequent passes see the unmodified graph.


[ghstack-poisoned]
ydwu4 added a commit that referenced this pull request May 11, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack) (oldest at
bottom):
* #3250
* #3248
* #3247
* #3246
* __->__ #3249

Add a ``support_autograd_grad`` opt-in flag to ``ChunkedCELoss.Config``
that exposes the lm_head parameter gradients as explicit autograd
outputs of the returned loss tensor. Designed for FX-tracing flows
(e.g. graph_trainer's aot_fx_trace) where ``param.grad`` side-effect
writes from ``chunk_loss.backward()`` inside the chunk loop don't
survive into the captured graph and replay therefore produces
all-zero param grads.

Mechanism, when the flag is True:

  - The chunk loop runs unchanged: per-chunk ``chunk_loss.backward()``
    populates ``lm_head.weight.grad`` with the correctly sharded value
    (FSDP last-chunk reduce-scatter still handles the actual reduction).
  - After the loop, the sharded ``param.grad`` is captured via
    ``p.grad.detach()`` and ``p.grad`` is cleared.
  - The captured grads (plus the existing accumulated hidden_states
    grad) are plumbed through a new ``_ChunkedLossWithParamGrads``
    autograd Function as saved tensors. Its backward returns them as
    grads for the corresponding lm_head parameter inputs, so outer
    ``torch.autograd.grad(loss, lm_head.parameters())`` resolves to
    real gradients instead of None / zeros.
  - Under FSDP, ``set_requires_gradient_sync(False)`` is set on lm_head
    and restored after the outer backward via a callback queued on the
    autograd engine. Without this, outer ``loss.backward()`` would
    re-fire the post-accumulate-grad hook on already-sharded grads and
    either error or produce wrong values.

Both autograd Functions (the existing ``_DecoderOutputGradientBackProp``
and the new ``_ChunkedLossWithParamGrads``) return saved grads as-is
without chain-ruling through ``grad_output``. The contract is that the
loss returned by these Functions is the autograd endpoint — callers
must pass any scaling factor (e.g. ``global_valid_tokens``) into
``loss_fn`` rather than dividing the returned loss externally. See
graph_trainer's ``compute_loss`` for the canonical pattern. This
matches the pre-existing behavior of ``_DecoderOutputGradientBackProp``
and avoids a structural FSDP+TP problem: ``grad_output`` is a
``Replicate()`` scalar DTensor on the loss's mesh (typically ``(tp,)``)
while saved param grads live on the params' mesh (e.g. ``(fsdp, tp)``);
DTensor refuses cross-mesh ``aten.mul.Tensor``, so any chain-rule
multiply would crash at runtime.

Tests:

  - tests/unit_tests/test_loss.py: parametrized ``support_autograd_grad
    in {False, True}`` equivalence check against the unchunked CE
    standard path; bitwise (rtol=0, atol=0) check that True and False
    paths produce identical grads; side-effect contract check that the
    True path doesn't populate ``param.grad``.
  - graph_trainer/tests/test_trace_module.py: end-to-end test that
    traces a small ``lm_head + ChunkedCELoss(support_autograd_grad=
    True)`` train_step via ``trace_train_step`` and verifies
    ``torch.equal`` between eager and replayed loss + h grad + lm_head
    grad on a CUDA model.

The flag defaults to False so existing callers (the eager torchtitan
trainer) are unaffected; consumers that want explicit param grads
opt in. graph_trainer wires this in a separate commit.

@SherlockNoMad SherlockNoMad left a comment

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.

didn't review line-by-line, but I think this is useful...

I would suggest put this under an experimental/ dir.

@ydwu4 ydwu4 closed this Jun 12, 2026
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.

3 participants