Repository navigation
Keep the RoPE base frequency on transformers 5, and make triton optional - #11037
Conversation
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
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
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.
|
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
So no 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 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, 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 One residual worth writing down: a GB10 variant whose board files carried a Tegra string and carried neither Plus |
|
@codex security review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 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".
| if base is None: | ||
| base = carried |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…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]>
…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>
…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]>
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.
config.rope_scalingsilently drops the RoPE base frequency, so aLlama-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.pyfail on transformers 5.0.0 through 5.3.0. The alias setternow carries the base across the assignment.
unsloth/_gpu_init.pyimportedtritonunconditionally at module scope, purely to resolvelibcuda_dirson CUDA hosts. The PyPItritonproject publishes no Windows wheel, Windows isserved by the separate
triton-windowspackage, so on a CPU only Windows installimport unslothdied there with a bare
ModuleNotFoundError. That import is now optional, in the same shape as thebitsandbytesimport a few lines below it.Root cause
Replacing
config.rope_scalingdrops the base frequency (#2405)transformers 5 moved
rope_thetaoff the config and intoconfig.rope_parameters, and keptrope_scalingas an alias property whose setter replaces that whole dict(
configuration_utils.py:381-386on 5.3.0,:461-466on 5.4.0). Any assignment through the aliastherefore 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)instandardize_rope_params(
modeling_rope_utils.py:663and:676on 5.3.0,:660and:673on 5.4.0), and on transformers 5 aLlamaConfighas no such attribute, sorope_parameters["rope_theta"]becomesNoneand the computefunction raises:
That assignment is exactly what
_compute_config_rope_inv_freqinunsloth/models/llama.pydoes whenconfig.rope_scalingarrives as a config object rather than a dict: it retries on a copy carrying thenormalized 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_scalingis a plain attribute andrope_thetais 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.pyfails on 5.0.0 through 5.3.0 and skips from 5.4.0onward. 5.4.0 made every config a huggingface_hub strict dataclass
(
configuration_utils.py:27,:114,:293), so a non-dictrope_parametersis refused withStrictDataclassFieldValidationErrorand the object-style route the test needs cannot be built. Thatis 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_thetais a required key forlinear RoPE (
modeling_rope_utils.py:737, raising at:923) and save-time validation was added(
configuration_utils.py:516-517), sosave_pretrainedraisesKeyError: Missing required keys in 'rope_parameters' for 'rope_type'='linear': {'rope_theta'}. By5.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 tritonat GPU initunsloth/_gpu_init.pydid a bare module levelimport triton. Its only consumers in that file are thetwo
libcuda_dirsresolution sites for the CUDA branch, plus animportlib.reload(triton)after theldconfig repair. PyPI's
tritonhas no Windows wheel and the CPU torch wheels do not pullpytorch-tritonin, so the module is simply absent on a CPU only Windows install and the import raisedbefore any device handling ran. This was found while running PR #11015 on windows-latest.
Changes
RoPE base frequency
unsloth/import_fixes.pygainsfix_transformers_rope_scaling_drops_theta, wired intounsloth/_gpu_init.pyin the first fix batch, right afterfix_transformers_fully_masked_rows()andbefore anything builds a config.
It replaces the
rope_scalingproperty on whichever class inPretrainedConfig.__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,
Noneand a realRopeParametersallreach 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 wheretransformers 5 reads it, so the result does not depend on
standardize_rope_paramsbeing called firstand
validate_ropeandsave_pretrainedsee a complete dict. The top-levelrope_thetaattribute iswritten 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_typesdiscriminator and left alone. When the new parameterscarry 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
LlamaConfigwithrope_theta=500000.0and a linear scaling, asks transformers for the inverse frequencies, does the sameon a second config after replacing
rope_scalingwith the normalized dict, and compares. Two configs,because
ROPE_INIT_FUNCTIONSmutates the one it is handed. A base far from the 10000.0 default, so asilent 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 positiveevidence 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
reloadthatrestores 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 areguarded, 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-packagesistouched.
import unslothcosts the same: 4.79 s and 4.84 s before, 4.71 s and 4.61 s after, on transformers5.3.0, since
transformers.models.llamais already imported by unsloth and the probe adds no import.The triton import
tritonis bound toNonewhen it cannot be imported, and a new module levelTRITON_IMPORT_ERRORrecords the exception text, orNonewhen the import worked.fused Triton kernels really are gone, and an informational line naming
triton-windowsotherwise,which is the expected state of a CPU only install.
libcuda_dirssites toleratetriton is None, keeping the existinglambda: Nonedefault, andthe 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
tritonhad to be installed because_gpu_init.pyimports 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.ymland.github/workflows/workflow-trigger-lint.yml. No install listchanged.
Compatibility
transformers minors, for the RoPE fix
CPU only (
CUDA_VISIBLE_DEVICES="", compile disabled, CUDA spoof on), one environment pertransformers minor, run against current main and against this branch. Every cell is pass or fail, never absent.
Each cell is
main / this branch, and the test columns are<failed>F <passed>P <skipped>S. Thebranch'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 isthe declared PEFT 0.18.0 floor, where
peft.utils.transformers_weight_conversiondoes not exist, and ithas nothing to do with this change.
The skips are pre-existing. Six in
tests/utils/test_rope_scaling_drift.pyon every minor are therequires_gpucases a CPU-only run cannot execute. The seventh, on 5.4.0 and later only, istest_object_style_rope_scaling_on_config_delegates_correctly, which still skips there because strictdataclass validation refuses a non-dict
rope_parametersbefore unsloth sees it. Four intests/test_import_fixes_drift.pyaretorchvision,vllmtwice andxformersnot being installed inthe sweep venvs.
tests/version_compat, the whole directory, is unchanged by this branch: 30 failed, 1689 passed, 182skipped on both sides, on transformers 5.3.0 and on 5.17.0. Those 30 are the pre-existing
test_trl_fake_train_cpu.pyandtest_trl_padding_free_max_length.pyfailures.Two further before and after measurements, outside the test suites:
KeyErrorout ofsave_pretrainedunsloth/Llama-3.2-1B-Instructconfig through_compute_config_rope_inv_freqThe 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_gpucases were also run on a real device on the transformers 5.17.0 corner, which aCPU only run cannot reach:
tests/utils/test_rope_scaling_drift.pyis 15 passed, 1 skipped on main and18 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.
reprois a script that blockstritonwith
sys.modules["triton"] = Noneand reports whether the failure is still theimport tritoninside_gpu_init.py.Tests
RoPE base frequency
tests/utils/test_rope_scaling_drift.pygains three cases, none of which skip on any minor:test_replacing_rope_scaling_keeps_the_base_frequency, with a vacuity guard that a 500000.0 basedoes not match the 10000.0 default.
test_reassigning_the_configs_own_rope_parameters_changes_nothing, assertingtorch.equal, so thehealthy path is pinned bit for bit on 4.x and 5.x alike.
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.pygains four detectors, in that file's one perfix_*style, none ofwhich skip:
test_rope_scaling_replacement_keeps_the_base_frequency, which asks the live build whether thepathology 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.
test_rope_scaling_setter_patch_is_idempotent, on the property identity and on the absence of anested wrapper after a second call.
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_thetais set torope_local_base_freqonpurpose and must survive the replacement untouched.
test_rope_scaling_patch_wired_into_gpu_init, which asserts_gpu_init.pyboth calls anddels it.The repo's own
test_object_style_rope_scaling_on_config_delegates_correctly, the test that was failingon 5.0.0 through 5.3.0, now passes there.
ruff checkis 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 withsys.modules["triton"] = Nonein a fresh interpreter, which is the import system's own marker forblocked:
import tritonis inside atry, so the guard cannot be deleted silently,tritonandTRITON_IMPORT_ERRORcontract is present andtriton.__version__is still read,import tritonframe nor the innermost frame lies inunsloth/_gpu_init.py,triton-windows,triton is not NoneandTRITON_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.pyandtest_missing_optional_dep_skips.pyare 107 passed, 11 skipped, andthe 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.pyandtest_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.
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 branchnone of them touch
_gpu_init.pyat all: the guard prints "Unsloth:tritonis notavailable (ModuleNotFoundError: No module named 'triton') - continuing without the fused
Triton kernels", the import walks on, and what fails instead is
unsloth.models.llamareaching 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 thanasserting something the platform cannot produce.
Note on #11016
#11016 recorded this as a known limitation, naming
tests/utils/test_rope_scaling_drift.pyfailing ontransformers 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 thatcould 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 unslothstill needs Triton. With the_gpu_init.pyguard in place the import walks on andstops at the next module scope
import triton, which isunsloth_zoo/compiler.py, and with that oneguarded too, in a throwaway copy, at
unsloth_zoo/loss_utils.py. After those, the Triton kernelmodules under
unsloth/kernels(several applying@triton.jitat import time) andfrom triton import __version__inunsloth/models/llama.pyandunsloth/models/vision.pyarestill 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.
rope_scalingshape stays unreachable on a config from transformers 5.4.0 onward,because strict dataclass validation refuses a non dict
rope_parameters, sotest_object_style_rope_scaling_on_config_delegates_correctlystill skips there. The base frequencycarry is what covers those minors, and it is measured on 5.4.0, 5.5.0 and 5.17.0.
is a result on one torch and one TRL, the versions named in the table.
reporter's account. What is measured here is the inverse frequencies.
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_parametersalso writes into the dict the callerassigned. 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 with500000.0and nothing raised. That is silentlywrong inverse frequencies.
The base is now restored into a COPY which is assigned back to
rope_parameters. Verified on4.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_lostassertedthe 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.