Skip to content

Apply the activation remat policy to MTP layers - #6246

Merged
francesco-bertolotti merged 12 commits into
pytorch:mainfrom
francesco-bertolotti:f14-remat-mtp
Nov 22, 2026
Merged

francesco-bertolotti merged 12 commits into
pytorch:mainfrom
francesco-bertolotti:f14-remat-mtp

Conversation

@francesco-bertolotti

@francesco-bertolotti francesco-bertolotti commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator

Apply the activation remat policy to MTP layers

Summary (human-written)

Currently AC policy ignore deepseek-style MTP layers. For big models this easily causes an OOM. The fix is to propagate the policy to mtp layers as well.

Why

ActivationRematConfig.apply checkpoints only model.layers, so the DeepSeek-V3/V4 MTP blocks in model.mtp_layers keep every activation whatever the AC policy is.

DSV3, num_mtp_layers=2, Default AC
before: layers.* checkpointed, mtp_layers.* not
after:  layers.*, mtp_layers.* checkpointed, one offloader

What changed

  • apply(model_part, *, block_container_fqns) checkpoints the blocks of all listed containers in one call, so each model part still gets one ActivationOffloader.
  • BaseModel._remat_block_container_fqns() returns ["layers"]. MTPDecoder and DeepSeekV4Model append "mtp_layers", and MultimodalModel prepends its encoders' layers. MultimodalModel.parallelize is deleted.
  • Encoder block region names become vision_encoder.layers.<id> (previously layers.<id>, colliding with decoder blocks).
  • DSV3/DSV4 MTP blocks: remat.recompute_needs_tensor before bare ops on region outputs, which otherwise fail in backward once the blocks are checkpointed.
  • BlockRematOverride.blocks is no longer format-checked; a malformed name now matches nothing, like a name the model lacks.

A coarse _apply_activation_remat() hook doesn't compose for KimiK25Model (encoders + MTP): either two offloaders or skipped MTP blocks.

Numerics

Bitwise-identical loss and grad_norm vs. main (loss_compare.py --assert-equal, seed 42, deterministic, 10 steps, FSDP 4 on 4x GH200):

Config AC Result
deepseek_v3_debugmodel_mtp Default identical
deepseek_v3_debugmodel_mtp, seq 16384 Full identical

Testing

  • test_mtp_remat.py (new): DSV3 MTP blocks are checkpointed, and outputs and grads are bitwise equal to no remat under Full and Default AC.
  • test_activation_checkpoint.py: every container is checkpointed and only one offloader is installed.
  • DSV4 MTP checked locally (bitwise equal to no remat); DSV4 MTP training is broken on main, fixed separately.

@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 19, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 19, 2026
@pytorch-bot

pytorch-bot Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@github-actions
github-actions Bot requested a review from anijain2305 November 19, 2026 15:58
@francesco-bertolotti francesco-bertolotti changed the title remat mtp Apply the activation remat policy to MTP layers Nov 19, 2026
Comment on lines +209 to +214
mtp_layers = getattr(module, "mtp_layers", None)
if mtp_layers is not None:
transformer_blocks += [
(f"mtp_layers.{layer_id}", block)
for layer_id, block in mtp_layers.named_children()
]

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.

Instead hardcode "mtp" in this function, can we use / generalize module_fqn to move the logic to MTPDecoder https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/deepseek_v3/mtp.py#L191? similar to what we do for encoder
https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/common/multimodal.py#L113

I realized that it may not play super well with my suggestion for offloading's offload_last_block config #6020 (comment)

cc @anijain2305

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 37s —— View job


Request changes -- review (tianyu-l's design comment is unaddressed; MTP knowledge should move out of activation_remat.apply into the models, covering DSV4 too).

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

Verdict: Request changes -- The problem is real and the model-side guards look right. But apply hardcodes mtp_layers, and tianyu-l asked for the MTP knowledge to move into the model instead. That comment is unaddressed at HEAD, and the redesign changes most of the activation_remat.py diff.

What this PR does. ActivationRematConfig.apply now checkpoints the children of module.mtp_layers as well as module.layers, using the FQN mtp_layers.<id>. The PR also adds recompute_needs_tensor guards to the DSV3 and DSV4 MTP blocks, so that policies that save regions don't fail in backward.

Example.

DSV3, num_mtp_layers=2, DefaultActivationRematConfig
main: layers.0..N checkpointed; mtp_layers.0/.1 keep every activation
PR:   layers.*, mtp_layers.* checkpointed with the same policy

Must fix

  1. torchtitan/distributed/activation_remat.py:205-214 -- tianyu-l's comment is unaddressed. The comment is correct, but moving the logic only into MTPDecoder would miss DSV4: DeepSeekV4Model subclasses Decoder directly (deepseek_v4/model.py:124) and also owns mtp_layers. Smallest shape that covers both:
    • Change apply(module, *, module_fqn) to apply(blocks, *, blocks_fqn), where blocks is the container and blocks_fqn is its FQN, e.g. "layers", "vision_encoder.layers" or "mtp_layers". activation_remat.py then has no model-specific names, and _BLOCK_FQN becomes a generic <container fqn>.<id> pattern.
    • The models declare their containers. Either MTPDecoder and DeepSeekV4Model each call apply(self.mtp_layers, blocks_fqn="mtp_layers"), following the multimodal precedent at multimodal.py:110-113, or a ClassVar of container FQNs (like pipeline_last_stage_module_fqns) is read by BaseModel.parallelize. The ClassVar option would also absorb the multimodal encoder loop.
  2. tests/unit_tests/gpu/distributed/test_activation_checkpoint.py:199-213 -- the test only guards a config-time ValueError path; delete it (inline).
  3. torchtitan/distributed/ACTIVATION_REMAT.md:96 -- the doc lists the block FQN forms and still omits mtp_layers.<id>. Please update it.

Should consider

  • torchtitan/models/deepseek_v4/mtp.py:71 -- the V4 guard has no test and no numerics run, and the description says it does (inline).
  • test_mtp_layers_are_checkpointed overlaps with test_mtp_remat.py. The DSV3 test is the one that catches the real regression (backward fails under Default without the guards). After the redesign, the toy test only needs to check that apply(container, blocks_fqn=...) hooks and names blocks correctly. That is generic, so one non-layers container is enough.

Questions

  • For tianyu-l / #6020: with MTP blocks checkpointed, the last block of a model part in forward order is mtp_layers.<M-1>, not layers.<N-1>. Whichever design lands needs to tell offload_last_block which block is last. Should apply see all containers of a model part in one call, so that it knows the execution order?
Details
  • Gate: confirmed on main. apply only walks layers, and apply_fsdp_to_mtp_decoder (deepseek_v3/mtp.py:497-525) only inserts MTP blocks into layers temporarily for FSDP wrapping. PP + MTP is unsupported (MTP.md TODO 1), so the stage split doesn't matter here.
  • The DSV3 guards match the trunk-block pattern (deepseek_v3/model.py:51-53). The trailing add in MTP is not trailing (mtp_norm follows it), so using recompute_needs_tensor(ffn_out) instead of a recompute=False add region is consistent.
  • The other caller, transformers_modeling_backend/parallelize.py:175, also calls apply(model) and needs updating if the signature changes.

Not verified: GPU numerics, and whether DSV4 needs more guards beyond the one added.

Comment on lines +199 to +213
def test_block_overrides_name_mtp_blocks(self):
model = ToyModel()
model.mtp_layers = ModuleList([TransformerBlock()])
ActivationRematConfig(
save_regions=[],
block_overrides=[
BlockRematOverride(blocks=["mtp_layers.0"], save_regions=["*"])
],
).apply(model)
x_BD = torch.randn(8, 32, requires_grad=True)
(model(x_BD) + model.mtp_layers[0](x_BD)).backward()

block = model.mtp_layers[0]
self.assertEqual(block.input_projection.num_forwards, 1)
self.assertEqual(model.layers["0"].input_projection.num_forwards, 2)

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 test doesn't guard anything that could break silently. Override lookup (block_fqn in o.blocks) runs the same code for mtp_layers.<id> as for layers.<id>, and the existing override tests already cover it. The only new thing is the _BLOCK_FQN regex, and if that regressed, BlockRematOverride.__post_init__ would raise a ValueError at config time, which is loud, not silent. Please delete the test. If you want to keep coverage of the new FQN form, add "mtp_layers.0" to an existing override test.

embed_hidden = self.e_proj(self.enorm(mtp_input_embed))
prev_hidden = self.h_proj(self.hnorm(prev_hc_hidden))
# The unsqueeze and the add read both projection outputs with bare ops.
remat.recompute_needs_tensor(embed_hidden, prev_hidden)

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.

Nothing in this PR exercises this guard. test_mtp_remat.py builds only DeepSeek-V3, and the Numerics table has only deepseek_v3_debugmodel_mtp. The description says "as each block's test shows when the guard is removed", but V4 has no such test. This PR also starts checkpointing V4 MTP blocks (DeepSeekV4Model.mtp_layers), so please do one of two things. Either run a V4 debug config with MTP under Default AC through loss_compare.py --assert-equal and add the result to the table, or say in the description that V4 is unverified. Unverified whether other bare reads in DeepSeekV4TransformerBlock.forward or hc_head need guards once the block is checkpointed.

@francesco-bertolotti

francesco-bertolotti commented Nov 19, 2026 •

Copy link
Copy Markdown
Collaborator Author

now remat is applied from inside the model. Is this what you meant? (This is more of a quick draft, let me have another look at it tomorrow)

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 11s —— View job


Request changes -- review: MTP remat now lives in the models, but DSV3 and DSV4 each copy all of BaseModel.parallelize, and blocks_name duplicates module_fqn instead of generalizing it.

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

Verdict: Request changes -- The MTP knowledge is now in the models, as tianyu-l asked. But it got there by copying all of BaseModel.parallelize into DSV3 and DSV4, and by adding a second location parameter (blocks_name) next to module_fqn instead of generalizing module_fqn.

What changed since the last review. apply no longer names mtp_layers; it takes blocks_name="layers". MTPDecoder and DeepSeekV4Model override parallelize and call apply(self, blocks_name="mtp_layers"). The validation regex now accepts any <container>.<id>.

Example.

DSV3, num_mtp_layers=2, Default AC
main: layers.* checkpointed; mtp_layers.* keep every activation
PR:   MTPDecoder.parallelize -> apply(self); apply(self, blocks_name="mtp_layers")

Earlier must-fix items

  • tianyu-l's comment (keep MTP out of apply): partly resolved. The model now owns the MTP call. What is still open is how that is wired up; see items 1-2.
  • Override-validation test: resolved (deleted). The new test_blocks_name_selects_the_block_container is the generic container test that the last review suggested.
  • ACTIVATION_REMAT.md: resolved. It mentions mtp_layers.<id> now, though the edited paragraph has one unwrapped line.

Must fix

  1. torchtitan/models/deepseek_v3/mtp.py:252 and deepseek_v4/model.py:157 -- two full copies of BaseModel.parallelize (a third already exists in multimodal.py). Override only a small _apply_activation_remat step instead (inline).
  2. torchtitan/distributed/activation_remat.py:173 -- blocks_name and module_fqn are two ways to locate blocks. Merge them into one dotted blocks_fqn, as tianyu-l suggested (inline).
  3. PR description: "What changed" still says activation_remat.py: apply also checkpoints each mtp_layers.<id> block, and "as each block's test shows" still covers V4, which has no test. Please update both to match HEAD.

Should consider

  • torchtitan/distributed/activation_remat.py:29 -- with the looser regex, a typo like layer.3 is no longer caught at config time; the override just does nothing (inline).
  • Still open from the last review: the DSV4 mtp.py:71 guard has no test and no numerics run. Either run loss_compare.py --assert-equal on a V4 MTP debug config, or say in the description that V4 is unverified.
Details
  • Of the classes that own mtp_layers, DeepSeekV3Model gets the override from MTPDecoder, and DeepSeekV4Model subclasses Decoder directly. No other model overrides parallelize in a way that would skip the new call: kimi_k2_7 delegates to super() and has no MTP.
  • transformers_modeling_backend/parallelize.py:175 calls apply(model) and is unaffected if blocks_fqn defaults to "layers".
  • The mtp.py guards in DSV3 are unchanged since the last review.

Not verified: GPU numerics for DSV4 MTP; whether anything keys on encoder region_name.

Comment thread torchtitan/models/deepseek_v3/mtp.py Outdated
)
self.mtp_layers.append(layer_config.build())

def parallelize(

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 override and the one at deepseek_v4/model.py:157 are full copies of BaseModel.parallelize (base/model.py:149-171), and multimodal.py:91 is already a third. Only two lines differ between them. That means four copies of the parallelize lifecycle (local_compile -> _parallelize -> remat -> _apply_fsdp), and a new step added to the base has to be added to every copy by hand.

Smallest fix: move only the remat step into a method on BaseModel, and have the models override that method instead of parallelize:

# base/model.py, inside parallelize
if activation_remat is not None:
    self._apply_activation_remat(activation_remat)

def _apply_activation_remat(self, activation_remat: ActivationRematConfig) -> None:
    activation_remat.apply(self)

# MTPDecoder and DeepSeekV4Model
def _apply_activation_remat(self, activation_remat):
    super()._apply_activation_remat(activation_remat)
    if self.mtp_layers is not None:
        activation_remat.apply(self, blocks_fqn="mtp_layers")

This deletes about 50 lines here and in V4. multimodal.py could drop its parallelize override the same way. The len(...) > 0 check isn't needed either, because apply already returns early when the container is empty (activation_remat.py:207).

This also helps with the #6020 question from the last review: all the containers of a model part are handled in one method, in execution order, so that is the one place offload_last_block would need to look.

module: Module,
*,
module_fqn: str = "",
blocks_name: str = "layers",

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.

tianyu-l suggested generalizing module_fqn. This adds a second parameter next to it instead, so apply now has two ways to say where the blocks are:

  • apply(encoder, module_fqn="vision_encoder")
  • apply(self, blocks_name="mtp_layers")

get_submodule accepts dotted paths, so one parameter covers both cases. Use blocks_fqn: str = "layers" and drop module_fqn:

blocks = module.get_submodule(blocks_fqn)
...
block_fqn = f"{blocks_fqn}.{layer_id}"

Then the multimodal call becomes activation_remat.apply(self, blocks_fqn=f"{encoder_fqn}.layers"), and the base_fqn vs block_fqn split goes away.

One side effect: encoder blocks would get region_name and the saved_tensors_hooks FQN vision_encoder.layers.<id> instead of layers.<id>. Today that name collides with decoder block layers.<id>, so the change looks like a fix. Unverified whether anything keys on the old name. Please also update the doc paragraph at ACTIVATION_REMAT.md:96 to match, and rewrap it.



_BLOCK_FQN = re.compile(r"([A-Za-z_]\w*\.)?layers\.\d+")
_BLOCK_FQN = re.compile(r"([A-Za-z_]\w*\.)+\d+")

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.

The looser regex drops the one typo check overrides had. BlockRematOverride(blocks=["layer.3"], ...) used to raise at config time. Now it passes validation and then never matches a block, so the override does nothing and nothing reports it. Block names aren't checked against the model (see the TODO at :214). The test change from "layer.91" to "layers.last" shows that this case is no longer caught.

Keeping the layers suffix convention preserves the check without hardcoding mtp:

Suggested change
_BLOCK_FQN = re.compile(r"([A-Za-z_]\w*\.)+\d+")
_BLOCK_FQN = re.compile(r"([A-Za-z_]\w*\.)*[A-Za-z_]*layers\.\d+")

Then the test can keep "layer.91".

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

@tianyu-l Should we keep the BlockRematOverride.blocks format check (https://github.com/francesco-bertolotti/torchtitan/blob/0b3a0cf397148dc76b978a714b422eaffac59800/torchtitan/distributed/activation_remat.py\#L68-L75) With MTP it has to accept mtp_layers., so it now requires names ending in layers..

What it catches: typos like layer.3, wildcards like layers.* (blocks takes exact names, unlike save_regions), and submodule paths.
What it misses: well-formed names that don't exist (layers.999, model.layers.3). Those still do nothing silently.

I'd lean towards removing it: it ties overrides to a container naming convention that apply doesn't need, and the real fix is validating names across pipeline stages. Happy to keep it if you prefer the early error.

…call

ActivationRematConfig.apply takes block_container_fqns instead of
module_fqn/blocks_name. Models list their containers in
BaseModel.remat_block_container_fqns (MTP adds "mtp_layers", multimodal
adds "<encoder>.layers"), which removes the parallelize copies in
DSV3, DSV4 and multimodal. One call per model part installs a single
activation offloader; separate calls installed one per call.
Comment on lines 164 to +167
if activation_remat is not None:
activation_remat.apply(self)
activation_remat.apply(
self, block_container_fqns=self.remat_block_container_fqns()
)

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 might be nit comment:
Instead of providing very-fine-grained hook remat_block_container_fqns, I would rather provide self._apply_activation_remat() as the hook, similar to self._apply_fsdp(). I somehow think it'd be more durable...

@francesco-bertolotti francesco-bertolotti Nov 21, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The reason is composition across the MRO (as claude mentioned).

_apply_activation_remat() would work for every model except one that inherits block containers from two classes, like KimiK25Model:

  • MultimodalModel adds vision_encoder.layers
  • MTPDecoder adds mtp_layers

Neither class knows about the other's container.

The constraint is that apply must be called once per model part. Each call installs an ActivationOffloader, and that offloader hooks every checkpointed block in the model, so two calls mean two offloaders on the same blocks.

With a coarse _apply_activation_remat() hook, KimiK25Model has two options, and both are wrong:

  1. Both classes call apply: two offloaders.
  2. Only one class calls apply: the other class's blocks are silently not checkpointed.

With _remat_block_container_fqns(), each class only appends its own container and calls super(). BaseModel.parallelize then makes the single apply call with the full list:
["vision_encoder.layers", "layers", "mtp_layers"]

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 50s —— View job


Needs discussion -- review: the earlier code issues are fixed. tianyu-l's _apply_activation_remat() hook comment is still open; remat_block_container_fqns composes across KimiK25Model's MRO and a coarse hook wouldn't. The PR description is still out of date.

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

Verdict: Needs discussion -- The code issues from the last review are fixed. The open question is tianyu-l's latest comment (coarse _apply_activation_remat() hook instead of remat_block_container_fqns). The current design has a concrete reason the author should give in that thread: it composes across KimiK25Model's MRO, and a coarse hook wouldn't.

What changed since the last review. apply(module, *, module_fqn) is now apply(model_part, *, block_container_fqns). It runs once per model part and installs one offloader. BaseModel.parallelize passes self.remat_block_container_fqns(); MTPDecoder, DeepSeekV4Model and MultimodalModel extend it through super(). MultimodalModel.parallelize is deleted (-33 lines).

Example.

KimiK25Model MRO: MultimodalModel -> KimiK2Model -> DeepSeekV3Model -> MTPDecoder -> Decoder
remat_block_container_fqns() -> ["vision_encoder.layers", "layers", "mtp_layers"]
-> one apply call, one ActivationOffloader

Earlier must-fix items

  • Copies of BaseModel.parallelize in DSV3/DSV4: resolved. The multimodal copy is gone too.
  • blocks_name next to module_fqn: resolved (one block_container_fqns).
  • PR description out of date: still open (item 2).

Must fix

  1. tianyu-l's comment at base/model.py:167 is unaddressed (HEAD predates it). Evidence for the maintainer to weigh: apply must now run once per model part, or a second ActivationOffloader hooks every block again (test_apply_marks_blocks_of_every_container_and_installs_one_offloader). With a coarse _apply_activation_remat(activation_remat) hook, MultimodalModel and MTPDecoder can't both chain to super() for KimiK25Model (kimi_k2_7/model.py:73). Either the MRO-first override calls apply with only its own containers and MTP blocks are silently skipped, or both call apply and you get two offloaders. With the coarse hook, each model that mixes an encoder and MTP would need its own override listing every container. The FQN list avoids that. @francesco-bertolotti, please reply on that thread. If tianyu-l still prefers the coarse hook, apply has to accept repeated calls on one model part again.
  2. PR description: "What changed" still says apply checkpoints mtp_layers.<id> itself. It doesn't mention remat_block_container_fqns or the deleted MultimodalModel.parallelize. It also omits that encoder blocks' checkpoint region_name changes from layers.<id> to vision_encoder.layers.<id>, which removes a collision with decoder block names. "Testing" still lists the deleted block_overrides/mtp_layers test, and "as each block's test shows" still covers V4, which has no test.

Should consider

  • torchtitan/models/base/model.py:177 -- the "in run order" contract is never read by anything (inline).
  • torchtitan/distributed/activation_offload.py:358-360 -- the _hook_blocks docstring still says it runs "once apply has run for the model part and for each encoder in it, in whatever order". There is one call now; please update it.
  • Still open: the DSV4 mtp.py:71 guard has no test and no numerics run. Either run loss_compare.py --assert-equal on a V4 MTP debug config, or say in the description that V4 is unverified.
Details
  • Other callers: transformers_modeling_backend/parallelize.py:175 and the apply(model) tests rely on the ("layers",) default and are unaffected. Flux hand-rolls its block checkpointing and doesn't call apply. GraphTrainer drops activation_remat. gpt_oss, kimi_k2_7 and muse_glimmer delegate to super().parallelize.
  • Under PP, _pipeline_module_split replaces pruned ModuleLists with empty ones (pipeline_parallel.py:699-700), so DSV4's unconditional "mtp_layers" yields no blocks on non-last stages. Pruned encoders are None and filtered out in multimodal.py.
  • The _BLOCK_FQN regex at HEAD keeps the layers/<prefix>_layers check that the last review suggested. francesco-bertolotti's question on whether to drop it is still waiting for a maintainer.

Not verified: GPU numerics at HEAD (the table was measured against an earlier commit) and DSV4 MTP under remat.

Comment thread torchtitan/models/base/model.py Resolved

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

Due to the MRO limitation and "offloading should only be applied once" constraint, your solution seems fine. Please address my and claude comments.

Also I gave you write access to the repo, so that you could:

  • interact with claude to get its approval first before getting human review (actually one can run the pr-review skill locally first)
  • be able to get CI running, after converting a PR from draft mode to ready mode

Please use the power with care

Comment thread torchtitan/models/base/model.py Resolved
@francesco-bertolotti

Copy link
Copy Markdown
Collaborator Author

@claude review

@claude

claude Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @francesco-bertolotti's task in 1m 29s —— View job


Approve -- review: all earlier items are fixed; one doc-wrap nit is left in ACTIVATION_REMAT.md.

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

Verdict: Approve -- please address the items below before merging. Every item from the last review is fixed at HEAD. tianyu-l has approved the _remat_block_container_fqns design, and the only thing left is a doc-wrap nit.

What this PR does. ActivationRematConfig.apply(model_part, *, block_container_fqns) checkpoints the blocks of every listed container in one call, so each model part gets one ActivationOffloader. BaseModel._remat_block_container_fqns() returns ["layers"]. MultimodalModel prepends <encoder>.layers, and MTPDecoder and DeepSeekV4Model append mtp_layers. The DSV3 and DSV4 MTP blocks add recompute_needs_tensor guards so that backward works once those blocks are checkpointed.

Example.

KimiK25Model (MultimodalModel -> ... -> MTPDecoder -> Decoder)
main: apply(self); apply(vision_encoder, module_fqn=...)  -> mtp_layers.* keep every activation
PR:   apply(self, block_container_fqns=["vision_encoder.layers", "layers", "mtp_layers"])
      -> all blocks checkpointed, one offloader

Earlier items

  • tianyu-l's _apply_activation_remat() hook comment: resolved. The author answered on the thread with the MRO argument, and tianyu-l approved.
  • Make the method private: resolved (_remat_block_container_fqns).
  • "in run order" contract: resolved. It is gone from base/model.py and the multimodal comment. The remaining mention at activation_remat.py:441 describes the offloader's real hook-order chaining, which is correct.
  • _hook_blocks docstring: resolved.
  • PR description: resolved. It now covers the region-name change and the deleted MultimodalModel.parallelize, and it says DSV4 was only checked locally.

Must fix

  1. torchtitan/distributed/ACTIVATION_REMAT.md:97-104 -- the paragraph is unevenly wrapped. A suggestion is inline.
Details
  • Callers at HEAD: transformers_modeling_backend/parallelize.py:175 uses the ("layers",) default. gpt_oss, kimi_k2_7 and muse_glimmer delegate to super().parallelize. KimiK3MultimodalModel and MuseSparkMultimodalModel inherit MultimodalModel._remat_block_container_fqns through their MRO, and their decoder bases don't override it. Nothing else references module_fqn.
  • DSV4 always appends "mtp_layers". That is safe because mtp_layers is always a ModuleList (deepseek_v4/model.py:271), possibly empty. DSV3 skips it when mtp_layers is None.
  • _BLOCK_FQN still accepts only layers and <prefix>_layers containers. No maintainer has answered francesco-bertolotti's question about dropping the check. Keeping it is the more conservative choice, so it doesn't block this PR.
  • tianyu-l has approved, so the maintainer review of the core changes (base/model.py, activation_remat.py) is done.

Not verified: GPU numerics at HEAD (I can't run GPU tests here), and DSV4 MTP under remat, which is only checked locally.

Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
@francesco-bertolotti

Copy link
Copy Markdown
Collaborator Author

@tianyu-l

I've addressed Claude's comments, and the PR is now passing review. There's just one small item I'd like you to take a look at:

#6246 (comment)

Regarding the failing lint checks and tests, they don't seem to be related to this PR. I suspect one of the latest commits on main introduced these failures.

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

I'd lean towards removing it: it ties overrides to a container naming convention that apply doesn't need, and the real fix is validating names across pipeline stages. Happy to keep it if you prefer the early error.

let's go with what you suggested.

The CI error should've been fixed on main. Could you rebase.

Feel free to merge after that.

@francesco-bertolotti
francesco-bertolotti merged commit 69e31a2 into pytorch:main Nov 22, 2026
25 checks passed
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