Skip to content

Fix llama3 RoPE scaling dropped on transformers v5 - #6907

Merged
danielhanchen merged 5 commits into
mainfrom
fix_llama3_rope_transformers_v5
Jul 6, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
fix_llama3_rope_transformers_v5

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Jul 6, 2026 •

Copy link
Copy Markdown
Member

Summary

On transformers v5, llama3 (and yarn) RoPE scaling was silently dropped, leaving inv_freq unscaled: divided by 1 instead of the config factor (8 for Llama 3.1, 32 for Llama 3.2). This corrupts long-range positions and inflates long-context training loss roughly 3-5x. transformers 4.x was not affected.

Root cause

transformers v5 builds the model on meta and then replaces non-persistent buffers with uninitialized memory, so inv_freq has to be rebuilt after load. _fix_rope_inv_freq in unsloth/models/loader.py does that, but it recomputed a vanilla inv_freq and applied module._apply_inv_freq_scaling(...), which is a no-op on the base LlamaRotaryEmbedding. That base class is exactly the one used when the config/llama3 path is active (the scaling lives in the config derived inv_freq, not in _apply_inv_freq_scaling), so the repair overwrote the correctly scaled buffer with an unscaled one and copied it to every layer.

In other words LlamaRotaryEmbedding.__init__ computed the correct scaled inv_freq, then _fix_rope_inv_freq clobbered it right afterwards.

Fix

Give __init__ and the v5 repair a single source of truth, _unsloth_recompute_inv_freq, which returns the config scaled inv_freq (via _compute_config_rope_inv_freq) when it applies and otherwise falls back to vanilla plus the subclass _apply_inv_freq_scaling. The rotary module stashes its config so the repair can rebuild the same value. _fix_rope_inv_freq calls this method when present and keeps the old path for everything else (LongRope, Gemma, unknown rotaries), so behaviour is unchanged outside the base llama3 path.

Verification

Checked unsloth/Llama-3.2-1B-Instruct (factor 32), unsloth/Meta-Llama-3.1-8B-Instruct (factor 8) and a non scaled model (stays unscaled):

  • inv_freq ratio is restored to the config factor after the v5 repair on transformers 5.0.0, 5.1.0, 5.3.0, 5.5.0, 5.8.0, 5.11.0 and 5.13.0.
  • No change on transformers 4.55.0, 4.56.0 and 4.57.6 (the repair is gated to v5 and is a no-op there, and __init__ already scales correctly).
  • Long context LM loss, Llama-3.2-1B on wikitext-2:
seq scaled (this PR) unscaled (before)
8192 2.61 2.62
32768 2.48 5.67
65536 2.49 6.97
  • SFT smoke run with TRL trains without NaNs and loads with the correct scaling.

transformers v5 loads on meta then blanks non-persistent buffers, so
_fix_rope_inv_freq rebuilds inv_freq after load. It recomputed a vanilla
inv_freq and applied _apply_inv_freq_scaling, a no-op on the base
LlamaRotaryEmbedding used by the config/llama3 path, so inv_freq ended up
divided by 1 instead of the config factor (8 for Llama 3.1, 32 for Llama
3.2). This corrupts long-range positions and inflates long-context loss
about 3-5x. transformers 4.x was unaffected.

Route __init__ and the v5 repair through one _unsloth_recompute_inv_freq
so they cannot diverge, and stash the config on the rotary module so the
repair can rebuild the same scaled value.
@danielhanchen
danielhanchen requested a review from Datta0 as a code owner July 6, 2026 14:40

@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 refactors the RoPE inv_freq calculation in unsloth/models/llama.py by introducing a new helper method _unsloth_recompute_inv_freq(). This method consolidates the config scaling (such as Llama-3 or YaRN) and vanilla/subclass scaling logic, ensuring consistency between initialization and the RoPE repair process. In unsloth/models/loader.py, the _fix_rope_inv_freq function is updated to utilize this new helper method when available, preventing issues where unscaled values broke v5. There are no review comments to address, and no further 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 33965bee55

ℹ️ 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
)
)
inv_freq = self._apply_inv_freq_scaling(inv_freq)
inv_freq = self._unsloth_recompute_inv_freq()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Update the RoPE drift guard after the refactor

This refactor moves the rope_scaling lookup and _compute_config_rope_inv_freq call out of the if config is not None: branch, but the hard-gated CI step in .github/workflows/consolidated-tests-ci.yml lines 340-349 runs tests/utils/test_rope_scaling_drift.py, whose AST guard only inspects that branch and asserts it contains both rope_scaling and _compute_config_rope_inv_freq. With this line calling the new helper after the branch, that guard fails even though the runtime behavior is preserved, so please update the existing drift test or leave a branch-local hook it recognizes.

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. Updated the drift guard in tests/utils/test_rope_scaling_drift.py: the AST tripwire now follows the scaling into _unsloth_recompute_inv_freq (with a fallback to the old inline if config is not None branch), and I added test_v5_repair_reuses_recompute so it also asserts loader._fix_rope_inv_freq rebuilds inv_freq through that same helper. Added a CPU functional check of the helper too. Full suite passes (10 passed, 1 skipped).

…epair

The drift guard's AST tripwire asserted the config-scaling call lived in the
if config is not None branch of LlamaRotaryEmbedding.__init__. The fix moved
that into _unsloth_recompute_inv_freq, so follow it there (with a fallback to
the old inline branch) and add a guard that loader._fix_rope_inv_freq rebuilds
inv_freq through the same helper. Also add a CPU functional check of the helper
and drop the redundant standalone test.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 1886d4d5fe

ℹ️ 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 2fada48 into main Jul 6, 2026
33 of 50 checks passed
@danielhanchen
danielhanchen deleted the fix_llama3_rope_transformers_v5 branch July 6, 2026 16:13
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 7, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 7, 2026
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