Skip to content

Keep every nested RoPE base, and never put a per-label mapping in rope_theta - #11192

Merged
danielhanchen merged 2 commits into
mainfrom
rope-per-layer-carry-fix
Sep 17, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
rope-per-layer-carry-fix

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

#11037 taught the rope_scaling alias setter to carry the RoPE base frequency across an assignment. On a config whose rope_parameters is a NESTED per-label dict, that carry does two wrong things. Both are on main now.

Defect 1: a per-label mapping lands in the scalar rope_theta slot

_rope_theta_snapshot returns a {label: base} MAPPING when the parameters are nested, because that is the shape the bases live in. _carry_per_layer_rope_theta puts that mapping back one level down and returns None when it wrote nothing, and "every entry already names its own base" is one of the three reasons it answers None.

_carry_rope_theta_across_assignment reads that None as "no nested snapshot to restore, fall through", and the fall-through treats carried as a scalar base (import_fixes.py:1027-1032, then 1065-1067). So the mapping is assigned to config.rope_theta.

The result on transformers 5.17.0, assigning a T5Gemma2DecoderConfig its own parameters back:

import copy
from transformers.models.t5gemma2.configuration_t5gemma2 import T5Gemma2DecoderConfig

c = T5Gemma2DecoderConfig()
c.rope_scaling = copy.deepcopy(c.rope_parameters)
merge base of #11037 main (#11037 merged) this branch
c.rope_theta attribute absent {'sliding_attention': 10000.0, 'full_attention': 1000000.0} attribute absent
serialized config unchanged gains a "rope_theta" OBJECT unchanged

to_json_string() on main now contains:

"rope_theta": {
  "full_attention": 1000000.0,
  "sliding_attention": 10000.0
}

where a number belongs, on a config that had no rope_theta key at all. This is a regression #11037 introduced: the merge base adds no attribute and serializes identically, and it contradicts the no-op that #11037 claims for parameters that are already complete.

Defect 2: the nested discriminator misreads four real model families as flat

This is the more serious of the two. _rope_parameters_are_per_layer decided nested-vs-flat from config.layer_types with a subset test (import_fixes.py:945,949). transformers resolves the nesting axis differently:

# transformers 5.17.0 modeling_rope_utils.py:776-785, standardize_rope_params
# Deepseekv4 has `layer_types` which are different from `_rope_type_labels`
layer_types = getattr(self, "_rope_type_labels", getattr(self, "layer_types", None))
...
elif layer_types is None or rope_parameters == {} or set(rope_parameters.keys()).isdisjoint(layer_types):

_rope_type_labels comes first, and the test is isdisjoint, not issubset. DeepseekV4Config keys its rope by rope-type label while its layer_types names attention blocks (configuration_deepseek_v4.py:193-198):

_rope_type_labels = ("main", "compress")

So unsloth read a DeepSeek V4 config as flat: it took no nested snapshot, and it wrote a top-level rope_theta INTO the nested dict, which is exactly the "makes transformers read the whole thing as flat" failure the helper's own docstring warns about.

issubset versus isdisjoint is not a corner case either. A config may declare bases for more labels than its default layer_types actually uses, and three families ship exactly that on 5.17.0:

config rope keys default layer_types issubset not isdisjoint
laguna full_attention, sliding_attention ['full_attention'] False True
mellum full_attention, sliding_attention ['full_attention'] False True
zaya hybrid, hybrid_sliding ['hybrid'] False True

I swept every config class in CONFIG_MAPPING on 5.17.0. Of the 16 that ship a nested rope dict, four lose every base under the subset-only discriminator and none do after this change:

config      true bases                                     main                          this branch
deepseek_v4 {'main': 10000.0, 'compress': 160000.0}        both None + stray rope_theta  preserved
laguna      {'full_attention': 500000.0, 'sliding': 1e4}   both None                     preserved
mellum      {'full_attention': 500000.0, 'sliding': 1e4}   both None                     preserved
zaya        {'hybrid': 5000000.0, 'hybrid_sliding': 1e4}   both None                     preserved

Those None bases are not cosmetic. They are the failure #11037 exists to prevent, still live on main. Laguna, end to end on 5.17.0:

             main (#11037 merged)                       this branch
after assign {"full_attention": {"factor": 4.0,         {"full_attention": {"factor": 4.0,
              "rope_type": "linear"}, ...}               "rope_theta": 500000.0, ...}, ...}
standardize  "rope_theta": null                         "rope_theta": 500000.0
rope init    TypeError: unsupported operand type(s)     OK, inv_freq[0] = 0.25
             for ** or pow(): 'NoneType' and 'Tensor'

On transformers 5.17.0, replacing the per-label scaling on DeepSeek V4:

from transformers.models.deepseek_v4.configuration_deepseek_v4 import DeepseekV4Config

d = DeepseekV4Config()          # main 10000.0, compress 160000.0
d.rope_scaling = {"main": {"rope_type": "linear", "factor": 4.0},
                  "compress": {"rope_type": "default"}}
d.standardize_rope_params()
main (#11037 merged) this branch
rope_parameters top level gains a stray "rope_theta": 10000.0 no stray key
compression base 10000.0 (was 160000.0) 160000.0
main base 10000.0 10000.0

The base loss itself also happens on plain transformers with no unsloth patch at all, so that half is not a regression #11037 introduced. The point is that the carry exists to repair exactly this and did not, and that on DeepSeek V4 it additionally corrupted the dict. Both are fixed here.

The fix

unsloth/import_fixes.py, three changes, no behaviour change for any shape that already worked.

  1. New _rope_nesting_labels(config) mirrors transformers' own resolution, _rope_type_labels first with a sentinel so an explicitly None value is respected, falling back to layer_types. _rope_parameters_are_per_layer now uses it and switches issubset to not isdisjoint, so the predicate is spelled the same way transformers spells it.

  2. In the nested branch of _carry_rope_theta_across_assignment, when nothing was restored and carried is a mapping, return instead of falling through. A {label: base} mapping is meaningful only one level down; there is no scalar to fall through with, whether the reason was "nothing needed restoring" or "the write was refused".

  3. A isinstance(base, dict) guard immediately before the writes. A base frequency is a number, so no path can put a mapping in the scalar slot again.

The existing precedence is untouched: the new parameters' base, then the config's own, then what was carried. A per-layer replacement with a SCALAR carried base still sets config.rope_theta, which is where standardize_rope_params reads the base it hands to each label.

Tests

Five added to tests/test_import_fixes_drift.py, next to #11037's own helper test.

  • test_rope_theta_carry_never_puts_a_per_label_mapping_in_the_scalar_slot (defect 1, helper level, plus a config that refuses the nested write)
  • test_rope_theta_carry_follows_rope_type_labels_not_only_layer_types (defect 2, the _rope_type_labels half, including a genuinely flat replacement over the same config)
  • test_rope_carry_handles_rope_labels_not_all_present_in_layer_types (defect 2, the issubset vs isdisjoint half, which is the laguna / mellum / zaya shape)
  • test_rope_carry_on_the_real_nested_configs (both defects on the real T5Gemma2DecoderConfig and DeepseekV4Config, asserting to_json_string() is byte-identical across the no-op assignment)
  • test_rope_carry_keeps_every_nested_base_on_every_real_config sweeps CONFIG_MAPPING rather than naming models, so a new model with a nested rope dict is covered the day it lands

Plus one pin, test_rope_carry_leaves_the_zoo_gemma_local_base_alone_on_a_real_config: unsloth_zoo/empty_model.py:915-919 sets Gemma's LOCAL rotary base and then replaces the scaling, and that stated base must survive the carry. It passes on main and on this branch; it is here so the carry cannot be loosened later without noticing.

All five fail on main and pass here. On main, transformers 5.17.0:

FAILED test_rope_theta_carry_never_puts_a_per_label_mapping_in_the_scalar_slot
  AssertionError: the carry reported it carried a base across an assignment that lost nothing
  assert {'sliding_attention': 10000.0, 'full_attention': 1000000.0} is None

FAILED test_rope_theta_carry_follows_rope_type_labels_not_only_layer_types
  AssertionError: rope keyed by _rope_type_labels was read as a flat dict

FAILED test_rope_carry_handles_rope_labels_not_all_present_in_layer_types
  AssertionError: a nested rope dict was read as flat because one of its labels is
  absent from layer_types; transformers asks isdisjoint, not issubset

FAILED test_rope_carry_on_the_real_nested_configs
  AssertionError: T5Gemma2 rope_theta became a mapping:
    {'sliding_attention': 10000.0, 'full_attention': 1000000.0}

FAILED test_rope_carry_keeps_every_nested_base_on_every_real_config
  AssertionError: a per-label scaling replacement lost bases on
  ['deepseek_v4', 'laguna', 'mellum', 'zaya'] (checked 16 nested configs)

Test results

tests/test_import_fixes_drift.py, tests/utils/test_rope_scaling_drift.py, tests/test_triton_optional_import.py, tests/test_longrope_short_long_boundary.py, tests/test_callback_signature_drift.py, tests/utils/test_attn_mask_upstream_drift.py, tests/notebooks/test_colab_oracle_drift.py, tests/test_offload_device_property.py, on transformers 5.17.0:

result
main, unmodified 121 passed, 5 skipped, 0 failed
main, with the six new tests 122 passed, 5 skipped, 5 failed
this branch 127 passed, 5 skipped, 0 failed

No pre-existing failure in the touched area; the only failures anywhere are the five new tests against main. The sixth new test is the zoo Gemma pin, which passes on both.

Compatibility

One venv per transformers minor, python 3.13 / torch 2.11.0, running the four files #11037 touched or added:

transformers result
4.57.6 patch stays a NO-OP: no rope_scaling property to own, probe reports the base is not dropped, setter not patched, a replaced rope_scaling still leaves rope_theta == 500000.0
5.0.0, 5.1.0, 5.2.0, 5.3.0 pass
5.4.0, 5.5.4, 5.6.2, 5.7.0 pass
5.8.1, 5.9.0, 5.10.4, 5.11.0 pass
5.12.1, 5.13.1, 5.14.1, 5.15.1 pass
5.16.1, 5.17.0 pass

Alongside the suites, the two reproductions were run on each version. T5Gemma2DecoderConfig exists from 5.0.0, so defect 1 is reachable across the whole 5.x range and is repaired on all of it. DeepseekV4Config first appears in 5.8.1, and defect 2 is repaired on every version from there. The helper-level tests for both run everywhere, including where the model classes do not exist.

On 4.57.6 the no-op was verified rather than assumed: there is no rope_scaling property to own, the probe reports the base is not dropped, the setter is left unpatched, and a replaced rope_scaling still leaves rope_theta == 500000.0.

Note on #11037's Fixes #2405

Unrelated to the code here, worth recording: #2405 was closed as COMPLETED by #6197 on 2026-06-11, three months before #11037 was opened, and GitHub records #6197 as its closer. #11037's merge did not and could not close it. #2405 was also filed 2025-04-24, when the newest transformers was 4.51.3, and the rope_scaling alias property together with the move of rope_theta into rope_parameters first shipped in 5.0.0 on 2026-01-26 and is absent from every 4.x through the final 4.57.6. The accurate description of #11037 is that it hardens the transformers-5 behaviour of the code path #6197 added, not that it fixes #2405.

Refs #11037.

…e_theta

#11037 taught the rope_scaling alias setter to carry the RoPE base frequency
across an assignment. On a config whose rope_parameters is a NESTED per-label
dict it does two wrong things, both on main now.

First, _rope_theta_snapshot returns a {label: base} MAPPING for nested
parameters, and _carry_per_layer_rope_theta answers None for three different
reasons, one of which is the no-op "every entry already names its own base".
_carry_rope_theta_across_assignment read that None as "nothing nested to
restore, fall through" and the fall-through treated the mapping as a scalar, so
it landed in config.rope_theta. A T5Gemma2DecoderConfig assigned its own
parameters back now serializes a rope_theta OBJECT where a number belongs, on a
config that previously had no such key at all. The merge base of #11037 adds no
attribute and serializes identically, so this is a regression, and it
contradicts the no-op #11037 claims for already-complete parameters.

Second, _rope_parameters_are_per_layer decided nested-vs-flat from layer_types
alone with a subset test. transformers resolves the nesting axis as
getattr(self, "_rope_type_labels", getattr(self, "layer_types", None)) and asks
isdisjoint, not issubset. Both halves of that difference matter: DeepSeek V4
keys its rope by rope-type label (main / compress) while its layer_types names
attention blocks, and laguna, mellum and zaya each declare a base for a label
their default layer_types does not list. All four were read as flat, so no
nested snapshot was taken and every per-label base went to None, which is the
TypeError: unsupported operand type(s) for ** or pow(): 'NoneType' and 'Tensor'
this patch exists to prevent. On DeepSeek V4 a top-level rope_theta was also
written INTO the nested dict.

The fix is three changes. _rope_nesting_labels mirrors transformers' own
resolution, _rope_type_labels first with a sentinel so an explicitly None value
is respected; _rope_parameters_are_per_layer uses it and spells the predicate
the way transformers spells it. The nested branch returns instead of falling
through when carried is a mapping and nothing was restored. An isinstance check
before the writes makes "a base frequency is a number" structural.

Precedence is untouched, so a per-layer replacement with a scalar carried base
still sets config.rope_theta, and the zoo's deliberate Gemma local base still
wins.

Tests, next to #11037's own: the two defects at helper level, both on the real
config classes, and a sweep of CONFIG_MAPPING so a new model with a nested rope
dict is covered the day it lands. Five of the six fail on main. The sixth pins
unsloth_zoo/empty_model.py's Gemma local rotary base, which passes on both.

Verified one venv per transformers minor: 4.57.6 stays a no-op, and 5.0.0
through 5.17.0 all pass.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 17, 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-09-17T11:25:58.047784Z f2b87ca Manual request
🔒 Security Review ✅ Completed 2026-09-17T11:26:16.817826Z f2b87ca 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: f2b87ca218

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

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: f2b87ca218

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

@danielhanchen
danielhanchen merged commit 14be511 into main Sep 17, 2026
16 of 27 checks passed
@danielhanchen
danielhanchen deleted the rope-per-layer-carry-fix branch September 17, 2026 11:45
Stanley00 pushed a commit to stanley-fork/unsloth that referenced this pull request Sep 17, 2026
* Repair the three checks that went red on main today

All three reproduce on a clean origin/main (1d5210d) and none needs a product
behaviour change, but they do not share a cause, so each is attributed here.

install.ps1, studio/setup.ps1: unslothai#10533 added a comment naming an antivirus vendor
to Get-SecuritySoftwareNote. The ban on vendor names in shipped scripts landed
two days earlier in unslothai#10978, and it is not a style rule: PowerShell hands the
entire top-level script block to the scanner at compile time, so comments are
classifier input, and VirusTotal's analysis of install.ps1 quoted one of our own
comments back as grounds for suspicion. The knowledge is moved rather than
deleted, into AV_SHAPES_RECORD, which is where the guard's failure message says
it belongs and which now records what each suite calls its protected-folders
feature. The function never hard-coded a product name; it reads what
SecurityCenter2 registered, and that is now said where the list used to be.

tests/test_apply_qkv_fallback.py, tests/test_lora_dropout_patch_summary.py:
unslothai#11038 added two skip guards reading torch.cuda.is_available(), which
tests/_zoo_aggressive_cuda_spoof.py patches True process-wide and never puts
back. A skipif is evaluated at import, so either file sharing a session with
tests/version_compat or tests/vllm_compat un-skips on a CPU-only box and dies
inside torch. They go through tests/_shared/real_accelerator.py instead, which
records the answer before any spoof can run. test_apply_qkv_fallback_end_to_end
allocates on "cuda" by name, so it takes has_real_cuda rather than the broad
probe, which is also true on an XPU-only or Ascend NPU-only host.

tests/python/test_docker_hub_readme.py: here the test was wrong, not the README.
It took the first "#### Docker" heading and read to the next "####". The README
grew a second Docker heading above the one carrying the run command, so the pins
read a one-line pointer that was never meant to hold a docker run. It now picks
the section by content and requires exactly one section to carry a run command,
in both directions: zero is the regression it was written for, and more than one
means two places tell the user how to start the image while only one is pinned.
The stale-token check widened from that one section to every Docker section.

* Let the save-signature probe resolve the import unslothai#11067 deferred

Fourth check red on main today, in the (CPU, rest) shard: five failures in
tests/test_st_save_merged_signature.py, all KeyError: "'__name__' not in
globals".

unslothai#11067 put `from ..save import _is_adapter_save_method` inside
_save_pretrained_merged, deferred on purpose because a module-scope bind out of
unsloth.save closes an import cycle. This file reads the two closures out of the
source and execs them so the assertions run without importing unsloth, and a
bare globals dict has no __name__ or __package__ for a relative import to
resolve against, so every test that calls the body died on the import rather
than on what it was checking.

Satisfying it by importing unsloth would give up what the file is for, so the
harness now stands up a package of its own holding the REAL helper, pulled from
unsloth/save.py by source the way _normalize_save_method already is. The import
executes and binds the shipped function, so its spelling rules still reach these
tests; neutering that function fails three of them, which is how I checked the
resolution is not cosmetic.

That unmasked a second mismatch the import error was hiding.
test_the_forwarding_path_still_accepts_lora asserted that "lora" is accepted
when modules.json is present. unslothai#11067 deliberately retired that premise:
save_pretrained_merged writes a loadable SentenceTransformer and an adapter-only
save has no base weights for one, where previously "lora" matched no branch in
merge_and_overwrite_lora and fell through to a 16bit merge that happened to
write something loadable for a request that asked for adapters. Taking the
product as correct, the test now pins the new refusal.

The invariant it was really protecting survives and is what is checked: the
no_modules refusal must not leak into the branch that has modules.json. Both
paths raise now, so a bare pytest.raises would no longer notice one borrowing
the other's reason; the messages are pinned apart, and a second test holds the
pair distinct, which neither can see on its own.

* Drop the torch import the skip-guard fix left unused

Source lint caught it: tests/test_lora_dropout_patch_summary.py imported torch
only for the torch.cuda.is_available() in the guard this PR replaced, so the
import was left bound and unused. The sibling file still uses torch eleven
times and keeps its import.

* Let the rope carry drift tests run on a transformers that has no rope_parameters

Fifth check red on main, in Core (HF=4.57.6 + TRL<1). Both tests from unslothai#11192
assume transformers 5's config.rope_parameters and fail on the 4.x job:

  test_rope_carry_keeps_every_nested_base_on_every_real_config
    AssertionError: no config with a nested rope dict was found to check
  test_rope_carry_leaves_the_zoo_gemma_local_base_alone_on_a_real_config
    AttributeError: 'Gemma2Config' object has no attribute 'rope_parameters'

Both reproduce locally on transformers 4.57.6, the same pin that job resolves.

The second is a one word fix. It already treats rope_parameters as optional, via
an isinstance check, but read it with attribute access, and 4.x raises rather
than returning None, so the tolerance was unreachable. getattr with a default.

The first swept for nested rope dicts and asserted it found at least one. On 4.x
there is no rope_parameters at all, so the sweep is empty and the assert fires.
The two cases are now told apart: no rope_parameters anywhere is 4.x, where this
carry does not exist and there is nothing to damage, and skips with that reason;
the attribute present but no nested config is still drift and still fails.
Collapsing them would either red the 4.x job forever or silently stop testing
5.x.

Checked in both directions rather than assumed. On 4.57.6 the skip fires and the
Gemma test passes. On 5.17.0 the skip does not fire and the sweep finds 16
nested configs, including the four the docstring names: deepseek_v4, laguna,
mellum and zaya.

Also stopped the sweep being ended by an unrelated optional dependency.
CONFIG_MAPPING is lazy, so .items() imports every config module to hand back the
classes, and one model whose module needs something missing takes the whole
sweep down before the loop body runs. Seen with transformers.models.gemma3n,
which imports timm.data.ImageNetInfo and raises on a timm that does not export
it. Iterating keys and resolving inside the existing try skips that model, which
is right: a config that cannot be built here cannot be the one that regressed.

* Stop one test's account fence deciding another test's assertions

tests/multi_account/test_routing_invariance.py::test_owner_routing_facts_and_shared_queue
failed in Repo tests (CPU, rest) on

  assert active_generations._FENCED == set()

carrying an account id it never created. It passed when run alone, passed on
some pull requests and failed on others, which is the shape that eventually gets
a real test deleted for being flaky.

state.active_generations keeps _ACTIVE and _FENCED on the module, so they are
process-global and outlive the test that wrote them. Retiring or deactivating an
account fences it, and staying fenced is the CORRECT end state for those tests,
so none of them is at fault. What was missing is isolation, the same way a tmp
dir is isolated rather than every test being asked to clean up after itself.

Measured rather than guessed: a report-only probe over the backend suite names
15 leakers, in test_job_accounts.py, test_account_storage.py,
test_account_integration_wiring.py and test_account_retired_workspace_recreated.py.
Whichever of them landed in an xdist worker ahead of the routing test decided its
assertion.

So the reset goes in conftest as an autouse fixture, before and after each test,
using the reset_for_tests() the module already ships for exactly this. Before AND
after: clearing only on the way in leaves the last test of a worker holding a
fence, and clearing only on the way out trusts every other plugin to have left it
alone. The files that already reset around themselves keep doing so; resetting
twice costs nothing and the local call documents the intent at its own site.

Reproduced before fixing, and confirmed by differential. Running the four leaker
files together with the routing test:

  pristine main   3 failed, incl. test_owner_routing_facts_and_shared_queue
  with this fix   2 failed, that one gone

The remaining two are an unrelated rag_db pair that fails identically on main in
this environment.

test_generation_state_isolation.py guards the repair. The structural check reads
conftest rather than exercising ordering, because observing a leak functionally
would require assuming test ORDER and this suite runs under pytest-randomly,
where a test may not assume it. Dropping autouse from the fixture fails that
check, which is how I confirmed it is not decorative.
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…e_theta (unslothai#11192)

* Keep every nested RoPE base, and never put a per-label mapping in rope_theta

unslothai#11037 taught the rope_scaling alias setter to carry the RoPE base frequency
across an assignment. On a config whose rope_parameters is a NESTED per-label
dict it does two wrong things, both on main now.

First, _rope_theta_snapshot returns a {label: base} MAPPING for nested
parameters, and _carry_per_layer_rope_theta answers None for three different
reasons, one of which is the no-op "every entry already names its own base".
_carry_rope_theta_across_assignment read that None as "nothing nested to
restore, fall through" and the fall-through treated the mapping as a scalar, so
it landed in config.rope_theta. A T5Gemma2DecoderConfig assigned its own
parameters back now serializes a rope_theta OBJECT where a number belongs, on a
config that previously had no such key at all. The merge base of unslothai#11037 adds no
attribute and serializes identically, so this is a regression, and it
contradicts the no-op unslothai#11037 claims for already-complete parameters.

Second, _rope_parameters_are_per_layer decided nested-vs-flat from layer_types
alone with a subset test. transformers resolves the nesting axis as
getattr(self, "_rope_type_labels", getattr(self, "layer_types", None)) and asks
isdisjoint, not issubset. Both halves of that difference matter: DeepSeek V4
keys its rope by rope-type label (main / compress) while its layer_types names
attention blocks, and laguna, mellum and zaya each declare a base for a label
their default layer_types does not list. All four were read as flat, so no
nested snapshot was taken and every per-label base went to None, which is the
TypeError: unsupported operand type(s) for ** or pow(): 'NoneType' and 'Tensor'
this patch exists to prevent. On DeepSeek V4 a top-level rope_theta was also
written INTO the nested dict.

The fix is three changes. _rope_nesting_labels mirrors transformers' own
resolution, _rope_type_labels first with a sentinel so an explicitly None value
is respected; _rope_parameters_are_per_layer uses it and spells the predicate
the way transformers spells it. The nested branch returns instead of falling
through when carried is a mapping and nothing was restored. An isinstance check
before the writes makes "a base frequency is a number" structural.

Precedence is untouched, so a per-layer replacement with a scalar carried base
still sets config.rope_theta, and the zoo's deliberate Gemma local base still
wins.

Tests, next to unslothai#11037's own: the two defects at helper level, both on the real
config classes, and a sweep of CONFIG_MAPPING so a new model with a nested rope
dict is covered the day it lands. Five of the six fail on main. The sixth pins
unsloth_zoo/empty_model.py's Gemma local rotary base, which passes on both.

Verified one venv per transformers minor: 4.57.6 stays a no-op, and 5.0.0
through 5.17.0 all pass.

* Trim the RoPE carry comments to the facts the code cannot state

---------

Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: danielhanchen <[email protected]>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
* Repair the three checks that went red on main today

All three reproduce on a clean origin/main (1d5210d) and none needs a product
behaviour change, but they do not share a cause, so each is attributed here.

install.ps1, studio/setup.ps1: unslothai#10533 added a comment naming an antivirus vendor
to Get-SecuritySoftwareNote. The ban on vendor names in shipped scripts landed
two days earlier in unslothai#10978, and it is not a style rule: PowerShell hands the
entire top-level script block to the scanner at compile time, so comments are
classifier input, and VirusTotal's analysis of install.ps1 quoted one of our own
comments back as grounds for suspicion. The knowledge is moved rather than
deleted, into AV_SHAPES_RECORD, which is where the guard's failure message says
it belongs and which now records what each suite calls its protected-folders
feature. The function never hard-coded a product name; it reads what
SecurityCenter2 registered, and that is now said where the list used to be.

tests/test_apply_qkv_fallback.py, tests/test_lora_dropout_patch_summary.py:
unslothai#11038 added two skip guards reading torch.cuda.is_available(), which
tests/_zoo_aggressive_cuda_spoof.py patches True process-wide and never puts
back. A skipif is evaluated at import, so either file sharing a session with
tests/version_compat or tests/vllm_compat un-skips on a CPU-only box and dies
inside torch. They go through tests/_shared/real_accelerator.py instead, which
records the answer before any spoof can run. test_apply_qkv_fallback_end_to_end
allocates on "cuda" by name, so it takes has_real_cuda rather than the broad
probe, which is also true on an XPU-only or Ascend NPU-only host.

tests/python/test_docker_hub_readme.py: here the test was wrong, not the README.
It took the first "#### Docker" heading and read to the next "####". The README
grew a second Docker heading above the one carrying the run command, so the pins
read a one-line pointer that was never meant to hold a docker run. It now picks
the section by content and requires exactly one section to carry a run command,
in both directions: zero is the regression it was written for, and more than one
means two places tell the user how to start the image while only one is pinned.
The stale-token check widened from that one section to every Docker section.

* Let the save-signature probe resolve the import unslothai#11067 deferred

Fourth check red on main today, in the (CPU, rest) shard: five failures in
tests/test_st_save_merged_signature.py, all KeyError: "'__name__' not in
globals".

unslothai#11067 put `from ..save import _is_adapter_save_method` inside
_save_pretrained_merged, deferred on purpose because a module-scope bind out of
unsloth.save closes an import cycle. This file reads the two closures out of the
source and execs them so the assertions run without importing unsloth, and a
bare globals dict has no __name__ or __package__ for a relative import to
resolve against, so every test that calls the body died on the import rather
than on what it was checking.

Satisfying it by importing unsloth would give up what the file is for, so the
harness now stands up a package of its own holding the REAL helper, pulled from
unsloth/save.py by source the way _normalize_save_method already is. The import
executes and binds the shipped function, so its spelling rules still reach these
tests; neutering that function fails three of them, which is how I checked the
resolution is not cosmetic.

That unmasked a second mismatch the import error was hiding.
test_the_forwarding_path_still_accepts_lora asserted that "lora" is accepted
when modules.json is present. unslothai#11067 deliberately retired that premise:
save_pretrained_merged writes a loadable SentenceTransformer and an adapter-only
save has no base weights for one, where previously "lora" matched no branch in
merge_and_overwrite_lora and fell through to a 16bit merge that happened to
write something loadable for a request that asked for adapters. Taking the
product as correct, the test now pins the new refusal.

The invariant it was really protecting survives and is what is checked: the
no_modules refusal must not leak into the branch that has modules.json. Both
paths raise now, so a bare pytest.raises would no longer notice one borrowing
the other's reason; the messages are pinned apart, and a second test holds the
pair distinct, which neither can see on its own.

* Drop the torch import the skip-guard fix left unused

Source lint caught it: tests/test_lora_dropout_patch_summary.py imported torch
only for the torch.cuda.is_available() in the guard this PR replaced, so the
import was left bound and unused. The sibling file still uses torch eleven
times and keeps its import.

* Let the rope carry drift tests run on a transformers that has no rope_parameters

Fifth check red on main, in Core (HF=4.57.6 + TRL<1). Both tests from unslothai#11192
assume transformers 5's config.rope_parameters and fail on the 4.x job:

  test_rope_carry_keeps_every_nested_base_on_every_real_config
    AssertionError: no config with a nested rope dict was found to check
  test_rope_carry_leaves_the_zoo_gemma_local_base_alone_on_a_real_config
    AttributeError: 'Gemma2Config' object has no attribute 'rope_parameters'

Both reproduce locally on transformers 4.57.6, the same pin that job resolves.

The second is a one word fix. It already treats rope_parameters as optional, via
an isinstance check, but read it with attribute access, and 4.x raises rather
than returning None, so the tolerance was unreachable. getattr with a default.

The first swept for nested rope dicts and asserted it found at least one. On 4.x
there is no rope_parameters at all, so the sweep is empty and the assert fires.
The two cases are now told apart: no rope_parameters anywhere is 4.x, where this
carry does not exist and there is nothing to damage, and skips with that reason;
the attribute present but no nested config is still drift and still fails.
Collapsing them would either red the 4.x job forever or silently stop testing
5.x.

Checked in both directions rather than assumed. On 4.57.6 the skip fires and the
Gemma test passes. On 5.17.0 the skip does not fire and the sweep finds 16
nested configs, including the four the docstring names: deepseek_v4, laguna,
mellum and zaya.

Also stopped the sweep being ended by an unrelated optional dependency.
CONFIG_MAPPING is lazy, so .items() imports every config module to hand back the
classes, and one model whose module needs something missing takes the whole
sweep down before the loop body runs. Seen with transformers.models.gemma3n,
which imports timm.data.ImageNetInfo and raises on a timm that does not export
it. Iterating keys and resolving inside the existing try skips that model, which
is right: a config that cannot be built here cannot be the one that regressed.

* Stop one test's account fence deciding another test's assertions

tests/multi_account/test_routing_invariance.py::test_owner_routing_facts_and_shared_queue
failed in Repo tests (CPU, rest) on

  assert active_generations._FENCED == set()

carrying an account id it never created. It passed when run alone, passed on
some pull requests and failed on others, which is the shape that eventually gets
a real test deleted for being flaky.

state.active_generations keeps _ACTIVE and _FENCED on the module, so they are
process-global and outlive the test that wrote them. Retiring or deactivating an
account fences it, and staying fenced is the CORRECT end state for those tests,
so none of them is at fault. What was missing is isolation, the same way a tmp
dir is isolated rather than every test being asked to clean up after itself.

Measured rather than guessed: a report-only probe over the backend suite names
15 leakers, in test_job_accounts.py, test_account_storage.py,
test_account_integration_wiring.py and test_account_retired_workspace_recreated.py.
Whichever of them landed in an xdist worker ahead of the routing test decided its
assertion.

So the reset goes in conftest as an autouse fixture, before and after each test,
using the reset_for_tests() the module already ships for exactly this. Before AND
after: clearing only on the way in leaves the last test of a worker holding a
fence, and clearing only on the way out trusts every other plugin to have left it
alone. The files that already reset around themselves keep doing so; resetting
twice costs nothing and the local call documents the intent at its own site.

Reproduced before fixing, and confirmed by differential. Running the four leaker
files together with the routing test:

  pristine main   3 failed, incl. test_owner_routing_facts_and_shared_queue
  with this fix   2 failed, that one gone

The remaining two are an unrelated rag_db pair that fails identically on main in
this environment.

test_generation_state_isolation.py guards the repair. The structural check reads
conftest rather than exercising ordering, because observing a leak functionally
would require assuming test ORDER and this suite runs under pytest-randomly,
where a test may not assume it. Dropping autouse from the fixture fails that
check, which is how I confirmed it is not decorative.
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.

Unsloth models output gibberish on LONG inputs

2 participants