Skip to content

Gemma: apply the loader's linear RoPE scaling past the native window - #18818

Merged
danielhanchen merged 6 commits into
unslothai:mainfrom
vineethsaivs:fix/gemma-linear-rope-scaling
Nov 23, 2026
Merged

danielhanchen merged 6 commits into
unslothai:mainfrom
vineethsaivs:fix/gemma-linear-rope-scaling

Conversation

@vineethsaivs

@vineethsaivs vineethsaivs commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

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 (#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 #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:

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 [Issue] protobuf version #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 [Issue] protobuf version #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 [Issue] protobuf version #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 Keep the trained RoPE scaling in merged_16bit exports 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.

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.
vineethsaivs added a commit to vineethsaivs/unsloth-zoo that referenced this pull request Nov 22, 2026
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.
@danielhanchen danielhanchen self-assigned this Nov 22, 2026
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]
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-22T16:36:30.591080Z 7c9e55b Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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: 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".

Comment thread unsloth/models/gemma.py Resolved
Comment thread unsloth/models/gemma.py Resolved
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]
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@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: 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".

Comment thread unsloth/save.py Resolved
Comment thread unsloth/save.py Resolved
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]
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@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: 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".

Comment thread unsloth/save.py Resolved
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.
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@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: 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".

Comment thread unsloth/save.py Resolved
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]
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Nice work!

Reviewed commit: 7c9e55bdff

ℹ️ 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".

@danielhanchen
danielhanchen merged commit 3588f64 into unslothai:main Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants