Skip to content

Add remat regions to model-specific attention paths - #4883

Closed
anijain2305 wants to merge 26 commits into
gh/anijain2305/42/basefrom
gh/anijain2305/42/head
Closed

anijain2305 wants to merge 26 commits into
gh/anijain2305/42/basefrom
gh/anijain2305/42/head

Conversation

@anijain2305

@anijain2305 anijain2305 commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Commit "Give every Linear its own remat region" already covers every
projection, so the remaining uncontrolled compute in the model-specific
attention paths is the TP input gather that several plain projections share,
and the attention kernel itself. Profiling picked these two as the regions
worth controlling beyond the projections.

  • Add maybe_gather_tp_input(module, x) in common/linear.py. It declares
    <module fqn>.tp_gather with the same semantics as the
    ColumnParallelLinear gather, which now uses it too. DeepSeek V3 and Kimi K3
    MLA, Kimi K3 KDA, Qwen3.5-family attention and DeltaNet, Muse Glimmer
    attention, and the Qwen3.5 MoE EP input call it once at their common
    boundary instead of an unregioned spmd.redistribute.
  • Wrap the attention kernel in <module fqn>.inner_attention in DeepSeek V3,
    Kimi K3 MLA and KDA, Qwen3.5 attention and DeltaNet, Muse Glimmer, and
    gpt-oss, matching the common attention modules.
  • Pin the kernel output, which is read by bare ops. Projection outputs stay
    pinned by their Linear, so the Kimi K3 KDA projections that feed only the
    kernel region are kept when saved (+0.05-0.07 GiB peak on the debug model
    under save-all; other models are unchanged).
  • Split the DeepSeek V3 projections into _project_qkv, so FusedMLA overrides
    only the projections and shares the gather, kernel region and output
    projection with the eager path.

Test Plan:

  • pytest tests/unit_tests/gpu/test_remat.py (new shared tp_gather test)
  • For every touched model, RegionAC save none vs save * gives bitwise equal
    loss at 1 GPU, TP2 and TP2+EP2 (DP2+EP2 for Kimi K3).

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Sep 25, 2026
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Sep 26, 2026
Regions isolate expensive projections, attention kernels, and shared TP collectives. Cheaper normalization, reshaping, and elementwise work remains outside them for recomputation.

ghstack-source-id: 4c9c7ed

Pull-Request: pytorch/torchtitan#4883
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Sep 26, 2026
Regions isolate expensive projections, attention kernels, and shared TP collectives. Cheaper normalization, reshaping, and elementwise work remains outside them for recomputation.

ghstack-source-id: 0d0f4a9

Pull-Request: pytorch/torchtitan#4883
[ghstack-poisoned]
[ghstack-poisoned]
anijain2305 added a commit that referenced this pull request Sep 26, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* #4893
* #4883
* __->__ #4878

For review, see the MoE sharding diagram:

https://github.com/pytorch/torchtitan/blob/main/assets/images/moe_sharding.png

Goals:
- Make all core MoE collectives explicit; remove automatic src -> dst
redistribution.
- Place collectives in the appropriate remat regions.

Main changes:
- Add SharedExpertRowParallelLinear for shared-expert w2. It explicitly
reduce-scatters to Shard(0) with SP, or keeps Partial without SP so the
shared and routed outputs can be combined before one all-reduce. The
existing w2 region now covers both compute and communication.
- Explicitly handle the TP -> EP input transition for routed
activations, padding masks, and DeepSeek V4 hash-router token IDs.
- Explicitly convert the routed output from Shard(0) -> Partial and
perform the final Partial -> Invariant all-reduce when SP is disabled.
- Remove the remaining src -> dst MoE sharding boundaries and add
regions for routed w13 and w2.
- Keep the final all-reduce in a standalone remat region because routed
combine and branch addition prevent colocating it with either w2
computation.
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Sep 26, 2026
Regions isolate expensive projections, attention kernels, and shared TP collectives. Cheaper normalization, reshaping, and elementwise work remains outside them for recomputation.

ghstack-source-id: 7392d20

Pull-Request: pytorch/torchtitan#4883
[ghstack-poisoned]
@anijain2305
anijain2305 marked this pull request as ready for review September 28, 2026 18:49
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Sep 28, 2026
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Sep 28, 2026
Regions isolate expensive projections, attention kernels, and shared TP collectives. Cheaper normalization, reshaping, and elementwise work remains outside them for recomputation.

How the regions were chosen: each model (llama3, deepseek_v3, qwen3, qwen3_5, gpt_oss, kimi_k3, muse_glimmer) was profiled at production width, truncated to 4 layers, on H100. Backward recompute kernel time was attributed to each region and bare op, and leave-one-out save sweeps measured the activation memory each region keeps. Regions were kept where the recompute time avoided per MB kept is at or above the break-even point set by the unregioned ops. TP/EP collective regions were checked on DeepSeek V3 with EP4 and TP2EP2+SP. Candidates that only helped eager (e.g. a fused MoE combine op, and RoPE/QK-norm inside the qkv region) were re-measured under torch.compile and dropped.

Testing: losses are bitwise identical with --debug.seed=42 --debug.deterministic across no-AC and selective AC (gpt_oss: HEAD vs this change vs no AC; 8 steps), and region placement is covered by tests/unit_tests/gpu/test_remat.py.

ghstack-source-id: 4cff3d8

Pull-Request: pytorch/torchtitan#4883

@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.

Regions were kept where the recompute time avoided per MB kept is at or above the break-even point set by the unregioned ops.

Could you say more about the break-even point set by the unregioned ops? I feel if we "unregion" more ops, then we are picking less function / module / ops to be wrapped with remat -- how did you set the threshold? Theoretically, we should

  • recompute anything that spends less time than read-from-HBM (not sure if this sentence makes sense or not)
  • be able to recover full AC because that enables memory-poor training

Comment thread docs/remat.md Outdated
## Regions by model

Attention region names use the same meanings across models: `qkv` covers the
query, key, and value input projections; `latent_projections` covers the MLA

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.

qkv and wo also contains the TP comms, which this AC policy couples together -- is this intentional? I vaguely remember we were recomputing all-gather, but not reduce-scatter in old policy.

also the naming is not consistent, should we use wqkv?

Comment thread torchtitan/models/qwen3_5/gdn.py Outdated
self.out_proj = config.out_proj.build()
self.inner_gated_delta_net = config.inner_gated_delta_net.build()

def _maybe_gather_tp_input(self, x_TD: torch.Tensor) -> torch.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.

I'm seeing this function a lot, wonder if it should be abstracted into a common util

[ghstack-poisoned]
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Sep 30, 2026
Commit "Give every Linear its own remat region" already covers every
projection, so the remaining uncontrolled compute in the model-specific
attention paths is the TP input gather that several plain projections share,
and the attention kernel itself. Profiling picked these two as the regions
worth controlling beyond the projections.

- Add `maybe_gather_tp_input(module, x)` in `common/linear.py`. It declares
  `<module fqn>.tp_gather` with the same semantics as the
  `ColumnParallelLinear` gather, which now uses it too. DeepSeek V3 and Kimi K3
  MLA, Kimi K3 KDA, Qwen3.5-family attention and DeltaNet, Muse Glimmer
  attention, and the Qwen3.5 MoE EP input call it once at their common
  boundary instead of an unregioned `spmd.redistribute`.
- Wrap the attention kernel in `<module fqn>.inner_attention` in DeepSeek V3,
  Kimi K3 MLA and KDA, Qwen3.5 attention and DeltaNet, Muse Glimmer, and
  gpt-oss, matching the common attention modules.
- Drop pins whose only consumer is now the `inner_attention` region, and pin
  the kernel output, which is read by bare ops.
- Split the DeepSeek V3 projections into `_project_qkv`, so FusedMLA overrides
  only the projections and shares the gather, kernel region and output
  projection with the eager path.

Test Plan:
- `pytest tests/unit_tests/gpu/test_remat.py` (new shared `tp_gather` test)
- For every touched model, RegionAC save none vs save `*` gives bitwise equal
  loss at 1 GPU, TP2 and TP2+EP2 (DP2+EP2 for Kimi K3).

ghstack-source-id: 766bf99
Pull-Request: pytorch/torchtitan#4883
@anijain2305
anijain2305 marked this pull request as draft September 30, 2026 20:27
@pytorch-bot pytorch-bot Bot removed the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Sep 30, 2026
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@anijain2305 anijain2305 closed this Oct 1, 2026
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.

2 participants