Repository navigation
Resolve apply_qkv and apply_o defensively, and explain zero patch counts - #11038
Conversation
…els were skipped Unsloth replaces the attention forward class-wide during pre_patch, but attaches apply_qkv and apply_o per instance afterwards, in the loader. Any instance of a patched architecture that the loader never walked therefore hit a bare attribute read and raised AttributeError: a plain AutoModelForCausalLM of the same architecture built in the same process (#1713), and vLLM's Transformers backend running the already patched module during profile_run, which happens before the attach step when fast_inference is on (#2587). All seven patched forwards now resolve through getattr(self, "apply_qkv", original_apply_qkv), so the instance attribute still wins and the fused LoRA path is unchanged, and the fallback only fires where the old code raised. The six sibling model files reached original_apply_qkv and original_apply_o through `from .llama import *`. They now name both in an explicit import, so an __all__ or a rename in llama.py cannot silently break a load bearing call site. patch_peft_model gates the fused kernels on lora_dropout == 0 and bias == "none". With either set, the patched layers summary reported 0 QKV, 0 O and 0 MLP layers with no reason, which reads as a failed patch even though training is unaffected (#2076). A new module level _fused_lora_skip_reason supplies the missing clause, and returns "" so the common summary line is byte for byte what it was. tests/test_apply_qkv_fallback.py pins the call sites in all seven files, the explicit imports, that an instance attribute still wins over the fallback, and #1713 end to end on a GPU. tests/test_lora_dropout_patch_summary.py pins the reason text and its parity with the gate it mirrors.
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. |
|
Confirmed this hits the bare self.apply_qkv and self.apply_o call sites in unsloth/models/llama.py, which the loader only attaches per instance after the class-wide patch, and the getattr fallback leaves the fused LoRA path selected. Will get this reviewed. |
|
Second pass over this branch, independent of the one that opened it. No code change was needed; one limitation was added to the body. What was re-run,
Two things worth recording, both now in Known limitations rather than left implicit. A subclass that defines |
|
@codex review |
|
@codex security review |
|
You have reached your Codex usage limits for security reviews. Please try again later. |
|
Codex Review: Didn't find any major issues. Chef's kiss. 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". |
Performance, before against afterB200 (GPU 5 of 8), Xeon Platinum 8559C, torch 2.14.0+cu130, transformers 4.57.6, trl 0.24.0, Every process asserted before measuring: Where the changed code runs, counted rather than assumed
The decode number is the one worth knowing: unsloth routes single-token decode through The resolution itself, 200k iterations by 15 repeats, loop overhead subtractedThe timed expression is lifted out of each arm's own
So +14.43 ns and +13.63 ns per resolution, against a base-versus-control gap of 0.20 and Predicted cost in context: 96 x 14.43 + 96 x 13.63 = 2.69 microseconds per step, against a End to end training, 8 reps per arm, rotated orderLlama-3.2-1B-Instruct 4bit, LoRA r=16 on all 7 projections,
The head delta is smaller than the control's own delta between two identical checkouts, and on End to end generation, 10 reps per arm
head vs base +0.14%, control vs base -0.98%. Consistent with zero resolutions per decoded token: Do the numbers still match
The loss curve is not bitwise reproducible on this stack: two runs of the same unmodified code with VerdictPerf neutral. +14 ns on a resolution that runs 192 times per step and zero times per decoded token, Not measuredThe six sibling architectures were not run on GPU. Every arm asserts that cohere, falcon_h1, gemma2, |
… the shared lock Repo tests (CPU, python) is red on main. Two causes, neither of them a PR's. test_accelerator_skip_guards fails on the two files unslothai#11038 added: both gate on a bare torch.cuda.is_available(), which tests/_zoo_aggressive_cuda_spoof.py patches to True process-wide, so they un-skip on a CPU-only box and try to load a real checkpoint. Gated on the probes that test names, has_real_cuda() for the one that asks for a cuda device and has_real_accelerator() for the one that does not. All 24 guard tests pass; the two files still collect, 76 passed. The second is a flake, and it is the one that cost this job a red run. studio.py resolves STUDIO_HOME once at import, and update() takes a NON-BLOCKING flock on the single .studio-runtime.lock beneath it. Left at the real ~/.unsloth/studio that file is shared by every xdist worker: STUDIO_HOME: ~/.unsloth/studio lock: ~/.unsloth/studio/.studio-runtime.lock second holder -> StudioRuntimeGateBusy -> typer.Exit(1) which is exactly how test_non_windows_preserves_call_order_without_launcher_operations died on gw3 with nothing wrong. _configure_windows already redirected it; the tests that build their own environment did not. Redirecting in the fixture covers both. Measured: before, the run creates the real lock file; after, it never appears.
* 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.
…nts (unslothai#11038) * Resolve apply_qkv and apply_o defensively, and say why the fused kernels were skipped Unsloth replaces the attention forward class-wide during pre_patch, but attaches apply_qkv and apply_o per instance afterwards, in the loader. Any instance of a patched architecture that the loader never walked therefore hit a bare attribute read and raised AttributeError: a plain AutoModelForCausalLM of the same architecture built in the same process (unslothai#1713), and vLLM's Transformers backend running the already patched module during profile_run, which happens before the attach step when fast_inference is on (unslothai#2587). All seven patched forwards now resolve through getattr(self, "apply_qkv", original_apply_qkv), so the instance attribute still wins and the fused LoRA path is unchanged, and the fallback only fires where the old code raised. The six sibling model files reached original_apply_qkv and original_apply_o through `from .llama import *`. They now name both in an explicit import, so an __all__ or a rename in llama.py cannot silently break a load bearing call site. patch_peft_model gates the fused kernels on lora_dropout == 0 and bias == "none". With either set, the patched layers summary reported 0 QKV, 0 O and 0 MLP layers with no reason, which reads as a failed patch even though training is unaffected (unslothai#2076). A new module level _fused_lora_skip_reason supplies the missing clause, and returns "" so the common summary line is byte for byte what it was. tests/test_apply_qkv_fallback.py pins the call sites in all seven files, the explicit imports, that an instance attribute still wins over the fallback, and unslothai#1713 end to end on a GPU. tests/test_lora_dropout_patch_summary.py pins the reason text and its parity with the gate it mirrors. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Skip the two checkpoint-loading tests when no accelerator is present --------- Co-authored-by: danielhanchen <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
* 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.
Summary
Two reports, one root cause, plus a message fix in the same
get_peft_modelpath.FastLanguageModel.from_pretrainedreplacesLlamaAttention.forward(and the six siblingarchitectures) class wide, but attaches
apply_qkvandapply_oper instance, later.Anything that runs one of those forwards on an instance the loader never touched dies with
This closes #1713 (a plain transformers model built in the same process), #2587 (vLLM's
Transformers backend running the already patched module during
profile_run, before theattach step), and #2076 (the patched layers summary reporting
0 QKV layers, 0 O layers and 0 MLP layerswith no reason, which reads as a failed patch).Root cause
unsloth/models/llama.py:154and:161defineoriginal_apply_qkvandoriginal_apply_o.They are what the loader attaches at
llama.py:2811-2812, immediately aftermodel_patcher.post_patch:get_peft_modellater swaps in the fused kernels atllama.py:3740and:3757(
apply_lora_qkv,apply_lora_o) when LoRA is eligible.The seven patched attention forwards read those attributes with a bare
self.apply_qkv(...),so every window in which the class is patched but the instance is not is an
AttributeError:AutoModelForCausalLMof the same architecture, loaded separately. The class isalready patched globally, and nothing attaches the attributes to its layers.
fast_inference = Trueloads vLLM atllama.py:2771, which is before the attachat
:2811. When vLLM falls back to its Transformers backend it runs the patched moduleduring
profile_runand raises, re-surfacing as aRuntimeErrorfromload_vllm.For #2076,
patch_peft_modelgates the fused kernels onif lora_dropout == 0 and bias == "none":. Withlora_dropout = 0.1the whole loop isskipped, so all three counters stay at zero and the summary line gives no reason.
Changes
unsloth/models/{llama,cohere,falcon_h1,gemma2,granite,mistral,qwen3}.pyBoth call sites in each of the seven files now resolve through the module level fallback:
The instance attribute still wins, so a loaded and LoRA-patched model keeps
apply_lora_qkv/apply_lora_oand the fused kernels are untouched. The fallback onlyfires where the old code raised.
The six sibling files reached the two fallbacks through
from .llama import *. They nowname them in an explicit
from .llama import (...)block, so a future__all__or renamein
llama.pycannot silently break a load bearing call site.unsloth/models/llama.pyNew module level
_fused_lora_skip_reason(lora_dropout, bias)returns the missing clause,or
""when the fused kernels really were installed.patch_peft_modelappends it:With
lora_dropout = 0andbias = "none"the summary line is byte for byte what it was.No behaviour depends on a version number.
original_apply_qkvandoriginal_apply_ohaveexisted in every supported transformers, the fallback only changes what happens when the
instance attribute is absent, and
lora_dropout/biascome offmodel.peft_config, whichis stable from PEFT 0.18.0 up.
Compatibility
Every corner below is its own virtual environment, and every one of them was run twice, once
against
mainand once against this branch, so each cell is a measurement rather than anexpectation. The cpu columns run the new test files and the existing suites of every touched
module with no accelerator visible; the gpu columns run the repro and a three step LoRA
regression on a B200; the vllm columns run #2587's
fast_inferencepath.Every corner also passes the import sanity lane and the two zoo import suites.
The cells that are not a plain pass, each one measured rather than assumed:
fails the harness matmul probe with
CUDA error: no kernel image is available for execution on the device. Everyneeds: gpusteprecords that as the skip reason. The cpu lane on mA, which is the 4.57.6 plus TRL 0.22.2 plus
PEFT 0.18.0 plus python 3.10 floor, passes in full.
tests/utils/test_rope_scaling_drift.py::test_object_style_rope_scaling_on_config_delegates_correctlyfails on transformers 5.0.0. Re-run in the same corner against the shared clone on
main:identical failure, same assertion. Nothing in this PR touches rope scaling. transformers 5.0.0
is already a
!=exclusion in the zoo pin, so this corner is informational.summary-with-dropoutandsummary-without-dropoutboth diein
peft/tuners/lora/torchao.py:151,ImportError: cannot import name 'LinearActivationQuantizedTensor' from 'torchao.quantization'. PEFT 0.18.0'sdispatch_torchaoimports that symbol unconditionally and torchao 0.18.0 removed it; PEFT 0.20.0guards it. Isolated with no Unsloth in the process at all:
peft.get_peft_modelon a barenn.Linearfails the same way in mX1 and succeeds in mD (PEFT 0.20.0, same torchao) and mA(PEFT 0.18.0, torchao 0.13.0). Re-run against the shared clone on
main: identical failure. Sothis is a PEFT 0.18.0 plus torchao 0.18.0 incompatibility in that corner, and
get_peft_modelis unusable there for any model. PEFT 0.18.0 is still covered on the same transformers by the
mX1 cpu lane, which passes in full, and on the GPU by mV1 in the vllm lane, which is also PEFT
0.18.0 and passes. So there is no version combination in this table where PEFT 0.18.0 is left
unmeasured by anything.
Before and after on the same corners, to show the matrix is measuring the fix and not the
environment:
mainrepro-1713-4bitVERDICT: REPRODUCEDVERDICT: NO_REPROregression-3-step-lorarepro-2587-fast-inference, 4 bit, vllm 0.11.2VERDICT: REPRODUCEDVERDICT: NO_REPROrepro-2587-fast-inference-bf16, vllm 0.29.0VERDICT: REPRODUCEDVERDICT: NO_REPROregression-3-step-lorapassing on both sides is the control: the fused LoRA path is byte forbyte the path it was before, and the getattr default only fires where the old code raised.
The vllm step is split per corner. vllm 0.29.0 moved bitsandbytes out of tree, so Unsloth refuses
load_in_4bitthere withInstall it with pip install vllm-bnb-pluginbefore the loader isreached; mV2 therefore runs the same repro in bf16. The #2587 ordering defect is in the loader and
is independent of the weight format, and it reproduces on
mainin both corners.Kaggle T4x2
The B200 in the matrix above has bfloat16 and the newest triton, so the fix was also run on a
rented Kaggle kernel with two Tesla T4s (sm_75, no bfloat16, driver 580.159.04), at both ends of
the support matrix: torch 2.6.0 with transformers 4.57.6, TRL 0.22.2 and PEFT 0.18.0 on python
3.10, and torch 2.14.0 with transformers 5.17.0, TRL 1.13.0 and PEFT 0.20.0 on python 3.13. Each
corner ran the repro twice in one kernel, once against
mainand once against this branch, withthe loaded module path and a source marker checked in each phase.
mainthe reporter's reduction raisesAttributeError: 'LlamaAttention' object has no attribute 'apply_qkv'; on this branch itcompletes.
loss on
mainand on the branch (1.0725805759429932 on the older corner, 1.0727750062942505 onthe newer one), and
apply_lora_qkvstill wins afterget_peft_model.lora_dropout = 0.1and never withlora_dropout = 0.mainand give 76 passed on the branch, and the gpumarked tests pass on a T4 on the newer corner.
That run is also why
test_apply_qkv_fallback_end_to_endno longer builds its plain model at thecheckpoint dtype. bfloat16 cannot be assembled on sm_75 under triton 3.2.0, so the test used to
fail inside ptxas rather than in the code under test. It now selects float16 on a card without
bfloat16, and sets the config dtype attributes as well as the
dtypekeyword, because the patchedforward casts activations to the config dtype and on transformers 4.57.6 the keyword leaves
config.dtypeat the checkpoint value. Both branches were re-run on the B200, which hasbfloat16, and both pass.
Tests
New
tests/test_apply_qkv_fallback.py(40 failures onmain, all green here):self.apply_qkv(...)orself.apply_o(...)call is left in any of theseven files, and that each has the
getattr(self, ..., original_apply_*)form;check that every one of the seven modules resolves them to the same objects as
llama.py;transformersLlamaAttentionbuilt outside the loader: neither attribute ispresent, the fallback resolves, and running it produces correctly shaped Q, K, V and output;
apply_lora_qkv/apply_lora_oset on the instance still win over the fallback;@pytest.mark.gpu: Unsloth overwrites the forward call function of a model loaded by huggingface library #1713 as reported, end to end. Load with Unsloth, then build a plainAutoModelForCausalLMof the same architecture in the same process and run it, then confirmthe fused kernels are still selected after
get_peft_model.New
tests/test_lora_dropout_patch_summary.py(does not import onmain, all green here):lora_dropout == 0 and bias == "none"gate is closed, plus an AST read of that gate so thetwo cannot drift apart;
@pytest.mark.gpu: the reason reaches the user's console on a real 4 bit load.Existing suites re-run on every touched module:
tests/test_attention_implementation.py,tests/test_attn_impl_honor_explicit.py,tests/test_attn_dtype_custom_datatype.py,tests/test_dispatch_hook_repair.py,tests/test_finetune_last_n_layers.py,tests/test_gradient_checkpointing_restore.py,tests/test_pretrain_compile_reset.py,tests/saving/test_torchao_remote_code_consent.py,tests/utils/test_packing.py,tests/utils/test_prepare_inputs_leftpad.py,tests/utils/test_rope_scaling_drift.py, and thehard gates
tests/test_import_fixes_drift.py,tests/test_public_api_surface.py,tests/test_callback_signature_drift.py,tests/test_python39_compatibility.py, and the--collect-onlydrift list fromconsolidated-tests-ci.yml. 342 passed. The fourtests/utils/test_packing.pyfailures are present onmainat the same commit and areunrelated to this change.
Fused path proof on the GPU: after
get_peft_modelthe instance attributes are stillapply_lora_qkvandapply_lora_o, 16 QKV and 16 O layers are patched, and three LoRA stepstrain (1.101 to 1.082).
Commands, on python 3.13.12 with torch 2.14.0+cu130, transformers 5.17.0, TRL 1.13.0 and PEFT
0.20.0:
Evidence
The decisive lines, all of them from runs recorded while preparing this change:
main, the Unsloth overwrites the forward call function of a model loaded by huggingface library #1713 reduction:AttributeError: 'LlamaAttention' object has no attribute 'apply_qkv', thenVERDICT: REPRODUCED. On this branch, the same script:vanilla HF forward logits (1, 8, 128256), thenVERDICT: NO_REPRO.mainwithfast_inference = True, [Bug]RuntimeError: 'Qwen3Attention' object has no attribute 'apply_qkv' #2587:VERDICT: REPRODUCEDon both vllm 0.11.2 andvllm 0.29.0. On this branch,
VERDICT: NO_REPROon both.(1.0725805759429932 and 1.0727750062942505 on a T4, and a matching pass on the B200).
lora_dropout = 0.1, the console line is nowUnsloth 2026.9.4 patched 16 layers with 0 QKV layers, 0 O layers and 0 MLP layers. The fused LoRA kernels were skipped because lora_dropout = 0.1, which is why the counts are zero. Training is unaffected.Withlora_dropout = 0the added sentence is absent and the line is byte for byte what it was.Colab L4
Validated on a rented Colab L4, one NVIDIA L4, compute capability 8.9, 23034 MiB, driver 580.82.07, against torch 2.14.0, transformers 5.17.0, TRL 1.13.0, PEFT 0.20.0 and datasets 5.0.1 in a venv built on the VM, with the base and head trees pinned to exact commits and the loaded module path checked in each phase. Because sm_89 has bfloat16, the reduction from the issue runs exactly as reported rather than needing a dtype adaptation: on
main, loading a model throughFastLanguageModeland then building a plain transformers Llama in the same process raisesAttributeError: 'LlamaAttention' object has no attribute 'apply_qkv'; on this branch the same script forwards and prints the logits shape. The same reduction was repeated in float16 with the same outcome, so the fallback is not dtype dependent. The regression guard still selects the fused kernels, withapply_lora_qkvandapply_lora_oattached afterget_peft_modeland a three step LoRA train loss of 1.0813191731770833 onmainand on the branch, identical to the digit. For the patch summary,lora_dropout = 0.1printspatched 16 layers with 0 QKV layers, 0 O layers and 0 MLP layersonmainand adds the reason sentence on the branch, whilelora_dropout = 0still reports 16 of each with no reason line. The new test files give 76 passed on the branch and 2 passed on the GPU marked selection; onmainthey cannot be collected at all, since the patch summary test imports a symbolmaindoes not have, and that collection error aborts the session before the apply_qkv test file itself runs.Known limitations
@pytest.mark.gputests are outside the repository's default selection(
addopts = "-m 'not gpu and not slow and not server'"), so they run in the gpu leg and in thematrix gpu lane, not in a default local run.
vLLM's Transformers backend, and the cpu and gpu lanes prove the same missing attribute on the
same line through Unsloth overwrites the forward call function of a model loaded by huggingface library #1713's route.
test_apply_qkv_fallback_end_to_endbuilds its plain model from config with one hidden layer,so it checks the attribute resolution and the output shapes, not numerics.
apply_qkv. A third party thatsubclasses a patched attention class and defines
apply_qkvas an ordinary method gets abound method out of the lookup, so the explicit
selfmakes three arguments and raisesTypeError. That is unchanged frommain, where the same call was writtenself.apply_qkv(self, ...), and the attribute is Unsloth's own internal protocol, so asubclass that merely inherits, which is the reported case, is the one that is fixed here.
lora_magnitude_vectoris checked per layer rather than in the
lora_dropout == 0 and bias == "none"gate, so theexisting per layer warning is what fires there and the summary sentence stays as it was.
Fixes #1713
Fixes #2587
Fixes #2076
Review round: two tests ran on a CPU runner that cannot run them
Repo tests (CPU, rest)was red on this PR withRuntimeError: pin_memory=True requires a CUDA or other accelerator backendfrominitialize_unsloth_gradient_checkpointing, intest_apply_qkv_fallback_end_to_endandtest_summary_reason_is_logged_for_a_real_model. Both are this PR's own files and both load areal checkpoint through
FastLanguageModel.from_pretrained.Both were already marked
@pytest.mark.gpu, andaddoptsin pyproject deselects that marker.The job does not get it: it passes
-m 'not server and not e2e'on the command line, andpytest's last
-mwins, so the marker filter is replaced rather than extended and everygpu-marked test in that selection runs on the CPU runner.
Rather than change the shared job, both tests now also carry
@pytest.mark.skipif(not torch.cuda.is_available(), ...), which is the idiom already used intests/test_fp8_pre_sm89_dequant_fallback.py. Reproduced locally with the job's exact selection:CUDA_VISIBLE_DEVICES="" pytest ... -m 'not server and not e2e' -n 4gives 2 failed / 76 passedbefore and 76 passed / 2 skipped after, with both skips naming the reason.
Hardware evidence from the companion lane, on a T4 at fp16:
AttributeError: no attribute 'apply_qkv'on the base, no reproduction on the head, and theregression loss bit-identical at
1.0727750062942505.