Skip to content

[graph_trainer] Fix ChunkedCELoss interactions with SAC and bucketing passes - #3247

Closed
ydwu4 wants to merge 19 commits into
gh/ydwu4/4/basefrom
gh/ydwu4/4/head
Closed

ydwu4 wants to merge 19 commits into
gh/ydwu4/4/basefrom
gh/ydwu4/4/head

Conversation

@ydwu4

@ydwu4 ydwu4 commented May 6, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Two pass-level fixes needed for ChunkedCELoss to compose correctly
with graph_trainer's compile pipeline. Neither fix exercises a
ChunkedCELoss code path on its own (graph_trainer's
to_graph_trainer_config still swaps ChunkedCELoss to
CrossEntropyLoss until the next commit flips the toggle); the fixes
land here so the toggle commit doesn't bundle pass-pipeline changes
with config flips.

  1. apply_sac_pass: skip nodes whose module is outside the transformer
    layer stack (layer_id == _NOT_IN_LAYERS). Matches eager
    apply_ac (torchtitan/distributed/activation_checkpoint.py),
    which iterates model.layers.named_children() and wraps each
    transformer block — never the loss / lm_head / norm at the top
    level.

    Without this skip, ChunkedCELoss's chunked region (lm_head +
    per-chunk ce_loss) gets tagged PREFER_RECOMPUTE. Per-chunk
    chunk_loss.backward() dispatches autograd ops that get tagged
    meta["autograd_backward"] = True (one tagged region per
    chunk, plus the outer training-loop backward). When the upstream
    remat_using_tags_for_fwd_loss_bwd_graph pass then walks the
    joint graph and finds N+1 disjoint backward regions where
    PREFER_RECOMPUTE forward nodes feed in, it errors with: "Detected
    N disjoint backward regions that require recomputation, but
    remat only supports one such region in a forward-loss-backward
    graph."

  2. joint_transformer_block_bucketing_reordering_pass: wrap with
    skip_module(["loss", "lm_head"]). The bucketing pass topologically
    reorders ops to overlap collectives with compute but uses arg-edge
    topology only, so it doesn't track tensor aliasing/mutation
    dependencies. ChunkedCELoss's GradAccumulator populates a buffer
    via aten.copy_(slice_view, src) in-place writes; the
    downstream view + to that read the buffer have no arg-edge
    dependence on the writes (the dependency is via shared storage
    between slice_view and the buffer, not via FX node args).

    The bucketing pass therefore sees the readers as freely movable
    compute and pulls them into an overlap window of a downstream
    collective — leaving the readers seeing the unwritten zeros
    buffer. Empirically: accumulated_grad returned for
    hidden_states is all-zero at runtime (verified by forcing
    torch.ones_like and watching grad_norm jump), so decoder
    backward propagates zero and every decoder gradient is zero.
    Loss matches eager step 1 (forward path is unaffected) but
    diverges step 2+ because the optimizer only updates the lm_head.

    Wrapping the bucketing entry in skip_module shields the
    loss/lm_head region behind control_deps HOPs so the bucketing
    pass treats it as an opaque ordered chain and respects the
    original write-then-read sequence.

End-to-end verification of the cumulative stack (this commit + the
flip in the next commit) is documented in the next commit's message.

… passes

Two pass-level fixes needed for ChunkedCELoss to compose correctly
with graph_trainer's compile pipeline. Neither fix exercises a
ChunkedCELoss code path on its own (graph_trainer's
``to_graph_trainer_config`` still swaps ChunkedCELoss to
CrossEntropyLoss until the next commit flips the toggle); the fixes
land here so the toggle commit doesn't bundle pass-pipeline changes
with config flips.

1. apply_sac_pass: skip nodes whose module is outside the transformer
   layer stack (``layer_id == _NOT_IN_LAYERS``). Matches eager
   ``apply_ac`` (torchtitan/distributed/activation_checkpoint.py),
   which iterates ``model.layers.named_children()`` and wraps each
   transformer block — never the loss / lm_head / norm at the top
   level.

   Without this skip, ChunkedCELoss's chunked region (lm_head +
   per-chunk ce_loss) gets tagged ``PREFER_RECOMPUTE``. Per-chunk
   ``chunk_loss.backward()`` dispatches autograd ops that get tagged
   ``meta["autograd_backward"] = True`` (one tagged region per
   chunk, plus the outer training-loop backward). When the upstream
   ``remat_using_tags_for_fwd_loss_bwd_graph`` pass then walks the
   joint graph and finds N+1 disjoint backward regions where
   PREFER_RECOMPUTE forward nodes feed in, it errors with: "Detected
   N disjoint backward regions that require recomputation, but
   remat only supports one such region in a forward-loss-backward
   graph."

2. joint_transformer_block_bucketing_reordering_pass: wrap with
   skip_module(["loss", "lm_head"]). The bucketing pass topologically
   reorders ops to overlap collectives with compute but uses arg-edge
   topology only, so it doesn't track tensor aliasing/mutation
   dependencies. ChunkedCELoss's GradAccumulator populates a buffer
   via ``aten.copy_(slice_view, src)`` in-place writes; the
   downstream ``view + to`` that read the buffer have no arg-edge
   dependence on the writes (the dependency is via shared storage
   between ``slice_view`` and the buffer, not via FX node args).

   The bucketing pass therefore sees the readers as freely movable
   compute and pulls them into an overlap window of a downstream
   collective — leaving the readers seeing the unwritten zeros
   buffer. Empirically: ``accumulated_grad`` returned for
   ``hidden_states`` is all-zero at runtime (verified by forcing
   ``torch.ones_like`` and watching grad_norm jump), so decoder
   backward propagates zero and every decoder gradient is zero.
   Loss matches eager step 1 (forward path is unaffected) but
   diverges step 2+ because the optimizer only updates the lm_head.

   Wrapping the bucketing entry in ``skip_module`` shields the
   loss/lm_head region behind ``control_deps`` HOPs so the bucketing
   pass treats it as an opaque ordered chain and respects the
   original write-then-read sequence.

End-to-end verification of the cumulative stack (this commit + the
flip in the next commit) is documented in the next commit's message.

[ghstack-poisoned]
…d bucketing passes"

Two pass-level fixes needed for ChunkedCELoss to compose correctly
with graph_trainer's compile pipeline. Neither fix exercises a
ChunkedCELoss code path on its own (graph_trainer's
``to_graph_trainer_config`` still swaps ChunkedCELoss to
CrossEntropyLoss until the next commit flips the toggle); the fixes
land here so the toggle commit doesn't bundle pass-pipeline changes
with config flips.

1. apply_sac_pass: skip nodes whose module is outside the transformer
   layer stack (``layer_id == _NOT_IN_LAYERS``). Matches eager
   ``apply_ac`` (torchtitan/distributed/activation_checkpoint.py),
   which iterates ``model.layers.named_children()`` and wraps each
   transformer block — never the loss / lm_head / norm at the top
   level.

   Without this skip, ChunkedCELoss's chunked region (lm_head +
   per-chunk ce_loss) gets tagged ``PREFER_RECOMPUTE``. Per-chunk
   ``chunk_loss.backward()`` dispatches autograd ops that get tagged
   ``meta["autograd_backward"] = True`` (one tagged region per
   chunk, plus the outer training-loop backward). When the upstream
   ``remat_using_tags_for_fwd_loss_bwd_graph`` pass then walks the
   joint graph and finds N+1 disjoint backward regions where
   PREFER_RECOMPUTE forward nodes feed in, it errors with: "Detected
   N disjoint backward regions that require recomputation, but
   remat only supports one such region in a forward-loss-backward
   graph."

2. joint_transformer_block_bucketing_reordering_pass: wrap with
   skip_module(["loss", "lm_head"]). The bucketing pass topologically
   reorders ops to overlap collectives with compute but uses arg-edge
   topology only, so it doesn't track tensor aliasing/mutation
   dependencies. ChunkedCELoss's GradAccumulator populates a buffer
   via ``aten.copy_(slice_view, src)`` in-place writes; the
   downstream ``view + to`` that read the buffer have no arg-edge
   dependence on the writes (the dependency is via shared storage
   between ``slice_view`` and the buffer, not via FX node args).

   The bucketing pass therefore sees the readers as freely movable
   compute and pulls them into an overlap window of a downstream
   collective — leaving the readers seeing the unwritten zeros
   buffer. Empirically: ``accumulated_grad`` returned for
   ``hidden_states`` is all-zero at runtime (verified by forcing
   ``torch.ones_like`` and watching grad_norm jump), so decoder
   backward propagates zero and every decoder gradient is zero.
   Loss matches eager step 1 (forward path is unaffected) but
   diverges step 2+ because the optimizer only updates the lm_head.

   Wrapping the bucketing entry in ``skip_module`` shields the
   loss/lm_head region behind ``control_deps`` HOPs so the bucketing
   pass treats it as an opaque ordered chain and respects the
   original write-then-read sequence.

End-to-end verification of the cumulative stack (this commit + the
flip in the next commit) is documented in the next commit's message.

[ghstack-poisoned]
ydwu4 added 6 commits May 6, 2026 13:30
…d bucketing passes"

Two pass-level fixes needed for ChunkedCELoss to compose correctly
with graph_trainer's compile pipeline. Neither fix exercises a
ChunkedCELoss code path on its own (graph_trainer's
``to_graph_trainer_config`` still swaps ChunkedCELoss to
CrossEntropyLoss until the next commit flips the toggle); the fixes
land here so the toggle commit doesn't bundle pass-pipeline changes
with config flips.

1. apply_sac_pass: skip nodes whose module is outside the transformer
   layer stack (``layer_id == _NOT_IN_LAYERS``). Matches eager
   ``apply_ac`` (torchtitan/distributed/activation_checkpoint.py),
   which iterates ``model.layers.named_children()`` and wraps each
   transformer block — never the loss / lm_head / norm at the top
   level.

   Without this skip, ChunkedCELoss's chunked region (lm_head +
   per-chunk ce_loss) gets tagged ``PREFER_RECOMPUTE``. Per-chunk
   ``chunk_loss.backward()`` dispatches autograd ops that get tagged
   ``meta["autograd_backward"] = True`` (one tagged region per
   chunk, plus the outer training-loop backward). When the upstream
   ``remat_using_tags_for_fwd_loss_bwd_graph`` pass then walks the
   joint graph and finds N+1 disjoint backward regions where
   PREFER_RECOMPUTE forward nodes feed in, it errors with: "Detected
   N disjoint backward regions that require recomputation, but
   remat only supports one such region in a forward-loss-backward
   graph."

2. joint_transformer_block_bucketing_reordering_pass: wrap with
   skip_module(["loss", "lm_head"]). The bucketing pass topologically
   reorders ops to overlap collectives with compute but uses arg-edge
   topology only, so it doesn't track tensor aliasing/mutation
   dependencies. ChunkedCELoss's GradAccumulator populates a buffer
   via ``aten.copy_(slice_view, src)`` in-place writes; the
   downstream ``view + to`` that read the buffer have no arg-edge
   dependence on the writes (the dependency is via shared storage
   between ``slice_view`` and the buffer, not via FX node args).

   The bucketing pass therefore sees the readers as freely movable
   compute and pulls them into an overlap window of a downstream
   collective — leaving the readers seeing the unwritten zeros
   buffer. Empirically: ``accumulated_grad`` returned for
   ``hidden_states`` is all-zero at runtime (verified by forcing
   ``torch.ones_like`` and watching grad_norm jump), so decoder
   backward propagates zero and every decoder gradient is zero.
   Loss matches eager step 1 (forward path is unaffected) but
   diverges step 2+ because the optimizer only updates the lm_head.

   Wrapping the bucketing entry in ``skip_module`` shields the
   loss/lm_head region behind ``control_deps`` HOPs so the bucketing
   pass treats it as an opaque ordered chain and respects the
   original write-then-read sequence.

End-to-end verification of the cumulative stack (this commit + the
flip in the next commit) is documented in the next commit's message.

[ghstack-poisoned]
…d bucketing passes"

Two pass-level fixes needed for ChunkedCELoss to compose correctly
with graph_trainer's compile pipeline. Neither fix exercises a
ChunkedCELoss code path on its own (graph_trainer's
``to_graph_trainer_config`` still swaps ChunkedCELoss to
CrossEntropyLoss until the next commit flips the toggle); the fixes
land here so the toggle commit doesn't bundle pass-pipeline changes
with config flips.

1. apply_sac_pass: skip nodes whose module is outside the transformer
   layer stack (``layer_id == _NOT_IN_LAYERS``). Matches eager
   ``apply_ac`` (torchtitan/distributed/activation_checkpoint.py),
   which iterates ``model.layers.named_children()`` and wraps each
   transformer block — never the loss / lm_head / norm at the top
   level.

   Without this skip, ChunkedCELoss's chunked region (lm_head +
   per-chunk ce_loss) gets tagged ``PREFER_RECOMPUTE``. Per-chunk
   ``chunk_loss.backward()`` dispatches autograd ops that get tagged
   ``meta["autograd_backward"] = True`` (one tagged region per
   chunk, plus the outer training-loop backward). When the upstream
   ``remat_using_tags_for_fwd_loss_bwd_graph`` pass then walks the
   joint graph and finds N+1 disjoint backward regions where
   PREFER_RECOMPUTE forward nodes feed in, it errors with: "Detected
   N disjoint backward regions that require recomputation, but
   remat only supports one such region in a forward-loss-backward
   graph."

2. joint_transformer_block_bucketing_reordering_pass: wrap with
   skip_module(["loss", "lm_head"]). The bucketing pass topologically
   reorders ops to overlap collectives with compute but uses arg-edge
   topology only, so it doesn't track tensor aliasing/mutation
   dependencies. ChunkedCELoss's GradAccumulator populates a buffer
   via ``aten.copy_(slice_view, src)`` in-place writes; the
   downstream ``view + to`` that read the buffer have no arg-edge
   dependence on the writes (the dependency is via shared storage
   between ``slice_view`` and the buffer, not via FX node args).

   The bucketing pass therefore sees the readers as freely movable
   compute and pulls them into an overlap window of a downstream
   collective — leaving the readers seeing the unwritten zeros
   buffer. Empirically: ``accumulated_grad`` returned for
   ``hidden_states`` is all-zero at runtime (verified by forcing
   ``torch.ones_like`` and watching grad_norm jump), so decoder
   backward propagates zero and every decoder gradient is zero.
   Loss matches eager step 1 (forward path is unaffected) but
   diverges step 2+ because the optimizer only updates the lm_head.

   Wrapping the bucketing entry in ``skip_module`` shields the
   loss/lm_head region behind ``control_deps`` HOPs so the bucketing
   pass treats it as an opaque ordered chain and respects the
   original write-then-read sequence.

End-to-end verification of the cumulative stack (this commit + the
flip in the next commit) is documented in the next commit's message.

[ghstack-poisoned]
…d bucketing passes"

Two pass-level fixes needed for ChunkedCELoss to compose correctly
with graph_trainer's compile pipeline. Neither fix exercises a
ChunkedCELoss code path on its own (graph_trainer's
``to_graph_trainer_config`` still swaps ChunkedCELoss to
CrossEntropyLoss until the next commit flips the toggle); the fixes
land here so the toggle commit doesn't bundle pass-pipeline changes
with config flips.

1. apply_sac_pass: skip nodes whose module is outside the transformer
   layer stack (``layer_id == _NOT_IN_LAYERS``). Matches eager
   ``apply_ac`` (torchtitan/distributed/activation_checkpoint.py),
   which iterates ``model.layers.named_children()`` and wraps each
   transformer block — never the loss / lm_head / norm at the top
   level.

   Without this skip, ChunkedCELoss's chunked region (lm_head +
   per-chunk ce_loss) gets tagged ``PREFER_RECOMPUTE``. Per-chunk
   ``chunk_loss.backward()`` dispatches autograd ops that get tagged
   ``meta["autograd_backward"] = True`` (one tagged region per
   chunk, plus the outer training-loop backward). When the upstream
   ``remat_using_tags_for_fwd_loss_bwd_graph`` pass then walks the
   joint graph and finds N+1 disjoint backward regions where
   PREFER_RECOMPUTE forward nodes feed in, it errors with: "Detected
   N disjoint backward regions that require recomputation, but
   remat only supports one such region in a forward-loss-backward
   graph."

2. joint_transformer_block_bucketing_reordering_pass: wrap with
   skip_module(["loss", "lm_head"]). The bucketing pass topologically
   reorders ops to overlap collectives with compute but uses arg-edge
   topology only, so it doesn't track tensor aliasing/mutation
   dependencies. ChunkedCELoss's GradAccumulator populates a buffer
   via ``aten.copy_(slice_view, src)`` in-place writes; the
   downstream ``view + to`` that read the buffer have no arg-edge
   dependence on the writes (the dependency is via shared storage
   between ``slice_view`` and the buffer, not via FX node args).

   The bucketing pass therefore sees the readers as freely movable
   compute and pulls them into an overlap window of a downstream
   collective — leaving the readers seeing the unwritten zeros
   buffer. Empirically: ``accumulated_grad`` returned for
   ``hidden_states`` is all-zero at runtime (verified by forcing
   ``torch.ones_like`` and watching grad_norm jump), so decoder
   backward propagates zero and every decoder gradient is zero.
   Loss matches eager step 1 (forward path is unaffected) but
   diverges step 2+ because the optimizer only updates the lm_head.

   Wrapping the bucketing entry in ``skip_module`` shields the
   loss/lm_head region behind ``control_deps`` HOPs so the bucketing
   pass treats it as an opaque ordered chain and respects the
   original write-then-read sequence.

End-to-end verification of the cumulative stack (this commit + the
flip in the next commit) is documented in the next commit's message.

[ghstack-poisoned]
…d bucketing passes"

Two pass-level fixes needed for ChunkedCELoss to compose correctly
with graph_trainer's compile pipeline. Neither fix exercises a
ChunkedCELoss code path on its own (graph_trainer's
``to_graph_trainer_config`` still swaps ChunkedCELoss to
CrossEntropyLoss until the next commit flips the toggle); the fixes
land here so the toggle commit doesn't bundle pass-pipeline changes
with config flips.

1. apply_sac_pass: skip nodes whose module is outside the transformer
   layer stack (``layer_id == _NOT_IN_LAYERS``). Matches eager
   ``apply_ac`` (torchtitan/distributed/activation_checkpoint.py),
   which iterates ``model.layers.named_children()`` and wraps each
   transformer block — never the loss / lm_head / norm at the top
   level.

   Without this skip, ChunkedCELoss's chunked region (lm_head +
   per-chunk ce_loss) gets tagged ``PREFER_RECOMPUTE``. Per-chunk
   ``chunk_loss.backward()`` dispatches autograd ops that get tagged
   ``meta["autograd_backward"] = True`` (one tagged region per
   chunk, plus the outer training-loop backward). When the upstream
   ``remat_using_tags_for_fwd_loss_bwd_graph`` pass then walks the
   joint graph and finds N+1 disjoint backward regions where
   PREFER_RECOMPUTE forward nodes feed in, it errors with: "Detected
   N disjoint backward regions that require recomputation, but
   remat only supports one such region in a forward-loss-backward
   graph."

2. joint_transformer_block_bucketing_reordering_pass: wrap with
   skip_module(["loss", "lm_head"]). The bucketing pass topologically
   reorders ops to overlap collectives with compute but uses arg-edge
   topology only, so it doesn't track tensor aliasing/mutation
   dependencies. ChunkedCELoss's GradAccumulator populates a buffer
   via ``aten.copy_(slice_view, src)`` in-place writes; the
   downstream ``view + to`` that read the buffer have no arg-edge
   dependence on the writes (the dependency is via shared storage
   between ``slice_view`` and the buffer, not via FX node args).

   The bucketing pass therefore sees the readers as freely movable
   compute and pulls them into an overlap window of a downstream
   collective — leaving the readers seeing the unwritten zeros
   buffer. Empirically: ``accumulated_grad`` returned for
   ``hidden_states`` is all-zero at runtime (verified by forcing
   ``torch.ones_like`` and watching grad_norm jump), so decoder
   backward propagates zero and every decoder gradient is zero.
   Loss matches eager step 1 (forward path is unaffected) but
   diverges step 2+ because the optimizer only updates the lm_head.

   Wrapping the bucketing entry in ``skip_module`` shields the
   loss/lm_head region behind ``control_deps`` HOPs so the bucketing
   pass treats it as an opaque ordered chain and respects the
   original write-then-read sequence.

End-to-end verification of the cumulative stack (this commit + the
flip in the next commit) is documented in the next commit's message.

[ghstack-poisoned]
…d bucketing passes"

Two pass-level fixes needed for ChunkedCELoss to compose correctly
with graph_trainer's compile pipeline. Neither fix exercises a
ChunkedCELoss code path on its own (graph_trainer's
``to_graph_trainer_config`` still swaps ChunkedCELoss to
CrossEntropyLoss until the next commit flips the toggle); the fixes
land here so the toggle commit doesn't bundle pass-pipeline changes
with config flips.

1. apply_sac_pass: skip nodes whose module is outside the transformer
   layer stack (``layer_id == _NOT_IN_LAYERS``). Matches eager
   ``apply_ac`` (torchtitan/distributed/activation_checkpoint.py),
   which iterates ``model.layers.named_children()`` and wraps each
   transformer block — never the loss / lm_head / norm at the top
   level.

   Without this skip, ChunkedCELoss's chunked region (lm_head +
   per-chunk ce_loss) gets tagged ``PREFER_RECOMPUTE``. Per-chunk
   ``chunk_loss.backward()`` dispatches autograd ops that get tagged
   ``meta["autograd_backward"] = True`` (one tagged region per
   chunk, plus the outer training-loop backward). When the upstream
   ``remat_using_tags_for_fwd_loss_bwd_graph`` pass then walks the
   joint graph and finds N+1 disjoint backward regions where
   PREFER_RECOMPUTE forward nodes feed in, it errors with: "Detected
   N disjoint backward regions that require recomputation, but
   remat only supports one such region in a forward-loss-backward
   graph."

2. joint_transformer_block_bucketing_reordering_pass: wrap with
   skip_module(["loss", "lm_head"]). The bucketing pass topologically
   reorders ops to overlap collectives with compute but uses arg-edge
   topology only, so it doesn't track tensor aliasing/mutation
   dependencies. ChunkedCELoss's GradAccumulator populates a buffer
   via ``aten.copy_(slice_view, src)`` in-place writes; the
   downstream ``view + to`` that read the buffer have no arg-edge
   dependence on the writes (the dependency is via shared storage
   between ``slice_view`` and the buffer, not via FX node args).

   The bucketing pass therefore sees the readers as freely movable
   compute and pulls them into an overlap window of a downstream
   collective — leaving the readers seeing the unwritten zeros
   buffer. Empirically: ``accumulated_grad`` returned for
   ``hidden_states`` is all-zero at runtime (verified by forcing
   ``torch.ones_like`` and watching grad_norm jump), so decoder
   backward propagates zero and every decoder gradient is zero.
   Loss matches eager step 1 (forward path is unaffected) but
   diverges step 2+ because the optimizer only updates the lm_head.

   Wrapping the bucketing entry in ``skip_module`` shields the
   loss/lm_head region behind ``control_deps`` HOPs so the bucketing
   pass treats it as an opaque ordered chain and respects the
   original write-then-read sequence.

End-to-end verification of the cumulative stack (this commit + the
flip in the next commit) is documented in the next commit's message.

[ghstack-poisoned]
…d bucketing passes"

Two pass-level fixes needed for ChunkedCELoss to compose correctly
with graph_trainer's compile pipeline. Neither fix exercises a
ChunkedCELoss code path on its own (graph_trainer's
``to_graph_trainer_config`` still swaps ChunkedCELoss to
CrossEntropyLoss until the next commit flips the toggle); the fixes
land here so the toggle commit doesn't bundle pass-pipeline changes
with config flips.

1. apply_sac_pass: skip nodes whose module is outside the transformer
   layer stack (``layer_id == _NOT_IN_LAYERS``). Matches eager
   ``apply_ac`` (torchtitan/distributed/activation_checkpoint.py),
   which iterates ``model.layers.named_children()`` and wraps each
   transformer block — never the loss / lm_head / norm at the top
   level.

   Without this skip, ChunkedCELoss's chunked region (lm_head +
   per-chunk ce_loss) gets tagged ``PREFER_RECOMPUTE``. Per-chunk
   ``chunk_loss.backward()`` dispatches autograd ops that get tagged
   ``meta["autograd_backward"] = True`` (one tagged region per
   chunk, plus the outer training-loop backward). When the upstream
   ``remat_using_tags_for_fwd_loss_bwd_graph`` pass then walks the
   joint graph and finds N+1 disjoint backward regions where
   PREFER_RECOMPUTE forward nodes feed in, it errors with: "Detected
   N disjoint backward regions that require recomputation, but
   remat only supports one such region in a forward-loss-backward
   graph."

2. joint_transformer_block_bucketing_reordering_pass: wrap with
   skip_module(["loss", "lm_head"]). The bucketing pass topologically
   reorders ops to overlap collectives with compute but uses arg-edge
   topology only, so it doesn't track tensor aliasing/mutation
   dependencies. ChunkedCELoss's GradAccumulator populates a buffer
   via ``aten.copy_(slice_view, src)`` in-place writes; the
   downstream ``view + to`` that read the buffer have no arg-edge
   dependence on the writes (the dependency is via shared storage
   between ``slice_view`` and the buffer, not via FX node args).

   The bucketing pass therefore sees the readers as freely movable
   compute and pulls them into an overlap window of a downstream
   collective — leaving the readers seeing the unwritten zeros
   buffer. Empirically: ``accumulated_grad`` returned for
   ``hidden_states`` is all-zero at runtime (verified by forcing
   ``torch.ones_like`` and watching grad_norm jump), so decoder
   backward propagates zero and every decoder gradient is zero.
   Loss matches eager step 1 (forward path is unaffected) but
   diverges step 2+ because the optimizer only updates the lm_head.

   Wrapping the bucketing entry in ``skip_module`` shields the
   loss/lm_head region behind ``control_deps`` HOPs so the bucketing
   pass treats it as an opaque ordered chain and respects the
   original write-then-read sequence.

End-to-end verification of the cumulative stack (this commit + the
flip in the next commit) is documented in the next commit's message.

[ghstack-poisoned]
# break the read-after-write ordering.
preserve_ops_order(["loss", "lm_head"])(
functools.partial(
joint_transformer_block_bucketing_reordering_pass,

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 had previously intended to ban the use of topo_sort in graph pass to prevent such case from happening.

This preserve_ops_order is giving me some new ideas.

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.

Yeah, we could do this partial-order thing through annotations/graph passes.

ydwu4 added 7 commits May 6, 2026 21:50
…d bucketing passes"

Two pass-level fixes needed for ChunkedCELoss to compose correctly
with graph_trainer's compile pipeline. Neither fix exercises a
ChunkedCELoss code path on its own (graph_trainer's
``to_graph_trainer_config`` still swaps ChunkedCELoss to
CrossEntropyLoss until the next commit flips the toggle); the fixes
land here so the toggle commit doesn't bundle pass-pipeline changes
with config flips.

1. apply_sac_pass: skip nodes whose module is outside the transformer
   layer stack (``layer_id == _NOT_IN_LAYERS``). Matches eager
   ``apply_ac`` (torchtitan/distributed/activation_checkpoint.py),
   which iterates ``model.layers.named_children()`` and wraps each
   transformer block — never the loss / lm_head / norm at the top
   level.

   Without this skip, ChunkedCELoss's chunked region (lm_head +
   per-chunk ce_loss) gets tagged ``PREFER_RECOMPUTE``. Per-chunk
   ``chunk_loss.backward()`` dispatches autograd ops that get tagged
   ``meta["autograd_backward"] = True`` (one tagged region per
   chunk, plus the outer training-loop backward). When the upstream
   ``remat_using_tags_for_fwd_loss_bwd_graph`` pass then walks the
   joint graph and finds N+1 disjoint backward regions where
   PREFER_RECOMPUTE forward nodes feed in, it errors with: "Detected
   N disjoint backward regions that require recomputation, but
   remat only supports one such region in a forward-loss-backward
   graph."

2. joint_transformer_block_bucketing_reordering_pass: wrap with
   skip_module(["loss", "lm_head"]). The bucketing pass topologically
   reorders ops to overlap collectives with compute but uses arg-edge
   topology only, so it doesn't track tensor aliasing/mutation
   dependencies. ChunkedCELoss's GradAccumulator populates a buffer
   via ``aten.copy_(slice_view, src)`` in-place writes; the
   downstream ``view + to`` that read the buffer have no arg-edge
   dependence on the writes (the dependency is via shared storage
   between ``slice_view`` and the buffer, not via FX node args).

   The bucketing pass therefore sees the readers as freely movable
   compute and pulls them into an overlap window of a downstream
   collective — leaving the readers seeing the unwritten zeros
   buffer. Empirically: ``accumulated_grad`` returned for
   ``hidden_states`` is all-zero at runtime (verified by forcing
   ``torch.ones_like`` and watching grad_norm jump), so decoder
   backward propagates zero and every decoder gradient is zero.
   Loss matches eager step 1 (forward path is unaffected) but
   diverges step 2+ because the optimizer only updates the lm_head.

   Wrapping the bucketing entry in ``skip_module`` shields the
   loss/lm_head region behind ``control_deps`` HOPs so the bucketing
   pass treats it as an opaque ordered chain and respects the
   original write-then-read sequence.

End-to-end verification of the cumulative stack (this commit + the
flip in the next commit) is documented in the next commit's message.

[ghstack-poisoned]
…d bucketing passes"

Two pass-level fixes needed for ChunkedCELoss to compose correctly
with graph_trainer's compile pipeline. Neither fix exercises a
ChunkedCELoss code path on its own (graph_trainer's
``to_graph_trainer_config`` still swaps ChunkedCELoss to
CrossEntropyLoss until the next commit flips the toggle); the fixes
land here so the toggle commit doesn't bundle pass-pipeline changes
with config flips.

1. apply_sac_pass: skip nodes whose module is outside the transformer
   layer stack (``layer_id == _NOT_IN_LAYERS``). Matches eager
   ``apply_ac`` (torchtitan/distributed/activation_checkpoint.py),
   which iterates ``model.layers.named_children()`` and wraps each
   transformer block — never the loss / lm_head / norm at the top
   level.

   Without this skip, ChunkedCELoss's chunked region (lm_head +
   per-chunk ce_loss) gets tagged ``PREFER_RECOMPUTE``. Per-chunk
   ``chunk_loss.backward()`` dispatches autograd ops that get tagged
   ``meta["autograd_backward"] = True`` (one tagged region per
   chunk, plus the outer training-loop backward). When the upstream
   ``remat_using_tags_for_fwd_loss_bwd_graph`` pass then walks the
   joint graph and finds N+1 disjoint backward regions where
   PREFER_RECOMPUTE forward nodes feed in, it errors with: "Detected
   N disjoint backward regions that require recomputation, but
   remat only supports one such region in a forward-loss-backward
   graph."

2. joint_transformer_block_bucketing_reordering_pass: wrap with
   skip_module(["loss", "lm_head"]). The bucketing pass topologically
   reorders ops to overlap collectives with compute but uses arg-edge
   topology only, so it doesn't track tensor aliasing/mutation
   dependencies. ChunkedCELoss's GradAccumulator populates a buffer
   via ``aten.copy_(slice_view, src)`` in-place writes; the
   downstream ``view + to`` that read the buffer have no arg-edge
   dependence on the writes (the dependency is via shared storage
   between ``slice_view`` and the buffer, not via FX node args).

   The bucketing pass therefore sees the readers as freely movable
   compute and pulls them into an overlap window of a downstream
   collective — leaving the readers seeing the unwritten zeros
   buffer. Empirically: ``accumulated_grad`` returned for
   ``hidden_states`` is all-zero at runtime (verified by forcing
   ``torch.ones_like`` and watching grad_norm jump), so decoder
   backward propagates zero and every decoder gradient is zero.
   Loss matches eager step 1 (forward path is unaffected) but
   diverges step 2+ because the optimizer only updates the lm_head.

   Wrapping the bucketing entry in ``skip_module`` shields the
   loss/lm_head region behind ``control_deps`` HOPs so the bucketing
   pass treats it as an opaque ordered chain and respects the
   original write-then-read sequence.

End-to-end verification of the cumulative stack (this commit + the
flip in the next commit) is documented in the next commit's message.

[ghstack-poisoned]
…d bucketing passes"

Two pass-level fixes needed for ChunkedCELoss to compose correctly
with graph_trainer's compile pipeline. Neither fix exercises a
ChunkedCELoss code path on its own (graph_trainer's
``to_graph_trainer_config`` still swaps ChunkedCELoss to
CrossEntropyLoss until the next commit flips the toggle); the fixes
land here so the toggle commit doesn't bundle pass-pipeline changes
with config flips.

1. apply_sac_pass: skip nodes whose module is outside the transformer
   layer stack (``layer_id == _NOT_IN_LAYERS``). Matches eager
   ``apply_ac`` (torchtitan/distributed/activation_checkpoint.py),
   which iterates ``model.layers.named_children()`` and wraps each
   transformer block — never the loss / lm_head / norm at the top
   level.

   Without this skip, ChunkedCELoss's chunked region (lm_head +
   per-chunk ce_loss) gets tagged ``PREFER_RECOMPUTE``. Per-chunk
   ``chunk_loss.backward()`` dispatches autograd ops that get tagged
   ``meta["autograd_backward"] = True`` (one tagged region per
   chunk, plus the outer training-loop backward). When the upstream
   ``remat_using_tags_for_fwd_loss_bwd_graph`` pass then walks the
   joint graph and finds N+1 disjoint backward regions where
   PREFER_RECOMPUTE forward nodes feed in, it errors with: "Detected
   N disjoint backward regions that require recomputation, but
   remat only supports one such region in a forward-loss-backward
   graph."

2. joint_transformer_block_bucketing_reordering_pass: wrap with
   skip_module(["loss", "lm_head"]). The bucketing pass topologically
   reorders ops to overlap collectives with compute but uses arg-edge
   topology only, so it doesn't track tensor aliasing/mutation
   dependencies. ChunkedCELoss's GradAccumulator populates a buffer
   via ``aten.copy_(slice_view, src)`` in-place writes; the
   downstream ``view + to`` that read the buffer have no arg-edge
   dependence on the writes (the dependency is via shared storage
   between ``slice_view`` and the buffer, not via FX node args).

   The bucketing pass therefore sees the readers as freely movable
   compute and pulls them into an overlap window of a downstream
   collective — leaving the readers seeing the unwritten zeros
   buffer. Empirically: ``accumulated_grad`` returned for
   ``hidden_states`` is all-zero at runtime (verified by forcing
   ``torch.ones_like`` and watching grad_norm jump), so decoder
   backward propagates zero and every decoder gradient is zero.
   Loss matches eager step 1 (forward path is unaffected) but
   diverges step 2+ because the optimizer only updates the lm_head.

   Wrapping the bucketing entry in ``skip_module`` shields the
   loss/lm_head region behind ``control_deps`` HOPs so the bucketing
   pass treats it as an opaque ordered chain and respects the
   original write-then-read sequence.

End-to-end verification of the cumulative stack (this commit + the
flip in the next commit) is documented in the next commit's message.

[ghstack-poisoned]
…d bucketing passes"

Two pass-level fixes needed for ChunkedCELoss to compose correctly
with graph_trainer's compile pipeline. Neither fix exercises a
ChunkedCELoss code path on its own (graph_trainer's
``to_graph_trainer_config`` still swaps ChunkedCELoss to
CrossEntropyLoss until the next commit flips the toggle); the fixes
land here so the toggle commit doesn't bundle pass-pipeline changes
with config flips.

1. apply_sac_pass: skip nodes whose module is outside the transformer
   layer stack (``layer_id == _NOT_IN_LAYERS``). Matches eager
   ``apply_ac`` (torchtitan/distributed/activation_checkpoint.py),
   which iterates ``model.layers.named_children()`` and wraps each
   transformer block — never the loss / lm_head / norm at the top
   level.

   Without this skip, ChunkedCELoss's chunked region (lm_head +
   per-chunk ce_loss) gets tagged ``PREFER_RECOMPUTE``. Per-chunk
   ``chunk_loss.backward()`` dispatches autograd ops that get tagged
   ``meta["autograd_backward"] = True`` (one tagged region per
   chunk, plus the outer training-loop backward). When the upstream
   ``remat_using_tags_for_fwd_loss_bwd_graph`` pass then walks the
   joint graph and finds N+1 disjoint backward regions where
   PREFER_RECOMPUTE forward nodes feed in, it errors with: "Detected
   N disjoint backward regions that require recomputation, but
   remat only supports one such region in a forward-loss-backward
   graph."

2. joint_transformer_block_bucketing_reordering_pass: wrap with
   skip_module(["loss", "lm_head"]). The bucketing pass topologically
   reorders ops to overlap collectives with compute but uses arg-edge
   topology only, so it doesn't track tensor aliasing/mutation
   dependencies. ChunkedCELoss's GradAccumulator populates a buffer
   via ``aten.copy_(slice_view, src)`` in-place writes; the
   downstream ``view + to`` that read the buffer have no arg-edge
   dependence on the writes (the dependency is via shared storage
   between ``slice_view`` and the buffer, not via FX node args).

   The bucketing pass therefore sees the readers as freely movable
   compute and pulls them into an overlap window of a downstream
   collective — leaving the readers seeing the unwritten zeros
   buffer. Empirically: ``accumulated_grad`` returned for
   ``hidden_states`` is all-zero at runtime (verified by forcing
   ``torch.ones_like`` and watching grad_norm jump), so decoder
   backward propagates zero and every decoder gradient is zero.
   Loss matches eager step 1 (forward path is unaffected) but
   diverges step 2+ because the optimizer only updates the lm_head.

   Wrapping the bucketing entry in ``skip_module`` shields the
   loss/lm_head region behind ``control_deps`` HOPs so the bucketing
   pass treats it as an opaque ordered chain and respects the
   original write-then-read sequence.

End-to-end verification of the cumulative stack (this commit + the
flip in the next commit) is documented in the next commit's message.

[ghstack-poisoned]
…d bucketing passes"

Two pass-level fixes needed for ChunkedCELoss to compose correctly
with graph_trainer's compile pipeline. Neither fix exercises a
ChunkedCELoss code path on its own (graph_trainer's
``to_graph_trainer_config`` still swaps ChunkedCELoss to
CrossEntropyLoss until the next commit flips the toggle); the fixes
land here so the toggle commit doesn't bundle pass-pipeline changes
with config flips.

1. apply_sac_pass: skip nodes whose module is outside the transformer
   layer stack (``layer_id == _NOT_IN_LAYERS``). Matches eager
   ``apply_ac`` (torchtitan/distributed/activation_checkpoint.py),
   which iterates ``model.layers.named_children()`` and wraps each
   transformer block — never the loss / lm_head / norm at the top
   level.

   Without this skip, ChunkedCELoss's chunked region (lm_head +
   per-chunk ce_loss) gets tagged ``PREFER_RECOMPUTE``. Per-chunk
   ``chunk_loss.backward()`` dispatches autograd ops that get tagged
   ``meta["autograd_backward"] = True`` (one tagged region per
   chunk, plus the outer training-loop backward). When the upstream
   ``remat_using_tags_for_fwd_loss_bwd_graph`` pass then walks the
   joint graph and finds N+1 disjoint backward regions where
   PREFER_RECOMPUTE forward nodes feed in, it errors with: "Detected
   N disjoint backward regions that require recomputation, but
   remat only supports one such region in a forward-loss-backward
   graph."

2. joint_transformer_block_bucketing_reordering_pass: wrap with
   skip_module(["loss", "lm_head"]). The bucketing pass topologically
   reorders ops to overlap collectives with compute but uses arg-edge
   topology only, so it doesn't track tensor aliasing/mutation
   dependencies. ChunkedCELoss's GradAccumulator populates a buffer
   via ``aten.copy_(slice_view, src)`` in-place writes; the
   downstream ``view + to`` that read the buffer have no arg-edge
   dependence on the writes (the dependency is via shared storage
   between ``slice_view`` and the buffer, not via FX node args).

   The bucketing pass therefore sees the readers as freely movable
   compute and pulls them into an overlap window of a downstream
   collective — leaving the readers seeing the unwritten zeros
   buffer. Empirically: ``accumulated_grad`` returned for
   ``hidden_states`` is all-zero at runtime (verified by forcing
   ``torch.ones_like`` and watching grad_norm jump), so decoder
   backward propagates zero and every decoder gradient is zero.
   Loss matches eager step 1 (forward path is unaffected) but
   diverges step 2+ because the optimizer only updates the lm_head.

   Wrapping the bucketing entry in ``skip_module`` shields the
   loss/lm_head region behind ``control_deps`` HOPs so the bucketing
   pass treats it as an opaque ordered chain and respects the
   original write-then-read sequence.

End-to-end verification of the cumulative stack (this commit + the
flip in the next commit) is documented in the next commit's message.

[ghstack-poisoned]
…d bucketing passes"

Two pass-level fixes needed for ChunkedCELoss to compose correctly
with graph_trainer's compile pipeline. Neither fix exercises a
ChunkedCELoss code path on its own (graph_trainer's
``to_graph_trainer_config`` still swaps ChunkedCELoss to
CrossEntropyLoss until the next commit flips the toggle); the fixes
land here so the toggle commit doesn't bundle pass-pipeline changes
with config flips.

1. apply_sac_pass: skip nodes whose module is outside the transformer
   layer stack (``layer_id == _NOT_IN_LAYERS``). Matches eager
   ``apply_ac`` (torchtitan/distributed/activation_checkpoint.py),
   which iterates ``model.layers.named_children()`` and wraps each
   transformer block — never the loss / lm_head / norm at the top
   level.

   Without this skip, ChunkedCELoss's chunked region (lm_head +
   per-chunk ce_loss) gets tagged ``PREFER_RECOMPUTE``. Per-chunk
   ``chunk_loss.backward()`` dispatches autograd ops that get tagged
   ``meta["autograd_backward"] = True`` (one tagged region per
   chunk, plus the outer training-loop backward). When the upstream
   ``remat_using_tags_for_fwd_loss_bwd_graph`` pass then walks the
   joint graph and finds N+1 disjoint backward regions where
   PREFER_RECOMPUTE forward nodes feed in, it errors with: "Detected
   N disjoint backward regions that require recomputation, but
   remat only supports one such region in a forward-loss-backward
   graph."

2. joint_transformer_block_bucketing_reordering_pass: wrap with
   skip_module(["loss", "lm_head"]). The bucketing pass topologically
   reorders ops to overlap collectives with compute but uses arg-edge
   topology only, so it doesn't track tensor aliasing/mutation
   dependencies. ChunkedCELoss's GradAccumulator populates a buffer
   via ``aten.copy_(slice_view, src)`` in-place writes; the
   downstream ``view + to`` that read the buffer have no arg-edge
   dependence on the writes (the dependency is via shared storage
   between ``slice_view`` and the buffer, not via FX node args).

   The bucketing pass therefore sees the readers as freely movable
   compute and pulls them into an overlap window of a downstream
   collective — leaving the readers seeing the unwritten zeros
   buffer. Empirically: ``accumulated_grad`` returned for
   ``hidden_states`` is all-zero at runtime (verified by forcing
   ``torch.ones_like`` and watching grad_norm jump), so decoder
   backward propagates zero and every decoder gradient is zero.
   Loss matches eager step 1 (forward path is unaffected) but
   diverges step 2+ because the optimizer only updates the lm_head.

   Wrapping the bucketing entry in ``skip_module`` shields the
   loss/lm_head region behind ``control_deps`` HOPs so the bucketing
   pass treats it as an opaque ordered chain and respects the
   original write-then-read sequence.

End-to-end verification of the cumulative stack (this commit + the
flip in the next commit) is documented in the next commit's message.

[ghstack-poisoned]
…d bucketing passes"

Two pass-level fixes needed for ChunkedCELoss to compose correctly
with graph_trainer's compile pipeline. Neither fix exercises a
ChunkedCELoss code path on its own (graph_trainer's
``to_graph_trainer_config`` still swaps ChunkedCELoss to
CrossEntropyLoss until the next commit flips the toggle); the fixes
land here so the toggle commit doesn't bundle pass-pipeline changes
with config flips.

1. apply_sac_pass: skip nodes whose module is outside the transformer
   layer stack (``layer_id == _NOT_IN_LAYERS``). Matches eager
   ``apply_ac`` (torchtitan/distributed/activation_checkpoint.py),
   which iterates ``model.layers.named_children()`` and wraps each
   transformer block — never the loss / lm_head / norm at the top
   level.

   Without this skip, ChunkedCELoss's chunked region (lm_head +
   per-chunk ce_loss) gets tagged ``PREFER_RECOMPUTE``. Per-chunk
   ``chunk_loss.backward()`` dispatches autograd ops that get tagged
   ``meta["autograd_backward"] = True`` (one tagged region per
   chunk, plus the outer training-loop backward). When the upstream
   ``remat_using_tags_for_fwd_loss_bwd_graph`` pass then walks the
   joint graph and finds N+1 disjoint backward regions where
   PREFER_RECOMPUTE forward nodes feed in, it errors with: "Detected
   N disjoint backward regions that require recomputation, but
   remat only supports one such region in a forward-loss-backward
   graph."

2. joint_transformer_block_bucketing_reordering_pass: wrap with
   skip_module(["loss", "lm_head"]). The bucketing pass topologically
   reorders ops to overlap collectives with compute but uses arg-edge
   topology only, so it doesn't track tensor aliasing/mutation
   dependencies. ChunkedCELoss's GradAccumulator populates a buffer
   via ``aten.copy_(slice_view, src)`` in-place writes; the
   downstream ``view + to`` that read the buffer have no arg-edge
   dependence on the writes (the dependency is via shared storage
   between ``slice_view`` and the buffer, not via FX node args).

   The bucketing pass therefore sees the readers as freely movable
   compute and pulls them into an overlap window of a downstream
   collective — leaving the readers seeing the unwritten zeros
   buffer. Empirically: ``accumulated_grad`` returned for
   ``hidden_states`` is all-zero at runtime (verified by forcing
   ``torch.ones_like`` and watching grad_norm jump), so decoder
   backward propagates zero and every decoder gradient is zero.
   Loss matches eager step 1 (forward path is unaffected) but
   diverges step 2+ because the optimizer only updates the lm_head.

   Wrapping the bucketing entry in ``skip_module`` shields the
   loss/lm_head region behind ``control_deps`` HOPs so the bucketing
   pass treats it as an opaque ordered chain and respects the
   original write-then-read sequence.

End-to-end verification of the cumulative stack (this commit + the
flip in the next commit) is documented in the next commit's message.

[ghstack-poisoned]
ydwu4 added 2 commits May 7, 2026 16:40
…d bucketing passes"

Two pass-level fixes needed for ChunkedCELoss to compose correctly
with graph_trainer's compile pipeline. Neither fix exercises a
ChunkedCELoss code path on its own (graph_trainer's
``to_graph_trainer_config`` still swaps ChunkedCELoss to
CrossEntropyLoss until the next commit flips the toggle); the fixes
land here so the toggle commit doesn't bundle pass-pipeline changes
with config flips.

1. apply_sac_pass: skip nodes whose module is outside the transformer
   layer stack (``layer_id == _NOT_IN_LAYERS``). Matches eager
   ``apply_ac`` (torchtitan/distributed/activation_checkpoint.py),
   which iterates ``model.layers.named_children()`` and wraps each
   transformer block — never the loss / lm_head / norm at the top
   level.

   Without this skip, ChunkedCELoss's chunked region (lm_head +
   per-chunk ce_loss) gets tagged ``PREFER_RECOMPUTE``. Per-chunk
   ``chunk_loss.backward()`` dispatches autograd ops that get tagged
   ``meta["autograd_backward"] = True`` (one tagged region per
   chunk, plus the outer training-loop backward). When the upstream
   ``remat_using_tags_for_fwd_loss_bwd_graph`` pass then walks the
   joint graph and finds N+1 disjoint backward regions where
   PREFER_RECOMPUTE forward nodes feed in, it errors with: "Detected
   N disjoint backward regions that require recomputation, but
   remat only supports one such region in a forward-loss-backward
   graph."

2. joint_transformer_block_bucketing_reordering_pass: wrap with
   skip_module(["loss", "lm_head"]). The bucketing pass topologically
   reorders ops to overlap collectives with compute but uses arg-edge
   topology only, so it doesn't track tensor aliasing/mutation
   dependencies. ChunkedCELoss's GradAccumulator populates a buffer
   via ``aten.copy_(slice_view, src)`` in-place writes; the
   downstream ``view + to`` that read the buffer have no arg-edge
   dependence on the writes (the dependency is via shared storage
   between ``slice_view`` and the buffer, not via FX node args).

   The bucketing pass therefore sees the readers as freely movable
   compute and pulls them into an overlap window of a downstream
   collective — leaving the readers seeing the unwritten zeros
   buffer. Empirically: ``accumulated_grad`` returned for
   ``hidden_states`` is all-zero at runtime (verified by forcing
   ``torch.ones_like`` and watching grad_norm jump), so decoder
   backward propagates zero and every decoder gradient is zero.
   Loss matches eager step 1 (forward path is unaffected) but
   diverges step 2+ because the optimizer only updates the lm_head.

   Wrapping the bucketing entry in ``skip_module`` shields the
   loss/lm_head region behind ``control_deps`` HOPs so the bucketing
   pass treats it as an opaque ordered chain and respects the
   original write-then-read sequence.

End-to-end verification of the cumulative stack (this commit + the
flip in the next commit) is documented in the next commit's message.

[ghstack-poisoned]
…d bucketing passes"

Two pass-level fixes needed for ChunkedCELoss to compose correctly
with graph_trainer's compile pipeline. Neither fix exercises a
ChunkedCELoss code path on its own (graph_trainer's
``to_graph_trainer_config`` still swaps ChunkedCELoss to
CrossEntropyLoss until the next commit flips the toggle); the fixes
land here so the toggle commit doesn't bundle pass-pipeline changes
with config flips.

1. apply_sac_pass: skip nodes whose module is outside the transformer
   layer stack (``layer_id == _NOT_IN_LAYERS``). Matches eager
   ``apply_ac`` (torchtitan/distributed/activation_checkpoint.py),
   which iterates ``model.layers.named_children()`` and wraps each
   transformer block — never the loss / lm_head / norm at the top
   level.

   Without this skip, ChunkedCELoss's chunked region (lm_head +
   per-chunk ce_loss) gets tagged ``PREFER_RECOMPUTE``. Per-chunk
   ``chunk_loss.backward()`` dispatches autograd ops that get tagged
   ``meta["autograd_backward"] = True`` (one tagged region per
   chunk, plus the outer training-loop backward). When the upstream
   ``remat_using_tags_for_fwd_loss_bwd_graph`` pass then walks the
   joint graph and finds N+1 disjoint backward regions where
   PREFER_RECOMPUTE forward nodes feed in, it errors with: "Detected
   N disjoint backward regions that require recomputation, but
   remat only supports one such region in a forward-loss-backward
   graph."

2. joint_transformer_block_bucketing_reordering_pass: wrap with
   skip_module(["loss", "lm_head"]). The bucketing pass topologically
   reorders ops to overlap collectives with compute but uses arg-edge
   topology only, so it doesn't track tensor aliasing/mutation
   dependencies. ChunkedCELoss's GradAccumulator populates a buffer
   via ``aten.copy_(slice_view, src)`` in-place writes; the
   downstream ``view + to`` that read the buffer have no arg-edge
   dependence on the writes (the dependency is via shared storage
   between ``slice_view`` and the buffer, not via FX node args).

   The bucketing pass therefore sees the readers as freely movable
   compute and pulls them into an overlap window of a downstream
   collective — leaving the readers seeing the unwritten zeros
   buffer. Empirically: ``accumulated_grad`` returned for
   ``hidden_states`` is all-zero at runtime (verified by forcing
   ``torch.ones_like`` and watching grad_norm jump), so decoder
   backward propagates zero and every decoder gradient is zero.
   Loss matches eager step 1 (forward path is unaffected) but
   diverges step 2+ because the optimizer only updates the lm_head.

   Wrapping the bucketing entry in ``skip_module`` shields the
   loss/lm_head region behind ``control_deps`` HOPs so the bucketing
   pass treats it as an opaque ordered chain and respects the
   original write-then-read sequence.

End-to-end verification of the cumulative stack (this commit + the
flip in the next commit) is documented in the next commit's message.

[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.
…d bucketing passes"

Two pass-level fixes needed for ChunkedCELoss to compose correctly
with graph_trainer's compile pipeline. Neither fix exercises a
ChunkedCELoss code path on its own (graph_trainer's
``to_graph_trainer_config`` still swaps ChunkedCELoss to
CrossEntropyLoss until the next commit flips the toggle); the fixes
land here so the toggle commit doesn't bundle pass-pipeline changes
with config flips.

1. apply_sac_pass: skip nodes whose module is outside the transformer
   layer stack (``layer_id == _NOT_IN_LAYERS``). Matches eager
   ``apply_ac`` (torchtitan/distributed/activation_checkpoint.py),
   which iterates ``model.layers.named_children()`` and wraps each
   transformer block — never the loss / lm_head / norm at the top
   level.

   Without this skip, ChunkedCELoss's chunked region (lm_head +
   per-chunk ce_loss) gets tagged ``PREFER_RECOMPUTE``. Per-chunk
   ``chunk_loss.backward()`` dispatches autograd ops that get tagged
   ``meta["autograd_backward"] = True`` (one tagged region per
   chunk, plus the outer training-loop backward). When the upstream
   ``remat_using_tags_for_fwd_loss_bwd_graph`` pass then walks the
   joint graph and finds N+1 disjoint backward regions where
   PREFER_RECOMPUTE forward nodes feed in, it errors with: "Detected
   N disjoint backward regions that require recomputation, but
   remat only supports one such region in a forward-loss-backward
   graph."

2. joint_transformer_block_bucketing_reordering_pass: wrap with
   skip_module(["loss", "lm_head"]). The bucketing pass topologically
   reorders ops to overlap collectives with compute but uses arg-edge
   topology only, so it doesn't track tensor aliasing/mutation
   dependencies. ChunkedCELoss's GradAccumulator populates a buffer
   via ``aten.copy_(slice_view, src)`` in-place writes; the
   downstream ``view + to`` that read the buffer have no arg-edge
   dependence on the writes (the dependency is via shared storage
   between ``slice_view`` and the buffer, not via FX node args).

   The bucketing pass therefore sees the readers as freely movable
   compute and pulls them into an overlap window of a downstream
   collective — leaving the readers seeing the unwritten zeros
   buffer. Empirically: ``accumulated_grad`` returned for
   ``hidden_states`` is all-zero at runtime (verified by forcing
   ``torch.ones_like`` and watching grad_norm jump), so decoder
   backward propagates zero and every decoder gradient is zero.
   Loss matches eager step 1 (forward path is unaffected) but
   diverges step 2+ because the optimizer only updates the lm_head.

   Wrapping the bucketing entry in ``skip_module`` shields the
   loss/lm_head region behind ``control_deps`` HOPs so the bucketing
   pass treats it as an opaque ordered chain and respects the
   original write-then-read sequence.

End-to-end verification of the cumulative stack (this commit + the
flip in the next commit) is documented in the next commit's message.

[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.
…d bucketing passes"

Two pass-level fixes needed for ChunkedCELoss to compose correctly
with graph_trainer's compile pipeline. Neither fix exercises a
ChunkedCELoss code path on its own (graph_trainer's
``to_graph_trainer_config`` still swaps ChunkedCELoss to
CrossEntropyLoss until the next commit flips the toggle); the fixes
land here so the toggle commit doesn't bundle pass-pipeline changes
with config flips.

1. apply_sac_pass: skip nodes whose module is outside the transformer
   layer stack (``layer_id == _NOT_IN_LAYERS``). Matches eager
   ``apply_ac`` (torchtitan/distributed/activation_checkpoint.py),
   which iterates ``model.layers.named_children()`` and wraps each
   transformer block — never the loss / lm_head / norm at the top
   level.

   Without this skip, ChunkedCELoss's chunked region (lm_head +
   per-chunk ce_loss) gets tagged ``PREFER_RECOMPUTE``. Per-chunk
   ``chunk_loss.backward()`` dispatches autograd ops that get tagged
   ``meta["autograd_backward"] = True`` (one tagged region per
   chunk, plus the outer training-loop backward). When the upstream
   ``remat_using_tags_for_fwd_loss_bwd_graph`` pass then walks the
   joint graph and finds N+1 disjoint backward regions where
   PREFER_RECOMPUTE forward nodes feed in, it errors with: "Detected
   N disjoint backward regions that require recomputation, but
   remat only supports one such region in a forward-loss-backward
   graph."

2. joint_transformer_block_bucketing_reordering_pass: wrap with
   skip_module(["loss", "lm_head"]). The bucketing pass topologically
   reorders ops to overlap collectives with compute but uses arg-edge
   topology only, so it doesn't track tensor aliasing/mutation
   dependencies. ChunkedCELoss's GradAccumulator populates a buffer
   via ``aten.copy_(slice_view, src)`` in-place writes; the
   downstream ``view + to`` that read the buffer have no arg-edge
   dependence on the writes (the dependency is via shared storage
   between ``slice_view`` and the buffer, not via FX node args).

   The bucketing pass therefore sees the readers as freely movable
   compute and pulls them into an overlap window of a downstream
   collective — leaving the readers seeing the unwritten zeros
   buffer. Empirically: ``accumulated_grad`` returned for
   ``hidden_states`` is all-zero at runtime (verified by forcing
   ``torch.ones_like`` and watching grad_norm jump), so decoder
   backward propagates zero and every decoder gradient is zero.
   Loss matches eager step 1 (forward path is unaffected) but
   diverges step 2+ because the optimizer only updates the lm_head.

   Wrapping the bucketing entry in ``skip_module`` shields the
   loss/lm_head region behind ``control_deps`` HOPs so the bucketing
   pass treats it as an opaque ordered chain and respects the
   original write-then-read sequence.

End-to-end verification of the cumulative stack (this commit + the
flip in the next commit) is documented in the next commit's message.

[ghstack-poisoned]
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.

2 participants