Repository navigation
Make ChunkedCELoss support torch.autograd.grad - #3249
Conversation
…ding externally 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. [ghstack-poisoned]
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.
[ghstack-poisoned]
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.
[ghstack-poisoned]
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.
[ghstack-poisoned]
| """If True, plumb the sharded lm_head param grads (already produced | ||
| by the chunk loop's reduce-scatter) out as explicit autograd outputs | ||
| so outer ``torch.autograd.grad(loss, [hidden_states, | ||
| *lm_head.parameters()])`` returns them directly — no reliance on | ||
| ``param.grad`` side effects. Required for FX tracing / replay where | ||
| side-effecting ``.grad`` writes don't survive. Compatible with both | ||
| outer ``loss.backward()`` and ``torch.autograd.grad`` consumers. |
There was a problem hiding this comment.
this is a smart fix.
do you have a tlparse on the graph of chunked loss I can take a look?
There was a problem hiding this comment.
There was a problem hiding this comment.
nice, the graph looks good to me.
| class Config(BaseLoss.Config): | ||
| num_chunks: int = 8 | ||
| """Number of chunks to split the sequence into.""" | ||
| support_autograd_grad: bool = False |
There was a problem hiding this comment.
sounds that a cleaner, non-intrusive way would be
- making a subclass of chunked loss class, e.g. by turning the autograd function a class variable and override it
- swapping to use it for graph trainer configs
There was a problem hiding this comment.
Sure, refactored accordingly!
…grad"
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.
[ghstack-poisoned]
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.
[ghstack-poisoned]
…grad"
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.
[ghstack-poisoned]
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.
[ghstack-poisoned]
| ) | ||
|
|
||
|
|
||
| class ChunkedCELossWithParamGrads(ChunkedCELoss): |
There was a problem hiding this comment.
please define this in graph trainer, as it's not required as part of core
There was a problem hiding this comment.
Moved into graph trainer.
| return accumulated_grad, None, None | ||
|
|
||
|
|
||
| class _ChunkedLossWithParamGrads(torch.autograd.Function): |
…grad"
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.
[ghstack-poisoned]
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.
[ghstack-poisoned]
…grad"
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.
[ghstack-poisoned]
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.
[ghstack-poisoned]
…grad"
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.
[ghstack-poisoned]
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.
[ghstack-poisoned]
| @dataclass(kw_only=True, slots=True) | ||
| class Config(ChunkedCELoss.Config): | ||
| pass |
There was a problem hiding this comment.
not sure if this required or not?
There was a problem hiding this comment.
Probably not. Can just remove it I feel. If we need, we could add it back later.
|
in the latter PR, we should have a variant that uses chunked loss in the test_bitwise_deterministic.py |
…grad"
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.
[ghstack-poisoned]
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.
[ghstack-poisoned]
…grad"
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.
[ghstack-poisoned]
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.
[ghstack-poisoned]
…grad"
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.
[ghstack-poisoned]
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.
[ghstack-poisoned]
…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.
…grad"
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.
[ghstack-poisoned]
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.
[ghstack-poisoned]
… commit `659a0d`). This CL imports TorchTitan head and stabilizes the build. Supporting feature gaps to be done in follow-up CLs. **For a summary of major changes and disabled tests see [internal link]** In this CL, we bypass the [ban](https://github.com/pytorch/torchtitan/blob/1c40dd26a91b0489249011a53d1da69061b03d38/torchtitan/models/common/config_utils.py#L85) of SDPA backend for language models in `models/common/config_utils.py` so our monkey patch to apply splash attention kernel works. Deprecation of sdpa backend on TPU and supporting document packing in the SplashAttention kernel is handled in child cl/954755047 In OSS, torch>=2.12 is **required**. After this update several files import `DataParallelMeshDims` from `torch.distributed.fsdp` which is only available in torch >=2.12 It disables the following tests: b/540005818 Disabled for numerical divergences: - test_train_minimal_distributed llama3_fsdp - test_train_minimal_distributed llama3_simplefsdp - test_train_minimal_distributed qwen3_simplefsdp - test_flux_qkv_split TestFluxSingleStreamUnbind Disabled for other reasons: - b/540119277 test_fused_swiglu_override - circular import issue with spmd_type - b/540048441 graph trainer tests (upstream refactored trace_train_step into minimal_fx_tracer API): - b/540049946 deepseek_v3_tp_dtensor - Linear: output DTensor has placements (Shard(dim=1),), but out_src_shardings expects (Shard(dim=2),) Tested on OSS with image built from torch 2.12: - redacted SimpleFSDP Compiled: [10,925 TPS]([internal link]) (10,0922 at head) - FLUX SimpleFSDP Compiled (F32 + BF16 MP): [3,737 TPS]([internal link]) (3652 at head) - Llama3 SimpleFSDP Compiled: [5,444 TPS]([internal link]) (5384 at head) See the list of commits: pytorch/torchtitan@627126f...659a0d2 #MIGRATION_3P_PY_TORCHTITAN__DEFAULT - 95ae6a0 ci: regenerate qwen3_moe_rocm_mi350x.txt baseline with ac... by Rishi Sinha <[email protected]> - db5da4b Refactor pipeline parallel helpers for graph PP reuse (#2... by sanketpurandare <[email protected]> - 6065055 Revert precompile PRs (pytorch#3107, pytorch#3178) to fix CI (pytorch#3212) by Bob Ren <[email protected]> - 179d9e1 CP AllGather on the wrong dimension (pytorch#3206) by francesco-bertolotti <[email protected]> - f522db0 Fix commands in DSV3 readme (pytorch#3116) by Daniel Vega-Myhre <[email protected]> - 0b148a2 [CI] Run integration tests in parallel (pytorch#3144) by Yuankai Chen <[email protected]> - 080c1d4 [GraphTrainer] Annotate loss region with module_fqn (pytorch#3207) by Sherlock Huang <[email protected]> - b2cd149 Observability: structured logging + training instrumentat... by Felipe Mello <[email protected]> - 706ed8d [GraphTrainer] Annotate generated FX code with user sourc... by Aditya Venkataraman <[email protected]> - af8d243 [GraphTrainer] Skip identity-slice rewrite when start/end... by Aditya Venkataraman <[email protected]> - d3c96e8 [mxfp8] Fix MXFP8GroupedExpertsConverter to actually swap... by Aditya Venkataraman <[email protected]> - d341407 [MoE] Pad token count to a multiple of sp_size in AllToAl... by Jiani Wang <[email protected]> - 2ae1340 [rl] add import torch to provisioner bootstrap to avoid c... by Shuhua Yu <[email protected]> - 0b6a29e [rl] Set PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True... by Felipe Mello <[email protected]> - 2c237ae refactor get_attention_masks to use positions instead of ... by liangel-02 <[email protected]> - 74bac7e [graph_trainer] FSDP AG RS overlap (pytorch#3156) by Yiming Zhou <[email protected]> - b6830b2 Upgrades torchtitan-ubuntu docker image to 22.04 and CTK ... by Syed Tousif Ahmed <[email protected]> - 5fa7af6 [float8] Quantize GroupedExperts params during conversion... by Aditya Venkataraman <[email protected]> - e62ab09 [rl] Fix CI loss=0 and logprob=NaN (pytorch#3232) by Jiani Wang <[email protected]> - f32a5bb [GraphTrainer] Overhaul README for accuracy and clarity (... by Sherlock Huang <[email protected]> - e425316 [rl] Remove VLLMGenerator.__del__ cleanup method (pytorch#3224) by Danielle Pintz <[email protected]> - ef54395 [graph_trainer] Move all FSDP-specific passes to fsdp_pas... by Yiming Zhou <[email protected]> - 301384b [GraphTrainer] Register BlockMask pytree node in aot_fx_t... by Bob Ren <[email protected]> - a24b247 [graph_trainer] Disable cpu_offload_all CI test for upstr... by Sherlock Huang <[email protected]> - 2dfee86 [GraphTrainer] Update manifesto: hardware heterogeneity, ... by Sherlock Huang <[email protected]> - c6cfaa2 Re-land "Enable bucketing pass in precompile path" (pytorch#3107... by Bob Ren <[email protected]> - ae5ff10 [cpu-offloading] Implement prefetching for cpu offloading... by Michael Lazos <[email protected]> - 046fdbb Support mark_unbacked in minimal_fx_tracer (pytorch#3046) by Tugsbayasgalan Manlaibaatar <[email protected]> - 8599818 [rl] Add a tag to trigger RL CI runs (pytorch#3230) by Jiani Wang <[email protected]> - 466da8c [graph_trainer] Port remat_using_tags_for_fwd_loss_bwd_gr... by Sherlock Huang <[email protected]> - 94d5f59 Re-land "Fix FlexAttention precompile bitwise determinist... by Bob Ren <[email protected]> - e2fea3f Wrong token count in validation when CP>1 (pytorch#3257) by francesco-bertolotti <[email protected]> - 1d392ca [torchtitan][llama4_parallelize] fixing fsdp_mesh_info bu... by anshul-si <[email protected]> - d91a9fc [Qwen3VL] remove local_map for dtensor interpolation (pytorch#29... by Shuhua Yu <[email protected]> - 19f88a3 profiler: drop duplicate dataclass fields (pytorch#3227) by Felipe Mello <[email protected]> - 52f3142 [GraphTrainer] Log graph pass names and total time (pytorch#3261) by Sherlock Huang <[email protected]> - bf2842d [GraphTrainer] Add memory policy registry and extra graph... by Syed Tousif Ahmed <[email protected]> - 4ebb089 Tests HybridEP integration with GraphTrainer (pytorch#3184) by Syed Tousif Ahmed <[email protected]> - da6ff79 [rl] Graceful shutdown GRPO (pytorch#3238) by Felipe Mello <[email protected]> - 54887a3 [GraphTrainer] Add compile.disable_passes to selectively ... by Sherlock Huang <[email protected]> - 4ed3c53 [codex] Fix weight tying parameter accounting (pytorch#3225) by 岛石 <[email protected]> - 5638c49 [codex] Fix shared BOS and EOS token inference (pytorch#3279) by 岛石 <[email protected]> - ecd117e [graph_trainer] Pass global_valid_tokens into loss_fn ins... by Yidi Wu <[email protected]> - 0fae167 [graph_trainer] AutoParallel AOT FX Trace Integration (#2... by sanketpurandare <[email protected]> - 74181b1 [LoRA] Add LoRA converter and rename quantization to conv... by Yifan Mao <[email protected]> - 0d8f57c Remove unnecessary clone from ChunkedCELoss (pytorch#3272) by Jiani Wang <[email protected]> - 28b83bd Merge lora and float8 tests (pytorch#3310) by Yifan Mao <[email protected]> - e917ff4 Avoid repeat_interleave output-size sync (pytorch#3274) by Simon Fan <[email protected]> - acece3b [graph_trainer] Disable flexattn integration test due to ... by Sherlock Huang <[email protected]> - 8ba1c6b Support kwargs in minimal_fx_tracer (pytorch#3262) by Tugsbayasgalan Manlaibaatar <[email protected]> - d107aa4 [Quantization] Use class factory for MXFP8/Float8 Grouped... by Yifan Mao <[email protected]> - ca4c7f2 [rl] Register customized config parser to vllm + less vll... by Jiani Wang <[email protected]> - 0b5e899 Fix precompile tests (pytorch#3316) by Tugsbayasgalan Manlaibaatar <[email protected]> - 0fadde3 [graph_trainer] Fix AutoParallel input_fn to include posi... by Ivan Kobzarev <[email protected]> - 2ceff82 [graph_trainer] Add log_timer utility for tracing step ti... by Sherlock Huang <[email protected]> - e9dbff6 [graph_trainer] Refactor selective activation remat to in... by Tugsbayasgalan Manlaibaatar <[email protected]> - b301dfa Remove MoE expert for-loop fallback (pytorch#3308) by sanketpurandare <[email protected]> - 1a0fe3e [graph_trainer] Refactor passes.py into focused modules (... by Sherlock Huang <[email protected]> - d57df09 Make ChunkedCELoss support torch.autograd.grad (pytorch#3249) by Yidi Wu <[email protected]> - 5ca23a5 [GraphTrainer] Add Context Parallel support (pytorch#3305) by Aditya Venkataraman <[email protected]> - 7f070c9 Enhance Lychee Link Checker (Resiliency & Performance) (#... by Andrei-Aksionov <[email protected]> - 7f602b9 Add AGENTS.md symlinks for Codex usage (pytorch#3326) by sanketpurandare <[email protected]> - 34801c0 [graph_trainer] Improve SAC tagging and CPU offload pass ... by Sherlock Huang <[email protected]> - 1a22c2d [graph_trainer] Remove deprecated AOT compile mode (pytorch#3327) by Sherlock Huang <[email protected]> - 7b418ab Revert "Avoid repeat_interleave output-size sync (pytorch#3274)"... by Simon Fan <[email protected]> - 6f2fa2f [rl] switch to vllm v2 engine (pytorch#3330) by Jiani Wang <[email protected]> - 1690e0a [cpu-offloading] Encode last consumer as dep arg in ao.wa... by Michael Lazos <[email protected]> - cee4982 [graph_trainer] Fix SAC remat to produce fresh FakeTensor... by Ivan Kobzarev <[email protected]> - d4a3c63 [graph_trainer] Generalize minimal_fx_tracer to module + ... by Tugsbayasgalan Manlaibaatar <[email protected]> - 4614e30 [graph_trainer] Support multiple FSDP PGs in overlap_fsdp... by Sherlock Huang <[email protected]> - 3781d1d Back out "[graph_trainer] Fix SAC remat to produce fresh ... by Sherlock Huang <[email protected]> - a2a0d99 RL: observability spans across trainer/generator/controll... by Felipe Mello <[email protected]> - 8cdfdc2 [rl] Better initial weight loading (pytorch#3318) by Jiani Wang <[email protected]> - f0795f0 [RL] - Enable experiment metrics (pytorch#3237) by Felipe Mello <[email protected]> - b64292b [graph_trainer] Remove fsdp_reshard_after_fwd_pass (pytorch#3370) by Sherlock Huang <[email protected]> - a670699 [graph_trainer] Skip dense numerics tests due to upstream... by Sherlock Huang <[email protected]> - cb7bf09 ci: declare workflow-level `contents: read` on 2 workflow... by Arpit Jain <[email protected]> - d64eabc [Full DTensor] Config-based Full DTensor for Llama3 (pytorch#3159) by Chien-Chin Huang <[email protected]> - a866d04 Fix memory snapshot pickle protocol for compatibility wit... by francesco-bertolotti <[email protected]> - 9f9ae4d [graph_trainer] Fix H100 CI failure from DeepEP compilati... by Sherlock Huang <[email protected]> - c9126af [graph_trainer] Add bucketing ops to precompile serializa... by Ivan Kobzarev <[email protected]> - 013890b [graph_trainer] Defer cudagraph compatibility check to pa... by Ivan Kobzarev <[email protected]> - 6a1b334 Fix optimizer state and module state coupling (pytorch#3356) by Tugsbayasgalan Manlaibaatar <[email protected]> - 4238c35 Re-enable compile for gpt-oss integration tests (pytorch#3373) by Aditya Venkataraman <[email protected]> - ebfceeb [rl] Add TITO generator and gen metrics (pytorch#3391) by Felipe Mello <[email protected]> - cf3c431 [graph_trainer] Re-enable FlexAttention tests after upstr... by Sherlock Huang <[email protected]> - 8aa96ac [graph_trainer] Fix eager SAC policy mm counter to reset ... by Ivan Kobzarev <[email protected]> - 52a292d [graph_trainer] Gate overlap_fsdp_ag_rs_pass behind a con... by Yiming Zhou <[email protected]> - 2057b56 [rl] fix CI timeout issue by properly tear down for vllm ... by Jiani Wang <[email protected]> - cfe97c6 [rl] use wandb=False in CI (pytorch#3408) by Felipe Mello <[email protected]> - 83e4904 [graph_trainer] Rework full_inductor_compilation_pass via... by Tugsbayasgalan Manlaibaatar <[email protected]> - 963c20c [MoE][5/n] Refactor MoE to clean DTensor boundaries for s... by Jessica Zhong <[email protected]> - da38566 [MoE][6/n] Extract local_reorder, split DeepEP/HybridEP d... by Jessica Zhong <[email protected]> - 3f721b4 [graph_trainer] Fix fsdp_passes compat with BitsetAncesto... by Ivan Kobzarev <[email protected]> - b585282 Fix imports for latest DeepEP (pytorch#3414) by Steffen Hirschmann <[email protected]> - c2a3771 [loss] Fix ChunkedCELoss + TP gradient placement mismatch... by Chien-Chin Huang <[email protected]> - 19c567f Debug Numerics with DebugMode (pytorch#3323) by Shangdi Yu <[email protected]> - 78b08dd [graph_trainer] Add DeepSeek V3 16B SDPA config (pytorch#3361) by sanketpurandare <[email protected]> - af33f76 [Module] Replace from_nn_module with native Module subcla... by Chien-Chin Huang <[email protected]> - 58b0344 Add FSDP symmetric memory configuration and related tests... by Masaki <[email protected]> (And 259 more changes) PiperOrigin-RevId: 956923721
Stack from ghstack (oldest at bottom):
Add a
support_autograd_gradopt-in flag toChunkedCELoss.Configthat 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.gradside-effectwrites from
chunk_loss.backward()inside the chunk loop don'tsurvive into the captured graph and replay therefore produces
all-zero param grads.
Mechanism, when the flag is True:
chunk_loss.backward()populates
lm_head.weight.gradwith the correctly sharded value(FSDP last-chunk reduce-scatter still handles the actual reduction).
param.gradis captured viap.grad.detach()andp.gradis cleared.grad) are plumbed through a new
_ChunkedLossWithParamGradsautograd 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 toreal gradients instead of None / zeros.
set_requires_gradient_sync(False)is set on lm_headand restored after the outer backward via a callback queued on the
autograd engine. Without this, outer
loss.backward()wouldre-fire the post-accumulate-grad hook on already-sharded grads and
either error or produce wrong values.
Both autograd Functions (the existing
_DecoderOutputGradientBackPropand the new
_ChunkedLossWithParamGrads) return saved grads as-iswithout chain-ruling through
grad_output. The contract is that theloss returned by these Functions is the autograd endpoint — callers
must pass any scaling factor (e.g.
global_valid_tokens) intoloss_fnrather than dividing the returned loss externally. Seegraph_trainer's
compute_lossfor the canonical pattern. Thismatches the pre-existing behavior of
_DecoderOutputGradientBackPropand avoids a structural FSDP+TP problem:
grad_outputis aReplicate()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-rulemultiply would crash at runtime.
Tests:
support_autograd_grad in {False, True}equivalence check against the unchunked CEstandard 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.traces a small
lm_head + ChunkedCELoss(support_autograd_grad= True)train_step viatrace_train_stepand verifiestorch.equalbetween eager and replayed loss + h grad + lm_headgrad 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.