Repository navigation
Honour YaRN passed as rope_parameters, and rope_scaling on FastModel - #15214
Conversation
transformers v5 and TRL's long-context recipe pass the RoPE override as
rope_parameters (SFTConfig(model_init_kwargs = {"rope_parameters": ...})).
FastLanguageModel ignored it, and past the checkpoint's window its automatic
linear scaling replaced the YaRN request; FastModel passed it to the model
constructor (TypeError). FastModel also dropped rope_scaling entirely, so
FastLanguageModel's full finetuning / 8-bit delegation lost it too.
rope_parameters is now read as rope_scaling in both loaders, and FastModel puts
rope_scaling on the text config before the model is built (per-layer-type
RoPE configs such as Gemma 3 need a dict keyed by layer type).
|
@codex review |
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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0b1b7f6684
ℹ️ 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 user_rope_scaling is not None: | ||
| _apply_user_rope_scaling(model_config, user_rope_scaling) |
There was a problem hiding this comment.
Forward the RoPE override to the vLLM engine too
When FastModel.from_pretrained(..., fast_inference=True, rope_scaling=yarn) is used, this now changes the Hugging Face configuration but removes the override from kwargs. The vLLM branch builds load_vllm_kwargs from those remaining kwargs, so it never passes load_vllm's explicit rope_scaling argument. That utility reads the checkpoint configuration independently and only applies the override through that argument. Consequently, the reconstructed training model uses YaRN while fast_generate uses the checkpoint's original RoPE, producing inconsistent rollout and training probabilities. Forward the normalized override to load_vllm as well.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in b3fab69: FastBaseModel.from_pretrained now forwards the caller's override to load_vllm(rope_scaling = ...), so fast_generate runs the same RoPE as training. Overrides vLLM cannot take (one RoPE setting per layer type, or an unsloth_zoo whose load_vllm has no rope_scaling argument) are refused before any weights load, pointing to fast_inference = False. The test checks both the refusal and that load_vllm_kwargs receives the override.
| "Unsloth: this model keeps one RoPE setting per layer type " | ||
| f"({sorted(current)}); pass rope_scaling as a dict keyed by those layer types." | ||
| ) | ||
| target.rope_parameters = {k: dict(v) for k, v in scaling.items()} |
There was a problem hiding this comment.
Preserve each layer type's base when replacing nested RoPE
For a transformers v5 Gemma 3 config, a layer-keyed override such as {"full_attention": {"rope_type": "yarn", "factor": 4.0}, "sliding_attention": {"rope_type": "default"}} passes this validation but replaces both existing dictionaries without their rope_theta values. Unlike the flat path, this bypasses both _user_rope_scaling and the patched rope_scaling setter that preserves existing bases. Gemma 3's default rotary initialization directly indexes config.rope_parameters[layer_type]["rope_theta"], so loading fails with KeyError for the sliding-attention entry. Carry the existing per-layer bases into entries that omit them before assigning the replacement.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in b3fab69: per-layer-type entries now start from the existing rope_theta / partial_rotary_factor of that layer type, and the caller's keys override them. The test covers your example ({"full_attention": {"rope_type": "yarn", "factor": 4.0}, "sliding_attention": {"rope_type": "default"}}), which failed on the previous head and keeps both bases now.
|
@codex review |
|
Codex Review: Didn't find any major issues. You're on a roll. 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". |
…o Gemma 3 full attention, forward the applied dict to vLLM [skip ci]
|
@codex review |
|
@codex review |
|
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". |
|
The 23 That test lifts the loader's precision / download code out of |
|
@codex review |
|
Codex Review: Didn't find any major issues. Swish! 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". |
…evice index as CUDA in the YaRN load check (#15351) ## Problem Two tests in the `Repo tests (CPU, rest)` shard fail on main itself, so every PR based on it inherits them (seen on #15326 and #15339). Both are test bugs; the product code they guard is fine. **1. `tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding`** ``` Pass encoding = "utf-8": ['tests/test_parallel_general_gloo.py:732: open()'] ``` #15230 added `test_every_whole_model_export_is_guarded`, which reads `unsloth/save.py` with a bare `open(...).read()`. That uses the locale encoding, which on Windows is the ANSI codepage. The read now names `encoding = "utf-8"` and closes the file. **2. `tests/test_yarn_rope_parameters_load.py::test_yarn_reaches_the_model[lang-*]`** ``` RuntimeError: Cannot access accelerator device when none is available. ``` #15214 added this subprocess check. It runs FastLanguageModel on a spoofed CUDA box and sends CUDA tensor allocations to the CPU through an `_is_cuda(device)` helper. The rotary embedding allocates with `device = get_current_device()`, which is a bare index (`0`). The helper called `torch.device(0)`, and on CPU-only torch 2.10 that resolves the index through the accelerator and raises before the YaRN assertion is reached. The `model` cases passed only because that path does not allocate with a bare index. A bare int is now treated as a CUDA ordinal without asking torch, and strings and `torch.device` values go through `torch.device(...)` as before. ## Verification - On main: `test_source_read_encoding.py` 1 failed and `test_yarn_rope_parameters_load.py` 2 failed. The yarn test also fails at #15214's own merge commit (801ba6d), and #15214 never ran a `rest` shard. - With this change: - `test_source_read_encoding.py`: 16 passed - `test_yarn_rope_parameters_load.py`: 5 passed - `test_parallel_general_gloo.py::test_every_whole_model_export_is_guarded`: passed - Sabotage: with FastLanguageModel's `_fold_rope_parameters` call replaced by `rope_scaling = None`, both `lang` cases now fail on the YaRN assertion itself (`{'type': 'linear', 'factor': 4.0, ...}`). Before this change they crashed first, so they could not catch a dropped YaRN.
TRL's long-context guide enables YaRN with
SFTConfig(model_init_kwargs = {"rope_parameters": {"rope_type": "yarn", "rope_theta": ..., "factor": 4.0, "original_max_position_embeddings": 40960}}), which is the transformers v5 spelling. Under Unsloth the same dict is passed tofrom_pretrained, and on main:FastLanguageModel.from_pretrained(..., rope_parameters = yarn)ignores it. Oncemax_seq_lengthis past the checkpoint's window (the whole point of YaRN), the automatic linear scaling is applied instead, so the model trains with linear factor 4 and no attention factor.FastModel.from_pretrained(..., rope_parameters = yarn)raisesTypeError: Qwen3ForCausalLM.__init__() got an unexpected keyword argument 'rope_parameters'.FastModel.from_pretrained(..., rope_scaling = yarn)silently drops it (the argument was marked "No effect"), so the model keeps plain RoPE. FastLanguageModel's full finetuning and 8-bit paths delegate to FastModel, so they lostrope_scalingtoo.FastLanguageModel.from_pretrained(..., rope_scaling = yarn)was already correct.Changes:
rope_parametersasrope_scaling. Passing both with different values raises.rope_scalingdown, and FastBaseModel puts it on the text config before the model is built. The caller's keys go over the checkpoint's rotary layout keys (rope_theta,partial_rotary_factor,mrope_section,mrope_interleaved), so Qwen2-VL's multimodal sections and StableLM's partial rotary survive an override.full_attentiononly, as transformers' Gemma 3 config does; a dict keyed by layer type replaces just those entries, each keeping its ownrope_theta. A layer-type dict on a model with one RoPE setting raises a clear error.fast_inference = True: the dict applied to the model (withrope_thetaandoriginal_max_position_embeddingsfilled in) is forwarded toload_vllm, so rollouts run the same RoPE as training. Overrides vLLM cannot apply the same way (per layer type, a vision-language config whose text model holds RoPE, or an unsloth_zoo whoseload_vllmhas norope_scalingargument) are refused before any weights load.Verification, tiny Qwen3 with
max_position_embeddings = 64, YaRN factor 4, sequence 256, compared against plain transformers eager with the same YaRN config. transformers 5.17.FastLanguageModel logits on GPU in bf16 (training forward): 3.3e-3 max diff against eager bf16 with YaRN, against 0.14 when YaRN is dropped. For scale, YaRN against no YaRN in plain transformers differs by 0.17.
tests/test_yarn_rope_parameters_load.pyloads the tiny Qwen3 on CPU through both loaders with both spellings and checks the config and the built rotary (rope type and attention factor 0.1 * ln(4) + 1), plus the layout-key, per-layer-type and vLLM forwarding rules. On main 4 of its 5 tests fail; with this PR all 5 pass on transformers 5.17, and 3 pass, 2 skipped (the v5 spelling) on 4.57.6.Simulation on tiny models, CPU, both transformers 4.57.6 and 5.17: every load without a RoPE kwarg is unchanged (52 of 52 cells, 34 with bitwise logits), FastLanguageModel
rope_scalingis unchanged (8 of 8), and FastModel YaRN matches plain transformers YaRN to 5.6e-8 in logits. Tiny Qwen2-VL (both versions), StableLM and Gemma 3 with a flat YaRN dict load and run with their layout keys kept. The neighbouring rope and config tests (test_remote_rope_scaling_none,test_legacy_config_type_coercion,test_omni_text_only_load,test_validate_rope_ignore_keys) pass.Not covered: a real vLLM run of FastModel with
fast_inference = True(the forwarded dict was checked against unsloth_zoo'sload_vllmoverride code, not run), and real-size checkpoints.