Repository navigation
Gemma 2 bug fixes + All RoPE Scaling Support - #736
Merged
Merged
Conversation
abiswas-realadvice
pushed a commit
to abiswas-realadvice/unsloth
that referenced
this pull request
May 14, 2026
* Update gemma2.py * Update llama.py * Update llama.py * Update gemma2.py * init * Update gemma2.py * Update gemma2.py * Update _utils.py * Update _utils.py * Update _utils.py * Update _utils.py * Update _utils.py * Update gemma2.py * Update gemma2.py * Update gemma2.py * All RoPE Scaling support * cleanup * Update llama.py * Update llama.py * Update _utils.py * Update _utils.py * exec * exec * Attention_Module * attention_module * imports * exec * Update llama.py * Update llama.py * boolean mask * revert masking * Update llama.py * Update save.py * Update llama.py * Update gemma2.py * Update gemma2.py * Update gemma2.py * Update utils.py * retry * Update gemma2.py * Update gemma2.py * Update gemma2.py * Update _utils.py * Update _utils.py * Update gemma2.py * Update chat_templates.py * Gemma 2 Ollama support * Update llama.py * Update llama.py
dayanruben
pushed a commit
to dayanruben/unsloth
that referenced
this pull request
Nov 23, 2026
…nslothai#18818) With `max_seq_length` past Gemma's native 8192 and no `rope_scaling`, `FastLanguageModel` logs "kaiokendev's RoPE scaling of X" and writes linear scaling to the config, but Gemma and Gemma 2 still train and decode with unscaled RoPE. **Cause:** since transformers 4.48 `GemmaModel` builds the rotary from the config. `patch_linear_scaling` (unslothai#736) only rewrites the attention init, so `GemmaFixedLinearScalingRotaryEmbedding` is never built, and `GemmaFixedRotaryEmbedding` reads only `rope_theta`. **Fix:** `GemmaFixedRotaryEmbedding` reads linear scaling from the config and sets `scaling_factor` before `_init_rope_cache_state`, so the per-device table and the compiled path both apply it. The subclass's duplicate `_set_cos_sin_cache` goes away. **Test:** new `test_gemma_rotary_applies_config_linear_scaling`: 4 failed on main, 6 passed after. A real `FastLanguageModel` load on the GPU code path (CUDA spoofed onto CPU as the repo's tests do; tiny Gemma and Gemma 2, native 256, `max_seq_length` 1024): cos/sin are 2.0 off transformers' linear RoPE on main and 7.6e-06 after; logits 10.6 and 8.9 off on main, under 7e-05 after. **Behavior change:** loads past the native window now apply the announced factor, as Llama, Mistral and Qwen already do. Configs without `rope_scaling` are bit-identical below the native window. Adapters trained past 8192 on older builds learned unscaled RoPE; reload them with `max_seq_length` <= 8192 to keep that. To avoid any numeric change instead, Gemma could skip the automatic extension with a warning, like unslothai#13315 does for an explicit `rope_scaling`. Merged exports (merged_16bit, GGUF) keep the scaling: with unslothai/unsloth-zoo#2636 through its export, and on an older zoo through a local config repair here; GGUF gets the llama.cpp RoPE scaling keys added. Not run: GPU kernels, vLLM, transformers 4.x. ## Verification Setup: tiny Gemma and Gemma 2 checkpoints (`trl-internal-testing`, native window 8192), loaded with `max_seq_length = 16384` and no `rope_scaling`, so the loader applies linear scaling with factor 2.0. Base is the merge base `5d68c40207`, head is this PR. **CPU, every transformers release.** Tested on 4.57.6 and on every 5.x release from 5.0.0 to 5.24.0 (46 versions), for both families and both ways the loader hands the scaling to the config: - On base, all 184 scaled cases build cos/sin with no scaling: max error 2.0 against an fp64 linear oracle in the eager table, the compiled per-position path and the decode-grown table. - On head, all three paths match the oracle to 2.4e-05. transformers' own linear rotary is at 3.7e-05. - Without scaling, all 92 tables are byte-identical between base and head (sha256). - The new test passes on 4.57.6, 5.0.0, 5.18.0 and 5.24.0. **GPU (Colab L4, transformers 4.57.6 and 5.18.0, float32).** Input is one 10240-token sequence. LoRA r=8 on all projections, 5 AdamW steps, with the same LoRA init in every arm. The reference is stock transformers + PEFT, with and without `rope_type: linear, factor 2.0`. | check | base | head | |---|---|---| | Gemma logits at 11 positions (0 to 10239) vs the scaled reference | max diff 0.081, argmax agrees 1/11 | 1.2e-06, 11/11 | | Gemma 2 logits vs the scaled reference | 0.085, 1/11 | 3.2e-07, 11/11 | | Gemma LoRA losses (scaled reference: 12.45329, 12.45317, 12.45305, 12.45294, 12.45284) | 12.45311, 12.453, 12.45288, 12.45278, 12.45268 | identical to the reference | | Gemma 2 LoRA losses (scaled reference: 12.45339, 12.45329, 12.4532, 12.45312, 12.45304) | 12.45309, 12.45298, 12.45288, 12.45278, 12.45269 | identical to the reference | | Grad norms | follow the unscaled reference | identical to the scaled reference | | `for_inference` greedy decode, 8200-token prompt + 16 tokens | 16/16 tokens match the unscaled reference | 16/16 tokens match the scaled reference | | `torch.compile(fullgraph = True)` rotary | factor 1.0 | factor 2.0, no graph break, 6.0e-08 vs eager | | Adapter save and reload at 16384 | reloads unscaled | reloads with factor 2.0, hidden states identical | | Peak memory, Gemma / Gemma 2 | 0.556 / 7.219 GB | 0.556 / 7.219 GB | Both transformers versions gave the same results. Gemma 3 and Gemma 4 load through `FastModel` with the stock rotary and no automatic extension, so this change does not touch them. ## Behaviour change for adapters trained past 8192 on earlier versions The change only affects Gemma and Gemma 2 runs with `max_seq_length` above 8192 and no `rope_scaling`. Those runs now use the linear scaling the loader already wrote to the config and announced in its log, as the Llama, Mistral and Qwen paths already do. To keep the old unscaled positions for an adapter trained that way, load with: ```python model, tokenizer = FastLanguageModel.from_pretrained( "your-gemma-adapter", max_seq_length = 16384, rope_scaling = {"type": "linear", "factor": 1.0}, ) ``` With this, the hidden states on the GPU check above were bit-identical to the previous behaviour. No environment variable is added. ## Exports and merge order - **zoo unslothai#2636 is the main export fix.** Today the merged 16-bit export writes the base checkpoint's config, which has no RoPE scaling, so a Gemma trained linear-scaled past 8192 would reload about 0.11 off in logits (measured on transformers 4.57.6, 5.18.0 and 5.24.0). zoo unslothai#2636 writes the scaling training actually used into the export. For installs on an older zoo, this PR repairs the merged config itself (see the update below), so it no longer depends on the release order for correctness. - **Cross-repo contract.** The zoo export recognises Gemma's rotary by the class name `GemmaFixedRotaryEmbedding`, and reads a `scaling_factor` attribute as proof that linear scaling was applied. This PR sets `scaling_factor` only in that case. A new test pins both, so a rename or an always-present attribute fails here first. - **Follow-up:** raise the `unsloth_zoo` floor in `pyproject.toml` once a zoo release containing unslothai#2636 exists. It is not changed here. ## Exports keep the trained RoPE (update) - **Merged 16-bit on an older unsloth_zoo.** unsloth_zoo releases without the RoPE carry-over from unslothai/unsloth-zoo#2636 write the base checkpoint's config into a merged export. So if a Gemma or Gemma 2 rotary applied linear scaling (it records `scaling_factor`), `unsloth_generic_save` now writes the trained scaling and window into the saved config.json itself: `rope_parameters` on transformers 5, `rope_scaling` on 4.x. The repaired config reloads as linear factor 2 in stock transformers 4.57.6, 5.18.0 and 5.24.0, and the rotary's `inv_freq` equals the unscaled one divided by the factor. A streamed merged upload (`push_to_hub_merged` without a revision) has no local config to fix, so on an older zoo it raises before merging and asks for a zoo upgrade or a local save. With a zoo that has the carry-over, nothing extra runs, so this PR no longer depends on the zoo release order for correctness. - **GGUF.** llama.cpp's Gemma and Gemma 2 converters write no RoPE scaling, but llama.cpp reads `<arch>.rope.scaling.type` and `<arch>.rope.scaling.factor` for every architecture, and Gemma 2 applies the factor to its sliding window layers too. `save_to_gguf` now adds both keys to the converter's output when the merged config has linear scaling, before llama-quantize runs. Every quant inherits them. Checked on the unslothai llama.cpp prebuilt b12347 with tiny Gemma and Gemma 2 at factor 2: F16, Q8_0 and Q4_K_M load with `freq_scale_train = 0.5` (and `freq_scale_swa = 0.5` on Gemma 2). Before this change, F16 and Q4_K_M loaded with 1. If the keys cannot be added, the export raises instead of shipping an unscaled GGUF. `UNSLOTH_GGUF_ALLOW_UNSCALED_ROPE=1` keeps the file anyway. - Unscaled Gemma, other architectures, and configs with factor 1.0 are untouched: their GGUF bytes and merged configs stay identical. --------- Co-authored-by: Daniel Han <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
No description provided.