Skip to content

Keep the RoPE base frequency on transformers 5, and make triton optional - #11037

Merged
danielhanchen merged 12 commits into
mainfrom
pr/import-guards-devices
Sep 17, 2026
Merged

danielhanchen merged 12 commits into
mainfrom
pr/import-guards-devices

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 15, 2026 •

Copy link
Copy Markdown
Member

Summary

This pairs with unslothai/unsloth-zoo#1235, which carries the zoo half of the same work; that PR has converged.

Two import time fixes, both narrow, both with a behaviour probe rather than a version gate.

  1. On transformers 5, replacing config.rope_scaling silently drops the RoPE base frequency, so a
    Llama-3.1 style checkpoint whose scaling arrives as a config object falls back to unscaled RoPE and
    degrades past its original context. That is issue Unsloth models output gibberish on LONG inputs #2405, and it is what made
    tests/utils/test_rope_scaling_drift.py fail on transformers 5.0.0 through 5.3.0. The alias setter
    now carries the base across the assignment.
  2. unsloth/_gpu_init.py imported triton unconditionally at module scope, purely to resolve
    libcuda_dirs on CUDA hosts. The PyPI triton project publishes no Windows wheel, Windows is
    served by the separate triton-windows package, so on a CPU only Windows install import unsloth
    died there with a bare ModuleNotFoundError. That import is now optional, in the same shape as the
    bitsandbytes import a few lines below it.

Root cause

Replacing config.rope_scaling drops the base frequency (#2405)

transformers 5 moved rope_theta off the config and into config.rope_parameters, and kept
rope_scaling as an alias property whose setter replaces that whole dict
(configuration_utils.py:381-386 on 5.3.0, :461-466 on 5.4.0). Any assignment through the alias
therefore takes the base frequency with it. The only place transformers recovers it from is the 4.x
attribute, rope_theta = getattr(self, "rope_theta", None) in standardize_rope_params
(modeling_rope_utils.py:663 and :676 on 5.3.0, :660 and :673 on 5.4.0), and on transformers 5 a
LlamaConfig has no such attribute, so rope_parameters["rope_theta"] becomes None and the compute
function raises:

TypeError: unsupported operand type(s) for ** or pow(): 'NoneType' and 'Tensor'

That assignment is exactly what _compute_config_rope_inv_freq in unsloth/models/llama.py does when
config.rope_scaling arrives as a config object rather than a dict: it retries on a copy carrying the
normalized dict. The retry raises, the exception is caught, and the model falls back to unscaled RoPE,
so a Llama-3.1 style checkpoint runs with the wrong inverse frequencies and degrades past its original
context. On 4.57.6 the same retry works, because there rope_scaling is a plain attribute and
rope_theta is a separate one the assignment cannot touch.

Two things are worth stating precisely, because the visible symptom differs per minor while the cause
does not.

First, tests/utils/test_rope_scaling_drift.py fails on 5.0.0 through 5.3.0 and skips from 5.4.0
onward. 5.4.0 made every config a huggingface_hub strict dataclass
(configuration_utils.py:27, :114, :293), so a non-dict rope_parameters is refused with
StrictDataclassFieldValidationError and the object-style route the test needs cannot be built. That
is the test becoming unable to ask the question, not the answer changing.

Second, the base frequency is still dropped by a plain dict replacement on 5.4.0, 5.5.0 and 5.17.0,
measured. What differs is what happens next. On 5.4.0 and 5.5.0 rope_theta is a required key for
linear RoPE (modeling_rope_utils.py:737, raising at :923) and save-time validation was added
(configuration_utils.py:516-517), so save_pretrained raises
KeyError: Missing required keys in 'rope_parameters' for 'rope_type'='linear': {'rope_theta'}. By
5.17.0 the key is optional again, so the save succeeds and a config whose base reloads as the 10000.0
default is written out quietly instead.

The unconditional import triton at GPU init

unsloth/_gpu_init.py did a bare module level import triton. Its only consumers in that file are the
two libcuda_dirs resolution sites for the CUDA branch, plus an importlib.reload(triton) after the
ldconfig repair. PyPI's triton has no Windows wheel and the CPU torch wheels do not pull
pytorch-triton in, so the module is simply absent on a CPU only Windows install and the import raised
before any device handling ran. This was found while running PR #11015 on windows-latest.

Changes

RoPE base frequency

unsloth/import_fixes.py gains fix_transformers_rope_scaling_drops_theta, wired into
unsloth/_gpu_init.py in the first fix batch, right after fix_transformers_fully_masked_rows() and
before anything builds a config.

It replaces the rope_scaling property on whichever class in PretrainedConfig.__mro__ defines it,
reusing the original getter, deleter and docstring and wrapping only the setter. The wrapper reads the
base the parameters held before the assignment, calls the original setter unchanged, then puts the base
back. Nothing is normalized or rejected on the way in: a dict, None and a real RopeParameters all
reach the original setter exactly as before.

The base is never taken from anyone who stated one. A base the new parameters name wins, then a base the
config states for itself, then the carried one. It is written into rope_parameters, which is where
transformers 5 reads it, so the result does not depend on standardize_rope_params being called first
and validate_rope and save_pretrained see a complete dict. The top-level rope_theta attribute is
written only where it is the one slot that can hold the base, which is the non-dict replacement this
issue is about, or where it already exists and would otherwise go stale. A per-layer-type dict is
recognised with transformers' own layer_types discriminator and left alone. When the new parameters
carry their own base and the config states none, nothing is written at all, so a saved config gains no
key it did not have before and the wrapper neutralises itself on a transformers that keeps the base by
itself.

The gate is a behaviour probe, not a version comparison. It builds a small LlamaConfig with
rope_theta=500000.0 and a linear scaling, asks transformers for the inverse frequencies, does the same
on a second config after replacing rope_scaling with the normalized dict, and compares. Two configs,
because ROPE_INIT_FUNCTIONS mutates the one it is handed. A base far from the 10000.0 default, so a
silent fallback reads as a difference rather than a match. CPU device explicitly, so a
torch.set_default_device("meta") cannot turn the comparison into a false negative. Absent positive
evidence it answers no and leaves transformers alone. The probe answers no on 4.57.6, where nothing is
installed, and yes on every 5.x, and it answers no again once the fix is in.

The idempotence guard reads the live descriptor rather than a flag on the class, so a reload that
restores upstream's property is re-patched rather than skipped, and the original setter is unwrapped
through __wrapped__ before wrapping, so a second call cannot stack. Both halves of the wrapper are
guarded, since it runs inside a config setter on every model load; the original assignment itself is
not, because swallowing that would be a silent behaviour change. No file under site-packages is
touched.

import unsloth costs the same: 4.79 s and 4.84 s before, 4.71 s and 4.61 s after, on transformers
5.3.0, since transformers.models.llama is already imported by unsloth and the probe adds no import.

The triton import

  • the import is guarded, triton is bound to None when it cannot be imported, and a new module level
    TRITON_IMPORT_ERROR records the exception text, or None when the import worked.
  • one message, chosen by device state: a warning when a usable accelerator is present, because the
    fused Triton kernels really are gone, and an informational line naming triton-windows otherwise,
    which is the expected state of a CPU only install.
  • both libcuda_dirs sites tolerate triton is None, keeping the existing lambda: None default, and
    the post ldconfig retry no longer reports a missing Triton as a CUDA linking failure.
    importlib.reload(triton) runs only when the module exists.

Three CI comments said triton had to be installed because _gpu_init.py imports it unconditionally,
two of them citing a line number that had moved. The install is still needed, for a different reason,
so the comments now name that reason instead: .github/actions/core-cpu-setup/action.yml,
.github/workflows/notebooks-ci.yml and .github/workflows/workflow-trigger-lint.yml. No install list
changed.

Compatibility

transformers minors, for the RoPE fix

CPU only (CUDA_VISIBLE_DEVICES="", compile disabled, CUDA spoof on), one environment per
transformers minor, run against current main and against this branch. Every cell is pass or fail, never absent.

venv transformers torch replacement keeps the base rope scaling drift import fixes drift zoo longrope
mA 4.57.6 2.6.0 pass / pass 10P 6S / 13P 6S 1F 31P 4S / 1F 35P 4S 16P / 16P
mS_5_0 5.0.0 2.11.0 fail / pass 1F 9P 6S / 13P 6S 32P 4S / 36P 4S 16P / 16P
mS_5_1 5.1.0 2.11.0 fail / pass 1F 9P 6S / 13P 6S 32P 4S / 36P 4S 16P / 16P
mS_5_2 5.2.0 2.11.0 fail / pass 1F 9P 6S / 13P 6S 32P 4S / 36P 4S 16P / 16P
mS_5_3 5.3.0 2.11.0 fail / pass 1F 9P 6S / 13P 6S 32P 4S / 36P 4S 16P / 16P
mS_5_4 5.4.0 2.11.0 fail / pass 9P 7S / 12P 7S 32P 4S / 36P 4S 16P / 16P
mC 5.5.0 2.11.0 fail / pass 9P 7S / 12P 7S 32P 4S / 36P 4S 16P / 16P
mD 5.17.0 2.14.0 fail / pass 9P 7S / 12P 7S 32P 4S / 36P 4S 16P / 16P

Each cell is main / this branch, and the test columns are <failed>F <passed>P <skipped>S. The
branch's higher passed counts are exactly the seven new tests. mA's single failure,
test_peft_transformers_weight_conversion_importable_and_signature, is identical on both sides: it is
the declared PEFT 0.18.0 floor, where peft.utils.transformers_weight_conversion does not exist, and it
has nothing to do with this change.

The skips are pre-existing. Six in tests/utils/test_rope_scaling_drift.py on every minor are the
requires_gpu cases a CPU-only run cannot execute. The seventh, on 5.4.0 and later only, is
test_object_style_rope_scaling_on_config_delegates_correctly, which still skips there because strict
dataclass validation refuses a non-dict rope_parameters before unsloth sees it. Four in
tests/test_import_fixes_drift.py are torchvision, vllm twice and xformers not being installed in
the sweep venvs.

tests/version_compat, the whole directory, is unchanged by this branch: 30 failed, 1689 passed, 182
skipped on both sides, on transformers 5.3.0 and on 5.17.0. Those 30 are the pre-existing
test_trl_fake_train_cpu.py and test_trl_padding_free_max_length.py failures.

Two further before and after measurements, outside the test suites:

check transformers main this branch
save then reload a config after a replacement 5.0.0, 5.3.0, 5.17.0 base comes back as the 10000.0 default base kept
the same 5.4.0, 5.5.0 KeyError out of save_pretrained base kept
the same 4.57.6 base kept base kept
the real unsloth/Llama-3.2-1B-Instruct config through _compute_config_rope_inv_freq 4.57.6, 5.3.0, 5.4.0, 5.5.0, 5.17.0 matches transformers' llama3 initializer matches

The last row is there to show the normal load path is untouched: that checkpoint carries its scaling as
a dict, so it never took the retry this fixes.

The six requires_gpu cases were also run on a real device on the transformers 5.17.0 corner, which a
CPU only run cannot reach: tests/utils/test_rope_scaling_drift.py is 15 passed, 1 skipped on main and
18 passed, 1 skipped on this branch, the difference being the three new tests.

The triton guard

Three corners, cpu and gpu lanes, main against this branch. repro is a script that blocks triton
with sys.modules["triton"] = None and reports whether the failure is still the import triton inside
_gpu_init.py.

step lane mA 4.57.6 mC 5.5.0 mD 5.17.0
new test file cpu skip on main (branch only file) / pass skip / pass skip / pass
new test file gpu skip both (torch 2.6.0 has no sm_100 for this host) skip / pass skip / pass
import neighbours cpu pass / pass pass / pass pass / pass
import fixes drift cpu fail / fail, identical PEFT 0.18.0 floor failure pass / pass pass / pass
CI workflow shape suites cpu pass / pass pass / pass pass / pass
repro cpu fail / pass fail / pass fail / pass

Tests

RoPE base frequency

tests/utils/test_rope_scaling_drift.py gains three cases, none of which skip on any minor:

  1. test_replacing_rope_scaling_keeps_the_base_frequency, with a vacuity guard that a 500000.0 base
    does not match the 10000.0 default.
  2. test_reassigning_the_configs_own_rope_parameters_changes_nothing, asserting torch.equal, so the
    healthy path is pinned bit for bit on 4.x and 5.x alike.
  3. test_clearing_rope_scaling_keeps_the_base_frequency, since unscaled is not the same as unbased.

On main, 1 and 3 fail on every transformers 5 minor from 5.0.0 to 5.17.0 and pass on 4.57.6; 2 passes on
main everywhere by design. On this branch all three pass everywhere. Measured by copying the new file
into a worktree of main, so the tests ran against main's code rather than against the branch's.

tests/test_import_fixes_drift.py gains four detectors, in that file's one per fix_* style, none of
which skip:

  1. test_rope_scaling_replacement_keeps_the_base_frequency, which asks the live build whether the
    pathology is still active and cross-checks that against whether anything is installed, so it fails
    both when the fix stops working and when the two disagree.
  2. test_rope_scaling_setter_patch_is_idempotent, on the property identity and on the absence of a
    nested wrapper after a second call.
  3. test_rope_theta_carry_only_writes_when_the_base_would_be_lost, over eight parameter shapes:
    parameters that name their own base, an attribute that must be kept in step, the base being lost, an
    object-style replacement, the normalized retry that follows it, nothing to carry, a per-layer-type
    dict, and unsloth_zoo's Gemma local rotary, where rope_theta is set to rope_local_base_freq on
    purpose and must survive the replacement untouched.
  4. test_rope_scaling_patch_wired_into_gpu_init, which asserts _gpu_init.py both calls and dels it.

The repo's own test_object_style_rope_scaling_on_config_delegates_correctly, the test that was failing
on 5.0.0 through 5.3.0, now passes there.

ruff check is clean on every Python file this PR changes, under the repo's [tool.ruff] configuration.

The triton import

tests/test_triton_optional_import.py, 5 tests, the absent module simulated with
sys.modules["triton"] = None in a fresh interpreter, which is the import system's own marker for
blocked:

  1. the module level import triton is inside a try, so the guard cannot be deleted silently,
  2. the triton and TRITON_IMPORT_ERROR contract is present and triton.__version__ is still read,
  3. with Triton blocked, neither an import triton frame nor the innermost frame lies in
    unsloth/_gpu_init.py,
  4. the message names triton-windows,
  5. with Triton installed nothing changes: triton is not None and TRITON_IMPORT_ERROR is None.

All 5 fail on main and pass on this branch. Alongside them, on transformers 5.17.0:
test_allow_cpu_import_driverless.py, test_broken_tf_does_not_break_import.py,
test_import_fixes_drift.py, test_public_api_surface.py, test_collection_hygiene.py,
test_ci_repo_cpu_shards.py and test_missing_optional_dep_skips.py are 107 passed, 11 skipped, and
the four workflow shape suites are 126 passed, 1 skipped.

The two fixes were also run together on the combined branch: 70 passed, 11 skipped over the new file,
test_import_fixes_drift.py, tests/utils/test_rope_scaling_drift.py,
test_allow_cpu_import_driverless.py, test_public_api_surface.py and test_collection_hygiene.py.

Cross platform evidence

Both halves were run on GitHub hosted runners, off the main queue, with the same dependency
list and the same suites: current main on one branch and this branch on another. The base
half runs the two suites that exist on main, the head half adds the new file.

runner main this branch
ubuntu-latest pass pass, 49 passed 15 skipped
macos-15, Apple Silicon pass pass, 49 passed 15 skipped
windows-latest fail, 8 failed 30 passed 14 skipped fail, 11 failed 36 passed 17 skipped

windows-latest is where the triton defect is real, and the two columns say exactly what
changed. On main every one of those 8 failures ends at
unsloth\_gpu_init.py:396: ModuleNotFoundError: No module named 'triton'. On this branch
none of them touch _gpu_init.py at all: the guard prints "Unsloth: triton is not
available (ModuleNotFoundError: No module named 'triton') - continuing without the fused
Triton kernels", the import walks on, and what fails instead is unsloth.models.llama
reaching the Triton kernel modules. The 11 are the same 8 tests plus the 3 new RoPE tests,
all for that one remaining reason, which is the known limitation below.

On macOS the import completes without Triton, because Apple Silicon takes the MLX path and
never executes _gpu_init.py. The message test skips there with that reason rather than
asserting something the platform cannot produce.

Note on #11016

#11016 recorded this as a known limitation, naming tests/utils/test_rope_scaling_drift.py failing on
transformers 5.0.0, 5.1.0, 5.2.0 and 5.3.0 and leaving the choice between fixing the delegation and
excluding those two minors by name to a maintainer call. This PR takes the first option, so that
limitation no longer applies and no != exclusion is needed. It also answers the part of that note that
could not be settled from a passing test: 5.4.0 and later were not correct, only untested, because the
test skips there, and the same base frequency is dropped on every transformers 5 minor measured up to
5.17.0.

Known limitations

  • import unsloth still needs Triton. With the _gpu_init.py guard in place the import walks on and
    stops at the next module scope import triton, which is unsloth_zoo/compiler.py, and with that one
    guarded too, in a throwaway copy, at unsloth_zoo/loss_utils.py. After those, the Triton kernel
    modules under unsloth/kernels (several applying @triton.jit at import time) and
    from triton import __version__ in unsloth/models/llama.py and unsloth/models/vision.py are
    still unconditional. A fully Triton free import is a larger change across both repositories and is
    not claimed here. What this fixes is the first stop, which is also the only one that exists purely
    for CUDA library resolution, and the message a Windows user gets.
  • The object style rope_scaling shape stays unreachable on a config from transformers 5.4.0 onward,
    because strict dataclass validation refuses a non dict rope_parameters, so
    test_object_style_rope_scaling_on_config_delegates_correctly still skips there. The base frequency
    carry is what covers those minors, and it is measured on 5.4.0, 5.5.0 and 5.17.0.
  • transformers 5.6.0 through 5.16.1 were not run for the RoPE fix, only 5.17.0. Each per minor result
    is a result on one torch and one TRL, the versions named in the table.
  • No long context generation was run, so the reported gibberish past the original context remains the
    reporter's account. What is measured here is the inverse frequencies.
  • No Windows host was available locally. The Windows behaviour of the triton guard rests on the
    simulated absence and on cross platform staging CI, not on a real Windows box without Triton.

Fixes #2405


Review round: the RoPE carry mutated the caller's dictionary

Codex raised that restoring the base into rope_parameters also writes into the dict the caller
assigned. Reproduced before fixing, on transformers 5.0.0, 5.5.4 and 5.17.0: the setter stores
the assigned object verbatim, so one scaling dict reused across two configs (an ordinary loop
over several models) carried the FIRST config's base into it, and the second config, which
declared rope_theta=10000.0, came out with 500000.0 and nothing raised. That is silently
wrong inverse frequencies.

The base is now restored into a COPY which is assigned back to rope_parameters. Verified on
4.57.6, 5.0.0, 5.5.4 and 5.17.0: the shared dict is untouched and each config keeps its own base.

Two existing cases in test_rope_theta_carry_only_writes_when_the_base_would_be_lost asserted
the in-place write, so they were pinning the bug and would have made the fix look like a
regression. They now read the result off the config and additionally assert the dict handed in is
unchanged; case 6 is the reuse scenario itself.

unsloth/_gpu_init.py imported triton unconditionally at module scope, purely to
resolve libcuda_dirs on CUDA hosts. The PyPI triton project publishes no Windows
wheel, Windows is served by the separate triton-windows package, so a CPU only
Windows install has no triton at all and import unsloth died there with a bare
ModuleNotFoundError before any device handling ran.

The import now follows the same shape as the optional bitsandbytes import a few
lines below: it is guarded, triton is bound to None when it cannot be imported,
TRITON_IMPORT_ERROR records why, and both libcuda_dirs resolution sites tolerate
the absent module. A real accelerator with no triton warns, a CPU only host
prints the expected state and names triton-windows.

Three CI comments claimed triton had to be installed because of this
unconditional import. The install is still needed, for the Triton kernel modules
under unsloth/kernels and for unsloth_zoo, so the comments now say that instead.
transformers 5 moved rope_theta off the config and into config.rope_parameters,
and kept rope_scaling as an alias property that replaces that whole dict. Any
assignment through the alias therefore takes the base frequency with it:
standardize_rope_params refills rope_theta from getattr(self, "rope_theta", None),
which on 5.x is nothing, and _compute_linear_scaling_rope_parameters then raises
TypeError: unsupported operand type(s) for ** or pow(): 'NoneType' and 'Tensor'.

That assignment is what models/llama.py's _compute_config_rope_inv_freq does when
config.rope_scaling arrives as a config object rather than a dict: it retries on a
copy carrying the normalized dict. The retry raises, the exception is caught, and
the model falls back to unscaled RoPE, so a Llama-3.1 style checkpoint runs with
the wrong inverse frequencies and degrades past its original context. On 4.57.6
the retry works, because there rope_theta is a config attribute the assignment
cannot touch.

fix_transformers_rope_scaling_drops_theta wraps the alias setter, which is the
only place where the outgoing and the incoming parameters are both visible, and
puts the base back inside rope_parameters, where 5.x reads it. A per-layer dict is
left alone, and the config's own rope_theta attribute is written only where it is
the one slot that can hold the base, which is the non-dict replacement issue #2405
is about, or where it already exists and would otherwise go stale. A base the new
parameters name, or one the config states for itself, always wins, so Gemma's
local rotary in unsloth_zoo/empty_model.py keeps rope_local_base_freq. Nothing is
written at all when the new parameters carry their own base and the config states
none, so the wrapper neutralises itself on a transformers that keeps the base by
itself, and a saved config gains no key it did not have before.

Probe-gated on behaviour, not on a version: it replaces a scaling dict on a
throwaway LlamaConfig and compares the inverse frequencies against an untouched
one, so it no-ops on 4.57.6 and fires on every 5.x, where it was measured to fire.
On 5.4.0 and later a config refuses a non-dict rope_parameters outright, so the
object-style route is unreachable there, but the base is still dropped by a dict
assignment, and on 5.4.0 and 5.5.0 save_pretrained then raises a missing-key
KeyError instead of persisting a wrong base.

tests/utils/test_rope_scaling_drift.py gains three cases: a replacement keeps the
base, writing a config's own parameters back changes nothing, and clearing the
scaling still leaves the base readable. The first and third fail on main on every
transformers 5 minor from 5.0.0 to 5.17.0 and pass on 4.57.6.
tests/test_import_fixes_drift.py gains the fix's own detector, its idempotence
check, the carry helper over all eight parameter shapes, and the wiring check.

Fixes #2405
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 15, 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-16T11:00:52.056555Z 253b9df 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 added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 15, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 15, 2026
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 15, 2026
Apple Silicon takes the MLX path and never executes unsloth/_gpu_init.py, so the
message the guard prints is not emitted there and the assertion failed on
macos-15 for a reason that has nothing to do with the guard. The child now
reports whether _gpu_init ran, from sys.modules or from the traceback, since a
failed import drops the module again, and the message test skips with that
reason when it did not.
@danielhanchen

Copy link
Copy Markdown
Member Author

Second pass over this branch, thirty cases. Nothing needed changing here; the one edit this pass produced is to #11016's body, because this PR answers its open question.

#11016 recorded a known limitation naming tests/utils/test_rope_scaling_drift.py failing on transformers 5.0.0, 5.1.0, 5.2.0 and 5.3.0, and asked for a maintainer call between fixing the delegation and excluding those minors by name. This PR takes the first option, and the measurement across one venv per minor says so:

transformers main this branch
4.57.6 14 passed 2 skipped 17 passed 2 skipped, fix inert
5.0.0, 5.1.0, 5.2.0, 5.3.0 1 failed 15 passed 19 passed
5.4.0 through 5.17.0 15 passed 1 skipped 18 passed 1 skipped

So no !=5.2.0 or !=5.3.0 exclusion is needed. #11016's body now says that, with the numbers.

RoPE edge cases, on 4.57.6, 5.2.0, 5.5.0 and 5.17.0. On 4.57.6 there is no alias property, the probe answers False and nothing is patched, so the wrapper is genuinely inert rather than merely harmless. A replacement dict that names its own rope_theta wins, so nothing a caller said is overwritten. A per-layer rope dict, checked with a real Gemma 3 config carrying layer_types, does not acquire a global key. save_pretrained gains no key it did not have: the saved config.json key set is identical before and after an assignment on all four versions, which is the part that would otherwise leak into checkpoints. del config.rope_scaling behaves exactly as upstream does, raising "no deleter", because the wrapper passes fdel through. Assignment inside a torch.compiled function is fine. A config subclass keeps its base. Object-style rope_scaling is accepted and repaired on 5.2.0 and refused by transformers itself from 5.5.0 on with StrictDataclassFieldValidationError, which is upstream behaviour and unchanged here. The probe costs 1.4 milliseconds and import unsloth is unchanged within noise.

Idempotence is the nice detail: after patching, the probe answers False, so a second call returns early at the probe rather than at the flag, and the mark travels on the live descriptor so a reload that restores upstream's property gets re-patched instead of skipped.

Triton. With triton present, nothing changes: the module stays bound and no error is recorded. With triton blocked, _gpu_init.py no longer raises, the warning names triton-windows, and the import walks on. import unsloth still does NOT complete, stopping at unsloth_zoo/compiler.py:55 and past that at the kernel modules, which this PR's body already states plainly and which I confirmed here by blocking triton and reading the traceback. A separate cross-platform run on the #11023 branch, which lacks this guard, fails on windows-latest at unsloth\_gpu_init.py:406: import triton, so the line this PR guards is independently confirmed as the one that breaks a Windows CPU install. Resolution also confirms the premise: a bare pip install unsloth on Windows gets no triton at all, and unsloth[huggingface] gets triton-windows.

Tegra (unslothai/unsloth-zoo#1235). Board identities spoofed on a faked aarch64: Jetson Orin, Nano and Thor are excluded; DGX Spark is not, both the NVIDIA model string and an OEM board carrying nvidia,gb10; Grace Hopper GH200 and GB200 are not, and their GPUs are not integrated so the driver-side second opinion cannot fire either; Ampere Altra and Graviton are not; x86_64 answers with one string compare and never stats a path. UNSLOTH_FORCE_EXPANDABLE_SEGMENTS works in both directions and falls through to detection when unset or unrecognised. The module imports only os, platform and sys, so it really can run before torch. On macOS arm64 and Windows ARM64, where platform.machine() is in the ARM list, the POSIX board files simply do not open and the answer is False.

One residual worth writing down: a GB10 variant whose board files carried a Tegra string and carried neither gb10 nor dgx spark anywhere would be excluded wrongly. I could not find an authoritative device-tree dump for those boards, mainline carries no GB10 DT, and the OEM model strings vary, so the escape hatch is the answer there and it works.

Plus tests/test_import_fixes_drift.py and tests/test_triton_optional_import.py, 41 passed 4 skipped; the zoo suites, 42 passed; and an 8-step LoRA on Llama-3.2-1B with both branches, training to the same loss as main to three decimals with correct generation.

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 16, 2026
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 16, 2026
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 16, 2026
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 16, 2026
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 16, 2026
danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Sep 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: a99a167a97

ℹ️ 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 self-assigned this Sep 16, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 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: 07a471d840

ℹ️ 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/import_fixes.py
Comment on lines +1065 to +1066
if base is None:
base = carried

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 Avoid carrying a per-layer mapping into a scalar RoPE base

When a config currently has per-layer parameters (for example T5Gemma2) and a caller replaces them with a flat rope_scaling dict that omits rope_theta, _rope_theta_snapshot supplies carried as {layer_type: base} but the new parameters are classified as flat. This fallback therefore chooses that mapping as base, and the code below writes it to rope_parameters["rope_theta"], where Transformers expects a numeric scalar; subsequent RoPE initialization will fail when it performs arithmetic with the dict. Handle the per-layer-to-flat shape transition explicitly rather than passing the snapshot mapping through the scalar path.

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 253b9df. That was mine to fix: the snapshot can be a mapping and the scalar path below writes whatever it is handed into rope_parameters["rope_theta"], so a per-layer config replaced by a flat dict would have put a dict where transformers expects a number. The transition is now handled explicitly: a mapping whose layer types all agree on one base carries that number, and a mapping where they disagree carries nothing, since no scalar is true there and inventing one is worse than leaving the base to transformers. Tests cover both, plus a sweep asserting neither rope_parameters["rope_theta"] nor config.rope_theta is ever a dict.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 253b9df79e

ℹ️ 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 65facff into main Sep 17, 2026
26 of 29 checks passed
@danielhanchen
danielhanchen deleted the pr/import-guards-devices branch September 17, 2026 09:47
danielhanchen added a commit that referenced this pull request Sep 17, 2026
…e_theta (#11192)

* Keep every nested RoPE base, and never put a per-label mapping in rope_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.

* 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
…nal (unslothai#11037)

* Treat triton as an optional import at GPU init

unsloth/_gpu_init.py imported triton unconditionally at module scope, purely to
resolve libcuda_dirs on CUDA hosts. The PyPI triton project publishes no Windows
wheel, Windows is served by the separate triton-windows package, so a CPU only
Windows install has no triton at all and import unsloth died there with a bare
ModuleNotFoundError before any device handling ran.

The import now follows the same shape as the optional bitsandbytes import a few
lines below: it is guarded, triton is bound to None when it cannot be imported,
TRITON_IMPORT_ERROR records why, and both libcuda_dirs resolution sites tolerate
the absent module. A real accelerator with no triton warns, a CPU only host
prints the expected state and names triton-windows.

Three CI comments claimed triton had to be installed because of this
unconditional import. The install is still needed, for the Triton kernel modules
under unsloth/kernels and for unsloth_zoo, so the comments now say that instead.

* Keep the RoPE base frequency when config.rope_scaling is replaced

transformers 5 moved rope_theta off the config and into config.rope_parameters,
and kept rope_scaling as an alias property that replaces that whole dict. Any
assignment through the alias therefore takes the base frequency with it:
standardize_rope_params refills rope_theta from getattr(self, "rope_theta", None),
which on 5.x is nothing, and _compute_linear_scaling_rope_parameters then raises
TypeError: unsupported operand type(s) for ** or pow(): 'NoneType' and 'Tensor'.

That assignment is what models/llama.py's _compute_config_rope_inv_freq does when
config.rope_scaling arrives as a config object rather than a dict: it retries on a
copy carrying the normalized dict. The retry raises, the exception is caught, and
the model falls back to unscaled RoPE, so a Llama-3.1 style checkpoint runs with
the wrong inverse frequencies and degrades past its original context. On 4.57.6
the retry works, because there rope_theta is a config attribute the assignment
cannot touch.

fix_transformers_rope_scaling_drops_theta wraps the alias setter, which is the
only place where the outgoing and the incoming parameters are both visible, and
puts the base back inside rope_parameters, where 5.x reads it. A per-layer dict is
left alone, and the config's own rope_theta attribute is written only where it is
the one slot that can hold the base, which is the non-dict replacement issue unslothai#2405
is about, or where it already exists and would otherwise go stale. A base the new
parameters name, or one the config states for itself, always wins, so Gemma's
local rotary in unsloth_zoo/empty_model.py keeps rope_local_base_freq. Nothing is
written at all when the new parameters carry their own base and the config states
none, so the wrapper neutralises itself on a transformers that keeps the base by
itself, and a saved config gains no key it did not have before.

Probe-gated on behaviour, not on a version: it replaces a scaling dict on a
throwaway LlamaConfig and compares the inverse frequencies against an untouched
one, so it no-ops on 4.57.6 and fires on every 5.x, where it was measured to fire.
On 5.4.0 and later a config refuses a non-dict rope_parameters outright, so the
object-style route is unreachable there, but the base is still dropped by a dict
assignment, and on 5.4.0 and 5.5.0 save_pretrained then raises a missing-key
KeyError instead of persisting a wrong base.

tests/utils/test_rope_scaling_drift.py gains three cases: a replacement keeps the
base, writing a config's own parameters back changes nothing, and clearing the
scaling still leaves the base readable. The first and third fail on main on every
transformers 5 minor from 5.0.0 to 5.17.0 and pass on 4.57.6.
tests/test_import_fixes_drift.py gains the fix's own detector, its idempotence
check, the carry helper over all eight parameter shapes, and the wiring check.

Fixes unslothai#2405

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Only assert the missing triton message where GPU init runs

Apple Silicon takes the MLX path and never executes unsloth/_gpu_init.py, so the
message the guard prints is not emitted there and the assertion failed on
macos-15 for a reason that has nothing to do with the guard. The child now
reports whether _gpu_init ran, from sys.modules or from the traceback, since a
failed import drops the module again, and the message test skips with that
reason when it did not.

* Restore the RoPE base into a copy instead of the caller's scaling dict

* Run the triton-absent guard in CI, and let a healthy alias setter stay unpatched

* Patch the live rope_scaling owner when the cached probe cannot see it

* Preserve each layer type's RoPE base across a per-layer scaling replacement

* Never carry a per-layer base mapping into the scalar RoPE slot

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Shorten the rope_scaling comments

---------

Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Unsloth models output gibberish on LONG inputs

2 participants