Repository navigation
Conversation
… 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
requested review from
SherlockNoMad,
aditvenk,
sanketpurandare,
tianyu-l,
xmfan and
yiming0416
as code owners
May 6, 2026 19:32
This was referenced May 6, 2026
…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]
This was referenced May 6, 2026
…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, |
Contributor
There was a problem hiding this comment.
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.
Contributor
Author
There was a problem hiding this comment.
Yeah, we could do this partial-order thing through annotations/graph passes.
…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]
…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]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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_configstill swaps ChunkedCELoss toCrossEntropyLoss until the next commit flips the toggle); the fixes
land here so the toggle commit doesn't bundle pass-pipeline changes
with config flips.
apply_sac_pass: skip nodes whose module is outside the transformer
layer stack (
layer_id == _NOT_IN_LAYERS). Matches eagerapply_ac(torchtitan/distributed/activation_checkpoint.py),which iterates
model.layers.named_children()and wraps eachtransformer 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-chunkchunk_loss.backward()dispatches autograd ops that get taggedmeta["autograd_backward"] = True(one tagged region perchunk, plus the outer training-loop backward). When the upstream
remat_using_tags_for_fwd_loss_bwd_graphpass then walks thejoint 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."
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; thedownstream
view + tothat read the buffer have no arg-edgedependence on the writes (the dependency is via shared storage
between
slice_viewand 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_gradreturned forhidden_statesis all-zero at runtime (verified by forcingtorch.ones_likeand watching grad_norm jump), so decoderbackward 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_moduleshields theloss/lm_head region behind
control_depsHOPs so the bucketingpass 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.