Repository navigation
Fix transformers v5 RoPE inv_freq corruption and generate() BatchEncoding compat - #4112
Conversation
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.
Summary of ChangesHello @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 Highlights
🧠 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
Activity
Using Gemini Code AssistThe 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
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 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
|
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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.
| 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.
Backwards/forwards compatibility verifiedTested on transformers 4.57.6, 5.0.0, 5.1.0, and 5.2.0. All versions pass all tests.
Model: Llama 3.2 1B Instruct (4-bit), LoRA r=8, alpaca-cleaned dataset, 5 training steps.
|
|
|
||
| seen_ids = set() | ||
| for name, module in model.named_modules(): | ||
| if id(module) in seen_ids: |
There was a problem hiding this comment.
Why? we iterate over a module only once right?
There was a problem hiding this comment.
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.
| seen_ids.add(id(module)) | ||
|
|
||
| # LlamaRotaryEmbedding and subclasses (Extended, LinearScaling, Granite) | ||
| if ( |
There was a problem hiding this comment.
Vision models won't hit this path but Gemma3 has custom Gemma3RotaryEmbedding ig.
There was a problem hiding this comment.
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.
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).
…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>
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()inmodeling_utils.pyreplaces all non-persistent buffers withtorch.empty_like()(uninitialized GPU memory). Vanilla transformers handles this by restoringinv_freqin_init_weights()via ahasattr(module, "original_inv_freq")check, but Unsloth'sLlamaRotaryEmbeddingand subclasses lack this attribute, soinv_freqstays corrupted.Corrupted
inv_freqproduces 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:
_move_missing_keys_from_meta_to_device()iterates ALL non-persistent buffers and replaces them withtorch.empty_like()-- this corruptsinv_freq_init_weights()tries to restoreinv_freqby checkinghasattr(module, "original_inv_freq")-- this fails for Unsloth's rope classesinv_freqstays as uninitialized memory, producing garbage positional encodingsFix: Added
_fix_rope_inv_freq()toloader.py, called at the end of bothFastLanguageModel.from_pretrained()andFastModel.from_pretrained(). It recomputesinv_freqfrom the storedbaseanddim, applies model-specific scaling via_apply_inv_freq_scaling(), and rebuilds cos/sin caches. Also handlesLongRopeRotaryEmbedding(Phi-3.5 style). Guarded bytransformers_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:This worked on transformers v4 because
generate()internally extracted the tensor. Transformers v5 calls.shapeoninput_idsdirectly, which crashes sinceBatchEncodinghas no.shapeattribute.Fix: In
unsloth_fast_generate(), detect wheninput_idsis a dict-like object (BatchEncoding) and unpack its contents into separate kwargs before forwarding to the underlyinggenerate(). 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:
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_stepsbefore reporting). Actual optimizer updates are identical.