Repository navigation
Gemma: apply the loader's linear RoPE scaling past the native window - #18818
Conversation
With max_seq_length above the native window and no rope_scaling, the loader writes linear scaling to the config and logs that the context was extended, but Gemma and Gemma 2 kept unscaled RoPE in training and decode. Since transformers 4.48 GemmaModel builds GemmaFixedRotaryEmbedding from the config, so patch_linear_scaling (which rewrote the rotary in the attention init) never installs GemmaFixedLinearScalingRotaryEmbedding, and the config branch read only rope_theta. GemmaFixedRotaryEmbedding now reads linear scaling from rope_scaling or rope_parameters and sets scaling_factor before _init_rope_cache_state, so the per-device table and the compiled per-position path both apply it. The scaled subclass's identical _set_cos_sin_cache override is removed; its explicit scaling_factor still wins. Unscaled configs are bit-identical to before.
The Gemma guard skipped the carry-over for every GemmaFixedRotaryEmbedding. With unslothai/unsloth#18818 the rotary applies the loader's linear scaling and records it as scaling_factor, so only skip when that factor is 1.
unsloth_zoo's merged export recognises GemmaFixedRotaryEmbedding by class name and treats a scaling_factor attribute as proof that linear scaling was applied, so it can write that scaling into the exported config. Pin both: the attribute exists only for linear configs (type or rope_type key) and carries the config's factor; default, dynamic and missing configs leave it unset. [skip ci]
|
@codex review |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5d1ddb01ae
ℹ️ 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".
An unsloth_zoo without the RoPE carry-over writes the base checkpoint's unscaled config into a merged export, so a Gemma / Gemma 2 rotary that applied linear scaling now gets it written into the saved config.json (rope_parameters on transformers 5, rope_scaling on 4.x). A streamed merged upload on such a zoo is refused before merging. llama.cpp's Gemma / Gemma 2 converters write no RoPE scaling, while llama.cpp reads <arch>.rope.scaling.* for every architecture. save_to_gguf now adds both keys to the converter output before llama-quantize, and raises if it cannot (UNSLOTH_GGUF_ALLOW_UNSCALED_ROPE=1 opts out). [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0f8f672d27
ℹ️ 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".
A non-PEFT Gemma reused from its local checkpoint stages the base config.json, which carries no scaling, so the GGUF step found nothing to record although the live rotary applied linear scaling. The factor now comes from the loaded model's rotary and is passed to save_to_gguf (gemma_linear_rope); the staged config is read only when none is given. The two rope.scaling keys are now spliced into each GGUF header in place, shifting the tensor data by a few alignment units, instead of writing a second full copy that the disk preflight never budgeted. The file is edited under a temporary name so an interrupted edit never leaves a broken GGUF behind. [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 120eeb41a2
ℹ️ 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".
A split conversion (over the converter's shard limit, e.g. Gemma 2 27B at f16) writes general.architecture and the hparams only into the first shard; later shards hold split.* keys alone. Skip those instead of failing, and still fail (unless UNSLOTH_GGUF_ALLOW_UNSCALED_ROPE=1) when no shard carries the metadata. llama.cpp's loader and llama-quantize read every key from the first shard.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bbf44e68c9
ℹ️ 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".
Appending .rope_scaling.tmp to a near-limit GGUF basename overflows a 255-byte filename limit or Windows MAX_PATH and aborts the export after conversion. Stage the edit as a short hidden sibling in the same directory. [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
With
max_seq_lengthpast Gemma's native 8192 and norope_scaling,FastLanguageModellogs "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
GemmaModelbuilds the rotary from the config.patch_linear_scaling(#736) only rewrites the attention init, soGemmaFixedLinearScalingRotaryEmbeddingis never built, andGemmaFixedRotaryEmbeddingreads onlyrope_theta.Fix:
GemmaFixedRotaryEmbeddingreads linear scaling from the config and setsscaling_factorbefore_init_rope_cache_state, so the per-device table and the compiled path both apply it. The subclass's duplicate_set_cos_sin_cachegoes away.Test: new
test_gemma_rotary_applies_config_linear_scaling: 4 failed on main, 6 passed after. A realFastLanguageModelload on the GPU code path (CUDA spoofed onto CPU as the repo's tests do; tiny Gemma and Gemma 2, native 256,max_seq_length1024): 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_scalingare bit-identical below the native window. Adapters trained past 8192 on older builds learned unscaled RoPE; reload them withmax_seq_length<= 8192 to keep that. To avoid any numeric change instead, Gemma could skip the automatic extension with a warning, like #13315 does for an explicitrope_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 withmax_seq_length = 16384and norope_scaling, so the loader applies linear scaling with factor 2.0. Base is the merge base5d68c40207, 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:
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.for_inferencegreedy decode, 8200-token prompt + 16 tokenstorch.compile(fullgraph = True)rotaryBoth transformers versions gave the same results. Gemma 3 and Gemma 4 load through
FastModelwith 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_lengthabove 8192 and norope_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:
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
GemmaFixedRotaryEmbedding, and reads ascaling_factorattribute as proof that linear scaling was applied. This PR setsscaling_factoronly in that case. A new test pins both, so a rename or an always-present attribute fails here first.unsloth_zoofloor inpyproject.tomlonce a zoo release containing [Issue] protobuf version #2636 exists. It is not changed here.Exports keep the trained RoPE (update)
scaling_factor),unsloth_generic_savenow writes the trained scaling and window into the saved config.json itself:rope_parameterson transformers 5,rope_scalingon 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'sinv_freqequals the unscaled one divided by the factor. A streamed merged upload (push_to_hub_mergedwithout 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.<arch>.rope.scaling.typeand<arch>.rope.scaling.factorfor every architecture, and Gemma 2 applies the factor to its sliding window layers too.save_to_ggufnow 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 withfreq_scale_train = 0.5(andfreq_scale_swa = 0.5on 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=1keeps the file anyway.