Skip to content

Resolve apply_qkv and apply_o defensively, and explain zero patch counts - #11038

Merged
danielhanchen merged 3 commits into
mainfrom
pr/apply-qkv-fallback
Sep 17, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
pr/apply-qkv-fallback

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 15, 2026 •

Copy link
Copy Markdown
Member

Summary

Two reports, one root cause, plus a message fix in the same get_peft_model path.

FastLanguageModel.from_pretrained replaces LlamaAttention.forward (and the six sibling
architectures) class wide, but attaches apply_qkv and apply_o per instance, later.
Anything that runs one of those forwards on an instance the loader never touched dies with

AttributeError: 'LlamaAttention' object has no attribute 'apply_qkv'

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 the
attach step), and #2076 (the patched layers summary reporting 0 QKV layers, 0 O layers and 0 MLP layers with no reason, which reads as a failed patch).

Root cause

unsloth/models/llama.py:154 and :161 define original_apply_qkv and original_apply_o.
They are what the loader attaches at llama.py:2811-2812, immediately after
model_patcher.post_patch:

for idx, layer in enumerate(model.model.layers):
    layer.self_attn.apply_qkv = original_apply_qkv
    layer.self_attn.apply_o = original_apply_o

get_peft_model later swaps in the fused kernels at llama.py:3740 and :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:

For #2076, patch_peft_model gates the fused kernels on
if lora_dropout == 0 and bias == "none":. With lora_dropout = 0.1 the whole loop is
skipped, 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}.py

  • Both call sites in each of the seven files now resolve through the module level fallback:

    Q, K, V = getattr(self, "apply_qkv", original_apply_qkv)(self, hidden_states)
    ...
    attn_output = getattr(self, "apply_o", original_apply_o)(self, attn_output)

    The instance attribute still wins, so a loaded and LoRA-patched model keeps
    apply_lora_qkv / apply_lora_o and the fused kernels are untouched. The fallback only
    fires where the old code raised.

  • The six sibling files reached the two fallbacks through from .llama import *. They now
    name them in an explicit from .llama import (...) block, so a future __all__ or rename
    in llama.py cannot silently break a load bearing call site.

unsloth/models/llama.py

  • New module level _fused_lora_skip_reason(lora_dropout, bias) returns the missing clause,
    or "" when the fused kernels really were installed. patch_peft_model appends it:

    Unsloth 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.
    

    With lora_dropout = 0 and bias = "none" the summary line is byte for byte what it was.

No behaviour depends on a version number. original_apply_qkv and original_apply_o have
existed in every supported transformers, the fallback only changes what happens when the
instance attribute is absent, and lora_dropout / bias come off model.peft_config, which
is 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 main and once against this branch, so each cell is a measurement rather than an
expectation. 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_inference path.

corner python torch transformers TRL PEFT cpu lane gpu lane vllm lane
mA 3.10.19 2.6.0+cu124 4.57.6 0.22.2 0.18.0 pass skip n/a
mB 3.13.12 2.8.0+cu128 5.0.0 0.27.2 0.19.1 pass, 1 pre-existing fail pass n/a
mC 3.13.12 2.11.0+cu130 5.5.0 1.0.0 0.20.0 pass pass n/a
mD 3.13.12 2.14.0+cu130 5.17.0 1.13.0 0.20.0 pass pass n/a
mX1 3.13.12 2.14.0+cu130 5.17.0 1.13.0 0.18.0 pass pass, 2 pre-existing fails n/a
mX2 3.13.12 2.11.0+cu130 4.57.6 1.13.0 0.19.1 pass pass n/a
mV1 3.13.12 2.9.0+cu128 4.57.6 0.22.2 0.18.0 n/a n/a pass, vllm 0.11.2
mV2 3.13.12 2.13.0+cu130 5.17.0 1.13.0 0.20.0 n/a n/a pass, vllm 0.29.0

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:

  • mA gpu: skip. torch 2.6.0's PyPI wheel is cu124 and carries no sm_100, so this host's B200
    fails the harness matmul probe with
    CUDA error: no kernel image is available for execution on the device. Every needs: gpu step
    records 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.
  • mB cpu: 1 pre-existing fail.
    tests/utils/test_rope_scaling_drift.py::test_object_style_rope_scaling_on_config_delegates_correctly
    fails 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.
  • mX1 gpu: 2 pre-existing fails. summary-with-dropout and summary-without-dropout both die
    in peft/tuners/lora/torchao.py:151, ImportError: cannot import name 'LinearActivationQuantizedTensor' from 'torchao.quantization'. PEFT 0.18.0's
    dispatch_torchao imports that symbol unconditionally and torchao 0.18.0 removed it; PEFT 0.20.0
    guards it. Isolated with no Unsloth in the process at all: peft.get_peft_model on a bare
    nn.Linear fails 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. So
    this is a PEFT 0.18.0 plus torchao 0.18.0 incompatibility in that corner, and get_peft_model
    is 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:

corner lane step on main on this branch
mD gpu repro-1713-4bit VERDICT: REPRODUCED VERDICT: NO_REPRO
mD gpu regression-3-step-lora pass pass
mV1 vllm repro-2587-fast-inference, 4 bit, vllm 0.11.2 VERDICT: REPRODUCED VERDICT: NO_REPRO
mV2 vllm repro-2587-fast-inference-bf16, vllm 0.29.0 VERDICT: REPRODUCED VERDICT: NO_REPRO

regression-3-step-lora passing on both sides is the control: the fused LoRA path is byte for
byte 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_4bit there with Install it with pip install vllm-bnb-plugin before the loader is
reached; 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 main in 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 main and once against this branch, with
the loaded module path and a source marker checked in each phase.

  • On main the reporter's reduction raises
    AttributeError: 'LlamaAttention' object has no attribute 'apply_qkv'; on this branch it
    completes.
  • The fused path is unchanged: the three step 4-bit LoRA run produces a bit identical training
    loss on main and on the branch (1.0725805759429932 on the older corner, 1.0727750062942505 on
    the newer one), and apply_lora_qkv still wins after get_peft_model.
  • The patch summary sentence appears only with lora_dropout = 0.1 and never with
    lora_dropout = 0.
  • The two new test files fail to collect on main and give 76 passed on the branch, and the gpu
    marked tests pass on a T4 on the newer corner.

That run is also why test_apply_qkv_fallback_end_to_end no longer builds its plain model at the
checkpoint 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 dtype keyword, because the patched
forward casts activations to the config dtype and on transformers 4.57.6 the keyword leaves
config.dtype at the checkpoint value. Both branches were re-run on the B200, which has
bfloat16, and both pass.

Tests

New tests/test_apply_qkv_fallback.py (40 failures on main, all green here):

  • an AST audit that no self.apply_qkv(...) or self.apply_o(...) call is left in any of the
    seven files, and that each has the getattr(self, ..., original_apply_*) form;
  • an AST audit that all six sibling files import the two fallbacks explicitly, plus a runtime
    check that every one of the seven modules resolves them to the same objects as llama.py;
  • a plain transformers LlamaAttention built outside the loader: neither attribute is
    present, the fallback resolves, and running it produces correctly shaped Q, K, V and output;
  • apply_lora_qkv / apply_lora_o set 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 plain
    AutoModelForCausalLM of the same architecture in the same process and run it, then confirm
    the fused kernels are still selected after get_peft_model.

New tests/test_lora_dropout_patch_summary.py (does not import on main, all green here):

  • the reason text for dropout only, bias only and both, and the empty string for neither;
  • a 12 case parity check that the reason is non empty exactly when the
    lora_dropout == 0 and bias == "none" gate is closed, plus an AST read of that gate so the
    two 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 the
hard 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-only drift list from consolidated-tests-ci.yml. 342 passed. The four
tests/utils/test_packing.py failures are present on main at the same commit and are
unrelated to this change.

Fused path proof on the GPU: after get_peft_model the instance attributes are still
apply_lora_qkv and apply_lora_o, 16 QKV and 16 O layers are patched, and three LoRA steps
train (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:

# CPU, no accelerator needed
pytest tests/test_apply_qkv_fallback.py tests/test_lora_dropout_patch_summary.py
# 76 passed, 2 deselected

# GPU, once at the device's widest dtype and once with float16 forced
pytest tests/test_apply_qkv_fallback.py tests/test_lora_dropout_patch_summary.py -m gpu
# 2 passed, 76 deselected
UNSLOTH_TEST_PLAIN_DTYPE=float16 pytest tests/test_apply_qkv_fallback.py -m gpu
# 1 passed, 57 deselected

Evidence

The decisive lines, all of them from runs recorded while preparing this change:

  • On 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', then VERDICT: REPRODUCED. On this branch, the same script:
    vanilla HF forward logits (1, 8, 128256), then VERDICT: NO_REPRO.
  • On main with fast_inference = True, [Bug]RuntimeError: 'Qwen3Attention' object has no attribute 'apply_qkv' #2587: VERDICT: REPRODUCED on both vllm 0.11.2 and
    vllm 0.29.0. On this branch, VERDICT: NO_REPRO on both.
  • The three step LoRA control, unchanged on both sides, bit identical on two separate cards
    (1.0725805759429932 and 1.0727750062942505 on a T4, and a matching pass on the B200).
  • With lora_dropout = 0.1, the console line is now Unsloth 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. With
    lora_dropout = 0 the 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 through FastLanguageModel and then building a plain transformers Llama in the same process raises AttributeError: '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, with apply_lora_qkv and apply_lora_o attached after get_peft_model and a three step LoRA train loss of 1.0813191731770833 on main and on the branch, identical to the digit. For the patch summary, lora_dropout = 0.1 prints patched 16 layers with 0 QKV layers, 0 O layers and 0 MLP layers on main and adds the reason sentence on the branch, while lora_dropout = 0 still 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; on main they cannot be collected at all, since the patch summary test imports a symbol main does not have, and that collection error aborts the session before the apply_qkv test file itself runs.

Known limitations

  • The @pytest.mark.gpu tests 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 the
    matrix gpu lane, not in a default local run.
  • Generation is not the only path [Bug]RuntimeError: 'Qwen3Attention' object has no attribute 'apply_qkv' #2587 can take; the vllm lane above is the one that exercises
    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_end builds its plain model from config with one hidden layer,
    so it checks the attribute resolution and the output shapes, not numerics.
  • The fallback covers a missing attribute, not a class level apply_qkv. A third party that
    subclasses a patched attention class and defines apply_qkv as an ordinary method gets a
    bound method out of the lookup, so the explicit self makes three arguments and raises
    TypeError. That is unchanged from main, where the same call was written
    self.apply_qkv(self, ...), and the attribute is Unsloth's own internal protocol, so a
    subclass that merely inherits, which is the reported case, is the one that is fixed here.
  • A zero patch count from DoRA is not explained by the new sentence. lora_magnitude_vector
    is checked per layer rather than in the lora_dropout == 0 and bias == "none" gate, so the
    existing 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 with
RuntimeError: pin_memory=True requires a CUDA or other accelerator backend from
initialize_unsloth_gradient_checkpointing, in test_apply_qkv_fallback_end_to_end and
test_summary_reason_is_logged_for_a_real_model. Both are this PR's own files and both load a
real checkpoint through FastLanguageModel.from_pretrained.

Both were already marked @pytest.mark.gpu, and addopts in pyproject deselects that marker.
The job does not get it: it passes -m 'not server and not e2e' on the command line, and
pytest's last -m wins, so the marker filter is replaced rather than extended and every
gpu-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 in
tests/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 4 gives 2 failed / 76 passed
before 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 the
regression loss bit-identical at 1.0727750062942505.

…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.
@danielhanchen danielhanchen changed the title Resolve apply_qkv and apply_o defensively, and say why the fused kernels were skipped Resolve apply_qkv and apply_o defensively, and explain zero patch counts Sep 15, 2026
@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-16T08:57:47.542152Z 2c78451 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@danielhanchen

Copy link
Copy Markdown
Member Author

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

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, main against this branch each time:

  • The reported case and the subclass case on a B200. A plain LlamaAttention built after pre_patch raises AttributeError: 'LlamaAttention' object has no attribute 'apply_qkv' on main and runs here, and so does a third party subclass of the patched class, which is the shape a router or adapter library produces.
  • fast_inference on both vLLM corners, which is the [Bug]RuntimeError: 'Qwen3Attention' object has no attribute 'apply_qkv' #2587 ordering: vLLM 0.11.2 with load_in_4bit, and vLLM 0.29.0 in bf16 because that release moved bitsandbytes out of tree. Reproduces on main in both, passes here in both.
  • The patch summary, four combinations. lora_dropout = 0.1, bias = "none" prints 0 QKV layers with no explanation on main and now appends The fused LoRA kernels were skipped because lora_dropout = 0.1, which is why the counts are zero. Training is unaffected.; bias = "all" names the bias; lora_dropout = 0, bias = "none" prints 16 QKV layers, 16 O layers and 16 MLP layers and the line is identical on both sides, which is the control.
  • The two new test files on five corners: transformers 4.57.6 with python 3.10 and torch 2.6, 4.57.6 with torch 2.9, 5.5.0, 5.17.0 with PEFT 0.20.0, and 5.17.0 with PEFT 0.18.0. 76 passed and 2 deselected on all five.

Two things worth recording, both now in Known limitations rather than left implicit. A subclass that defines apply_qkv as an ordinary class level method gets a bound method out of the lookup, so the explicit self makes three arguments and raises TypeError; that is unchanged from main, where the call was self.apply_qkv(self, ...), and the attribute is our own internal protocol. And a DoRA adapter also reports zero counts, which the new sentence does not explain, because lora_magnitude_vector is checked per layer rather than in the gate the sentence mirrors; the existing per layer warning is what covers that.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for security reviews. Please try again later.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: 2c7845170e

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

Copy link
Copy Markdown
Member Author

Performance, before against after

B200 (GPU 5 of 8), Xeon Platinum 8559C, torch 2.14.0+cu130, transformers 4.57.6, trl 0.24.0,
peft 0.20.0. Three arms selected by PYTHONPATH only, nothing edited in place: head 2c7845170,
base = the merge base 9bef060ea, and a second independent checkout of 9bef060ea as the negative
control. Each arm has its own UNSLOTH_COMPILE_LOCATION, never shared.

Every process asserted before measuring: unsloth.__file__ under its own worktree,
UNSLOTH_COMPILE_DISABLE unset, the call-site shape matching the arm by source inspection,
LlamaAttention.forward is that worktree's LlamaAttention_fast_forward after from_pretrained,
and self_attn.apply_qkv is apply_lora_qkv after get_peft_model, so the fused-kernel branch really
is the one on the hot path. No run was accepted without all of them.

Where the changed code runs, counted rather than assumed

what count
attention forwards per optimizer step 96 = 16 layers x 3 micro-batches x 2 for the checkpoint recompute
apply_qkv resolutions per step 96
apply_o resolutions per step 96
changed-expression evaluations per training step 192
resolutions during prefill of a 36-token prompt 32
resolutions per decoded token 0

The decode number is the one worth knowing: unsloth routes single-token decode through
LlamaAttention_fast_forward_inference, which calls fast_linear_forward(self.q_proj, ...) and
never touches apply_qkv or apply_o. Confirmed by counting, prefill plus 1 token and prefill plus
32 tokens both give 32.

The resolution itself, 200k iterations by 15 repeats, loop overhead subtracted

The timed expression is lifted out of each arm's own llama.py by AST, so an arm cannot be
mislabelled.

arm expression attribute resolved to net median
base self.apply_qkv present apply_lora_qkv 1.73 ns
control self.apply_qkv present apply_lora_qkv 1.93 ns
head getattr(self, "apply_qkv", original_apply_qkv) present apply_lora_qkv 16.15 ns
head same absent original_apply_qkv 15.96 ns
base self.apply_qkv absent AttributeError n/a
base self.apply_o present apply_lora_o 1.52 ns
head getattr(self, "apply_o", original_apply_o) present apply_lora_o 15.15 ns
head same absent original_apply_o 15.99 ns

So +14.43 ns and +13.63 ns per resolution, against a base-versus-control gap of 0.20 and
0.29 ns on the same statistic. The delta is real. The fallback branch costs the same as the hit
branch, so the fix is not slower in the case it exists to serve. There is no base number for the
absent shape because on base that shape is the crash this PR fixes.

Predicted cost in context: 96 x 14.43 + 96 x 13.63 = 2.69 microseconds per step, against a
measured 0.669 s step. 0.0004%.

End to end training, 8 reps per arm, rotated order

Llama-3.2-1B-Instruct 4bit, LoRA r=16 on all 7 projections, use_gradient_checkpointing="unsloth",
61 steps, batch 2 x grad accum 3, seed 3407. Statistic is the median steady-state step time over
steps 6 to 61.

arm reps median step per-run min..max peak alloc peak reserved
base 8 0.6688 s 0.6545 .. 0.7310 1.512 GiB 1.555 GiB
head 8 0.6737 s 0.6356 .. 0.7007 1.512 GiB 1.555 GiB
control 8 0.6762 s 0.6433 .. 0.7077 1.512 GiB 1.555 GiB
comparison delta bootstrap 95% CI Mann-Whitney, 448 pooled steps each
head vs base +0.72% -7.52% to +4.32% p = 0.689
control vs base +1.09% -7.02% to +4.01% p = 0.601
head vs control -0.37% -3.27% to +4.12%

The head delta is smaller than the control's own delta between two identical checkouts, and on
the pooled per-step distribution the ordering flips: head 0.045% faster than base, control 0.430%
faster. Peak memory is bit-identical across all 24 runs, as it must be, since the change allocates
nothing.

End to end generation, 10 reps per arm

arm tok/s median min..max
base 67.15 65.80 .. 68.21
head 67.24 65.56 .. 69.95
control 66.49 64.18 .. 68.54

head vs base +0.14%, control vs base -0.98%. Consistent with zero resolutions per decoded token:
there was nothing here to move.

Do the numbers still match

check head vs base
forward logits, sha256 of the fp32 tensor bitwise identical (63c2e83bf8703193...)
forward loss, hex float bitwise identical (0x1.8868880000000p+3)
greedy 256-token output, ids and text identical
61-step loss curve, worst max abs delta 4.8e-3
same figure, base against base 4.8e-3

The loss curve is not bitwise reproducible on this stack: two runs of the same unmodified code with
the same seed diverge by up to 4.8e-3 by step 61, steps 1 and 2 agreeing exactly and the backward
accumulating from there. The arm-to-arm figure equals the same-arm figure, and the deterministic
forward is bit-exact, which is the stronger statement.

Verdict

Perf neutral. +14 ns on a resolution that runs 192 times per step and zero times per decoded token,
2.69 us of a 0.669 s step. Every end-to-end delta is inside the negative control's own spread.

Not measured

The six sibling architectures were not run on GPU. Every arm asserts that cohere, falcon_h1, gemma2,
granite, mistral and qwen3 resolve original_apply_qkv and original_apply_o to the identical
object from llama.py, and the call sites are textually the same one-line change, but gemma2's
apply_o sits after a softcapping branch so its per-forward count could differ. Also not measured:
vllm fast_inference and the plain-transformers-in-the-same-process path, which are what the PR is
for. This measures the cost of the fix, not the fix.

@danielhanchen
danielhanchen merged commit ac9f9b8 into main Sep 17, 2026
29 of 36 checks passed
@danielhanchen
danielhanchen deleted the pr/apply-qkv-fallback branch September 17, 2026 10:19
danielhanchen pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 17, 2026
… 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.
Stanley00 pushed a commit to stanley-fork/unsloth that referenced this pull request Sep 17, 2026
* Repair the three checks that went red on main today

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  assert active_generations._FENCED == set()

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

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

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

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

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

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

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

test_generation_state_isolation.py guards the repair. The structural check reads
conftest rather than exercising ordering, because observing a leak functionally
would require assuming test ORDER and this suite runs under pytest-randomly,
where a test may not assume it. Dropping autouse from the fixture fails that
check, which is how I confirmed it is not decorative.
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…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>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
* Repair the three checks that went red on main today

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  assert active_generations._FENCED == set()

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

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

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

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

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

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

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

test_generation_state_isolation.py guards the repair. The structural check reads
conftest rather than exercising ordering, because observing a leak functionally
would require assuming test ORDER and this suite runs under pytest-randomly,
where a test may not assume it. Dropping autouse from the fixture fails that
check, which is how I confirmed it is not decorative.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

2 participants