Skip to content

Fix Llama 3.1+ rope scaling dropped on the FastLanguageModel path (long inputs become gibberish past ~29K tokens) - #6197

Merged
danielhanchen merged 7 commits into
mainfrom
fix/rope-scaling-config-path
Jun 11, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
fix/rope-scaling-config-path

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Fixes #2405.

Root cause

On modern transformers, LlamaModel builds the rotary embedding from config using Unsloth's replacement LlamaRotaryEmbedding class (llama.py swaps it into transformers.models.llama.modeling_llama). That class's config path computed vanilla inv_freq and never read config.rope_scaling. The existing llama3/linear/longrope dispatch in patch_llama_rope_scaling rewrites LlamaAttention.__init__, but modern transformers no longer constructs rotary embeddings there, so the dispatch never fires, and the model-level (unscaled) rotary is then copied onto every attention layer.

Net effect: Llama-3.1 / 3.2 / 3.3 ran with unscaled RoPE on the FastLanguageModel path. Unscaled rope at theta 500000 holds up to roughly 29K tokens and then collapses, which is exactly the reported "long inputs produce repeated patterns, short inputs fine".

Evidence

Needle-in-haystack retrieval, Llama-3.1-8B-Instruct, max_seq_length 65536, greedy:

Configuration 48K tokens before 48K tokens after
FastLanguageModel bf16 FAIL ("The 1. The 1. The 1...") PASS ("47291")
FastLanguageModel 4-bit FAIL (wrong answer) PASS
FastModel bf16 / 4-bit PASS (kept transformers' rotary, immune) PASS

Boundary on the broken path: PASS at 28,867 input tokens, FAIL at 31,767. Probing the loaded model confirmed inv_freq matched the unscaled formula exactly and not the llama3-scaled one; after this fix it matches transformers' ROPE_INIT_FUNCTIONS["llama3"] output exactly.

Blast radius: qwen2, qwen3, qwen3_moe, mistral and cohere assign the same base class with no scaling dispatch at all, so any rope-scaled config of those families (e.g. yarn long-context variants) was equally exposed. Fixing the base class covers all of them at once.

The fix

In the config path of the base LlamaRotaryEmbedding:

  • compute inv_freq and attention_scaling via transformers' ROPE_INIT_FUNCTIONS[rope_type](config, device) (covers default, llama3, linear, dynamic, yarn, longrope), with an inline llama3 fallback that reads the factors from config for older transformers, degrading to the previous behavior on any failure rather than crashing;
  • apply attention_scaling in _set_cos_sin_cache (default 1.0, an exact no-op for unscaled paths) so it persists across extend_rope_embedding growth;
  • a type(self) guard ensures the legacy scaled subclasses (LlamaExtendedRotaryEmbedding, LlamaLinearScalingRotaryEmbedding) never double-apply scaling on old-transformers paths.

No behavior change when rope_scaling is None or when constructed without a config.

Tests

tests/utils/test_rope_scaling_drift.py, same two-layer pattern as the left-padding guard: a stdlib-ast tripwire (the config path must reference rope_scaling) plus behavioral checks (inv_freq matches transformers' llama3 init exactly and not vanilla; vanilla config control; cos cache at long positions differs scaled vs unscaled; scaling survives extend_rope_embedding growth). Validated to fail 4 of 5 on the unfixed code and pass 5 of 5 with the fix. Wired into the existing consolidated CI HARD GATE step (renamed to "generation correctness guards"), so no new CI job.

Also verified the left-padded batched generation guard still passes end to end on this branch (exact solo-vs-batched token matches), and 20K-token inputs are unchanged (PASS before and after).

#2405)

On modern transformers, LlamaModel builds its rotary embedding from config
using unsloth's replacement LlamaRotaryEmbedding class, whose config path
computed vanilla inv_freq and ignored config.rope_scaling entirely. The
llama3/linear/longrope dispatch in patch_llama_rope_scaling rewrites
LlamaAttention.__init__, which no longer constructs rotary embeddings, so it
never fires; the model-level rotary is then copied onto every attention
layer. Result: Llama-3.1/3.2/3.3 ran with unscaled RoPE on the
FastLanguageModel path and collapsed into repetition loops past roughly 29K
tokens (PASS at 28867, FAIL at 31767 in needle retrieval). FastModel was
unaffected because vision.py keeps transformers' own rotary. qwen2, qwen3,
qwen3_moe, mistral and cohere assign the same base class, so any rope-scaled
config of those families was equally exposed.

The fix makes the base class config path compute inv_freq and
attention_scaling via transformers' ROPE_INIT_FUNCTIONS (covers llama3,
linear, dynamic, yarn, longrope), with an inline llama3 fallback reading
factors from config for older transformers, degrading to prior behavior on
any failure. attention_scaling is applied in _set_cos_sin_cache (1.0 default,
exact no-op for unscaled paths) and persists across extend_rope_embedding.
A type(self) guard prevents double-scaling via the legacy scaled subclasses.

Adds tests/utils/test_rope_scaling_drift.py (AST tripwire + behavioral
inv_freq/cos-cache/extension checks, validated to fail 4 of 5 on the unfixed
code) and wires it into the existing consolidated CI HARD GATE step.

Verified on GPU: 48K-token needle retrieval flips FAIL to PASS for
FastLanguageModel in bf16 and 4bit, 20K stays PASS, scaled inv_freq matches
transformers exactly, and the left-padded batch generation guard still gets
exact solo-vs-batched token matches.

@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 a regression guard and fixes an issue where RoPE scaling was silently dropped during model initialization in modern transformers. It adds a comprehensive test suite to verify RoPE scaling behavior and updates LlamaRotaryEmbedding to correctly compute and apply scaling factors from config.rope_scaling. The reviewer feedback highlights two valuable improvements: safely handling RopeScalingConfig objects to prevent potential AttributeError crashes, and vectorizing the loop in _llama3_inv_freq_from_config using PyTorch's native operations for better performance.

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.

Comment thread unsloth/models/llama.py Outdated
Comment on lines +1663 to +1672
new_freqs.append((1 - smooth) * freq / scale_factor + smooth * freq)
return torch.tensor(new_freqs, dtype = inv_freq.dtype, device = inv_freq.device)


def _compute_config_rope_inv_freq(config, rope_scaling):
"""Return (inv_freq, attention_scaling) honoring config.rope_scaling.

Delegates to transformers' ROPE_INIT_FUNCTIONS so the result matches stock
transformers exactly (default / linear / dynamic / yarn / longrope / llama3).
Falls back to an inline llama3 computation on older transformers. On any

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.

high

In newer versions of transformers, config.rope_scaling can be a RopeScalingConfig object (a dataclass) rather than a raw dictionary. Calling .get() directly on it will raise an AttributeError and crash the model initialization. Defensively converting rope_scaling to a dictionary or extracting its attributes safely prevents this crash.

def _compute_config_rope_inv_freq(config, rope_scaling):
    """Return (inv_freq, attention_scaling) honoring config.rope_scaling.

    Delegates to transformers' ROPE_INIT_FUNCTIONS so the result matches stock
    transformers exactly (default / linear / dynamic / yarn / longrope / llama3).
    Falls back to an inline llama3 computation on older transformers. On any
    unexpected failure returns (None, 1.0) so the caller keeps the prior vanilla
    behavior rather than crashing.
    """
    if not isinstance(rope_scaling, dict):
        if hasattr(rope_scaling, "to_dict"):
            rope_scaling = rope_scaling.to_dict()
        else:
            rope_scaling = {
                "rope_type": getattr(rope_scaling, "rope_type", None),
                "type": getattr(rope_scaling, "type", None),
                "factor": getattr(rope_scaling, "factor", None),
                "low_freq_factor": getattr(rope_scaling, "low_freq_factor", None),
                "high_freq_factor": getattr(rope_scaling, "high_freq_factor", None),
                "original_max_position_embeddings": getattr(rope_scaling, "original_max_position_embeddings", None),
            }
    rope_type = rope_scaling.get("rope_type", None) or rope_scaling.get("type", None)

Comment thread unsloth/models/llama.py Outdated
Comment on lines +1625 to +1660
def _llama3_inv_freq_from_config(
config,
rope_scaling,
device = "cpu",
):
"""Inline llama3 RoPE inv_freq using factors read from config.rope_scaling.

Fallback for transformers versions without modeling_rope_utils. Mirrors
meta-llama's llama3 scaling and LlamaExtendedRotaryEmbedding, but reads the
factors from config rather than hardcoding them.
"""
base = _get_rope_theta(config, default = 10000.0)
dim = getattr(config, "head_dim", None)
if dim is None:
dim = int(config.hidden_size // config.num_attention_heads)
inv_freq = 1.0 / (
base ** (torch.arange(0, dim, 2, dtype = torch.int64, device = device).float() / dim)
)

scale_factor = rope_scaling.get("factor", 8.0)
low_freq_factor = rope_scaling.get("low_freq_factor", 1.0)
high_freq_factor = rope_scaling.get("high_freq_factor", 4.0)
old_context_len = rope_scaling.get("original_max_position_embeddings", 8192)

low_freq_wavelen = old_context_len / low_freq_factor
high_freq_wavelen = old_context_len / high_freq_factor
new_freqs = []
for freq in inv_freq:
wavelen = 2 * math.pi / freq
if wavelen < high_freq_wavelen:
new_freqs.append(freq)
elif wavelen > low_freq_wavelen:
new_freqs.append(freq / scale_factor)
else:
assert low_freq_wavelen != high_freq_wavelen
smooth = (old_context_len / wavelen - low_freq_factor) / (

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.

medium

Looping over elements of a PyTorch tensor and appending them to a list is inefficient and can trigger UserWarning when converting the list back to a tensor. This can be fully vectorized using PyTorch's native operations (such as torch.where), which is much faster and cleaner.

def _llama3_inv_freq_from_config(config, rope_scaling, device = "cpu"):
    """Inline llama3 RoPE inv_freq using factors read from config.rope_scaling.

    Fallback for transformers versions without modeling_rope_utils. Mirrors
    meta-llama's llama3 scaling and LlamaExtendedRotaryEmbedding, but reads the
    factors from config rather than hardcoding them.
    """
    base = _get_rope_theta(config, default = 10000.0)
    dim = getattr(config, "head_dim", None)
    if dim is None:
        dim = int(config.hidden_size // config.num_attention_heads)
    inv_freq = 1.0 / (
        base ** (torch.arange(0, dim, 2, dtype = torch.int64, device = device).float() / dim)
    )

    scale_factor = rope_scaling.get("factor", 8.0)
    low_freq_factor = rope_scaling.get("low_freq_factor", 1.0)
    high_freq_factor = rope_scaling.get("high_freq_factor", 4.0)
    old_context_len = rope_scaling.get("original_max_position_embeddings", 8192)

    low_freq_wavelen = old_context_len / low_freq_factor
    high_freq_wavelen = old_context_len / high_freq_factor

    wavelen = 2 * math.pi / inv_freq
    denom = high_freq_factor - low_freq_factor
    if denom == 0:
        denom = 1.0
    smooth = (old_context_len / wavelen - low_freq_factor) / denom

    scaled_freq = inv_freq / scale_factor
    smooth_freq = (1 - smooth) * scaled_freq + smooth * inv_freq

    new_freqs = torch.where(
        wavelen < high_freq_wavelen,
        inv_freq,
        torch.where(
            wavelen > low_freq_wavelen,
            scaled_freq,
            smooth_freq
        )
    )
    return new_freqs

@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: 8c9c39195e

ℹ️ 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
Comment on lines +1734 to +1735
rope_scaling = getattr(config, "rope_scaling", None)
if rope_scaling is not None and type(self) is LlamaRotaryEmbedding:

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 Read rope_parameters when applying RoPE scaling

On Transformers 5.x/current Llama configs, RoPE settings are exposed as config.rope_parameters rather than config.rope_scaling, so this branch is skipped and config_inv_freq stays None; the constructor then falls back to vanilla inv_freq, leaving the same long-context gibberish for Llama-3.1+ on the latest config path this patch is meant to fix. Please normalize from rope_scaling or rope_parameters before deciding whether to call _compute_config_rope_inv_freq.

Useful? React with 👍 / 👎.

Comment thread unsloth/models/llama.py
Comment on lines +1676 to +1678
rope_init_fn = ROPE_INIT_FUNCTIONS[rope_type]
inv_freq, attention_scaling = rope_init_fn(config, torch.device("cpu"))
return inv_freq.to(dtype = torch.float32, device = "cpu"), float(attention_scaling)

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 Update dynamic/LongRoPE frequencies on cache growth

For configs using rope_type dynamic or longrope, this one-time initialization is not enough: Transformers recomputes inv_freq from the actual sequence length when positions grow past the cached/original length, while extend_rope_embedding() here only rebuilds cos/sin from the stale initial inv_freq. In those long-context decodes (e.g. dynamic NTK past max_position_embeddings, or LongRoPE past original_max_position_embeddings) the new config path still uses the wrong frequencies despite the patch claiming to delegate those schemes to ROPE_INIT_FUNCTIONS; store the rope type/config and recompute with the requested seq_len during cache growth.

Useful? React with 👍 / 👎.

… fallback

config.rope_scaling can be a config object rather than a dict on newer
transformers; _rope_scaling_as_dict normalizes it (to_dict/dict/vars
fallbacks) before any .get() access, with a regression test using a
dataclass stand-in. The inline llama3 fallback now uses torch.where instead
of a per-frequency Python loop; verified bit-for-bit equal to transformers
ROPE_INIT_FUNCTIONS for factor 8 (Llama-3.1) and factor 32 (Llama-3.2).
@danielhanchen

Copy link
Copy Markdown
Member Author

Addressed both review points in ef7f0fb: config.rope_scaling is now normalized through _rope_scaling_as_dict before any .get() access (handles object-style RopeScalingConfig; covered by a new dataclass-based regression test), and the inline llama3 fallback is vectorized with torch.where, verified bit-for-bit equal to transformers ROPE_INIT_FUNCTIONS for factor 8 (Llama-3.1) and factor 32 (Llama-3.2). All 17 guard tests pass; GPU probe still shows correctly scaled inv_freq.

@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: ea990d32b6

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread tests/utils/test_rope_scaling_drift.py Outdated

def test_llama3_scaling_applied_to_inv_freq():
config = _make_config(LLAMA3_ROPE_SCALING)
rot = _unsloth_rotary(config)

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 Avoid instantiating rotary caches on GPU-less CI

In the generation correctness guards workflow this file is run as a CPU guard, but these behavioral tests instantiate LlamaRotaryEmbedding, whose constructor immediately builds caches with torch.device(0) and moves cos/sin tensors to CUDA for every DEVICE_COUNT. The tests/conftest.py spoof only lets import unsloth survive on hosted CPU runners; it does not provide a real CUDA device, so this line fails before the RoPE assertion is reached on the documented GPU-less CI path. Consider stubbing the cache build/device path or testing the frequency computation without constructing CUDA caches.

Useful? React with 👍 / 👎.

Comment thread unsloth/models/llama.py Outdated
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS

rope_init_fn = ROPE_INIT_FUNCTIONS[rope_type]
inv_freq, attention_scaling = rope_init_fn(config, torch.device("cpu"))

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 Use normalized RoPE scaling when delegating

For the object-style rope_scaling case this helper is explicitly trying to support, normalizing into the local rope_scaling dict is not enough because the delegated ROPE_INIT_FUNCTIONS still read config.rope_scaling from the unchanged config. With a non-dict config object for linear, yarn, longrope, or dynamic, the delegate raises, this catch path has no fallback, and the function returns None so scaling is silently dropped; either pass a config whose RoPE field has been normalized or avoid delegating with the unmodified object.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

Both review points were correct and are addressed:

  • The behavioral tests did crash without a real CUDA device (reproduced locally with CUDA_VISIBLE_DEVICES="": 4 failures at get_current_device inside the constructor). Restructured into three layers: the AST tripwire additionally asserts the constructor stays wired to _compute_config_rope_inv_freq, the CPU layer tests that pure helper directly with no instantiation (llama3 dict and object, linear object, default type), and the instantiation/cache tests are gated behind a real-allocation CUDA probe so import-time spoofs cannot fool the skip. Verified in all three states: 9 passed with GPU, 5 passed 4 skipped with CUDA hidden, 5 failed 4 skipped on the unfixed code in CPU mode.
  • Delegation now retries ROPE_INIT_FUNCTIONS with a shallow config copy carrying the normalized rope_scaling dict when the original was a non-dict object. Covered by a new linear-object test, which has no inline fallback and only passes through that retry path.

…gation

The rotary constructor builds per-device CUDA caches, so the behavioral tests
that instantiate it cannot run on GPU-less CI. Restructured into three layers:
the AST tripwire now also asserts the constructor stays wired to
_compute_config_rope_inv_freq; the CPU layer tests that pure helper directly
(llama3 dict, llama3 object, linear object, default type) with no
instantiation; the instantiation and cache tests are gated behind a real CUDA
probe (actual tensor allocation, so import-time CUDA spoofs cannot fool the
gate). Verified: 9 passed with GPU; 5 passed 4 skipped with CUDA hidden; 5
failed 4 skipped on the unfixed code in CPU mode.

Delegation to ROPE_INIT_FUNCTIONS now retries with a shallow config copy
carrying the normalized rope_scaling dict when the original was an object the
installed transformers cannot read; covered by a linear-object test, which has
no inline fallback and passes only through that retry path.
Comment and docstring reduction only; verified code-identical with
scripts/comment_tools.py check --strip-docstrings (AST signature match on
both Python files). All guard tests unchanged: 20 passed with GPU, 5 passed
4 skipped with CUDA hidden.
@danielhanchen
danielhanchen merged commit d24ee77 into main Jun 11, 2026
40 of 43 checks passed
@danielhanchen
danielhanchen deleted the fix/rope-scaling-config-path branch June 11, 2026 14:48
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.

Unsloth models output gibberish on LONG inputs

1 participant