Skip to content

Keep native RoPE scaling when extending context; carry rope_theta for linear - #7028

Merged
danielhanchen merged 4 commits into
mainfrom
longctx-keep-native-rope
Jul 9, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
longctx-keep-native-rope

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

When max_seq_length exceeds a model's native context window, the loader replaced the model's rope_scaling with kaiokendev linear scaling. That has two problems:

  1. For a model that already ships a scaled RoPE (llama3 / yarn / longrope), overwriting it with linear is far worse for long context. Llama-3.1's llama3 scaling extends gracefully well past its trained window, while linear collapses.
  2. The synthesized dict {"type": "linear", "factor": F} carried no rope_theta. On transformers v5 (which stores rope_theta under rope_parameters) this replaces the whole block and drops the real theta, so the rotary base falls back to 10000 and RoPE breaks past a few thousand tokens.

This keeps a model's native scaled RoPE and just widens the window. Linear is synthesized only for plain RoPE models, and it now carries rope_theta so v5 keeps the real base.

Repro

Loading unsloth/Llama-3.1-8B (native 131072, llama3 factor 8, theta 500000) at max_seq_length = 262144 and measuring the perplexity of one fixed 2048 token passage placed at increasing absolute positions.

Before, with the linear override:

abs position v4 4.57.6 v5 5.13.0
0 10.1 13.8
7.8K 10.2 11316
65K 166 23697
130K 976 12632
195K 2134 15046
rotary base 500000 10000

On v5 the base drops to 10000 (the load logs Could not apply RoPE scaling 'linear' from config ... falling back to unscaled RoPE).

After, keeping native llama3 and widening the window:

abs position v4 4.57.6 v5 5.13.0
0 6.77 6.77
7.8K 6.44 6.43
65K 6.40 6.40
130K 6.47 6.48
195K 6.77 6.76
257K 8.94 8.93

Extension method compared directly at 256K (same passage, correct base 500000, only the rotary inv_freq swapped):

position llama3 linear 2.0 yarn 2.0
65K 6.4 166 169
130K 6.5 976 1058
195K 6.8 2134 3487
257K 8.9 1872 2717

Native llama3 stays flat out to 257K (2x the trained window), while linear and yarn both blow up. Plain RoPE models (for example unsloth/Qwen2.5-0.5B, theta 1000000) now extend with rotary.base = 1000000 instead of 10000.

Change

_extended_rope_scaling(config, factor) returns None to keep a native llama3 / yarn / longrope scaling, else a linear dict that carries rope_theta. The loader uses it in place of the unconditional linear override.

Tests

tests/utils/test_rope_scaling_drift.py::test_extended_rope_scaling_keeps_native_and_carries_theta (CPU): a llama3 config is kept untouched, and a v5 style plain config gets linear scaling that carries rope_theta. Full file: 15 passed, 1 skipped.

… linear

When max_seq_length exceeds a model's native window, the loader overwrote the
model's rope_scaling with linear scaling. For models that already ship a scaled
RoPE (llama3/yarn/longrope) that is far worse for long context, and on
transformers v5 the linear dict omitted rope_theta (v5 keeps it under
rope_parameters), so the rotary base fell back to 10000 and broke past ~8K tokens.

Keep the native scaling and just widen the window; only synthesize linear for
plain-RoPE models, and carry rope_theta so v5 keeps the real base.
@danielhanchen
danielhanchen requested a review from Datta0 as a code owner July 9, 2026 10:01
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

Gemini encountered an error creating the review. You can try again by commenting /gemini review.

@danielhanchen

Copy link
Copy Markdown
Member Author

/gemini review

@gemini-code-assist gemini-code-assist 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.

Code Review

This pull request introduces the _extended_rope_scaling helper function to handle RoPE scaling when extending a model's sequence length beyond its native window. It ensures that native scaled RoPE (such as llama3, yarn, or longrope) is preserved rather than being overwritten with linear scaling, and carries over rope_theta for plain RoPE to prevent transformers v5 from falling back to a default base value. Additionally, a unit test has been added to verify this behavior. There are no review comments, so no feedback is provided.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5f4e72dcf4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread unsloth/models/llama.py Outdated
"factor": factor,
"rope_theta": _get_rope_theta(config),
}, existing_type
return None, existing_type

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep unsupported native RoPE types loadable

When the existing config is yarn (or another non-linear/llama3/longrope type), this returns None, so the loader preserves that native rope_scaling whenever max_seq_length exceeds the config window. However the patched attention constructor in unsloth/models/_utils.py::patch_llama_rope_scaling only handles linear, llama3, and longrope before raising ValueError, so a YaRN Llama checkpoint that previously loaded via the linear override now fails during model construction. Either keep the override for types the patcher cannot instantiate, or add matching native support there first.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good catch. Fixed in a3f6d17: _extended_rope_scaling now preserves only native llama3; yarn (and any type patch_llama_rope_scaling cannot rebuild) falls back to the linear override, so model construction no longer raises. The linear fallback still carries rope_theta.

Comment thread unsloth/models/llama.py Outdated
"factor": factor,
"rope_theta": _get_rope_theta(config),
}, existing_type
return None, existing_type

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Don’t keep nested-only longrope configs

When a Llama longrope config stores original_max_position_embeddings only inside rope_scaling/rope_parameters, preserving the native scaling here sends it into the patched longrope constructor path, which reads self.config.original_max_position_embeddings in unsloth/models/_utils.py::patch_llama_rope_scaling instead of the nested value. Extending those checkpoints past their config window now raises AttributeError, whereas the previous linear override avoided that path; either copy the original length onto the config or keep linear until the longrope branch reads the nested key.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Good catch. Fixed in a3f6d17: only llama3 is kept native now, so a longrope config falls back to the linear override and never reaches the longrope constructor path that reads a top-level original_max_position_embeddings.

…ack otherwise

The patched attention constructor (patch_llama_rope_scaling) rebuilds only linear,
llama3 and longrope and its longrope branch reads a top-level
original_max_position_embeddings, so preserving yarn or a nested-only longrope config
would raise during construction on transformers <= 4.47.1. Keep only llama3 native;
yarn/longrope/other types fall back to the linear override, still carrying rope_theta.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: a3f6d173c2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: 6c8182da02

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit 534c877 into main Jul 9, 2026
51 checks passed
@danielhanchen
danielhanchen deleted the longctx-keep-native-rope branch July 9, 2026 11:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant