Skip to content

Unify CosSinRoPE and ComplexRoPE YaRN computation - #3787

Merged
tianyu-l merged 3 commits into
pytorch:mainfrom
sdmyzlp:br_cos_sin_rope
Jul 11, 2026
Merged

tianyu-l merged 3 commits into
pytorch:mainfrom
sdmyzlp:br_cos_sin_rope

Conversation

@sdmyzlp

@sdmyzlp sdmyzlp commented Jun 25, 2026 •

Copy link
Copy Markdown
Collaborator

Background

ComplexRoPE and CosSinRoPE are the two RoPE variants in torchtitan: ComplexRoPE uses an interleaved complex cache (DeepSeek V3, LLaMA 3, Qwen3.5); CosSinRoPE uses a concatenated cos/sin cache with rotate_half application (GPT-OSS, Qwen3). Both implement YaRN ("NTK-by-parts") for context-length extension, but they drifted apart in following ways:

  1. beta_fast/beta_slow assignment — CosSinRoPE mapped low ← beta_slow, high ← beta_fast, the inverse of the YaRN paper convention and of ComplexRoPE. GPT-OSS's config compensated with swapped values, hiding the inconsistency from users.

  2. Embedded rope mscale — CosSinRoPE multiplied the YaRN attention-magnitude factor (0.1·log(factor)+1) into its cos/sin cache, coupling the rope to the attention. GPT-OSS needed this; other rotate_half consumers may not. The rope should be a pure rotation, with mscale applied where each model's attention expects it.

This PR makes the two classes share one YaRN implementation, agreeing exactly when both enter their respective YaRN (or non-YaRN) branches.

Commits

1. Align CosSinRoPE beta_fast/beta_slow to the YaRN paper/HF convention
Swap low ← beta_slow to low ← beta_fast (extrapolation), high ← beta_fast to high ← beta_slow (interpolation). Un-swap GPT-OSS config to the official beta_fast=32.0, beta_slow=1.0. Numerically neutral (the two un-swaps cancel).

2. Extract a shared _yarn_inv_freq helper + truncate flag
A single source-of-truth function called by both classes. Add a truncate config flag (floor/ceil for DeepSeek; fractional for GPT-OSS, which uses truncate=False). Always clamps to [0, dim-1].

3. Make CosSinRoPE a pure rotation; let GPT-OSS handle mscale in its attention
Remove mscale from CosSinRoPE._precompute_cache (and the unused mscale field from RoPE.Config). GPT-OSS folds mscale² into its softmax_scale — mathematically equivalent. The rope is now modular: each model's attention owns its own mscale.

References

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Jun 25, 2026
@pytorch-bot

pytorch-bot Bot commented Jun 25, 2026 •

Copy link
Copy Markdown

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

@sdmyzlp sdmyzlp changed the title [rope] Unify YaRN; fix CosSinRoPE beta_fast/slow swap; gpt-oss mscale… Fix CosSinRoPE beta_fast/slow swap and move gpt-oss mscale out Jun 25, 2026
@tianyu-l
tianyu-l requested a review from shuhuayu June 25, 2026 21:06
@sdmyzlp sdmyzlp changed the title Fix CosSinRoPE beta_fast/slow swap and move gpt-oss mscale out Unify CosSinRoPE and ComplexRoPE YaRN computation Jun 26, 2026
@sdmyzlp
sdmyzlp force-pushed the br_cos_sin_rope branch 2 times, most recently from 768444b to 635cad2 Compare June 26, 2026 05:40
@sdmyzlp sdmyzlp mentioned this pull request Jun 26, 2026
1 task done
@sdmyzlp

sdmyzlp commented Jun 26, 2026

Copy link
Copy Markdown
Collaborator Author

@shuhuayu Could you please take a look at this? Thanks.

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
Comment thread torchtitan/models/common/rope.py Resolved
Comment thread torchtitan/models/common/rope.py Resolved
Comment thread torchtitan/models/gpt_oss/model.py Resolved
Comment thread torchtitan/models/gpt_oss/model.py Resolved
@sdmyzlp
sdmyzlp force-pushed the br_cos_sin_rope branch 2 times, most recently from 2a7a9fb to 1379dc2 Compare July 1, 2026 03:53
Comment thread torchtitan/models/common/rope.py Resolved
@sdmyzlp
sdmyzlp force-pushed the br_cos_sin_rope branch 2 times, most recently from 22ca5e7 to f7ef525 Compare July 1, 2026 07:47
@sdmyzlp
sdmyzlp requested a review from shuhuayu July 1, 2026 12:41

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

LGTM!

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

numerics CI seems broken https://github.com/pytorch/torchtitan/actions/runs/28502028306/job/84481564730?pr=3787

@shuhuayu could you make sure the main CI is healthy, and then ask for a rebase and verify this PR doesn't change numerics, and then merge?

Comment thread torchtitan/models/gpt_oss/__init__.py Resolved
@shuhuayu

shuhuayu commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

I think the current main ci failed the numerics test, we can check it first and land this pr later.

@sdmyzlp

sdmyzlp commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

Got it, will wait for the main CI issue to be resolved.

@sdmyzlp
sdmyzlp force-pushed the br_cos_sin_rope branch from f7ef525 to bac6082 Compare July 3, 2026 11:22
@sdmyzlp
sdmyzlp requested a review from shuhuayu July 4, 2026 07:48
@sdmyzlp

sdmyzlp commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator Author

Seems the lint/rocm CI is not fully recovered.

@shuhuayu

shuhuayu commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Seems the lint/rocm CI is not fully recovered.

yeah, we are trying to fix it.

sdmyzlp added 3 commits July 11, 2026 10:39
CosSinRoPE's YaRN correction range assigns beta_fast/beta_slow
backwards relative to the YaRN paper, HF Transformers, and
torchtitan's own ComplexRoPE. gpt-oss compensated with a swapped
config, hiding the bug.

- CosSinRoPE._precompute_cache: swap 'low <- beta_slow' ->
  'low <- beta_fast' (extrapolation), 'high <- beta_fast' ->
  'high <- beta_slow' (interpolation). Follows the YaRN paper
  (arXiv:2309.00071, Sec 3.2: beta=32 extrapolation, alpha=1
  interpolation) and HF _compute_yarn_parameters.

- gpt_oss config: un-swap to the official values (beta_fast=32.0,
  beta_slow=1.0), matching the upstream config and passing HF's
  beta_fast > beta_slow validation.

Numerically neutral: the two un-swaps cancel -- gpt-oss still gets
low=fcd(32), high=fcd(1). qwen3/qwen3_5 use CosSinRoPE without
YaRN and are unaffected.
Add a single-source-of-truth _yarn_inv_freq() function called by both
ComplexRoPE and CosSinRoPE so the two cache formats compute identical
frequencies. Add a 'truncate' config flag (True floors/ceils the
cutoffs; False keeps fractional cutoffs). Refactor both rope classes
to use it. The range is always clamped to [0,dim-1].

Numerically neutral: the helper reproduces the existing algebra exactly
(same low/high, same ramp, same blend), just uses the paper-correct
beta_fast/beta_slow assignment from the previous commit.
CosSinRoPE is now a pure rotation (no mscale baked into cos/sin).
gpt-oss, which was the only CosSinRoPE+YaRN user, instead folds
mscale^2 into its softmax_scale.

Mathematically equivalent: applying mscale to cos/sin scaled q and k
each by m, so the attention logit was scaled by m^2. Applying m^2 to
the softmax scale produces the same logit. Verified logit-neutral to
~1e-6 on gpt-oss params.
@sdmyzlp

sdmyzlp commented Jul 11, 2026

Copy link
Copy Markdown
Collaborator Author

yeah, we are trying to fix it.

Hi @shuhuayu — quick question on this PR. Is the main CI healthy now? Would it be possible to re-run the checks and revisit merging? Thanks!

@tianyu-l
tianyu-l merged commit 51c197c into pytorch:main Jul 11, 2026
16 of 19 checks passed
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Jul 12, 2026
Merged 3d277c1 (51c197c CosSinRoPE/ComplexRoPE YaRN unify pytorch#3787 +
0d7f4ab qwen3.5 spmd block / dsv3 compile fix pytorch#3901). No replays:
agpt/moe diff empty. RoPE change is numerically neutral for us -- agpt
uses cos_sin with scaling=none (never hits the modified YaRN branch),
never sets mscale (removed field is a no-op), and moe's mscale is on
Attention.Config not RoPE.Config. sync_smoke VERDICT ok (job 12470359),
all 3 configs bit-identical to 64th-67th syncs.
jemitche1 pushed a commit to jemitche1/torchtitan that referenced this pull request Jul 15, 2026
### Background

`ComplexRoPE` and `CosSinRoPE` are the two RoPE variants in torchtitan:
`ComplexRoPE` uses an interleaved complex cache (DeepSeek V3, LLaMA 3,
Qwen3.5); `CosSinRoPE` uses a concatenated cos/sin cache with
`rotate_half` application (GPT-OSS, Qwen3). Both implement YaRN
("NTK-by-parts") for context-length extension, but they drifted apart in
following ways:

1. **`beta_fast`/`beta_slow` assignment** — `CosSinRoPE` mapped `low ←
beta_slow`, `high ← beta_fast`, **the inverse of** the YaRN paper
convention and of `ComplexRoPE`. GPT-OSS's config compensated with
swapped values, hiding the inconsistency from users.

2. **Embedded rope `mscale`** — `CosSinRoPE` multiplied the YaRN
attention-magnitude factor (`0.1·log(factor)+1`) into its cos/sin cache,
coupling the rope to the attention. GPT-OSS needed this; other
`rotate_half` consumers may not. The rope should be a pure rotation,
with mscale applied where each model's attention expects it.

This PR makes the two classes share one YaRN implementation, agreeing
exactly when both enter their respective YaRN (or non-YaRN) branches.

### Commits

**1. Align `CosSinRoPE` `beta_fast`/`beta_slow` to the YaRN paper/HF
convention**
Swap `low ← beta_slow` to `low ← beta_fast` (extrapolation), `high ←
beta_fast` to `high ← beta_slow` (interpolation). Un-swap GPT-OSS config
to the official `beta_fast=32.0, beta_slow=1.0`. Numerically neutral
(the two un-swaps cancel).

**2. Extract a shared `_yarn_inv_freq` helper + `truncate` flag**
A single source-of-truth function called by both classes. Add a
`truncate` config flag (floor/ceil for DeepSeek; fractional for GPT-OSS,
which uses `truncate=False`). Always clamps to `[0, dim-1]`.

**3. Make `CosSinRoPE` a pure rotation; let GPT-OSS handle mscale in its
attention**
Remove `mscale` from `CosSinRoPE._precompute_cache` (and the unused
`mscale` field from `RoPE.Config`). GPT-OSS folds `mscale²` into its
`softmax_scale` — mathematically equivalent. The rope is now modular:
each model's attention owns its own mscale.

### References

- YaRN paper: [arXiv:2309.00071](https://arxiv.org/abs/2309.00071) (§3.2
NTK-by-parts, §3.3 attention temperature)
- DeepSeek-V3.2:
[`precompute_freqs_cis`](https://huggingface.co/deepseek-ai/DeepSeek-V3.2/blob/c69397e/inference/model.py#L324-L402)
— `low = floor(fcd(beta_fast))`, `high = ceil(fcd(beta_slow))`
- GPT-OSS official: [`ntk_alpha=1,
ntk_beta=32`](https://github.com/openai/gpt-oss/blob/d21f34e/gpt_oss/torch/model.py#L28-L29);
[`low ← ntk_beta` in
rope](https://github.com/openai/gpt-oss/blob/d21f34e/gpt_oss/torch/model.py#L85-L131)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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