Skip to content

[router] Fp32 for backward and use bf16x9 kernels - #4484

Merged
anijain2305 merged 1 commit into
mainfrom
router-fp32-backward
Sep 5, 2026
Merged

anijain2305 merged 1 commit into
mainfrom
router-fp32-backward

Conversation

@anijain2305

Copy link
Copy Markdown
Contributor

The PR introduces RouterLinear, a subclass of Linear

  • Forward happens in bf16 compute, but the output is kept fp32 (no truncation back to bf16)
  • Backward input grads are in fp32, and both dgrad and wgrad compute is in fp32

For the fp32 compute, we use "bf16x9" trick to emulate fp32 precision, this allows Blackwell to use tensor cores, and even though bf16x9 has way more compute ops than fp32, the tensor core acceleration overall benefits. This feature was recently introduced in pytorch/pytorch#195301

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Sep 4, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 4, 2026
Comment thread torchtitan/distributed/utils.py Resolved
parallel_dims=self.parallel_dims,
spmd_typechecking=False,
)

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.

accidental?

Comment thread torchtitan/models/common/moe.py Outdated
Comment on lines +208 to +212
if not isinstance(config.gate, RouterGateLinear.Config):
raise ValueError(
"TokenChoiceTopKRouter requires an unquantized "
"RouterGateLinear.Config gate."
)

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.

you already have the typing restriction above, so I feel this is less necessary

)


@spmd.register_local_autograd_function

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.

@pianpwk do we still need this for the trivial rule?

Comment thread torchtitan/models/common/linear.py Outdated
Comment on lines +99 to +108
@dataclass(kw_only=True, slots=True)
class Config(Linear.Config):
def build(self, **kwargs):
if get_spmd_backend() == "partial_dtensor":
raise ValueError(
"RouterGateLinear requires parallelism.spmd_backend="
"'spmd_types'; got 'partial_dtensor'. aten.mm.dtype has no "
"DTensor sharding strategy."
)
return Linear.Config.build(self, **kwargs)

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.

#4419 is removing partial_dtensor backend, I think it's fine to assume it'd be landed soon

Comment thread torchtitan/models/common/linear.py Outdated
with torch.autocast(device_type=input.device.type, enabled=False):
output_TE = _RouterGateLinearFunction.apply(input, self.weight)
if self.bias is not None:
output_TE = output_TE + self.bias.float()

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.

there's no addmm variant that can take this?

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.

We have an operator aten.addmm.dtype which supports addmm with output_dtype but it causes compile time failure. So I kept it outside.

If you would insist, I can go figure out whats going on with inductor here because it is giving a little weird error

TypeError: tuned_addmm() takes 3 positional arguments but 4 were given

But I think its a second order optimization (bias is 1D tensor).

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.

Comment thread torchtitan/models/common/linear.py Outdated
def forward(self, input: torch.Tensor) -> torch.Tensor:
# The router owns its input casts; an enclosing autocast context must not
# promote the BF16 forward operands back to FP32.
with torch.autocast(device_type=input.device.type, enabled=False):

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 this necessary -- what if we don't have this autocast?

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.

It was not necessary ... I tried to force the forward to be bf16 compute and missed that if the input dtypes are fp32, we should keep the compute in fp32.

Comment thread torchtitan/models/common/linear.py Outdated
)
else:
# aten.mm.dtype is CUDA-only. Multiplying the BF16-rounded values in
# FP32 is an exact CPU reference for BF16 products with FP32

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.

what if it's rocm or other GPU?

Comment thread torchtitan/models/common/linear.py Outdated
Comment on lines +57 to +58
input_bf16_TD = input_TD.to(torch.bfloat16)
weight_bf16_ED = weight_ED.to(torch.bfloat16)

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.

if input and weight are of fp32, do we still

  • convert them to bf16 in fwd and do matmul
  • save bf16 ctx and cast up again in bwd

I somehow feel we could just run high precision matmul anyway, in those uncommon cases.

Comment thread torchtitan/distributed/utils.py Outdated
if (
device_type != "cuda"
or not torch.cuda.is_available()
or torch.cuda.get_device_capability() not in {(10, 0), (10, 3)}

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.

Change the cond so that vera rubin and future gpus are also supported.

@anijain2305
anijain2305 force-pushed the router-fp32-backward branch 3 times, most recently from a427493 to 7311ca3 Compare September 5, 2026 05:52

@tianyu-l tianyu-l left a comment

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.

Looks great

@anijain2305
anijain2305 merged commit 23ebdfe into main Sep 5, 2026
21 of 22 checks passed
@tianyu-l
tianyu-l deleted the router-fp32-backward branch September 5, 2026 22:32
wwwjn added a commit that referenced this pull request Sep 7, 2026
## Summary

- automatically apply `ciflow/8gpu` when a PR changes files under
`tests/assets/losses/`
- refresh the stale Real-PG A10G goldens for DeepSeek V3, GPT-OSS, Muse
Glimmer, and Qwen3
- normalize the generated parallelism header in the DeepSeek V3 CP+PP
golden

## Why

A Fake-PG golden update signals an expected numerics change, but the
corresponding Real-PG numerics currently run only after merge unless the
author manually adds `ciflow/8gpu`. Labeling any golden update
automatically makes the author validate the full 8-GPU Real-PG suite
before landing.

The current Real-PG values became stale after #4484 changed MoE router
numerics and #4489 changed Muse Glimmer initialization.

## Test plan

- `pre-commit run --files .github/labeler.yml
tests/assets/losses/real_pg/*.txt`
- [8-GPU Real-PG golden export on current
main](https://github.com/pytorch/torchtitan/actions/runs/34075482250):
feature and model suites passed
- compared all exported goldens byte-for-byte with the checked-in files
- confirmed all 10 loss and grad-norm steps for the four changed
numerical goldens against an independent scheduled Real-PG run ([run
34070052002](https://github.com/pytorch/torchtitan/actions/runs/34070052002))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

MoE router gate's fp32 autocast forces a SIMT (non-tensor-core) GEMM: 4% of speed-of-light, ~8-9% of step time on B300

2 participants