Skip to content

Honour YaRN passed as rope_parameters, and rope_scaling on FastModel - #15214

Merged
danielhanchen merged 9 commits into
mainfrom
dh/s6-longctx-yarn
Oct 26, 2026
Merged

danielhanchen merged 9 commits into
mainfrom
dh/s6-longctx-yarn

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 25, 2026 •

Copy link
Copy Markdown
Member

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 to from_pretrained, and on main:

  • FastLanguageModel.from_pretrained(..., rope_parameters = yarn) ignores it. Once max_seq_length is 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) raises TypeError: 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 lost rope_scaling too.

FastLanguageModel.from_pretrained(..., rope_scaling = yarn) was already correct.

Changes:

  • Both loaders read rope_parameters as rope_scaling. Passing both with different values raises.
  • FastModel passes rope_scaling down, 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.
  • Configs that key RoPE by layer type (Gemma 3 on v5): a flat dict applies to full_attention only, as transformers' Gemma 3 config does; a dict keyed by layer type replaces just those entries, each keeping its own rope_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 (with rope_theta and original_max_position_embeddings filled in) is forwarded to load_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 whose load_vllm has no rope_scaling argument) 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.

Path main this PR
FastLanguageModel, rope_parameters linear scaling, cos/sin max diff 2.14, attention factor 1.0 cos/sin max diff 0 (CPU), attention factor 1.1386
FastLanguageModel, rope_scaling cos/sin max diff 0 unchanged
FastModel, rope_parameters TypeError logits max diff 1.3e-7 (fp32, GPU)
FastModel, rope_scaling plain RoPE, logits max diff 0.17 logits max diff 1.3e-7 (fp32, GPU)

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.py loads 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_scaling is 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's load_vllm override code, not run), and real-size checkpoints.

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).
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 25, 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-25T12:09:19.727849Z 9a38986 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: 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".

Comment thread unsloth/models/vision.py Outdated
Comment on lines +4098 to +4099
if user_rope_scaling is not None:
_apply_user_rope_scaling(model_config, user_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 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 👍 / 👎.

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.

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.

Comment thread unsloth/models/vision.py Outdated
"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()}

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 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 👍 / 👎.

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.

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: b3fab69e09

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

…o Gemma 3 full attention, forward the applied dict to vLLM

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: b666b7f9ad

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

The 23 Repo tests (CPU, rest) failures here are from this PR: tests/test_optimized_precision_conflicts.py (lines 134, 152, 173, 177 and the ModelScope cases) stops with

NameError: name '_fold_rope_parameters' is not defined

That test lifts the loader's precision / download code out of unsloth/models/loader.py into its own namespace, and the new _fold_rope_parameters helper the lifted code now calls is not in it. Lifting _fold_rope_parameters alongside the other helpers (or giving the harness a stand-in) clears all 23. The Source lint red is the duplicate import fixed on main by #15239.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 9a38986e9f

ℹ️ 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 801ba6d into main Oct 26, 2026
@danielhanchen
danielhanchen deleted the dh/s6-longctx-yarn branch October 26, 2026 06:32
danielhanchen added a commit that referenced this pull request Oct 26, 2026
…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.
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.

1 participant