Skip to content

[loss] Chain-rule grad_output through ChunkedCELoss autograd Function backwards - #3250

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

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

Conversation

@ydwu4

@ydwu4 ydwu4 commented May 6, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Both _DecoderOutputGradientBackProp (eager + support_autograd_grad = False) and _ChunkedLossWithParamGrads (support_autograd_grad = True) previously returned saved grads as-is, ignoring grad_output.
This violated the autograd contract — a Function backward owes the
caller dL/dinput = dout/dinput * grad_output — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. global_valid_tokens) into loss_fn rather
than scaling the returned loss externally, so grad_output is
always the autograd-start ones_like(loss).

Multiply through grad_output so the contract holds for any
consumer, including future ones that scale externally. The naive
g * grad_output is rejected by DTensor on FSDP+TP layouts because
grad_output lives on the loss output's mesh (typically the
activation mesh (tp,)) while saved param grads live on the params'
mesh (e.g. (fsdp, tp)); add a _maybe_redistribute_multiply
helper that redistributes grad_output to g's mesh first when
both are DTensors on different meshes. For the only grad_output
shape we actually encounter — a Replicate() scalar (what
torch.autograd.grad constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when grad_output is the autograd-start
ones_like(loss) (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of not
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (tests/unit_tests/test_loss.py,
test_skip_module.py, test_trace_module.py) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
support_autograd_grad=True; this commit is mathematically a no-op
on top of that since grad_output = ones_like(loss) in all those
configs.

… backwards

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

[ghstack-poisoned]
…ad Function backwards"

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

[ghstack-poisoned]
ydwu4 added a commit that referenced this pull request May 6, 2026
… backwards

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

ghstack-source-id: ff1dd39
Pull Request resolved: #3250
…ad Function backwards"

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

[ghstack-poisoned]
ydwu4 added a commit that referenced this pull request May 6, 2026
… backwards

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

ghstack-source-id: ff1dd39
Pull Request resolved: #3250
…ad Function backwards"

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

[ghstack-poisoned]
ydwu4 added a commit that referenced this pull request May 6, 2026
… backwards

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

ghstack-source-id: 07fcbd4
Pull Request resolved: #3250
…ad Function backwards"

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

[ghstack-poisoned]
ydwu4 added a commit that referenced this pull request May 6, 2026
… backwards

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

ghstack-source-id: 3970217
Pull Request resolved: #3250
…ad Function backwards"

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

[ghstack-poisoned]
ydwu4 added a commit that referenced this pull request May 6, 2026
… backwards

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

ghstack-source-id: 34fb27e
Pull Request resolved: #3250
…ad Function backwards"

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

[ghstack-poisoned]
ydwu4 added a commit that referenced this pull request May 6, 2026
… backwards

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

ghstack-source-id: e795c88
Pull Request resolved: #3250
Comment thread torchtitan/components/loss.py Outdated
and isinstance(grad_output, DTensor)
and g.device_mesh != grad_output.device_mesh
):
grad_output = grad_output.redistribute(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

ugh.. this is vibecoded. Not sure it's the correct way of doing this. The idea is to allow grad_output ( a sclalar tensor) to mulfiply with gradients (with a different device mesh).

…ad Function backwards"

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

[ghstack-poisoned]
ydwu4 added a commit that referenced this pull request May 7, 2026
… backwards

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

ghstack-source-id: 651b101
Pull Request resolved: #3250
Comment on lines +387 to +392
``NotImplementedError("Cross device mesh comm not supported yet!")``),
so a naive ``g * grad_output`` crashes whenever ``g`` (saved param
grad on, e.g., ``(fsdp, tp)``) and ``grad_output`` (loss on, e.g.,
``(tp,)``) live on different meshes. ``to_local`` on a Replicate
scalar is local-only — no collective fires — and ``g * scalar`` then
broadcasts cleanly regardless of ``g``'s mesh.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is not a problem under full dtensor mode as we always operate on a full SPMD mesh. So I prefer not to land this PR.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I think the real problem is that people might call ChunkedCELoss then do some more tensor ops on the output and get a new loss. We need to figure out a way to back propagate the grad_out somehow.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Do you have a concrete example in TorchTitan? If not now and this is a forward looking fix, then it may not be an issue once we migrate to spmd_types.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

#3244 is an example. Can you elaborate a bit more why spmd_types can help on this?

To be clear, it's fine we're not landing this. If ChunkedCELoss is a user-facing API, not back propagating grad_out is a footgun. We probably should warn user about it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Sorry my statement was too vague and not accurate. What I wanted to say is that we should avoid to_local() because it will not work with full_dtensor case. And The reason why you need to do to_local is the cross mesh issue, which is going to be fixed with full dtensor and spmd types.

Back propgating grad_out is not a concern.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Ok! Do we want to land a temporary fix to stop bleeding? If so, any recommendation on the proper implementation before full dtensor and spmd types support land?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Can this be moved to torchtitan/experiments/graph_trainer/chunked_loss.py? I saw that in the early PR, you already create a subclass. This way you won't be blocked by the full dtensor and spmd dtypes adoption.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

sure i'll just do it for the graph_trainer chunked loss then

…ad Function backwards"

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

[ghstack-poisoned]
ydwu4 added a commit that referenced this pull request May 7, 2026
… backwards

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

ghstack-source-id: 033ebc7
Pull Request resolved: #3250
…ad Function backwards"

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

[ghstack-poisoned]
ydwu4 added a commit that referenced this pull request May 7, 2026
… backwards

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

ghstack-source-id: 10cb7bb
Pull Request resolved: #3250
…ad Function backwards"

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

[ghstack-poisoned]
ydwu4 added a commit that referenced this pull request May 7, 2026
… backwards

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

ghstack-source-id: faf6a50
Pull Request resolved: #3250
…ad Function backwards"

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

[ghstack-poisoned]
ydwu4 added a commit that referenced this pull request May 7, 2026
… backwards

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

ghstack-source-id: 31d4e9b
Pull Request resolved: #3250
…ad Function backwards"

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

[ghstack-poisoned]
ydwu4 added a commit that referenced this pull request May 7, 2026
… backwards

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

ghstack-source-id: 5200e03
Pull Request resolved: #3250
…ad Function backwards"

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

[ghstack-poisoned]
ydwu4 added a commit that referenced this pull request May 7, 2026
… backwards

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

ghstack-source-id: 5b62220
Pull Request resolved: #3250
…ad Function backwards"

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

[ghstack-poisoned]
ydwu4 added a commit that referenced this pull request May 7, 2026
… backwards

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

ghstack-source-id: ac09976
Pull Request resolved: #3250
…ad Function backwards"

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

[ghstack-poisoned]
ydwu4 added a commit that referenced this pull request May 8, 2026
… backwards

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

ghstack-source-id: 1348c14
Pull Request resolved: #3250
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.
…ad Function backwards"

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

[ghstack-poisoned]
ydwu4 added a commit that referenced this pull request May 11, 2026
… backwards

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

ghstack-source-id: 3806772
Pull Request resolved: #3250
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.
…ad Function backwards"

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

[ghstack-poisoned]
ydwu4 added a commit that referenced this pull request May 13, 2026
… backwards

Both ``_DecoderOutputGradientBackProp`` (eager + ``support_autograd_grad
= False``) and ``_ChunkedLossWithParamGrads`` (``support_autograd_grad =
True``) previously returned saved grads as-is, ignoring ``grad_output``.
This violated the autograd contract — a Function backward owes the
caller ``dL/dinput = dout/dinput * grad_output`` — but worked in
practice because every in-tree caller follows the convention of passing
scaling factors (e.g. ``global_valid_tokens``) into ``loss_fn`` rather
than scaling the returned loss externally, so ``grad_output`` is
always the autograd-start ``ones_like(loss)``.

Multiply through ``grad_output`` so the contract holds for any
consumer, including future ones that scale externally. The naive
``g * grad_output`` is rejected by DTensor on FSDP+TP layouts because
``grad_output`` lives on the loss output's mesh (typically the
activation mesh ``(tp,)``) while saved param grads live on the params'
mesh (e.g. ``(fsdp, tp)``); add a ``_maybe_redistribute_multiply``
helper that redistributes ``grad_output`` to ``g``'s mesh first when
both are DTensors on different meshes. For the only ``grad_output``
shape we actually encounter — a ``Replicate()`` scalar (what
``torch.autograd.grad`` constructs for a scalar loss output) — the
redistribute is comm-free at runtime; it just rewrites placement
metadata.

The autograd-correctness change is independent of the ChunkedCELoss
enablement work: when ``grad_output`` is the autograd-start
``ones_like(loss)`` (the case for every in-tree caller after the
preceding commit "[graph_trainer] Pass global_valid_tokens into
loss_fn instead of dividing externally"), this commit is a runtime
no-op. It lands as a separate commit to keep the contract-correctness
discussion separate from the enablement diff. The risk of *not*
shipping this is silent wrong gradients for any future consumer that
scales the loss externally, which would be near-impossible to detect
from training logs.

Existing tests (``tests/unit_tests/test_loss.py``,
``test_skip_module.py``, ``test_trace_module.py``) still pass.
End-to-end equivalence: verified that the previous commit ("Make
ChunkedCELoss support torch.autograd.grad") bitwise-matches eager
across 6 graph_trainer configs (3 dense + 3 MoE) with
``support_autograd_grad=True``; this commit is mathematically a no-op
on top of that since ``grad_output = ones_like(loss)`` in all those
configs.

ghstack-source-id: 0d9a757
Pull Request resolved: #3250
@ydwu4 ydwu4 closed this Jun 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants