Skip to content

[HiMidLoLinear] Accumulate LM-head WGRAD into the running fp32 grad in place - #5137

Merged
anijain2305 merged 19 commits into
mainfrom
gh/anijain2305/65/head
Oct 10, 2026
Merged

anijain2305 merged 19 commits into
mainfrom
gh/anijain2305/65/head

Conversation

@anijain2305

@anijain2305 anijain2305 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):


  • LM-head (wide) backward adds WGRAD into the running fp32 weight.grad with
    addmm(out=), as MXFP8Linear already does; skips AccumulateGrad's add and a
    [vocab, D] fp32 temporary on ChunkedLossWrapper chunks / microbatches.
  • Router (narrow) and fp32-fallback paths unchanged; comments explain why.
  • Explicit inplace_wgrad_accum: bool = True config on HiMidLoLinear and
    MXFP8Linear (like DistMoeTransform). Raises instead of silently falling
    back when traced (torch.compile, make_fx) or for a non-leaf weight;
    HiMidLoLinear rejects num_linears > 1 with it on. GraphTrainer conversion
    and flavor builders turn it off, and GraphTrainer.Config rejects it on.
  • Shared helpers in models/common/inplace_wgrad_accum.py
    (uses_inplace_wgrad_accum, read-only running_grad); each backward clears
    weight.grad itself next to its in-place add.
  • Pipeline schedules that split backward into input and weight passes
    (ZBVZeroBubble, DualPipeV, InterleavedZeroBubble) turn the option off: both
    passes run under autograd.grad(), where AccumulateGrad never runs, and
    adding into .grad there dropped the earlier microbatches' gradients (an
    existing MXFP8 bug). 1F1B, Interleaved1F1B and GPipe keep it.
  • The in-place add uses the running grad's dtype (fp32 under an FSDP fp32
    reduce dtype, bf16 without FSDP), so it needs no dtype check; keep MXFP8's
    grad_dtype fallback, since FSDP clears grad_dtype during backward.
  • Qwen3-8B LM head, chunk-2 backward on H100: 11.98 -> 9.19 ms, peak
    3.54 -> 1.22 GiB; weight.grad bitwise identical.

[ghstack-poisoned]
[ghstack-poisoned]
@pytorch-bot pytorch-bot Bot added the ciflow/rl label Oct 8, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 8, 2026
anijain2305 added a commit that referenced this pull request Oct 8, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* #5137
* __->__ #5135

test_mxfp8_fsdp.py requires SM100, so it is skipped on the A10G GPU unit
test runners and was not exercised anywhere in CI. Add it to the B200
workflow's pytest step so regressions are caught.

Also remove the strict xfail on the fp32-reduce case of
test_mxfp8_fsdp_fused_wgrad_accum. pytorch/pytorch#194434 (landed as
38d3f6fd0d6e) makes FSDP set the unsharded parameter's grad_dtype to
reduce_dtype, so the fused wgrad accumulation path now fires with FP32
reduction as well.
[ghstack-poisoned]
[ghstack-poisoned]
anijain2305 added a commit that referenced this pull request Oct 8, 2026
…n place

ChunkedLossWrapper runs one backward per chunk with FSDP gradient sync
disabled until the last chunk, and with grad_dtype = reduce_dtype
(pytorch/pytorch#194434) the unsharded fp32 gradient stays on the parameter
between chunks. Each later chunk then paid for a full [vocab, D] fp32
grad_weight temporary plus a separate AccumulateGrad add.

Apply the trick MXFP8Linear already uses: when the weight's running .grad
exists and is fp32, the LM-head (wide) backward adds its WGRAD into it with
torch.addmm(out_dtype=fp32, out=running_grad) and returns that buffer, so
AccumulateGrad reattaches it instead of adding. Only the wide path does
this; the router (narrow) path and stacked weights (a non-leaf view) keep
the old behavior, as do traced backwards and bf16 .grads.

The read-and-clear logic moves into two shared helpers in
models/common/linear.py (can_accumulate_into_weight_grad,
pop_running_weight_grad), and MXFP8Linear now uses them too.

Qwen3-8B LM head (vocab 151936, D 4096, 2048-token chunks), second chunk's
backward on H100 with the fp32_to_bf16_split region compiled:
  unfused: 11.98 ms, 3.54 GiB peak extra
  fused:    9.19 ms, 1.22 GiB peak extra
weight.grad is bitwise identical to the AccumulateGrad path.

Tests: single-GPU (LM-head fires once, router/stacked never, bitwise equal
to reference) and a 2-GPU FSDP2 ChunkedLossWrapper-style test.

pop_running_weight_grad takes a running gradient at least as wide as the
WGRAD, not only an equal one. FSDP clears grad_dtype from pre-backward to
post-backward to defer its upcast, so an activation checkpoint recompute of
MXFP8Linear builds a BF16 WGRAD while the running gradient is FP32; an
equality check would silently stop MXFP8 fusing under AC. For the same
reason the MXFP8 "drop the grad_dtype fallback" TODO is replaced with a
comment: grad_dtype=None is a normal FSDP state during backward.

ghstack-source-id: 6dd4e54
Pull-Request: #5137
[ghstack-poisoned]
[ghstack-poisoned]
anijain2305 added a commit that referenced this pull request Oct 8, 2026
…n place

ChunkedLossWrapper runs one backward per chunk with FSDP gradient sync
disabled until the last chunk, and with grad_dtype = reduce_dtype
(pytorch/pytorch#194434) the unsharded fp32 gradient stays on the parameter
between chunks. Each later chunk then paid for a full [vocab, D] fp32
grad_weight temporary plus a separate AccumulateGrad add.

Apply the trick MXFP8Linear already uses: when the weight's running .grad
exists and is fp32, the LM-head (wide) backward adds its WGRAD into it with
torch.addmm(out_dtype=fp32, out=running_grad) and returns that buffer, so
AccumulateGrad reattaches it instead of adding. Only the wide path does
this; the router (narrow) path and stacked weights (a non-leaf view) keep
the old behavior, as do traced backwards and bf16 .grads.

The read-and-clear logic moves into a new shared module,
models/common/fused_grad_accumulation.py (can_fuse_grad_accumulation,
take_grad_for_fused_accumulation), and MXFP8Linear now uses it too.

Qwen3-8B LM head (vocab 151936, D 4096, 2048-token chunks), second chunk's
backward on H100 with the fp32_to_bf16_split region compiled:
  unfused: 11.98 ms, 3.54 GiB peak extra
  fused:    9.19 ms, 1.22 GiB peak extra
weight.grad is bitwise identical to the AccumulateGrad path.

Tests: single-GPU (LM-head fires once, router/stacked never, bitwise equal
to reference) and a 2-GPU FSDP2 ChunkedLossWrapper-style test.

take_grad_for_fused_accumulation takes a running gradient at least as wide as the
WGRAD, not only an equal one. FSDP clears grad_dtype from pre-backward to
post-backward to defer its upcast, so an activation checkpoint recompute of
MXFP8Linear builds a BF16 WGRAD while the running gradient is FP32; an
equality check would silently stop MXFP8 fusing under AC. For the same
reason the MXFP8 "drop the grad_dtype fallback" TODO is replaced with a
comment: grad_dtype=None is a normal FSDP state during backward.

ghstack-source-id: ba1b33f
Pull-Request: #5137
[ghstack-poisoned]
anijain2305 added a commit that referenced this pull request Oct 8, 2026
…n place

ChunkedLossWrapper runs one backward per chunk with FSDP gradient sync
disabled until the last chunk, and with grad_dtype = reduce_dtype
(pytorch/pytorch#194434) the unsharded fp32 gradient stays on the parameter
between chunks. Each later chunk then paid for a full [vocab, D] fp32
grad_weight temporary plus a separate AccumulateGrad add.

Apply the trick MXFP8Linear already uses: when the weight's running .grad
exists and is fp32, the LM-head (wide) backward adds its WGRAD into it with
torch.addmm(out_dtype=fp32, out=running_grad) and returns that buffer, so
AccumulateGrad reattaches it instead of adding. Only the wide path does
this; the router (narrow) path and stacked weights (a non-leaf view) keep
the old behavior, as do traced backwards and bf16 .grads.

The read-and-clear logic moves into a new shared module,
models/common/fused_grad_accumulation.py (can_fuse_grad_accumulation,
steal_grad_for_accumulation), and MXFP8Linear now uses it too.

Qwen3-8B LM head (vocab 151936, D 4096, 2048-token chunks), second chunk's
backward on H100 with the fp32_to_bf16_split region compiled:
  unfused: 11.98 ms, 3.54 GiB peak extra
  fused:    9.19 ms, 1.22 GiB peak extra
weight.grad is bitwise identical to the AccumulateGrad path.

Tests: single-GPU (LM-head fires once, router/stacked never, bitwise equal
to reference) and a 2-GPU FSDP2 ChunkedLossWrapper-style test.

steal_grad_for_accumulation takes a running gradient at least as wide as the
WGRAD, not only an equal one. FSDP clears grad_dtype from pre-backward to
post-backward to defer its upcast, so an activation checkpoint recompute of
MXFP8Linear builds a BF16 WGRAD while the running gradient is FP32; an
equality check would silently stop MXFP8 fusing under AC. For the same
reason the MXFP8 "drop the grad_dtype fallback" TODO is replaced with a
comment: grad_dtype=None is a normal FSDP state during backward.

ghstack-source-id: ea617b8
Pull-Request: #5137
[ghstack-poisoned]
anijain2305 added a commit that referenced this pull request Oct 8, 2026
…n place

ChunkedLossWrapper runs one backward per chunk with FSDP gradient sync
disabled until the last chunk, and with grad_dtype = reduce_dtype
(pytorch/pytorch#194434) the unsharded fp32 gradient stays on the parameter
between chunks. Each later chunk then paid for a full [vocab, D] fp32
grad_weight temporary plus a separate AccumulateGrad add.

Apply the trick MXFP8Linear already uses: when the weight's running .grad
exists and is fp32, the LM-head (wide) backward adds its WGRAD into it with
torch.addmm(out_dtype=fp32, out=running_grad) and returns that buffer, so
AccumulateGrad reattaches it instead of adding. Only the wide path does
this; the router (narrow) path and stacked weights (a non-leaf view) keep
the old behavior, as do traced backwards and bf16 .grads.

The read-and-clear logic moves into a new shared module,
models/common/fused_grad_accumulation.py (can_fuse_grad_accumulation,
steal_grad_for_accumulation), and MXFP8Linear now uses it too.

Qwen3-8B LM head (vocab 151936, D 4096, 2048-token chunks), second chunk's
backward on H100 with the fp32_to_bf16_split region compiled:
  unfused: 11.98 ms, 3.54 GiB peak extra
  fused:    9.19 ms, 1.22 GiB peak extra
weight.grad is bitwise identical to the AccumulateGrad path.

Tests: single-GPU (LM-head fires once, router/stacked never, bitwise equal
to reference) and a 2-GPU FSDP2 ChunkedLossWrapper-style test.

steal_grad_for_accumulation takes a running gradient at least as wide as the
WGRAD, not only an equal one. FSDP clears grad_dtype from pre-backward to
post-backward to defer its upcast, so an activation checkpoint recompute of
MXFP8Linear builds a BF16 WGRAD while the running gradient is FP32; an
equality check would silently stop MXFP8 fusing under AC. For the same
reason the MXFP8 "drop the grad_dtype fallback" TODO is replaced with a
comment: grad_dtype=None is a normal FSDP state during backward.

ghstack-source-id: 7596f94
Pull-Request: #5137
@anijain2305
anijain2305 marked this pull request as ready for review October 8, 2026 22:44
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 8, 2026
anijain2305 added a commit that referenced this pull request Oct 8, 2026
…n place

- LM-head (wide) backward adds WGRAD into the running fp32 weight.grad with
  addmm(out=), as MXFP8Linear already does; skips AccumulateGrad's add and a
  [vocab, D] fp32 temporary on ChunkedLossWrapper chunks / microbatches.
- Router (narrow) and fp32-fallback paths unchanged; comments explain why.
- Shared helpers in models/common/fused_grad_accumulation.py
  (can_fuse_grad_accumulation, steal_grad_for_accumulation); MXFP8Linear
  uses them too.
- Accept a running grad wider than the WGRAD, so MXFP8 still fuses under AC
  (FSDP clears grad_dtype during backward); keep MXFP8's grad_dtype fallback
  for the same reason.
- Qwen3-8B LM head, chunk-2 backward on H100: 11.98 -> 9.19 ms, peak
  3.54 -> 1.22 GiB; weight.grad bitwise identical.

ghstack-source-id: 7596f94
Pull-Request: #5137
from torch.fx.experimental.proxy_tensor import get_proxy_mode


def can_fuse_grad_accumulation(weight: torch.Tensor) -> bool:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I think this relates to previous discussion with @sanketpurandare on https://github.com/pytorch/torchtitan/blob/main/torchtitan/config/transform/dist_moe.py#L111

Should we prefer being explicit? O/w user may see regression that is hard to debug.

return not is_tracing and weight.is_leaf


def steal_grad_for_accumulation(

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.

nit: please consider using a more decent name than "steal"

@anijain2305 anijain2305 Oct 9, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Haha :) I think I have been desensitized to the word steal because "stealing the reference" while using Cpython APIs link is common.

But I will change it yeah.

[ghstack-poisoned]
[ghstack-poisoned]
anijain2305 added a commit that referenced this pull request Oct 9, 2026
…n place

- LM-head (wide) backward adds WGRAD into the running fp32 weight.grad with
  addmm(out=), as MXFP8Linear already does; skips AccumulateGrad's add and a
  [vocab, D] fp32 temporary on ChunkedLossWrapper chunks / microbatches.
- Router (narrow) and fp32-fallback paths unchanged; comments explain why.
- Shared helpers in models/common/fused_grad_accumulation.py
  (can_fuse_grad_accumulation, steal_grad_for_accumulation); MXFP8Linear
  uses them too.
- Accept a running grad wider than the WGRAD, so MXFP8 still fuses under AC
  (FSDP clears grad_dtype during backward); keep MXFP8's grad_dtype fallback
  for the same reason.
- Qwen3-8B LM head, chunk-2 backward on H100: 11.98 -> 9.19 ms, peak
  3.54 -> 1.22 GiB; weight.grad bitwise identical.

ghstack-source-id: d4b6c01
Pull-Request: #5137
[ghstack-poisoned]
@anijain2305 anijain2305 added ciflow/b200 Trigger B200 CI ciflow/real-pg Run the full 8-GPU Real PG integration suite labels Oct 9, 2026
[ghstack-poisoned]
anijain2305 added a commit that referenced this pull request Oct 9, 2026
…n place

- LM-head (wide) backward adds WGRAD into the running fp32 weight.grad with
  addmm(out=), as MXFP8Linear already does; skips AccumulateGrad's add and a
  [vocab, D] fp32 temporary on ChunkedLossWrapper chunks / microbatches.
- Router (narrow) and fp32-fallback paths unchanged; comments explain why.
- Explicit `inplace_wgrad_accum: bool = True` config on HiMidLoLinear and
  MXFP8Linear (like DistMoeTransform). Raises instead of silently falling
  back when traced (torch.compile, make_fx) or for a non-leaf weight;
  HiMidLoLinear rejects num_linears > 1 with it on. GraphTrainer conversion
  and flavor builders turn it off, and GraphTrainer.Config rejects it on.
- Shared helpers in models/common/inplace_wgrad_accum.py
  (uses_inplace_wgrad_accum, read-only running_grad); each backward clears
  weight.grad itself next to its in-place add.
- Accept a running grad wider than the WGRAD, so MXFP8 still fuses under AC
  (FSDP clears grad_dtype during backward); keep MXFP8's grad_dtype fallback
  for the same reason.
- Qwen3-8B LM head, chunk-2 backward on H100: 11.98 -> 9.19 ms, peak
  3.54 -> 1.22 GiB; weight.grad bitwise identical.

ghstack-source-id: 63180e3
Pull-Request: #5137
[ghstack-poisoned]
anijain2305 added a commit that referenced this pull request Oct 9, 2026
…n place

- LM-head (wide) backward adds WGRAD into the running fp32 weight.grad with
  addmm(out=), as MXFP8Linear already does; skips AccumulateGrad's add and a
  [vocab, D] fp32 temporary on ChunkedLossWrapper chunks / microbatches.
- Router (narrow) and fp32-fallback paths unchanged; comments explain why.
- Explicit `inplace_wgrad_accum: bool = True` config on HiMidLoLinear and
  MXFP8Linear (like DistMoeTransform). Raises instead of silently falling
  back when traced (torch.compile, make_fx) or for a non-leaf weight;
  HiMidLoLinear rejects num_linears > 1 with it on. GraphTrainer conversion
  and flavor builders turn it off, and GraphTrainer.Config rejects it on.
- Shared helpers in models/common/inplace_wgrad_accum.py
  (uses_inplace_wgrad_accum, read-only running_grad); each backward clears
  weight.grad itself next to its in-place add.
- running_grad also requires the backward to run the parameter's
  AccumulateGrad. Pipelining's split (zero-bubble) backward runs the node
  under autograd.grad() for dI and again for dW; adding into .grad there
  dropped the earlier microbatches' gradients (an existing MXFP8 bug).
- Accept a running grad wider than the WGRAD, so MXFP8 still fuses under AC
  (FSDP clears grad_dtype during backward); keep MXFP8's grad_dtype fallback
  for the same reason.
- Qwen3-8B LM head, chunk-2 backward on H100: 11.98 -> 9.19 ms, peak
  3.54 -> 1.22 GiB; weight.grad bitwise identical.

ghstack-source-id: bf5ffdb
Pull-Request: #5137
must set it to False; forward raises if it is traced with this on."""

def __post_init__(self) -> None:
if self.inplace_wgrad_accum and self.num_linears > 1:

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.

This restriction is fixed in the next PR in the stack. I wanted to keep this PR simple.

if weight_param is None or weight_param.grad is None:
return None
grad = weight_param.grad
if torch.promote_types(grad.dtype, wgrad_dtype) != grad.dtype:

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.

n00bq: what does this check/why we need this?

try:
return torch._C._will_engine_execute_node(node)
except RuntimeError:
# Raised for a leaf that autograd.grad() captures: it returns the

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.

curious under what case will we reach here?

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.

Oh let me check - this sneaked in without me noticing. Sorry, let me take a look.

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.

This is for Zero Pipeline Bubble, where there is a dI/dW split, so AccumulateGrad does not run.

I myself do not understand this, but I am going to change this so that we dont have this here, and just disable the fusion for Zero Pipeline Bubble case.

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.

Done

@anijain2305
anijain2305 marked this pull request as draft October 9, 2026 23:46
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 9, 2026
[ghstack-poisoned]
[ghstack-poisoned]
@anijain2305
anijain2305 marked this pull request as ready for review October 10, 2026 00:23
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 10, 2026


def disable_inplace_wgrad_accum(model: Module.Config) -> None:
"""Turn off ``inplace_wgrad_accum`` on every linear config in ``model`` that has 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.

is there a way to ban inplace_wgrad_accum for graph trainer rather than changing the config value here?

input_TD: torch.Tensor,
weight_OD: torch.Tensor,
num_pieces: int,
accumulate_into_weight_grad: bool,

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.

maybe not introduce multiple names for the same thing

Comment on lines +376 to +381
# Unlike _wide_backward, this never adds into the running weight.grad in place. The gradient
# is small ([num_experts, D] for a router, ~1 MiB), so fusing saves only a tiny temporary and
# add. Adding each piece into the running gradient would also round once per piece at the
# running gradient's scale, losing part of mid's and lo's correction, where summing the
# pieces first rounds there once. Keeping one rounding needs a single GEMM over stacked
# pieces, which copies the input once per piece (512 MiB at 64k tokens).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I didn't review this hard

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@anijain2305
anijain2305 changed the base branch from gh/anijain2305/65/base to main October 10, 2026 15:35
@anijain2305
anijain2305 merged commit de222da into main Oct 10, 2026
anijain2305 added a commit that referenced this pull request Oct 10, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.18.0)
(oldest at bottom):
* #5250
* __->__ #5249

Why:
- In-place WGRAD accumulation (#5137, and the bf16 Linear next in this
  stack) needs the parameter itself in backward, to read and clear its
  .grad and return a gradient in its shape. _linear only got a flattened
view, so implementations re-read self.weight or gave up on stacked
weights.
- Re-reading self.weight is not free: SimpleFSDP's parametrization
all-gathers on every read, and MXFP8Linear also quantizes, so each MXFP8
  forward did both twice (the quantize-count test asserted 2).
- A stacked weight's flattened view routes its gradient through the
view's
  backward, which rounds HiMidLoLinear's fp32 grad_weight to bf16
(pytorch/pytorch#189633), so HiMidLoLinear rejected stacked weights with
  inplace_wgrad_accum on.

What:
- Linear.forward reads weight and bias once and passes them to _linear
unflattened ([N, K] or [num_linears, N, K]); implementations flatten
them
with the static Linear._flatten_weight_and_bias(). Updates the TP,
vision,
  async TP, LoRA and NVFP4 call sites.
- MXFP8Linear uses its weight argument (quantize count back to 1).
- HiMidLoLinear's Function takes the parameter and flattens inside, so
  stacked weights accumulate in place and keep an fp32 grad.
- No numerics change for unstacked linears.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/real-pg Run the full 8-GPU Real PG integration suite ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants