Repository navigation
[mtp] Gather tok_embeddings once for all MTP depths, and run the final norm after the MTP pass - #6248
francesco-bertolotti wants to merge 7 commits into
Conversation
|
|
|
@claude review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The problem is real on main, the fix lives in the model's FSDP setup and uses only public FSDP2 APIs, and numerics are shown bitwise equal. What's left is small cleanup, plus one question about the memory trade-off.
What this PR does. MTPDecoder.forward and DeepSeek V4's mtp_forward call tok_embeddings once per MTP depth. Today FSDP re-gathers the full table on every call. Under EP, each call also re-prefetches layers.0, which then stays unsharded until its backward. This PR adds two forward hooks:
- After the trunk
norm,tok_embeddingsstops resharding and stops prefetching. - After the last MTP block, it reshards and both settings are restored.
Example (num_mtp_layers=3, FSDP, EP=2, untied, default policy, no PP):
main: tok_emb gathers 4x/step; layers.0 gathers 2x and is held from mtp_layers.0 until its backward
PR: tok_emb gathers 2x/step; layers.0 gathers 1x; table held from mtp depth 1 until mtp_layers[-1] ends
PP + default policy, weight tying, or policy "never": hooks not registered, behavior unchanged
Must fix
- The PR description: the "Summary (human-written)" section is empty. The author needs to fill it in.
torchtitan/models/deepseek_v3/mtp.py:538-576-- the helper has one caller and repeats the caller's guards. Inline it (inline comment).torchtitan/models/deepseek_v3/mtp.py:583-- the "backward recompute" comment is wrong for torch_remat: module forward hooks don't fire again during recompute. Delete it (inline comment).
Should consider
torchtitan/models/deepseek_v3/mtp.py:540-545-- the restored prefetch list copies a private rule fromapply_fsdp_to_decoder. If that rule changes, the restore silently goes stale. Use the same predicate and point to thefsdp.pycode it mirrors (inline comment).
Questions
- The measured peak memory goes up by the full table size (+1.00 GiB at FSDP 16). That is likely what the rejected alternative would also cost:
reshard_after_forward=Falseontok_embeddingswhen MTP is present, plus a permanently empty forward-prefetch list for it under EP. That alternative needs about 5 lines and no runtime hooks, and gets the table down to one gather per step instead of two. Its downside is thatlayers.0is no longer prefetched at the start of the trunk. Did you measure it? If peak memory and TPS come out the same, it is the smaller design.
Details
- Gate. The redundant gathers follow directly from FSDP2 resharding after every call of a module that runs several times in one forward. The
layers.0re-prefetch under EP is a real leak onmain:layers.0's post-forward never runs again in that step. The model folder'sapply_fsdp_to_mtp_decoderis the right place for the fix. It uses only public APIs (set_reshard_after_forward,set_modules_to_forward_prefetch,reshard), so no upstream TODO is needed. No overlapping open PR found. - Parallelisms. With PP and the default policy, the policy resolves to
False, so nothing is registered. With PP and"always", a stage withouttok_embeddingsornorm, or with no MTP layers, is skipped. Each stage's forward runs norm -> MTP in one call, so the two hooks stay paired per microbatch. Under EP, the forward chain built with the MTP layers temporarily insidemodel.layersislayers.N-1 -> mtp_layers.0 -> ... -> mtp_layers[-1] -> [norm, lm_head], and restoringtok_embeddings -> [layers.0]matches it. Embedding backward hasset_unshard_in_backward(False), so restoringreshard_after_forward=Truebefore backward changes nothing there. - Compile. torchtitan compiles local regions (
local_compile.py), not whole blocks, so Dynamo never traces these hooks. - Hook sites.
normis only called from_pre_lm_head_norm_and_gather, once per forward, in both DSv3 and DSv4.
Not verified (needs GPUs): the all-gather counts and the TPS and memory numbers in the description. A maintainer still needs to review.
| _gather_mtp_embedding_once( | ||
| model, | ||
| # apply_fsdp_to_decoder's explicit forward prefetch of the first | ||
| # decoder layer, set only under EP (unshard_in_current_stream is | ||
| # rejected above). | ||
| forward_prefetch=[cast(FSDPModule, next(iter(model.layers.values())))] | ||
| if ep_degree > 1 | ||
| else [], | ||
| ) | ||
|
|
||
|
|
||
| def _gather_mtp_embedding_once( | ||
| model: MTPDecoder, *, forward_prefetch: list[FSDPModule] | ||
| ) -> None: | ||
| """Keep ``tok_embeddings`` unsharded from the first MTP depth to the last. | ||
|
|
||
| The MTP pass calls ``tok_embeddings`` once per depth. FSDP reshards it | ||
| after each call, so every depth all-gathers the whole table again, with | ||
| nothing prefetching it. Under explicit prefetching (EP), each call also | ||
| repeats the embedding's forward prefetch of the first decoder layer, | ||
| which unshards that layer in the middle of the MTP pass and keeps it | ||
| whole until its backward. | ||
|
|
||
| From the trunk's final ``norm`` (run between the trunk and the MTP pass) | ||
| to the end of the last MTP block, the embedding keeps its unsharded | ||
| weight and prefetches nothing; then it reshards and gets its settings | ||
| back. One all-gather for the MTP pass instead of one per depth, at the | ||
| cost of holding the table through the MTP blocks. | ||
|
|
||
| Args: | ||
| model: The FSDP-wrapped MTP decoder, with ``tok_embeddings`` resharded | ||
| after forward. | ||
| forward_prefetch: The modules ``tok_embeddings`` prefetches in | ||
| forward, restored after the MTP pass. | ||
| """ | ||
| assert model.mtp_layers is not None | ||
| embedding = model.tok_embeddings | ||
| if not isinstance(embedding, FSDPModule) or model.norm is None: | ||
| return |
There was a problem hiding this comment.
_gather_mtp_embedding_once is only called from here (DeepSeek V4 reaches it through apply_fsdp_to_mtp_decoder, not directly). That breaks the "no function for a single call site" rule in design.md, and the split adds three guards that repeat the caller's checks: assert model.mtp_layers is not None, the isinstance(embedding, FSDPModule) check (always true once apply_fsdp_to_decoder has sharded a non-None tok_embeddings), and model.norm is None.
Inline it: add model.tok_embeddings is not None and model.norm is not None to the if above, make forward_prefetch a local, and define the two hooks in place. The 20-line docstring can shrink to a short comment, since the PR description already explains the mechanism. That should cut about 25 lines.
| # Also runs on the last MTP block's backward recompute, if any, where | ||
| # the embedding is already sharded: reshard() is then a no-op. |
There was a problem hiding this comment.
This comment doesn't match how remat works here. activation_remat.py:227 replaces transformer_block.forward with remat.checkpoint(...). Recompute calls that wrapped forward directly. Module forward hooks run in nn.Module._call_impl, outside forward, so a hook on mtp_layers[-1] does not fire again during backward recompute. Delete the comment so readers don't think there is a backward-time path to reason about.
| # Also runs on the last MTP block's backward recompute, if any, where | |
| # the embedding is already sharded: reshard() is then a no-op. |
There was a problem hiding this comment.
I feel you hallucinated here?
I think what the comment here refers to is about FSDP backward behavior, which handles its own "recompute" of unsharding of the embedding module, as long as get_fsdp_reshard_after_forward_policy returns True.
In general, FSDP wrapping is applied after remat wrapping, so FSDP logic is (mostly) invisible to remat.
There was a problem hiding this comment.
oh I think claude is partially correct, without the context in #6246. I'm now a bit confused.
@francesco-bertolotti Could you rebase onto #6246 and clarify what happens exactly in backward, under various reshard_after_forward policies and remat policies?
There was a problem hiding this comment.
Let me address you question a bit more clearly.
what happens exactly in backward, under various reshard_after_forward policies and remat policies?
The hooks never run in backward, whatever the remat policy. Both are module forward hooks:
- FSDP2 backward doesn't call module forward hooks and
- Remat replaces
block.forwardwithremat.checkpoint(...)(forward), and recompute calls that wrapped function directly, not throughnn.Module.__call__, so the hooks don't fire there either.
Here's a summary of what happens:
| Policy | Hooks | tok_embeddings |
|---|---|---|
| default / always | Registered | Gathered once for the MTP pass, then resharded after the last MTP block. Original settings are restored. |
| never | Not registered | Never resharded after the forward pass, same as the main layers. |
| Weight tying | Not registered | Shares the norm/lm_head unit, which is not resharded until lm_head runs. Same behavior as the main layers. |
| # apply_fsdp_to_decoder's explicit forward prefetch of the first | ||
| # decoder layer, set only under EP (unshard_in_current_stream is | ||
| # rejected above). | ||
| forward_prefetch=[cast(FSDPModule, next(iter(model.layers.values())))] | ||
| if ep_degree > 1 | ||
| else [], |
There was a problem hiding this comment.
This copies a private decision made inside apply_fsdp_to_decoder (fsdp.py: tok_embeddings prefetches transformer_blocks[0] only when ep_degree > 1 or unshard_in_current_stream). If that rule changes, for example if the MTP ban on unshard_in_current_stream is lifted, the reshard hook will quietly restore the wrong prefetch list every step. Nothing fails; only overlap changes, so nobody would notice. FSDP2 has no public getter for the current list, so the copy is probably unavoidable. At least state the condition in terms of the same predicate (ep_degree > 1 or unshard_in_current_stream) and point to the fsdp.py code it mirrors, so the two stay in sync.
|
@claude review my latest comment on your review |
There was a problem hiding this comment.
Re: @tianyu-l on mtp.py:584 ("I feel you hallucinated here?") -- Partly right. My explanation was incomplete: it missed the main reason. Deleting the comment is still the right fix, and the approval stands.
What I got wrong. I explained this through how torch_remat wraps forward. That mechanism is real (activation_remat.py:227), but it doesn't matter here, because MTP blocks are never rematerialized. BaseModel.parallelize calls activation_remat.apply(self) (models/base/model.py:165), and that only walks module.get_submodule("layers") (activation_remat.py:199). The MTP blocks live in model.mtp_layers. They are added to model.layers only for the duration of FSDP wrapping (mtp.py:502-526), which runs after remat. So "the last MTP block's backward recompute" never happens.
Why the comment isn't about FSDP backward either. What the comment says "also runs" is the reshard closure. That is a module forward hook on mtp_layers[-1] (mtp.py:590), and FSDP2's backward never calls module forward hooks:
- FSDP unshards
mtp_layers[-1]'s own parameters in backward through its pre-backward hooks on the block's output tensors. The parameters oftok_embeddingsare not involved. tok_embeddingsis never unsharded in backward. These hooks are registered only when weights are untied, and in that casefsdp.py:443setsset_unshard_in_backward(False)on it.
So reshard runs exactly once per forward, right after the last MTP block. There's no second run in backward, and so no no-op case to describe.
I agree that FSDP is applied after remat and is mostly invisible to it. That supports deleting the comment: the code has no backward-time path to describe.
Resolution (unchanged): delete the two comment lines at mtp.py:583-584. No code change is needed.
Not verified on GPU. This follows from reading the code paths cited above.
…er override; agent self-review; rl/transport (#6407) ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Why Since #5667, `@claude review` has reviewed 459 PRs. Of the 380 PRs it approved, 30 then got a formal "request changes" from a maintainer, and about 20 more got substantive inline asks. In nearly all of them the bot either saw the problem and approved anyway, or never asked the questions maintainers ask most ("does the repo already do this?", "who should own this?"). The opposite failure, the bot blocking something a maintainer was fine with, is rare: in the PRs we sampled, 2 of its 81 must-fix items were wrong and about a third were minor (the empty human-written summary was the biggest source). **Example** (#6112, controller sizes the rollout worker pool): ``` before: bot approved 10 times; tianyu-l then blocked: "the controller reads rollouter.rollouts_per_worker to compute a count it hands back to the Rollouter -- violates encapsulation" after: same commit, new skill -> Request changes, must-fix #1: "controller.py:589 -- wrong owner for the worker count ..." ``` There was also no way for a code owner to overrule the bot except dismissing its review in the GitHub UI, and a later `@claude review again` would block again. ## What changed **Review skill** (`.claude/skills/pr-review/`, `review-checklist.md`): - Verdict rules: Approve only when every remaining item is an edit the bot could write itself. Anything the author still owes (a design change, an unexplained golden change, evidence the PR rests on) is Request changes; anything only a maintainer can decide is Needs discussion. A hedge like "a maintainer should decide" can't come with Approve. - Always must-fix: a violated written rule, a silent wrong result, a second definition of an existing concept, a gate finding. - Design gate: new questions for the existing counterpart, in-repo ownership, and the design behind a bug; "ban only what doesn't work on main"; read the numbers behind a claim. The overlapping-PR search is mandatory and reported. - Re-review covers every commit since the last full review, including code taken from the bot's own suggestions. A scoped question gets a `COMMENT`, not a whole-PR verdict. - The bot fact-checks its own proposed fixes, and cites a source for claims about external tools or marks them unverified (never must-fix). - An empty "Summary (human-written)" is a one-line "Before merge" note that never affects the verdict. - Checklist: config ownership direction, general shared wrappers, dead code the PR creates, model variants as flavors, a mechanical pass over every new or changed function. **Code owner override** (`SKILL.md`, `claude-code.yml`, `CONTRIBUTING.md`): a code owner comments `@claude override` (optionally `@claude override 2,3: <reason>`); the bot approves if nothing else is open and doesn't re-raise the overridden items. A code owner's GitHub approval or "LGTM" is not an override, so a teammate can approve without the bot dropping its findings. Dismissing the bot's review still unblocks the PR, but isn't an override: the bot can't tell who dismissed it. **Agent self-review** (`CLAUDE.md`, `pr-description`): an agent preparing a PR runs `pr-review` in branch mode first and records unaddressed items in an optional "Self-review" section. PRs written without an agent are unaffected; a missing section is never a finding. Where each new rule comes from (maintainer asks the bot missed): | Change | PRs | | --- | --- | | No Approve with open design/evidence items or a "maintainer should decide" hedge | #6007, #5837, #5997, #5712, #5511, #5996 | | Author waiver can't clear a must-fix | #6201, #6202, #6203 | | Existing counterpart; one source of truth | #5228, #6169, #5881, #5823, #5824, #6059, #5812 | | Responsibility owner; config ownership direction | #6112, #6332, #5802, #5803, #6325 | | Fix the design behind the bug; a TODO doesn't justify a workaround | #5572, #5689, #5657 | | Fact-check the bot's own suggested fixes | #5740, #5802, #5511, #4819, #5543 | | Re-review covers all new commits; scoped asks don't approve | #5824, #5842 | | Mandatory overlap search | #5885, #6248 | | Ban only what doesn't work on main | #5543 | | Summary placeholder no longer a must-fix | #6119, #6174, #6112, #5868 | **Rules**: `design.md` gets the one-general-wrapper rule (moved from `models.md`, whose glob skipped `torchtitan/rl`), thin adapters, and the consumer owning its values; `config.md` gets ownership direction and "a Config doesn't read runtime state"; `direction.md` calls all-to-all the MoE reference implementation, so a new vendor-specific dispatch path (e.g. #6242) needs a reason the existing backends can't serve. **Area reviewers**: `.ci/` -> huydhn, wwwjn; `torchtitan/rl/transport/` -> d4l3k. **Mechanical, skim**: `torchtitan/rl/transport/` holds data movement between RL actors. - `rl/model_state_dict_transport.py` -> `rl/transport/model_state_dict.py` - `rl/MODEL_STATE_DICT_TRANSPORT.md` -> `rl/transport/MODEL_STATE_DICT_TRANSPORT.md` - `rl/trainer/rdma_microbatch.py` -> `rl/transport/rdma_microbatch.py` - tests: `tests/rl/unit_tests/cpu/test_{model_state_dict_transport,rdma_microbatch}.py` -> `tests/rl/unit_tests/cpu/transport/test_{model_state_dict,rdma_microbatch}.py` - imports, READMEs and `scripts/install_rl_env.sh` updated; no code changes. ## User-facing changes | Before | After | | --- | --- | | Overrule the bot: dismiss its review in the UI, and it blocks again on the next run | `@claude override [items]: <reason>`; the bot approves and doesn't re-raise them | | Empty human-written summary: bot must-fix | One "Before merge" line, no effect on the verdict | | `from torchtitan.rl.model_state_dict_transport import ...` | `from torchtitan.rl.transport.model_state_dict import ...` | | `from torchtitan.rl.trainer.rdma_microbatch import ...` | `from torchtitan.rl.transport.rdma_microbatch import ...` | ## Testing Backtest: the new skill run locally (nothing posted) on each PR at the commit and thread state the bot originally saw. | PR | Bot then | New skill | What the maintainer asked | | --- | --- | --- | --- | | #6112 | Approve | Request changes | worker-count ownership (caught) | | #5837 | Approve | Request changes | apply to `dp_shard` too (caught) | | #5572 | Approve | Request changes | delete the injection design (caught) | | #6201 | Approve after author waived pins | Request changes, waiver ignored | pins broke GPU tests after merge (caught) | | #6007 | Approve | Request changes | fold K3.1 into K3 (caught) | | #5543 | Request changes: "ban it" | Request changes: keep main's path | don't break gpt-oss + DeepEP (fixed) | | #6144, #5905 (controls) | Approve | Approve | -- | | #6137 (control) | Approve | Needs discussion | -- (merge gate on an upstream API) | Code owner override, simulated on #6201: override by a code owner lifts the named item; `@claude override` from the author changes nothing; a code owner's "LGTM" approval followed by "review again" keeps Request changes. Transport move: 83 RL CPU unit tests pass locally (`transport/test_model_state_dict.py`, `test_trainer.py`, `test_engine_loop.py`). `transport/test_rdma_microbatch.py`, `test_generator.py` and `test_batcher_actor.py` fail to collect in my env on `origin/main` too (stale attention-gym / Monarch), so CI is the check for those. ## Known issues / follow-ups - Open PRs that edit the moved files rebase cleanly (git follows the renames), but new imports of the old module paths will break: #6309 (adds a delta transport that should live in `rl/transport/`), #6237, #6176, #6177, #5862, and drafts #6127, #6393, #6163, #5764. - The Actions bot can't read dependency source (e.g. SGLang); follow-up for the workflow. ## Self-review pr-review (branch mode) at ad905a5: Needs discussion. Fixed: branch mode diffs against `origin/main` and skips description findings before a description exists; the "Config doesn't read runtime state" rule no longer contradicts hardware validation; dismissal dropped as an override form (the bot can't tell who dismissed); `test_rdma_microbatch.py` added to the transport area. Not addressed: - One concern per PR -- the five changes ship together at the maintainer's request. - Open PRs touching the moved files -- listed above; the maintainer will coordinate.
| return h_TMD | ||
| h_TD = self._pre_lm_head_norm_and_gather(self.hc_head(h_TMD)) | ||
|
|
||
| if len(self.mtp_layers) == 0: |
There was a problem hiding this comment.
Can the code style be unified between deepseek v3 and v4 regarding MTP? I don't mind if they have identical code or share a private function call.
| decoder_layers[-1].set_modules_to_forward_prefetch( | ||
| [ | ||
| cast(FSDPModule, self.tok_embeddings), | ||
| cast(FSDPModule, self.mtp_layers[0]), | ||
| ] | ||
| ) |
There was a problem hiding this comment.
wouldn't we need to set up explicit prefetching for backward as well? https://github.com/pytorch/torchtitan/blob/main/torchtitan/distributed/fsdp.py#L616
| ) | ||
| mtp_outputs.append(mtp_output) | ||
|
|
||
| h = self._pre_lm_head_norm_and_gather(h) |
There was a problem hiding this comment.
Sounds that it would work with this TODO, but please double check
torchtitan/torchtitan/models/common/decoder.py
Lines 444 to 446 in 076f2e8
It's OK if you don't want to work on the TODO itself.
Summary (human-written)
Notation
Summary
This PR fixes the FSDP gather order for MTP models. It removes redundant all-gathers and avoids holding the output embedding through the MTP loop.
Loss and grad_norm are bitwise identical to the previous version, with fsdp_unshard_in_current_stream both off and on.
Why
tok_embeddingsonce per depth, and FSDP re-gathers the whole table on every call. Under explicit prefetching, each call also prefetcheslayers.0again.norm/lm_headheld through the MTP pass: the final norm runs before the MTP pass, so FSDP keepsnorm/lm_headgathered through every MTP block.tok_embeddingscall that starts the MTP pass. That is whyfsdp_unshard_in_current_streamraised for MTP models.What changed
MTPDecoder._apply_fsdp:[tok_embeddings, mtp_layers.0].tok_embeddingsunsharded from the end of the trunk to the end of the last MTP block, then reshard it.fsdp_unshard_in_current_streamban for MTP is removed.forward: the final norm runs after the MTP pass. MTP consumes the pre-norm hidden state, so the math doesn't change.Numerics
Bitwise-equal loss and grad_norm, measured with
scripts/loss_compare.py --assert-equal:fsdp_unshard_in_current_streamoff vs onmainPerformance
Previous revision (embedding change only): DSV3 16B, 3 MTP layers, vocab 256000, 4 nodes x 4 GH200. TPS went up 1.6% on FSDP 16 and 1.4% on FSDP 16 + EP 4. Peak memory went up by about 1 GiB, which is the embedding table held through the MTP pass.