Skip to content

Declare remat regions for projections and attention - #4956

Merged
anijain2305 merged 24 commits into
mainfrom
gh/anijain2305/52/head
Oct 5, 2026
Merged

anijain2305 merged 24 commits into
mainfrom
gh/anijain2305/52/head

Conversation

@anijain2305

@anijain2305 anijain2305 commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Key design changes

  • Every Linear declares its own remat region around self._linear (<fqn>.linear), the seam that quantized and LoRA linears already override. Callers call the Linear directly instead of wrapping it in a region, since a saved outer region cannot contain a recomputed one.
  • ColumnParallelLinear and RowParallelLinear put their collectives in separately controlled sibling regions: <fqn>.tp_gather before the projection and <fqn>.tp_reduce after it. Modules whose projections share one TP input gather it once with maybe_gather_tp_input, which declares <module fqn>.tp_gather.
  • GroupedLinear gets the same treatment: a region around self._grouped_mm (routed_experts.w13.grouped_mm / w2.grouped_mm). LoRA adapters call their _linear / _grouped_mm directly, so they run inside the base projection's region instead of declaring their own.
  • Attention modules wrap their kernel in <fqn>.inner_attention.
  • Bare operations that read a projection or attention output (norms, rope, splits, gating, residual adds) call recompute_needs_tensor immediately before the read, with a comment naming the producer.

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Sep 30, 2026
Every `Linear` now runs its projection in a `<fqn>.linear` remat region, and
the TP collectives of the parallel linears become sibling regions next to it:

- ColumnParallelLinear: `<fqn>.tp_gather` (the input S(0)/I -> R
  redistribution, an all-gather under sequence parallelism) and
  `<fqn>.linear`.
- RowParallelLinear and InvariantRowParallelLinear: `<fqn>.linear` (the
  partial projection) and `<fqn>.tp_reduce` (the P -> S(0)/I reduction).
  `tp_reduce` shares the `linear` policy, so saving `<fqn>.linear` saves the
  reduced output and frees the partial one; saving only `tp_reduce` has no
  effect.
- AsyncColumnParallelLinear / AsyncRowParallelLinear: their fused collective
  matmul runs in a single `<fqn>.linear` region.

Quantized and LoRA linears only override `_linear`, so they get the region for
free. The model-level regions that used to wrap linear calls (`attention.wo`,
`feed_forward.w13`/`w2`, the vision `attn.qkv`/`attn.wo`/`mlp.w1`/`mlp.w2`,
and the Qwen3.5 shared-expert `input_projections`/`w2`) are removed: a saved
outer region cannot contain a recomputed inner region, so there must be only
one level. Bare ops that consume a linear output now pin it with
`remat.recompute_needs_tensor`, across all models (common attention/FFN/MoE
router/vision encoder, deepseek_v3/v4 including the fused MLA override,
gpt_oss, kimi_k3, muse_glimmer, qwen3_5).

Why: the old outer regions wrapped the SP all-gather together with the matmul,
so saving the projection also kept its gathered input for the weight gradient.
That activation is TP times larger per projection and cancels the memory
saving of sequence parallelism. With separate regions, saving `.linear` while
recomputing `.tp_gather` keeps only the sequence shard and replays the
all-gather for the weight gradient, as Megatron does. Saving both keeps the
previous behavior. A uniform per-Linear region also makes the save patterns
predictable (`*.linear`, `feed_forward.*`) instead of depending on
per-model wrappers.

User-visible change: RegionAC save patterns are renamed, e.g.
`attention.qkv_linear.wqkv` -> `attention.qkv_linear.wqkv.linear`,
`attention.wo` -> `attention.wo.linear`, `feed_forward.w13` ->
`feed_forward.w13.linear`, `feed_forward.w2` -> `feed_forward.w2.linear`.
SelectiveAC saves every region except the routed-expert `w13`/`w2`, so for
column-parallel projections it now saves `tp_gather` + `linear`, which matches
the old outer region. It also now saves Linears that previously had no region
(e.g. the MoE router gate and the model-specific attention projections),
which it used to recompute. RegionAC cannot warn about
patterns that match nothing at apply() time, since region names are only
known when the forward runs.

Test plan: saving no regions vs `*` gives bitwise-identical losses
(--debug.seed=42 --debug.deterministic) for llama3, qwen3, qwen3 MoE,
qwen3.5/3.6/3.8 (dense and MoE), deepseek_v3, gpt_oss (flex), muse_glimmer,
kimi_k3, kimi_k2.5, llama3 float8 and deepseek_v3 with fused MLA, across 1 GPU, TP2, TP2+EP2 and DP2+EP2.

ghstack-source-id: bf26664
Pull-Request: pytorch/torchtitan#4956
[ghstack-poisoned]
[ghstack-poisoned]
@anijain2305 anijain2305 changed the title Declare remat regions inside ColumnParallelLinear Give every Linear its own remat region Sep 30, 2026
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@anijain2305 anijain2305 changed the title Give every Linear its own remat region Declare remat regions for projections, attention, and their consumers Oct 1, 2026
[ghstack-poisoned]
[ghstack-poisoned]
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Oct 1, 2026
Make the remat regions follow the model's building blocks instead of
per-model wrappers, so a saved region's output is consumed by other regions
and torch_remat decides from the policy what to persist.

Projections. Every `Linear` runs `_linear` in a `<fqn>.linear` region, and
the TP collectives of the parallel linears become sibling regions:

- ColumnParallelLinear: `<fqn>.tp_gather` (the input S(0)/I -> R
  redistribution, an all-gather under sequence parallelism) and
  `<fqn>.linear`.
- RowParallelLinear and InvariantRowParallelLinear: `<fqn>.linear` (the
  partial projection) and `<fqn>.tp_reduce` (the P -> S(0)/I reduction).
  The two are controlled separately: saving `linear` while recomputing
  `tp_reduce` keeps the TP-times larger partial output for the replayed
  reduction, so save both to avoid it.
- AsyncColumnParallelLinear / AsyncRowParallelLinear: the fused collective
  matmul runs in a single `<fqn>.linear` region.

Quantized and LoRA linears only override `_linear`, so they get the region
for free. `maybe_gather_tp_input(module, x)` declares `<module fqn>.tp_gather`
for plain projections that share one TP input (DeepSeek V3 and Kimi K3 MLA,
Kimi K3 KDA, Qwen3.5 attention and DeltaNet, Muse Glimmer, Qwen3.5 MoE EP
input). Every attention kernel runs in `<module fqn>.inner_attention`
(DeepSeek V3, Kimi K3 MLA and KDA, Qwen3.5 attention and DeltaNet, Muse
Glimmer, gpt-oss, matching the common attention). DeepSeek V3's projections
move into `_project_qkv`, so FusedMLA overrides only the projections.

Consumers. A projection's output is usually read by a norm, rope, an
activation, or a residual add. These become regions, so a saved projection
needs no `recompute_needs_tensor`:

- `RMSNorm` (via a `_norm` hook), `LayerNorm`, Qwen3.5 `OffsetRMSNorm` and
  `RMSNormGated`, and Kimi `KimiRMSNormGated` declare `<fqn>.norm`; `RoPE`
  declares `<fqn>.rope`; the fused QKV reshape/split is
  `attention.qkv_linear.split`.
- Activations (`FeedForward`, `RoutedExperts`, `VisionMLP`, the Qwen3.5
  shared expert), the router score function (`router.score`), the
  shared-expert adds (`shared_add`), and the Qwen3.5 shared-expert gating
  (`gated_output`).
- Residual adds use `residual_add(self, x, branch, name)`
  (`attention_residual`, `ffn_residual`) in every transformer block and the
  vision block; Kimi K3's block attention residuals are `attention_res` and
  `ffn_res`.

A recomputed consumer region makes torch_remat persist a saved producer's
output for replay; a saved one is skipped during replay and persists nothing
beyond what its backward saves. Most consumer regions have a fixed choice,
because saving them never keeps less memory than recomputing them:

- Always recomputed: norms, rope, the QKV split, activations, the router
  score, the Qwen3.5 shared-expert gating, and the mid-block
  `attention_residual`. A saved one would persist its output for its
  recomputed consumers, even under full recomputation.
- Always saved: the end-of-block `ffn_residual` and `shared_add`, whose
  outputs only leave the block, so nothing is persisted for them.

Genuine bare consumers keep a consumer-side `recompute_needs_tensor` right
before the op: the routed-output TP zero-fill (EP + TP without SP), the
rope/nope concatenations in DeepSeek V3, Kimi K3 and Qwen3.5, the gating
multiplies in Kimi K3, Qwen3.5 and Muse Glimmer, the DeepSeek V4 query
rescale, compressor/indexer math and hyper-connection mixing, and the
FusedMLA kernel inputs. The routed-expert bf16 cast runs inside the w13
region. No pin sits between two regions.

Why: the old outer regions wrapped the SP all-gather together with the
matmul, so saving the projection also kept its gathered input for the weight
gradient, TP times larger per projection. With separate regions, saving
`.linear` while recomputing `.tp_gather` keeps only the sequence shard and
replays the all-gather for the weight gradient, as Megatron does. Making the
consumers regions instead of pinning inside `Linear` avoids keeping a
projection output that only a saved region reads (e.g. Kimi KDA's q/k/v).

User-visible change: RegionAC save patterns are renamed (e.g.
`attention.wo` -> `attention.wo.linear`, `feed_forward.w13` ->
`feed_forward.w13.linear`). The fixed consumer regions ignore save patterns,
so norms, rope and activations still always recompute, as they did as bare
ops. FullAC and SelectiveAC do not use remat regions, so they are unchanged.

Test plan: RegionAC save none vs save `*` gives identical losses for llama3,
qwen3 (dense and MoE), qwen3.5 (dense and MoE), deepseek_v3 (with and
without FusedMLA), gpt_oss (flex), kimi_k3, kimi_k2.5 and muse_glimmer (with
and without vision) at 1 GPU, TP2, TP2+EP2 and DP2+EP2.

ghstack-source-id: 9f685be
Pull-Request: pytorch/torchtitan#4956
Comment thread docs/remat.md Outdated
These consumer regions have fixed choices that save patterns do not change,
because saving them never keeps less memory than recomputing them:

- Always recomputed: norms, rope, the QKV split, activations, the router

@anijain2305 anijain2305 Oct 1, 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.

TODO -We should have a test for these instead of just documenting them in remat.md

submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Oct 2, 2026
Make the remat regions follow the model's building blocks instead of
per-model wrappers, so a saved region's output is consumed by other regions
and torch_remat decides from the policy what to persist.

Projections. Every `Linear` runs `_linear` in a `<fqn>.linear` region, and
the TP collectives of the parallel linears become sibling regions:

- ColumnParallelLinear: `<fqn>.tp_gather` (the input S(0)/I -> R
  redistribution, an all-gather under sequence parallelism) and
  `<fqn>.linear`.
- RowParallelLinear and InvariantRowParallelLinear: `<fqn>.linear` (the
  partial projection) and `<fqn>.tp_reduce` (the P -> S(0)/I reduction).
  The two are controlled separately: saving `linear` while recomputing
  `tp_reduce` keeps the TP-times larger partial output for the replayed
  reduction, so save both to avoid it.
- AsyncColumnParallelLinear / AsyncRowParallelLinear: the fused collective
  matmul runs in a single `<fqn>.linear` region.

Quantized and LoRA linears only override `_linear`, so they get the region
for free. `maybe_gather_tp_input(module, x)` declares `<module fqn>.tp_gather`
for plain projections that share one TP input (DeepSeek V3 and Kimi K3 MLA,
Kimi K3 KDA, Qwen3.5 attention and DeltaNet, Muse Glimmer, Qwen3.5 MoE EP
input). Every attention kernel runs in `<module fqn>.inner_attention`
(DeepSeek V3, Kimi K3 MLA and KDA, Qwen3.5 attention and DeltaNet, Muse
Glimmer, gpt-oss, matching the common attention). DeepSeek V3's projections
move into `_project_qkv`, so FusedMLA overrides only the projections.

Consumers. A projection's output is usually read by a norm, rope, an
activation, or a residual add. These become regions, so a saved projection
needs no `recompute_needs_tensor`:

- `RMSNorm` (via a `_norm` hook), `LayerNorm`, Qwen3.5 `OffsetRMSNorm` and
  `RMSNormGated`, and Kimi `KimiRMSNormGated` declare `<fqn>.norm`; `RoPE`
  declares `<fqn>.rope`; the fused QKV reshape/split is
  `attention.qkv_linear.split`.
- Activations (`FeedForward`, `RoutedExperts`, `VisionMLP`, the Qwen3.5
  shared expert), the router score function (`router.score`), the
  shared-expert adds (`shared_add`), and the Qwen3.5 shared-expert gating
  (`gated_output`).
- Residual adds use `residual_add(self, x, branch, name)`
  (`attention_residual`, `ffn_residual`) in every transformer block and the
  vision block; Kimi K3's block attention residuals are `attention_res` and
  `ffn_res`.

A recomputed consumer region makes torch_remat persist a saved producer's
output for replay; a saved one is skipped during replay and persists nothing
beyond what its backward saves. Most consumer regions have a fixed choice,
because saving them never keeps less memory than recomputing them:

- Always recomputed: norms, rope, the QKV split, activations, the router
  score, the Qwen3.5 shared-expert gating, and the mid-block
  `attention_residual`. A saved one would persist its output for its
  recomputed consumers, even under full recomputation.
- Always saved: the end-of-block `ffn_residual` and `shared_add`, whose
  outputs only leave the block, so nothing is persisted for them.

Genuine bare consumers keep a consumer-side `recompute_needs_tensor` right
before the op: the routed-output TP zero-fill (EP + TP without SP), the
rope/nope concatenations in DeepSeek V3, Kimi K3 and Qwen3.5, the gating
multiplies in Kimi K3, Qwen3.5 and Muse Glimmer, the DeepSeek V4 query
rescale, compressor/indexer math and hyper-connection mixing, and the
FusedMLA kernel inputs. The routed-expert bf16 cast runs inside the w13
region. No pin sits between two regions.

Why: the old outer regions wrapped the SP all-gather together with the
matmul, so saving the projection also kept its gathered input for the weight
gradient, TP times larger per projection. With separate regions, saving
`.linear` while recomputing `.tp_gather` keeps only the sequence shard and
replays the all-gather for the weight gradient, as Megatron does. Making the
consumers regions instead of pinning inside `Linear` avoids keeping a
projection output that only a saved region reads (e.g. Kimi KDA's q/k/v).

User-visible change: RegionAC save patterns are renamed (e.g.
`attention.wo` -> `attention.wo.linear`, `feed_forward.w13` ->
`feed_forward.w13.linear`). The fixed consumer regions ignore save patterns,
so norms, rope and activations still always recompute, as they did as bare
ops. FullAC and SelectiveAC do not use remat regions, so they are unchanged.

Test plan: RegionAC save none vs save `*` gives identical losses for llama3,
qwen3 (dense and MoE), qwen3.5 (dense and MoE), deepseek_v3 (with and
without FusedMLA), gpt_oss (flex), kimi_k3, kimi_k2.5 and muse_glimmer (with
and without vision) at 1 GPU, TP2, TP2+EP2 and DP2+EP2.

ghstack-source-id: 9f685be
Pull-Request: pytorch/torchtitan#4956
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@anijain2305
anijain2305 marked this pull request as ready for review October 2, 2026 05:53
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 2, 2026
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Oct 2, 2026
Seeking first review to see if the design makes sense

Key design changes
* More and more regions to avoid explicit recompute_needs_tensor. This allows in cases like (1) linear --> attention, (2) linear --> residual_add. All 3 are regions, and residual_add is recompute=True.
* ColumnParallelLinear and RowParallelLinear are broken into smaller regions. More specifically, we have a region around "self._linear" now and the collectives have their own regions.

ghstack-source-id: 804e768
Pull-Request: pytorch/torchtitan#4956
[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 Oct 2, 2026
Seeking first review to see if the design makes sense

Key design changes
* More and more regions to avoid explicit recompute_needs_tensor. This allows in cases like (1) linear --> attention, (2) linear --> residual_add. All 3 are regions, and residual_add is recompute=True.
* ColumnParallelLinear and RowParallelLinear are broken into smaller regions. More specifically, we have a region around "self._linear" now and the collectives have their own regions.
* GroupedLinear gets the same treatment: a region around "self._grouped_mm" (routed_experts.w13.grouped_mm / w2.grouped_mm). LoRA adapters call their _linear / _grouped_mm directly, so they run inside the base projection's region instead of declaring their own (a recomputed region cannot nest inside a saved one).

ghstack-source-id: 618e63d
Pull-Request: pytorch/torchtitan#4956

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 file was for thin titan wrappers over pytorch native modules -- if there's anything non-trivial, I'd put them into e.g. norm.py

return x
x = residual_add(self, x, attn_out, "attention_residual", recompute=True)
return residual_add(
self, x, self.mlp(self.norm2(x)), "ffn_residual", recompute=False

@tianyu-l tianyu-l Oct 2, 2026 •

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 set to False because

  • we want to get the early_stop benefit
  • and it "happens to be" that there's nothing additional to be saved, i.e. False and True save the same thing -- nothing

Just realized that I might be repeating what you put in the .md

@anijain2305 anijain2305 Oct 3, 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.

This is basically to make up for not having early_stop, yeah.

Comment on lines 293 to 295
with spmd.local():
q = q.view(num_tokens, -1, self.head_dim)
_assert_spmd_attention_type(q, tp=spmd.S(1))

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.

does this also not matter?

lambda q: q
* torch.rsqrt(q.square().mean(-1, keepdim=True) + self.norm_eps),
self.remat_region_name("q_rescale"),
# Consumer of the wq_b projection output: regionized so torch_remat persists

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 seems to be the main discussion point

  • This is a bit hard to read -- for naive user, it's hard to tell that how remat is applied inside wq_b. What if no remat is there in wq_b, then this code will be funny.
  • On the other hand, maybe in torchtitan, everyone should assume a submodule have had remat region applied everywhere, except for view ops.
  • I understand that this is a workaround for recompute_needs_tensor which itself suffers more or less similar readability issue + is not as optimal because the potential memory overhead it introduces

@anijain2305 anijain2305 Oct 3, 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.

You have aptly described the dilemma here. There are only 2 designs

  • Keep recompute_needs_tensor inside the submodule itself . Clean looking code, but we end up with situations like
region(linear)
recompute_needs_tensor()
region(attn)

if both are saved, the recompute_needs_tensor wastes memory.

  • Keep recompute_needs_tensor (or recompute region) next to the consumer. Dirty/funny code - abstractions leaking everywhere. But memory wise, this is correct.

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.

actually, I'm confused again

Are you saying the recompute_needs_tensor only wastes memory when both region are saved?

  • when 1st region is recompute, then remat will figure out it doesn't need to save -- we are good
  • when 2nd region is recompute, then anyway we have to spend memory on the recompute_needs_tensor -- we are good

In this PR, we seem to be hardcoding recompute=True everywhere for 2nd style regions, which according to the second point is not necessary?

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.

Both points are True. The question is how do you say in code that the first region out needs to be persisted. So for second case, there are 2 ways to say it

  • Have explicit recompute_needs_tensor and no region. The output of linear region for example directly goes into a torch.add op. If you don't add the recompute_needs_tensor, remat will fail.

OR

  • Have a region with recompute True. For example the residual_add region added in this PR.

Both are same. I have just chosen the second one.

The regions with recompute hard coded to True are the ones that are consumer of some heavy region and very fast at the same time.

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.

Citing your comment on internal doc:

  • region(linear) -> residual add - recompute_needs_tensor is the tax we must pay

In this case, I prefer explicit recompute_needs_tensor over making following code a region(recompute=True). I feel this is the "proper" way of using recompute_needs_tensor API.

  • region(linear) -> region(attention) - wasteful recompute_need_tensor if both are saved

In this case, I wonder if we can do (pseudo-code) if attention.is_recompute: recompute_need_tensor to not pay any unnecessary tax. (Is this your "pin" idea?). Here I didn't think much about multiple fanout cases.

Is your concern that now recompute_need_tensor cannot live in linear but leaked into other modules? But by using the region(recompute=True) alternative, it is also a kind of leaking.

@anijain2305 anijain2305 Oct 4, 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.

In this case, I prefer explicit recompute_needs_tensor over making following code a region(recompute=True). I feel this is the "proper" way of using recompute_needs_tensor API

Sounds good. For me, both of them are same. The only benefit of having a region is that remat has a diagnostic API to collect memory traces, and more regions means more visibility. But I don't have strong opinion on which one to choose.

Is your concern that now recompute_need_tensor cannot live in linear but leaked into other modules? But by using the region(recompute=True) alternative, it is also a kind of leaking.

Yes, both are leaking, we have to choose the lesser evil (and you are choosing explicit recompute_needs_tensor, I chose recompute_regions in the current PR).

In this case, I wonder if we can do (pseudo-code) if attention.is_recompute: recompute_need_tensor to not pay any unnecessary tax. (Is this your "pin" idea?). Here I didn't think much about multiple fanout cases.

If we are ok with linear not having recompute_needs_tensor and sprinkling it outside, we don't really have to do anything in this case (lets ignore the pin naming). We only need to worry about consumers of regions and if they are bare ops (torch ops), then we add a recompute_needs_tensor. If consumers are region, remat will take care automatically.

Comment thread torchtitan/models/common/linear.py Outdated
output = linear_fn(input, weight, bias)
if tp_group is not None:
# A recomputed reduction after a saved projection keeps the
# TP-times larger partial output for replay; save both to avoid 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.

trying to recall our previous conclusion

  • if we "recompute", and it is the last region in the block, then we don't enjoy the early stop that could've been done
  • if we "save", do we lose anything? save_for_backend for reduction should do nothing (although for the matmul would save input a and x)

so at least for tp_reduce, we should always "save"? I must be wrong.

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 wanted to save as you have figured it out. But, at the same time, RowParallelLinear is a common layer, and one might use it and still have ops later on. Today it happens to be used mostly in MLP. So I did not want to recompute it to False by default.

We can however handle this probably in configs where for the models that we care about, we have some reasonable defaults.

submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Oct 3, 2026
Seeking first review to see if the design makes sense

Key design changes
* More and more regions to avoid explicit recompute_needs_tensor. This allows in cases like (1) linear --> attention, (2) linear --> residual_add. All 3 are regions, and residual_add is recompute=True.
* ColumnParallelLinear and RowParallelLinear are broken into smaller regions. More specifically, we have a region around "self._linear" now and the collectives have their own regions.
* GroupedLinear gets the same treatment: a region around "self._grouped_mm" (routed_experts.w13.grouped_mm / w2.grouped_mm). LoRA adapters call their _linear / _grouped_mm directly, so they run inside the base projection's region instead of declaring their own (a recomputed region cannot nest inside a saved one).

ghstack-source-id: 618e63d
Pull-Request: pytorch/torchtitan#4956
[ghstack-poisoned]
@anijain2305 anijain2305 changed the title Declare remat regions for projections, attention, and their consumers Declare remat regions for projections and attention Oct 4, 2026
submartingales pushed a commit to botcanlearn/torchtitan-upstream that referenced this pull request Oct 4, 2026
Key design changes
* Every Linear declares its own remat region around `self._linear` (`<fqn>.linear`), the seam that quantized and LoRA linears already override. Callers call the Linear directly instead of wrapping it in a region, since a saved outer region cannot contain a recomputed one.
* ColumnParallelLinear and RowParallelLinear put their collectives in separately controlled sibling regions: `<fqn>.tp_gather` before the projection and `<fqn>.tp_reduce` after it. Modules whose projections share one TP input gather it once with `maybe_gather_tp_input`, which declares `<module fqn>.tp_gather`.
* GroupedLinear gets the same treatment: a region around `self._grouped_mm` (`routed_experts.w13.grouped_mm` / `w2.grouped_mm`). LoRA adapters call their `_linear` / `_grouped_mm` directly, so they run inside the base projection's region instead of declaring their own.
* Attention modules wrap their kernel in `<fqn>.inner_attention`.
* Bare operations that read a projection or attention output (norms, rope, splits, gating, residual adds) call `recompute_needs_tensor` immediately before the read, with a comment naming the producer.

ghstack-source-id: bb88347
Pull-Request: pytorch/torchtitan#4956

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

only one question regarding recomptue_needs_tensor before residual add

Comment thread torchtitan/models/gpt_oss/model.py Outdated
return self.wo(output)
output = self.wo(output)
# The block's residual add reads the wo projection output with bare ops.
remat.recompute_needs_tensor(output)

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 one I'm not so sure

  • universally we seem to have the principle "downstream consumers of a remat region calls recompute_needs_tensor", but here it's more or less "producer calls recompute_needs_tensor" -- do you think we should unify the rule? I guess the main concern is that your transformer block code will be complicated a bit (needs to insert this call in between addition), but is there any other consideration?
  • in addition, it seems in this PR we no longer tries to address the other issue around early_stop equivalence, which can complicates the story -- I'm totally fine, just to confirm

@anijain2305 anijain2305 Oct 5, 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.

  • Unified all the recompute_needs_tensor calls to the consumer. There was no main consideration, I just missed that one.
  • Yes, this is no longer addressing early_stop. Let's figure it out in a separate PR

[ghstack-poisoned]
[ghstack-poisoned]
@anijain2305
anijain2305 changed the base branch from gh/anijain2305/52/base to main October 5, 2026 17:20
@anijain2305
anijain2305 merged commit d75ddfa into main Oct 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests 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