Repository navigation
[RoPE] Move centralized freqs_cis to each transform layer - #3458
Conversation
tianyu-l
left a comment
There was a problem hiding this comment.
I think we need to make bigger changes
tianyu-l
left a comment
There was a problem hiding this comment.
haven't reviewed the device part, will review later.
| n_heads: int | ||
| qkv: Linear.Config | ||
| proj: Linear.Config | ||
| rope: RoPE.Config |
There was a problem hiding this comment.
I added a RoPE field in vision_encoder, but the usage is slightly different with other callsite:
- other callsite calls self.rope.forward()
- Qwen3-vl's vision encoder call self.rope.apply_rotary_emb(q, k, rope_cache) and take the rope_cache calculated outside.
The advantage of doing this is we don't need to maintain an extra helper function apply_rotary_emb which is only called in vision encoder now. cc @shuhuayu
| assert ndim > 1 | ||
| bz, seqlen, _, head_dim = x.shape | ||
| bsz, seqlen = x.shape[:2] | ||
| cache_width = rope_cache.shape[-1] |
There was a problem hiding this comment.
comment that this is head_dim * 2 for cos_sin, and head_dim for complex
There was a problem hiding this comment.
Added! it should be head_dim * 2 for cos_sin, and head_dim // 2 for complex.
For complex we have:
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() /
dim))
... # freqs shape doesn't change
freqs_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64
Since torch.arange(0, dim, 2) has dim // 2 items, freqs_cis has shape (max_seq_len, dim // 2)
| import logging | ||
| import os | ||
| import re | ||
|
|
There was a problem hiding this comment.
This empty line change is local linter issue, can be removed
| @@ -158,6 +158,7 @@ def to_hf(self, state_dict: dict[str, Any]) -> dict[str, Any]: | |||
| return hf_state_dict | |||
|
|
|||
| def from_hf(self, hf_state_dict: dict[str, Any]) -> dict[str, Any]: | |||
There was a problem hiding this comment.
I didn't further change from_hf() function signature because the callsite is generic checkpoint.py
| fuse_qkv=fuse_qkv, | ||
| mask_type=mask_type, | ||
| rope_backend="cos_sin", | ||
| rope=rope, |
There was a problem hiding this comment.
To preserve the same semantic, we check the RoPE type in state_dict_adapter
| non_blocking_capacity_factor: float | None = None, | ||
| ) -> list[TransformerBlock.Config]: | ||
| rope: RoPE.Config, | ||
| ) -> list[GptOssTransformerBlock.Config]: |
| self.grouped_expert_weight_placements[ | ||
| abstract_key | ||
| ] = value.placements | ||
| self.grouped_expert_weight_placements[abstract_key] = ( |
There was a problem hiding this comment.
This change is also linter, can be removed
| model_config: BaseModel.Config, | ||
| hf_assets_path: str | None, | ||
| ): | ||
| self.model_config = model_config |
There was a problem hiding this comment.
This is needed because we will access model_config when validation hf rope config
tianyu-l
left a comment
There was a problem hiding this comment.
very nice refactor!!!
Please make sure numerics are bitwise.
|
The RL test failure is unrelated to this PR, which will be fixed #3541 and @felipemello1 |
Upstream PR pytorch#3458 (commit 02d24f0, "Move centralized freqs_cis to each transform layer") restructured RoPE in three ways that need ezpz-side mirroring: 1. RoPE.Config split into ComplexRoPE.Config / CosSinRoPE.Config. The ``backend="complex"|"cos_sin"`` field is gone — backend is now encoded in the type. Concrete subclasses live in torchtitan.models.common. 2. The top-level ``Model.Config.rope`` field was removed; each layer's ``Attention.Config`` now owns its own rope via a ``rope: RoPE.Config`` field. Forward signatures no longer thread ``freqs_cis`` through; instead ``self.rope = config.rope.build()`` and the module call ``q, k = self.rope(q, k, positions)`` does both rotations in one go. 3. The helper functions ``apply_rotary_emb_complex``, ``apply_rotary_emb_cos_sin``, ``apply_rotary_emb_single_complex`` were removed from torchtitan.models.common.rope. Mirrored across four ezpz files: * agpt/__init__.py: _build_agpt_layers takes ``rope: RoPE.Config`` and threads it into make_gqa_config(rope=rope). _build_agpt_config builds a ComplexRoPE.Config / CosSinRoPE.Config based on the ``rope_backend`` string (kept for back-compat with external callers) and passes it down. Dropped the top-level rope= from AgptModel.Config(...). * agpt/config_registry.py: _set_rope_backend rewrites each layer's attention.rope as a fresh ComplexRoPE.Config or CosSinRoPE.Config, carrying forward all other fields (dim, max_seq_len, theta, scaling, yarn params) via dataclasses.fields(). Old version flipped a now-removed model.rope.backend + layer.attention.rope_backend pair. * moe/__init__.py: _make_moe_attn_config takes rope and sets Attention.Config(rope=dataclasses.replace(rope)) per deepseek_v3 template. _build_moe_layers takes rope and threads it. All 11 config functions (debugmodel through 10B_2B) push their ComplexRoPE.Config from moeModel.Config(...) into _build_moe_layers(rope=...). _small uses theta=50000 / max_seq_len=256128 (its original outlier params). * moe/model.py: Attention.Config drops rope_factor / rope_max_seq_len / rope_original_seq_len, adds rope: RoPE.Config. Attention.__init__ reads config.rope.max_seq_len etc., builds self.rope = config.rope.build(). Attention.forward drops the freqs_cis arg, replaces two apply_rotary_emb_single_complex calls with one self.rope(q_pe, k_pe.unsqueeze(2), positions) returning both rotated tensors. moeTransformerBlock.forward drops freqs_cis. moeModel.Config.update_from_config drops the rope-sync block that copied self.rope.{rope_factor, original_seq_len} into per-layer attention — no longer needed since each layer carries its own rope. Verified end-to-end: imports clean, build all agpt configs (debugmodel, 2B, 80B) and all 10 moe flavors (debugmodel through 10B_2B_sdpa). Build under torch 2.13 venv at HEAD of worktree-ezpz-46th-47th-sync. (Pre-existing untracked dep: upstream's new components/loss.py needs spmd_types==0.2.1; installed via uv pip into .venv.)
…tor still TODO Documents the 34-commit pull from upstream/main (27aa490..641b5f6, merge commit fb1c5a3, sitting in worktree ezpz-46th-47th-sync). Two structural refactors hit ezpz: - PR pytorch#3458 (RoPE refactor): REPLAYED in commit 02dd1e7, verified by importing + building all agpt + moe flavors under the torch 2.13 venv. Numerics smoke against baselines still pending. - PR pytorch#3269 (mixed-optimizer refactor): NOT YET STARTED. Affects OptimizersContainer.Config + 8 custom container subclasses in optimizer/containers.py + ~13 callsites in agpt/moe/competition config registries. Also documents that spmd_types==0.2.1 was installed into .venv (new upstream runtime dep from PR pytorch#3466/pytorch#3467/pytorch#3560) and notes the open follow-ups (replay PR pytorch#3269, smoke against baselines, audit RL). Doesn't update upstream-sync.md's "next-sync" reminder banner — this sync isn't complete yet (ezpz branch is not on the worktree HEAD).
…ixes Pulled 34 upstream commits (27aa490..641b5f6). Two structural refactors required ezpz replays — both done, both verified end-to-end with numerics smokes against the 2026-06-02 baselines. ezpz commits from the worktree: ac6b512 docs(ezpz): 47th sync — smokes + post-smoke fixes summary; mark READY TO MERGE 8746dfe ezpz/datasets: fix _make_text_processor pickle failure for num_workers>0 975a5bc ezpz/moe: default moe_10b_2b_sdpa{,_ep} to LBS=1 + AC=selective (only working combo) 455013e ezpz/moe: replay PR pytorch#3269 in moe/config_registry.py — 5 missed cfg.optimizer.lr mutations 6871e73 ezpz/optimizer: fix Config-dispatch bug — add subclass Configs so build() instantiates the subclass bc89aa8 docs(ezpz): mark 47th sync optimizer half replayed + verified bac0a34 ezpz: replay upstream PR pytorch#3269 mixed-optimizer refactor in containers + configs + train.py 3748b9e docs(ezpz): 47th upstream-sync entry — RoPE replayed, optimizer refactor still TODO 02dd1e7 ezpz: replay upstream PR pytorch#3458 RoPE refactor in agpt + moe Smoke verdict (Sunspot 2N + 4N): ✅ moe_2b_ep 2N — baseline bit-identical ✅ agpt_80b TP=2 4N — all 20 steps within ±0.08 nat of baseline ✅ agpt_2b — 10 steps clean (12.95→7.63) ✅ agpt_2b_real — 10 steps, validates CosSinRoPE swap ✅ agpt_20b — 10 steps, noisy but trains ✅ moe_2b LBS=2 — 10 steps clean ✅ moe_10b_2b_sdpa_ep LBS=1 AC=selective (new default) — 10 steps, 80% mem ✅ speedrun_2b_muon — 10 steps, validates Muon dispatch ✅ speedrun_2b_sophiag — 10 steps, validates SophiaG dispatch Full breakdown in docs/journal.md + docs/upstream-sync.md. # Conflicts: # torchtitan/experiments/ezpz/docs/journal.md
The MLA forward takes (x, attention_masks, positions). freqs_cis stopped being a forward arg at PR pytorch#3458, when the rope module took ownership of its cache, but the attention ShardingConfig still declared in_src/in_dst placements for it -- a contract for a parameter that does not exist. Upstream deepseek_v3/sharding.py declares none. Harmless (the contract check matches by argument name, so an entry with no matching arg is simply never consulted) but misleading: it reads as though freqs_cis still flows through the boundary, and it was noise while diagnosing the TP>1 wo placement mismatch. Not the cause of that mismatch -- that is still open. Verified: module imports clean, no live freqs_cis references remain (the two left are prose).
Why we make this change:
Test
Qwen3-VL loss comparision:
Result: passed. Losses were bitwise equal from TensorBoard:
step 1: baseline 12.634057998657227, test 12.634057998657227
step 2: baseline 12.479432106018066, test 12.479432106018066
DeepSeek-v3 loss comparision:
Result: passed. TensorBoard losses were exactly equal:
step 1: baseline 8.083154678344727, test 8.083154678344727
step 2: baseline 6.283287048339844, test 6.283287048339844