Repository navigation
Apply an explicit rope_scaling to the model and to vLLM - #13315
Conversation
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.
Codex Review SummaryThis 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. |
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| if isinstance(getattr(config, "rope_parameters", None), dict) and "rope_theta" not in scaling: | ||
| scaling["rope_theta"] = _get_rope_theta(config) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| if rope_scaling is not None: | ||
| model.config.rope_scaling = rope_scaling |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
| rope_scaling = _user_rope_scaling(model_config, rope_scaling) | ||
| model_config.rope_scaling = rope_scaling | ||
| kwargs["rope_scaling"] = rope_scaling |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| # 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 |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 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".
| # 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 |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
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.
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.
|
Codex Review: Didn't find any major issues. 🎉 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". |
|
Codex Review: Didn't find any major issues. 🚀 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". |
…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.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep them coming! 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". |
|
pre-commit.ci run |
…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.
…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]>
Fixes #3083
FastLanguageModel.from_pretrained(..., rope_scaling=...)accepted the argument but never applied it, for both the in-process load andfast_inference=True. Withfast_inference=TruevLLM kept the checkpoint's RoPE, so long-context GRPO on Qwen2.5 (YaRN past 32K) crashed during generation:Without
fast_inferencethe argument was silently dropped too: the model trained with plain RoPE.Changes in
FastLlamaModel.from_pretrained(so every model routed through it, Qwen2 included):rope_scalingis put on the config and intokwargs, so the in-process load uses it andload_vllmforwards 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).rope_scalingreplaces all ofrope_parameters, so the dict carries the config'srope_theta(without it YaRN init fails onNone ** tensor). A legacytypekey also fillsrope_type.rope_scalingis restored onmodel.config(saved configs keep it)._compute_config_rope_inv_freqruns the transformers RoPE init undertorch.device("cpu"): under the meta device load context, YaRN's internal aranges landed on meta and it warnedCould 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).original_max_position_embeddingstakes the checkpoint's window (its existing YaRN window if it has one), not the widenedmax_seq_length.linear,yarnandllama3scaling is applied. Gemma / Gemma 2, anddynamic,longropeor other types on any model, keep ignoringrope_scaling(now with a warning) and skip the automatic extension exactly as before:GemmaFixedRotaryEmbeddingdoes 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.fast_inferencenow says to passrope_scalingexplicitly.With
rope_scaling=Nonenothing 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.fast_inference=True, 52,867 token prompt,VLLM_ALLOW_LONG_MAX_MODEL_LEN=1(as in the issue)default, device-side assert< 32768yarnx4, generation completesVLLM_ALLOW_LONG_MAX_MODEL_LENUser-specified max_model_len (131072) is greater than the derived max_model_lenmax_model_len=131072, generation completes< 32768fast_inference=False,max_seq_length=65536default, rotary attention scaling 1.0yarn, rotary attention scaling 1.1386 (YaRN mscale for x4), inv_freq matches transformers' YaRNmodel.configafter afast_inferenceloaddefaultyarnTraining-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, legacytype, YaRN inv_freq equals transformers', YaRN init under a meta device context). The meta-context test fails without thetorch.device("cpu")change and the rope_theta test fails without the carry.tests/utils/test_rope_scaling_drift.pystill passes.Performance (base = main fc5cf50, head = this PR)
Exclusive B200, arms interleaved, fresh process and compile cache per run.
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 enteredtorch.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.pypasses on main and this PR; regression smoke 103 cases with nothing failing on this PR; jobssft/inference_smokeNO_REGRESSION; the new tests pass on ubuntu-latest, macos-15 and windows-latest.