Skip to content

[RoPE] Move centralized freqs_cis to each transform layer - #3458

Merged
wwwjn merged 21 commits into
mainfrom
rope-refactor-2
Jun 5, 2026
Merged

wwwjn merged 21 commits into
mainfrom
rope-refactor-2

Conversation

@wwwjn

@wwwjn wwwjn commented May 29, 2026 •

Copy link
Copy Markdown
Contributor
  • For language model: move the RoPE cache to each layer's attention
  • For qwen3-vl: the RoPE is related to the input.
    • Qwen3-VL computes input-dependent MRoPE position IDs with shape [3, batch, seq] from tokens, image/video grids, and packed-sequence positions, then passes those IDs through the normal layer positions argument.
    • Each attention layer keeps its own static RoPE cache; when RoPE.forward() sees 3D positions and mrope_section, it locally builds the interleaved 4D MRoPE cos/sin cache for that forward without mutating persistent layer state.

Why we make this change:

  • Allow registry kernels: Make RoPE replaceable as a module level.
  • For PP: every stage owns the RoPE modules for its local layers

Test

Qwen3-VL loss comparision:

  python scripts/loss_compare.py main <temp_patch_commit> \
    --baseline-module=qwen3_vl --baseline-config=qwen3_vl_debugmodel \
    --test-module=qwen3_vl --test-config=qwen3_vl_debugmodel \
    --baseline-options='--dataloader.dataset=cc12m-test' \
    --test-options='--dataloader.dataset=cc12m-test' \
    --steps=2 --baseline-ngpus=1 --test-ngpus=1 \
    --assert-equal

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:

  python scripts/loss_compare.py main <temp_patch_commit> \
    --baseline-module=deepseek_v3 --baseline-config=deepseek_v3_debugmodel \
    --test-module=deepseek_v3 --test-config=deepseek_v3_debugmodel \
    --steps=2 --baseline-ngpus=1 --test-ngpus=1 \
    --assert-equal

Result: passed. TensorBoard losses were exactly equal:

step 1: baseline 8.083154678344727, test 8.083154678344727
step 2: baseline 6.283287048339844, test 6.283287048339844

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label May 29, 2026
@wwwjn wwwjn changed the title [Draft] Move centralized freqs_cis to each transform layer [RoPE] Move centralized freqs_cis to each transform layer Jun 1, 2026
Comment thread torchtitan/models/llama3/__init__.py Resolved
Comment thread torchtitan/models/gpt_oss/sharding.py Resolved
Comment thread torchtitan/models/llama3/__init__.py Resolved
@wwwjn
wwwjn marked this pull request as ready for review June 1, 2026 20:18
@wwwjn
wwwjn requested review from fegin, tianyu-l and wconstab as code owners June 1, 2026 20:18
Comment thread torchtitan/models/common/rope.py Resolved
Comment thread torchtitan/models/llama3/__init__.py Resolved
Comment thread torchtitan/models/llama3/__init__.py Resolved
Comment thread torchtitan/models/qwen3_vl/model.py Resolved
Comment thread torchtitan/models/qwen3_vl/model.py Resolved
Comment thread torchtitan/models/common/rope.py Resolved
Comment thread torchtitan/models/common/rope.py Resolved
Comment thread torchtitan/models/common/rope.py Resolved
Comment thread torchtitan/models/common/rope.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.

I think we need to make bigger changes

Comment thread torchtitan/models/common/attention.py Resolved
Comment thread torchtitan/models/common/decoder.py Resolved
Comment thread torchtitan/models/common/rope.py Resolved
Comment thread torchtitan/models/common/rope.py Resolved
Comment thread torchtitan/models/common/decoder.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.

haven't reviewed the device part, will review later.

Comment thread torchtitan/models/qwen3/__init__.py Resolved
Comment thread torchtitan/models/qwen3_vl/model.py Resolved
Comment thread torchtitan/models/common/rope.py Resolved
Comment thread torchtitan/models/common/rope.py Resolved
n_heads: int
qkv: Linear.Config
proj: Linear.Config
rope: RoPE.Config

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

Comment thread torchtitan/models/common/decoder.py Resolved
Comment thread torchtitan/models/common/rope.py Resolved
@wwwjn
wwwjn force-pushed the rope-refactor-2 branch from 8a33a33 to 3052de6 Compare June 4, 2026 17:01
Comment thread torchtitan/models/common/rope.py Resolved
Comment thread torchtitan/models/common/rope.py Resolved
Comment thread torchtitan/models/gpt_oss/__init__.py Resolved
Comment thread torchtitan/models/gpt_oss/__init__.py Resolved
Comment thread torchtitan/models/common/rope.py Resolved
assert ndim > 1
bz, seqlen, _, head_dim = x.shape
bsz, seqlen = x.shape[:2]
cache_width = rope_cache.shape[-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.

comment that this is head_dim * 2 for cos_sin, and head_dim for complex

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.

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)

Comment thread torchtitan/models/common/rope.py Resolved
Comment thread torchtitan/models/common/rope.py Resolved
import logging
import os
import re

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

This empty line change is local linter issue, can be removed

Comment thread torchtitan/models/gpt_oss/__init__.py Resolved
@@ -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]:

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 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,

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.

To preserve the same semantic, we check the RoPE type in state_dict_adapter

@wwwjn
wwwjn force-pushed the rope-refactor-2 branch from fb0eb23 to b412a8a Compare June 5, 2026 03:10
Comment thread torchtitan/models/gpt_oss/__init__.py Outdated
non_blocking_capacity_factor: float | None = None,
) -> list[TransformerBlock.Config]:
rope: RoPE.Config,
) -> list[GptOssTransformerBlock.Config]:

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.

Will be reverted

self.grouped_expert_weight_placements[
abstract_key
] = value.placements
self.grouped_expert_weight_placements[abstract_key] = (

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 change is also linter, can be removed

model_config: BaseModel.Config,
hf_assets_path: str | None,
):
self.model_config = model_config

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 needed because we will access model_config when validation hf rope config

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

very nice refactor!!!

Please make sure numerics are bitwise.

@wwwjn
wwwjn force-pushed the rope-refactor-2 branch from 716d6a5 to ade492e Compare June 5, 2026 15:58
@wwwjn
wwwjn merged commit 02d24f0 into main Jun 5, 2026
21 of 25 checks passed
@wwwjn

wwwjn commented Jun 5, 2026

Copy link
Copy Markdown
Contributor Author

The RL test failure is unrelated to this PR, which will be fixed #3541 and @felipemello1

@tianyu-l
tianyu-l deleted the rope-refactor-2 branch June 5, 2026 18:02
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Jun 7, 2026
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.)
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Jun 7, 2026
…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).
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Jun 7, 2026
…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
wwwjn added a commit that referenced this pull request Jun 11, 2026
…update_from_config (#3605)

torchtitan/experiments/graph_trainer/tests/test_bitwise_deterministic.py::TestLlama3BitwiseDeterministic::test_eager_self_deterministic
- AssertionError: Mismatch between actual and expect strings:
 
- Failed because of #3458
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Aug 25, 2026
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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/rl ciflow/8gpu 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.

3 participants