Skip to content

Apply an explicit rope_scaling to the model and to vLLM - #13315

Merged
danielhanchen merged 8 commits into
mainfrom
fix-3083-rope-scaling-vllm
Oct 11, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
fix-3083-rope-scaling-vllm

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 11, 2026 •

Copy link
Copy Markdown
Member

Fixes #3083

FastLanguageModel.from_pretrained(..., rope_scaling=...) accepted the argument but never applied it, for both the in-process load and fast_inference=True. With fast_inference=True vLLM kept the checkpoint's RoPE, so long-context GRPO on Qwen2.5 (YaRN past 32K) crashed during generation:

Assertion `index out of bounds: 0 <= tl.broadcast_to(tmp12, [XBLOCK]) < 32768` failed.
torch.AcceleratorError: CUDA error: device-side assert triggered

Without fast_inference the argument was silently dropped too: the model trained with plain RoPE.

Changes in FastLlamaModel.from_pretrained (so every model routed through it, Qwen2 included):

  • An explicit rope_scaling is put on the config and into kwargs, so the in-process load uses it and load_vllm forwards it to vLLM (needs Forward rope_scaling from load_vllm to vLLM unsloth-zoo#1687; with an older zoo it is not forwarded, same as today).
  • On transformers v5, assigning rope_scaling replaces all of rope_parameters, so the dict carries the config's rope_theta (without it YaRN init fails on None ** tensor). A legacy type key also fills rope_type.
  • The model rebuilt from vLLM weights takes the checkpoint config, so the caller's rope_scaling is restored on model.config (saved configs keep it).
  • _compute_config_rope_inv_freq runs the transformers RoPE init under torch.device("cpu"): under the meta device load context, YaRN's internal aranges landed on meta and it warned Could not apply RoPE scaling 'yarn' ... falling back to unscaled RoPE (the v5 repair recomputed it later, but the warning was wrong and the fallback was real anywhere that repair does not run).
  • A YaRN override without original_max_position_embeddings takes the checkpoint's window (its existing YaRN window if it has one), not the widened max_seq_length.
  • Only static linear, yarn and llama3 scaling is applied. Gemma / Gemma 2, and dynamic, longrope or other types on any model, keep ignoring rope_scaling (now with a warning) and skip the automatic extension exactly as before: GemmaFixedRotaryEmbedding does not apply config scaling and Unsloth's rotary builds one static cache (no dynamic NTK update or LongRoPE factor switch), so forwarding them to vLLM alone would make generation and training disagree.
  • The automatic-extension error for fast_inference now says to pass rope_scaling explicitly.

With rope_scaling=None nothing changes (same branch as before, no new kwargs).

Evidence

B200, vLLM 0.31.0, transformers 5.17.0, torch 2.13, unsloth/Qwen2.5-0.5B-Instruct, rope_scaling={"rope_type": "yarn", "factor": 4.0, "original_max_position_embeddings": 32768}, max_seq_length=131072. Base = main + zoo main, head = this PR + the zoo PR.

# Check main this PR
1 fast_inference=True, 52,867 token prompt, VLLM_ALLOW_LONG_MAX_MODEL_LEN=1 (as in the issue) vLLM rope default, device-side assert < 32768 vLLM rope yarn x4, generation completes
2 Same without VLLM_ALLOW_LONG_MAX_MODEL_LEN User-specified max_model_len (131072) is greater than the derived max_model_len loads, max_model_len=131072, generation completes
3 The issue's GRPO flow (40,821 token prompt, 2 steps) device-side assert < 32768 trains, loss 0.024 / -0.083, grad norm 3.89 / 3.75
4 fast_inference=False, max_seq_length=65536 config rope default, rotary attention scaling 1.0 config rope yarn, rotary attention scaling 1.1386 (YaRN mscale for x4), inv_freq matches transformers' YaRN
5 model.config after a fast_inference load default yarn

Training-side vs vLLM agreement on the last 64 prompt tokens of the 52,867 token prompt (HF forward log-probs vs vLLM prompt_logprobs): mean abs diff 0.061 (max 1.11). Control without scaling at 27,667 tokens on the same build: 0.044 (max 0.78), so the two sides agree to bf16 noise; a RoPE mismatch would be off by whole nats.

Tests: tests/utils/test_rope_scaling_user_arg.py (rope_theta kept on v5, legacy type, YaRN inv_freq equals transformers', YaRN init under a meta device context). The meta-context test fails without the torch.device("cpu") change and the rope_theta test fails without the carry. tests/utils/test_rope_scaling_drift.py still passes.

Performance (base = main fc5cf50, head = this PR)

Exclusive B200, arms interleaved, fresh process and compile cache per run.

Check main this PR
SFT step time, Qwen3-0.6B, 8 runs x 20 steps ABBA (median of run medians) 204.6 ms (178.8 to 231.3) 207.9 ms (204.2 to 210.2)
SFT loss / peak memory 0.3739 / 1.3842 GB 0.3739 / 1.3842 GB
Inference, Qwen2.5-0.5B, 5 repeats: prefill / decode tok/s, TTFT 659 / 143 / 28.1 ms 688 / 147 / 27.4 ms
Inference, Llama-3.2-1B (llama3 RoPE): prefill / decode tok/s, TTFT 1258 / 277 / 16.2 ms 1248 / 281 / 16.7 ms
RoPE cos/sin cache checksums (default, yarn, linear, llama3) reference bit-identical

inference_ab.py: NO_REGRESSION on both models (all metrics inside the noise band). The only per-call addition on the normal path is the default-device check before RoPE init, 3.1 us per cache build (a 65K cache build takes about 13 ms); nothing runs per step. An earlier revision entered torch.device("cpu") unconditionally, which cost about 70 us per YaRN / llama3 inv_freq build; it is now entered only under a non-CPU default device (the meta load context).

Also: tests/fast_inference/test_fast_inference.py passes on main and this PR; regression smoke 103 cases with nothing failing on this PR; jobs sft / inference_smoke NO_REGRESSION; the new tests pass on ubuntu-latest, macos-15 and windows-latest.

FastLanguageModel.from_pretrained(rope_scaling=...) was accepted but never
applied, so fast_inference ran vLLM with the checkpoint's RoPE and long
prompts hit a device-side assert indexing past the cos/sin cache (#3083).

Put the caller's rope_scaling on the config and in kwargs (in-process load
and load_vllm), keep rope_theta on transformers v5, restore it on the
vLLM-rebuilt model's config, and build YaRN inv_freq outside the meta
device context so it no longer falls back to unscaled RoPE.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-11T12:50:22.656791Z f9c9c36 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.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@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: df8aef32eb

ℹ️ 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/llama.py
Comment on lines +1865 to +1866
if isinstance(getattr(config, "rope_parameters", None), dict) and "rope_theta" not in scaling:
scaling["rope_theta"] = _get_rope_theta(config)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve architecture-specific RoPE parameters

When a Transformers 5 checkpoint stores an architecture invariant such as partial_rotary_factor only in config.rope_parameters, this replacement carries forward only rope_theta and permanently drops that invariant. Subsequent RoPE standardization cannot recover it, so an explicit scaling request computes inverse frequencies for the full head dimension instead of the checkpoint's partial rotary dimension, potentially causing tensor-shape failures or changing model behavior. Merge non-scaling parameters such as partial_rotary_factor from the existing dictionary rather than preserving only the base.

Useful? React with 👍 / 👎.

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.

Not reachable here: rope_scaling goes through FastLlamaModel only for llama, mistral, gemma, gemma2, qwen2 and qwen3(_moe) (loader dispatch), and none of those configs carry partial_rotary_factor; everything else is routed to FastModel, which this PR does not touch.

Comment thread unsloth/models/llama.py
Comment on lines +3449 to +3450
if rope_scaling is not None:
model.config.rope_scaling = rope_scaling

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Rebuild fast-path rotary buffers after restoring scaling

With fast_inference=True on supported Transformers 4.x versions, convert_vllm_to_huggingface builds the target with the scaled config but then copies same-shaped rotary buffers from a checkpoint-config meta model, overwriting the scaled inv_freq; the v5-only _fix_rope_inv_freq repair does not run for this environment. Assigning model.config.rope_scaling here therefore fixes serialization but not the live training model, leaving HF training unscaled while vLLM uses YaRN and corrupting policy/log-prob agreement. Reinitialize the rotary modules or their buffers after restoring the config.

Useful? React with 👍 / 👎.

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.

The copied buffer is not what training reads. LlamaRotaryEmbedding.forward / get_cached return multi_gpu_cos_cached / multi_gpu_sin_cached (plain lists, not buffers, so _copy_rotary_buffers never touches them), and every _set_cos_sin_cache call recomputes inv_freq from _unsloth_rope_config, which _reinit_rotary_embeddings set to the scaled model_config. Measured on the fast_inference path: rotary attention_scaling 1.1386 (YaRN x4) and HF vs vLLM prompt log-probs at 52.9K tokens within the same noise as an unscaled 27.7K control.

Comment thread unsloth/models/llama.py
Comment on lines +2955 to +2957
rope_scaling = _user_rope_scaling(model_config, rope_scaling)
model_config.rope_scaling = rope_scaling
kwargs["rope_scaling"] = rope_scaling

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep the native window for dynamic RoPE

When fast_inference=False, an explicit dynamic/NTK scaling request combined with max_seq_length above the checkpoint limit is forwarded alongside the later max_position_embeddings = max_seq_length override. Transformers uses max_position_embeddings as both the dynamic-update threshold and the denominator in the NTK formula, so widening it to the requested length prevents scaling from activating anywhere inside that length and silently trains with plain RoPE. Preserve the checkpoint's native window for dynamic scaling, or retain it separately when forwarding this override.

Useful? React with 👍 / 👎.

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.

Below the bar: Unsloth's rotary has no dynamic NTK path (it builds a static cos/sin cache, no dynamic_rope_update), so an explicit dynamic request ran plain RoPE before this PR too, when the argument was dropped entirely. Nothing regresses; the widened max_position_embeddings is the existing behaviour for every in-process load.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@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: df8aef32eb

ℹ️ 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/llama.py
# checkpoint's RoPE and indexes past its cos/sin cache (#3083).
rope_scaling = _user_rope_scaling(model_config, rope_scaling)
model_config.rope_scaling = rope_scaling
kwargs["rope_scaling"] = rope_scaling

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Require the zoo version that forwards RoPE scaling

With fast_inference=True in installations retaining the declared minimum unsloth_zoo>=2026.10.3 (pyproject.toml:232), this assignment still does not reach vLLM: the later forwarding loop only copies keys accepted by load_vllm, while zoo 2026.10.3's load_vllm has no rope_scaling parameter. Consequently the reported long-context path continues using the checkpoint's unscaled RoPE and can hit the same out-of-bounds device assertion. Raise the dependency floor to the first zoo release containing the companion forwarding change, or provide a compatible forwarding path here.

Useful? React with 👍 / 👎.

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.

The floor cannot point at a zoo release that does not exist yet; the release that ships this bumps the unsloth_zoo pin with it, as for every paired change. Against an older zoo the argument is simply not forwarded, which is today's behaviour, so nothing regresses in the meantime.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@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: c5b8ff74ca

ℹ️ 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/llama.py
Comment on lines +3451 to +3453
# The rebuilt model takes the checkpoint's config, so put the caller's RoPE back for saving.
if rope_scaling is not None:
model.config.rope_scaling = rope_scaling

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Persist the extended window on the rebuilt model

With fast_inference=True, explicit scaling, and max_seq_length above the checkpoint limit, this branch restores only rope_scaling; unlike the in-process branches, it never assigns the computed max_position_embeddings to model_config or model.config. The returned model and any checkpoint saved from it therefore still advertise the native short window, so a later default reload selects that shorter length and HF-side generation checks can reject sequences that this load was configured to train. Restore max_position_embeddings alongside the scaling before returning or saving the rebuilt model.

Useful? React with 👍 / 👎.

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.

Below the bar: native max_position_embeddings plus a YaRN factor is the documented config shape (Qwen's own long-context instructions), and the fast_inference path never widened max_position_embeddings before this PR either. Nothing in Unsloth's generate or training rejects sequences against it.

A YaRN override without original_max_position_embeddings inherits the
checkpoint's YaRN window before falling back to max_position_embeddings.
Gemma and Gemma 2 use GemmaFixedRotaryEmbedding, which ignores config
scaling, so an explicit rope_scaling there is warned about and ignored as
before rather than sent to vLLM alone.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Unsloth's rotary builds a static cache with no dynamic NTK update, so a
dynamic rope_scaling would reach vLLM only. Like Gemma's, it is now warned
about and ignored, and an ignored request no longer falls into the automatic
linear extension, matching the behaviour before explicit scaling was applied.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

LongRoPE switches short/long factors on sequence length and dynamic NTK
rescales per length; Unsloth's rotary builds one static cache, so either
would reach vLLM only. Accept linear, yarn and llama3; warn about and
ignore the rest as before.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 11, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: d1782e5e51

ℹ️ 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 added a commit to Imagineer99/unsloth that referenced this pull request Oct 11, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: 3feb4ec37b

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

…device

The torch.device mode routes every op through __torch_function__, which
made YaRN / llama3 inv_freq builds about 70 us slower on the common path.
Only the meta-device load context needs it.
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Oct 11, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: f9c9c36bf2

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

Copy link
Copy Markdown
Member Author

pre-commit.ci run

@danielhanchen
danielhanchen merged commit 7d2bd01 into main Oct 11, 2026
@danielhanchen
danielhanchen deleted the fix-3083-rope-scaling-vllm branch October 11, 2026 15:45
danielhanchen added a commit that referenced this pull request Oct 11, 2026
…3336)

test_torchao_fqn_alias.py (from #13308) imports a fake diffusers package from tmp_path. monkeypatch.delitem records only entries that existed, so in an xdist worker where the real diffusers had not been imported yet, the fake one stayed in sys.modules and every later test in that worker saw a diffusers without AutoencoderKLWan or its pipelines: test_video_vae_bf16_decode_rocm, test_video_backend and test_train_precision_scheme_contract fail on main and on unrelated PRs (#13315). An autouse fixture now restores the diffusers/torchao entries of sys.modules exactly after every test.

Also apply the ruff-format-with-kwargs hook to the two files #13308 added, which test_formatter_fixed_point flags on main.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 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` (#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 #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 #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 #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]>
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.

[Bug] Rope Scaling not supported on Qwen 2.5 for long context GRPO

1 participant