Skip to content

Fix transformers v5 RoPE inv_freq corruption and generate() BatchEncoding compat - #4112

Merged
danielhanchen merged 4 commits into
mainfrom
fix/v5-rope-inv-freq-corruption
Feb 25, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
fix/v5-rope-inv-freq-corruption

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Feb 25, 2026 •

Copy link
Copy Markdown
Member

Summary

Two fixes for transformers v5 compatibility. Both are no-ops on v4.

1. RoPE inv_freq corruption (loader.py)

Transformers v5 introduced meta-device model initialization, where _move_missing_keys_from_meta_to_device() in modeling_utils.py replaces all non-persistent buffers with torch.empty_like() (uninitialized GPU memory). Vanilla transformers handles this by restoring inv_freq in _init_weights() via a hasattr(module, "original_inv_freq") check, but Unsloth's LlamaRotaryEmbedding and subclasses lack this attribute, so inv_freq stays corrupted.

Corrupted inv_freq produces wrong rotational position encodings, causing attention to attend to incorrect positions. This resulted in 5-11x higher training loss on transformers v5 for all models using Unsloth's rope classes.

Root cause chain:

  1. Transformers v5 creates model on meta device (shape-only tensors, no data)
  2. Weights are loaded from checkpoint
  3. _move_missing_keys_from_meta_to_device() iterates ALL non-persistent buffers and replaces them with torch.empty_like() -- this corrupts inv_freq
  4. _init_weights() tries to restore inv_freq by checking hasattr(module, "original_inv_freq") -- this fails for Unsloth's rope classes
  5. inv_freq stays as uninitialized memory, producing garbage positional encodings

Fix: Added _fix_rope_inv_freq() to loader.py, called at the end of both FastLanguageModel.from_pretrained() and FastModel.from_pretrained(). It recomputes inv_freq from the stored base and dim, applies model-specific scaling via _apply_inv_freq_scaling(), and rebuilds cos/sin caches. Also handles LongRopeRotaryEmbedding (Phi-3.5 style). Guarded by transformers_version >= 5.0.0.

Affected classes: LlamaRotaryEmbedding, LlamaExtendedRotaryEmbedding, LlamaLinearScalingRotaryEmbedding, GraniteRotaryEmbedding, LongRopeRotaryEmbedding. Models using native transformers rope (Gemma, Phi-4, Falcon-H1) are unaffected.

2. generate() BatchEncoding compat (llama.py)

Old notebooks pass the full tokenizer output as input_ids:

inputs = tokenizer(..., return_tensors="pt").to("cuda")
model.generate(input_ids=inputs, ...)

This worked on transformers v4 because generate() internally extracted the tensor. Transformers v5 calls .shape on input_ids directly, which crashes since BatchEncoding has no .shape attribute.

Fix: In unsloth_fast_generate(), detect when input_ids is a dict-like object (BatchEncoding) and unpack its contents into separate kwargs before forwarding to the underlying generate(). This makes both old (input_ids=inputs) and new (**inputs) notebook patterns work on both v4 and v5.

Test results

Training loss comparison (v4 baseline vs v5 with fix), LoRA + alpaca-cleaned dataset:

Model v4 Loss (first -> last) v5 Before Fix v5 After Fix Match?
Llama 3.1 8B 1.875 -> 1.001 9.952 -> 6.984 1.875 -> 0.999 Yes
Llama 3.2 3B 1.038 -> 0.968 0.000 -> 0.000 1.038 -> 0.969 Yes
Qwen3 14B 0.781 -> 0.441 8.890 -> 5.916 0.781 -> 0.441 Yes
Qwen3 4B 1.294 -> 0.751 9.041 -> 7.226 1.294 -> 0.755 Yes
Phi-4 14B 0.776 -> 0.690 0.776 -> 0.689 0.776 -> 0.689 Yes (was OK)
TinyLlama 1.1B 2.284 -> 1.540 2.284 -> 1.589 2.284 -> 1.589 Yes (was OK)
Mistral 7B 1.425 -> 0.833 1.425 -> 0.833 1.425 -> 0.833 Yes (was OK)
Gemma2 2B 1.896 -> 1.073 1.897 -> 1.073 1.897 -> 1.073 Yes (was OK)
Falcon-H1 0.5B 1.682 -> 1.185 1.682 -> 1.186 1.682 -> 1.186 Yes (was OK)

LoRA save/load and merged 16-bit model export also verified on v5 for Llama 3.1 8B, Qwen3 14B, and Qwen3 4B.

The ~0.33x grad norm ratio between v5 and v4 is a separate reporting-only change in transformers v5 (divides by gradient_accumulation_steps before reporting). Actual optimizer updates are identical.

Transformers v5 initializes models on the meta device, then
_move_missing_keys_from_meta_to_device() replaces all non-persistent
buffers with torch.empty_like() (uninitialized memory). Vanilla
transformers restores inv_freq via _init_weights() checking for
original_inv_freq, but Unsloth's LlamaRotaryEmbedding subclasses
lack this attribute, so inv_freq stays corrupted with garbage values.

This caused 5-11x higher training loss on transformers v5 for all
models using Unsloth's rope (Llama 3.x, Qwen3, Mistral, TinyLlama,
Granite). Models using native transformers rope (Gemma, Phi-4,
Falcon-H1) were unaffected.

The fix recomputes inv_freq from the stored base/dim after model
loading, applies model-specific scaling via _apply_inv_freq_scaling(),
and rebuilds cos/sin caches. Also handles LongRopeRotaryEmbedding
(Phi-3.5 style short/long inv_freq). Guarded by transformers >= 5.0.0
so it is a no-op on v4.

Tested on: Llama 3.1 8B, Llama 3.2 3B, Qwen3 14B, Qwen3 4B, Phi-4,
TinyLlama, Mistral 7B, Gemma2 2B, Falcon-H1 -- all v5 losses now
match v4 baselines to < 0.004 absolute difference.
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @danielhanchen, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request resolves a critical bug introduced in Transformers v5 where the meta-device initialization process inadvertently corrupted the inv_freq buffer within Unsloth's custom Rotary Positional Embedding implementations. This corruption led to incorrect positional encodings and a substantial increase in training loss for several models. The implemented solution recomputes and restores the correct inv_freq values and associated caches during model loading, ensuring accurate positional encoding and restoring training performance to v4 levels.

Highlights

  • Addresses inv_freq corruption in Transformers v5: Fixed an issue where Transformers v5's meta-device model initialization corrupted the inv_freq buffer in Unsloth's Rotary Positional Embedding (RoPE) classes, leading to significantly higher training loss.
  • Introduced _fix_rope_inv_freq() function: A new utility function, _fix_rope_inv_freq(), was added to recompute the inv_freq from stored base and dim attributes, apply model-specific scaling, and rebuild cos/sin caches for affected RoPE modules.
  • Broad compatibility and conditional application: The fix is applied to LlamaRotaryEmbedding and its subclasses (e.g., LlamaExtendedRotaryEmbedding, GraniteRotaryEmbedding), as well as LongRopeRotaryEmbedding. It is guarded by a transformers_version >= 5.0.0 check, ensuring it's a no-op on v4 and earlier versions.
  • Integration into model loading: The _fix_rope_inv_freq() function is now called at the end of both FastLanguageModel.from_pretrained() and FastModel.from_pretrained() to ensure inv_freq is correctly initialized upon model loading.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • unsloth/models/loader.py
    • Added _NEEDS_ROPE_FIX constant to conditionally enable the fix for Transformers v5 and above.
    • Introduced _fix_rope_inv_freq function to recompute and correct inv_freq for LlamaRotaryEmbedding and LongRopeRotaryEmbedding modules.
    • Integrated _fix_rope_inv_freq into FastLanguageModel.from_pretrained to apply the fix during model loading.
    • Integrated _fix_rope_inv_freq into FastModel.from_pretrained to apply the fix during model loading.
Activity
  • No human activity has occurred on this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@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 provides a crucial fix for an inv_freq corruption issue when loading models with transformers v5. The root cause is well-explained, and the fix by recomputing inv_freq and rebuilding caches in _fix_rope_inv_freq is direct and effective. The implementation correctly handles different RoPE embedding classes and is properly gated by the transformers version. The extensive test results confirm the fix's effectiveness. I have one minor suggestion to improve code readability.

Comment thread unsloth/models/loader.py
Comment on lines +185 to +190
and hasattr(module, "dim")
):
config = getattr(model, "config", None)
rope_scaling = getattr(config, "rope_scaling", None) if config else None
if rope_scaling is not None:
short_factor = rope_scaling.get("short_factor", None)

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

This nested checking for config, rope_scaling, short_factor, and long_factor can be slightly flattened to improve readability and reduce nesting depth. The current implementation is correct, but a more streamlined approach would be more maintainable.

Suggested change
and hasattr(module, "dim")
):
config = getattr(model, "config", None)
rope_scaling = getattr(config, "rope_scaling", None) if config else None
if rope_scaling is not None:
short_factor = rope_scaling.get("short_factor", None)
config = getattr(model, "config", None)
rope_scaling = getattr(config, "rope_scaling", None)
if rope_scaling is not None:
short_factor = rope_scaling.get("short_factor")
long_factor = rope_scaling.get("long_factor")
if short_factor is not None and long_factor is not None:

Old notebooks pass the full tokenizer output as input_ids:

    inputs = tokenizer(..., return_tensors="pt").to("cuda")
    model.generate(input_ids=inputs, ...)

This worked on transformers v4 because generate() internally
extracted the tensor. Transformers v5 calls .shape on input_ids
directly, which crashes since BatchEncoding has no .shape attribute.

Fix: in unsloth_fast_generate(), detect when input_ids is a dict-like
object (BatchEncoding) and unpack its contents into separate kwargs
before forwarding to the underlying generate(). This makes both old
and new notebook patterns work on both v4 and v5.
@danielhanchen danielhanchen changed the title Fix transformers v5 RoPE inv_freq corruption during model loading Fix transformers v5 RoPE inv_freq corruption and generate() BatchEncoding compat Feb 25, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

Backwards/forwards compatibility verified

Tested on transformers 4.57.6, 5.0.0, 5.1.0, and 5.2.0. All versions pass all tests.

Version inv_freq Training (5 steps) generate(input_ids=BatchEncoding) generate(**inputs) generate(input_ids=tensor)
4.57.6 PASS PASS -- [1.621, 1.177, 1.411, 1.810, 2.012] PASS PASS PASS
5.0.0 PASS PASS -- [1.623, 1.142, 1.381, 1.782, 1.932] PASS PASS PASS
5.1.0 PASS PASS -- [1.623, 1.142, 1.381, 1.782, 1.932] PASS PASS PASS
5.2.0 PASS PASS -- [1.620, 1.141, 1.384, 1.783, 1.931] PASS PASS PASS

Model: Llama 3.2 1B Instruct (4-bit), LoRA r=8, alpaca-cleaned dataset, 5 training steps.

  • inv_freq is correct on all versions (diff vs recomputed = 0.00, monotonically decreasing)
  • Training losses match across all 4 versions (~1.6 first step, no divergence)
  • Both the old notebook pattern (input_ids=tokenizer(...)) and new pattern (**tokenizer(...)) work on all versions
  • _fix_rope_inv_freq is a no-op on v4 (guarded by _NEEDS_ROPE_FIX = transformers_version >= 5.0.0)
  • BatchEncoding unpack is a no-op when input_ids is already a tensor (fast isinstance check)

Comment thread unsloth/models/loader.py Outdated

seen_ids = set()
for name, module in model.named_modules():
if id(module) in seen_ids:

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.

Why? we iterate over a module only once right?

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 -- named_modules() already deduplicates (remove_duplicate=True by default). We do share the same rotary_emb object across all attention layers (llama.py L2580-2584), but named_modules() handles that. Removed the redundant seen_ids in 4b4da24.

Comment thread unsloth/models/loader.py
seen_ids.add(id(module))

# LlamaRotaryEmbedding and subclasses (Extended, LinearScaling, Granite)
if (

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.

Vision models won't hit this path but Gemma3 has custom Gemma3RotaryEmbedding ig.

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.

Right -- Gemma3RotaryEmbedding (and other native v5 rotary classes) will not hit this path. That is intentional. These classes have the original_inv_freq attribute, so transformers v5's _init_weights() restores inv_freq via rope_init_fn() before Unsloth even touches the model. This fix only needs to handle Unsloth's custom LlamaRotaryEmbedding family which lacks original_inv_freq. Added a comment clarifying this in 4b4da24.

named_modules() already deduplicates with remove_duplicate=True (default).
Also clarify that native v5 rotary classes (Gemma3 etc.) have original_inv_freq
which transformers v5's _init_weights() uses to restore inv_freq, so they do
not need this fix.
@danielhanchen
danielhanchen merged commit 34ceb6b into main Feb 25, 2026
3 checks passed
@danielhanchen
danielhanchen deleted the fix/v5-rope-inv-freq-corruption branch February 25, 2026 16:18
vivekkalyanarangan30 added a commit to vivekkalyanarangan30/unsloth that referenced this pull request Feb 26, 2026
Integrates upstream PRs unslothai#4100 (leftpad prefill) and unslothai#4112 (v5 RoPE fix)
while preserving our multi-token prefill logic in
_fast_prepare_inputs_for_generation.

Key resolution: upstream's input_ids[:, [-1]] replaced with our
multi-token slicing (input_ids[:, past_len:]) while keeping upstream's
new infrastructure (max_cache_len, _unsloth_mask_needs_device caching,
mask_kwargs pattern, original_attention_mask-based position_ids).
abiswas-realadvice pushed a commit to abiswas-realadvice/unsloth that referenced this pull request May 14, 2026
…ding compat (unslothai#4112)

* Fix transformers v5 RoPE inv_freq corruption during model loading

Transformers v5 initializes models on the meta device, then
_move_missing_keys_from_meta_to_device() replaces all non-persistent
buffers with torch.empty_like() (uninitialized memory). Vanilla
transformers restores inv_freq via _init_weights() checking for
original_inv_freq, but Unsloth's LlamaRotaryEmbedding subclasses
lack this attribute, so inv_freq stays corrupted with garbage values.

This caused 5-11x higher training loss on transformers v5 for all
models using Unsloth's rope (Llama 3.x, Qwen3, Mistral, TinyLlama,
Granite). Models using native transformers rope (Gemma, Phi-4,
Falcon-H1) were unaffected.

The fix recomputes inv_freq from the stored base/dim after model
loading, applies model-specific scaling via _apply_inv_freq_scaling(),
and rebuilds cos/sin caches. Also handles LongRopeRotaryEmbedding
(Phi-3.5 style short/long inv_freq). Guarded by transformers >= 5.0.0
so it is a no-op on v4.

Tested on: Llama 3.1 8B, Llama 3.2 3B, Qwen3 14B, Qwen3 4B, Phi-4,
TinyLlama, Mistral 7B, Gemma2 2B, Falcon-H1 -- all v5 losses now
match v4 baselines to < 0.004 absolute difference.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Unpack BatchEncoding in generate() for v4/v5 backwards compatibility

Old notebooks pass the full tokenizer output as input_ids:

    inputs = tokenizer(..., return_tensors="pt").to("cuda")
    model.generate(input_ids=inputs, ...)

This worked on transformers v4 because generate() internally
extracted the tensor. Transformers v5 calls .shape on input_ids
directly, which crashes since BatchEncoding has no .shape attribute.

Fix: in unsloth_fast_generate(), detect when input_ids is a dict-like
object (BatchEncoding) and unpack its contents into separate kwargs
before forwarding to the underlying generate(). This makes both old
and new notebook patterns work on both v4 and v5.

* Remove redundant seen_ids dedup in _fix_rope_inv_freq

named_modules() already deduplicates with remove_duplicate=True (default).
Also clarify that native v5 rotary classes (Gemma3 etc.) have original_inv_freq
which transformers v5's _init_weights() uses to restore inv_freq, so they do
not need this fix.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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.

2 participants