Skip to content

Stop a removed torchao class from killing plain LoRA - #11168

Merged
danielhanchen merged 8 commits into
mainfrom
fix-peft-torchao-import
Sep 17, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
fix-peft-torchao-import

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Plain 16-bit LoRA dies at get_peft_model on torchao 0.18.0:

File ".../peft/tuners/lora/model.py", line 337, in _create_new_module
    new_module = dispatcher(target, adapter_name, lora_config=lora_config, **kwargs)
File ".../peft/tuners/lora/torchao.py", line 151, in dispatch_torchao
    from torchao.quantization import LinearActivationQuantizedTensor
ImportError: cannot import name 'LinearActivationQuantizedTensor' from 'torchao.quantization'

torchao 0.18.0 removed LinearActivationQuantizedTensor outright. It was not moved: no module in the package defines the name any more, and grep -rn across the installed package returns zero hits. peft 0.18 still imports it inside dispatch_torchao, purely to run one isinstance check.

peft's dispatch table runs every dispatcher in order and keeps the first that returns non-None, so a dispatcher that RAISES kills LoRA creation for models it does not even apply to:

[dynamic] -> bnb_8bit -> bnb_4bit -> eetq -> aqlm -> awq -> gptq -> hqq -> inc -> torchao -> megatron -> default

This is why the failure looks selective. QLoRA never reaches it, because dispatch_bnb_4bit matches and breaks out first. Plain LoRA falls all the way through to dispatch_torchao and dies. On the machine this was found on, a QLoRA run of unsloth/Qwen3-0.6B trained fine while a 16-bit LoRA run of unsloth/gemma-3-270m-it failed at step 0.

Scope

Only peft 0.18 and earlier. I read dispatch_torchao in 0.17.1, 0.18.0, 0.19.0 and 0.20.0: 0.19 and 0.20 already fixed this upstream by importing a single TorchAOBaseTensor from torchao.utils. On those versions the wrapper never sees a failure and calls straight through, so there is zero behaviour change.

What this does

Adds fix_peft_torchao_missing_tensor_subclass() to unsloth/import_fixes.py, wired into unsloth/_gpu_init.py next to the existing fix_peft_stale_torchao_import_error(). The two are complements: the existing one handles torchao being too OLD for peft, this one handles torchao being too NEW.

Rather than swallowing the ImportError and declining, the wrapper redoes upstream's own body against whichever of the two tensor subclasses this torchao actually ships: the BaseTunerLayer unwrap, the hasattr(weight) guard, is_torchao_available(), the isinstance check, then TorchaoLoraLinear. So a weight that still matches a surviving class still gets the torchao LoRA layer, and only genuinely unmatchable weights decline.

That distinction matters. An earlier revision of this change simply returned None on the ImportError, which fixes plain LoRA but would silently downgrade a real torchao user from TorchaoLoraLinear to an ordinary LoRA layer on a quantized weight. Preserving the isinstance semantics avoids trading a loud bug for a quiet one.

Details worth noting:

  • TorchaoLoraLinear, is_torchao_available and BaseTunerLayer are resolved from the original function's own __globals__ first, so the wrapper uses the very objects upstream would have, including an is_torchao_available already patched by the sibling fix.
  • Arguments are recovered with inspect.signature(original).bind(...) and read by position, because peft 0.19 renamed the third parameter from lora_config to config.
  • The patch sweeps sys.modules rather than patching only the defining module. peft/tuners/lora/model.py does from .torchao import dispatch_torchao, which copies the function object, so patching the definition alone would leave the real caller raising.
  • One wrapper per distinct original, shared across every module holding it, so the warning fires once.
  • An ImportError that is not about these two classes still propagates: a missing torchao, a missing submodule, or an _C extension built against another torch must not be masked.

A correction worth recording

AffineQuantizedTensor still imports on torchao 0.18.0, but it is no longer a real class. torchao/dtypes/__init__.py carries # TODO: remove this stub once external repos have migrated off AffineQuantizedTensor, and the class body is a docstring saying AQT has been deleted and the stub exists only so isinstance() returns False without errors. Its bases are (object,) and it is not a torch.Tensor subclass, so no real weight can be an instance of it.

So on torchao 0.18.0 specifically, the silent-downgrade scenario above cannot actually be triggered by any real weight. The implementation here is still the right one, because it preserves the isinstance semantics whatever the two classes happen to be, instead of hard-coding an assumption about what can or cannot exist. The regression test therefore substitutes a genuine tensor subclass for the stub, matching what torchao 0.17 and earlier shipped and what peft's check was written against, and the test docstrings label that stand-in clearly.

Verification

Before:

ImportError: cannot import name 'LinearActivationQuantizedTensor' from 'torchao.quantization'

After, same snippet:

OK layer = Linear
lora_A = dict_keys(['default']) (4, 8)
forward out (2, 8) requires_grad True

With a weight that really is an AffineQuantizedTensor, old revision against new:

[old] resolved LoRA class: peft.tuners.lora.layer.Linear                 is TorchaoLoraLinear: False
[new] resolved LoRA class: peft.tuners.lora.torchao.TorchaoLoraLinear    is TorchaoLoraLinear: True

QLoRA is unaffected: a bnb.nn.Linear4bit target still resolves to peft.tuners.lora.bnb.Linear4bit and runs a forward pass.

Tests

tests/test_peft_torchao_missing_tensor_subclass.py, 29 tests: the bug itself, AQT-still-matches plus the kwargs the layer is built with, a weight of neither class declines, the mirror case with AQT removed instead, neither class present, BaseTunerLayer unwrap, weightless target, is_torchao_available() False, torchao vanishing mid-run still raises, the peft 0.19 parameter rename, the warning text, and a real-torchao check that the helper agrees with peft's own two imports.

Full run with test_peft_stale_torchao.py and the broader import-fix suite: 168 passed, 25 skipped, 2 failed. Both failures are pre-existing and Windows specific (test_lint_duplicate_definitions non-ascii path, test_torchao_subprocess_fix own-hook trust), confirmed identical with these changes stashed on a clean tree.

What was not verified here

Testing ran on Windows ARM64, CPU only, against peft 0.18.1 / torchao 0.18.0 / torch 2.14.0. The four peft versions were compared by reading their source rather than by building a full uv sandbox per combination of peft, torchao, transformers and TRL. Nothing in the change is platform specific, but Linux, macOS and WSL were not exercised directly.

torchao 0.18.0 deleted LinearActivationQuantizedTensor outright, and peft 0.18
still imports it inside dispatch_torchao to run a single isinstance check.
peft's LoRA dispatch table takes the first dispatcher that returns a module, so
a dispatcher that raises ends get_peft_model for models that never touch
torchao. QLoRA never sees this because dispatch_bnb_4bit matches and returns
first; plain 16-bit LoRA falls through to the torchao dispatcher and dies at
step 0 with "cannot import name 'LinearActivationQuantizedTensor' from
'torchao.quantization'".

fix_peft_torchao_missing_tensor_subclass wraps the dispatcher. A torchao that
still ships both classes is untouched: the wrapper calls straight through and
only reacts to the import actually failing. When the import does fail over one
of the two class names, the wrapper redoes the dispatcher's own work against
whichever classes this torchao still ships, so a weight of a surviving subclass
still gets peft's TorchaoLoraLinear and only a weight matching nothing gets an
ordinary LoRA layer. Answering None for everything would have been a quieter
version of the same bug, since AffineQuantizedTensor is still importable.

Only the two tensor subclass names peft imports are treated as removals: a
torchao that is broken rather than newer, or absent entirely, still raises.
The degraded path reads the dispatcher's arguments by position, because peft
0.19 renamed the third parameter; peft 0.19 also replaced the two imports with
a single TorchAOBaseTensor one, so only peft 0.18 and older can reach that path
at all. peft.tuners.lora.model imported the dispatcher by value, so every peft
module holding it gets the same shared wrapper and the warning is emitted once.

Wired into _gpu_init.py next to the other peft fixes, and covered by
tests/test_peft_torchao_missing_tensor_subclass.py.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 17, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-17T12:43:03.705508Z 0dcde4c Manual request
🔒 Security Review ✅ Completed 2026-09-17T02:09:05.135469Z 48beea1 PR opened
ℹ️ 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.

pre-commit-ci Bot and others added 3 commits September 17, 2026 02:14
Ran peft 0.17.1/0.18.0/0.18.1/0.19.0/0.20.0 against torchao 0.17.0, 0.18.0 and
no torchao at all, on torch 2.14 and transformers 4.57.6 and 5.17.0. The fix
held everywhere: the three peft versions that still import
LinearActivationQuantizedTensor fail plain 16-bit LoRA on torchao 0.18.0 and
are repaired, peft 0.19+ calls straight through, and no combination regressed.
No defect surfaced, so this only turns the simulations that were worth keeping
into tests.

New coverage, each one a case the suite could not previously have caught:

- A bare `import peft` is enough for the sweep to reach
  peft.tuners.lora.model, which is where the dispatch list is really built. A
  fake peft cannot show this, so it runs in a child interpreter.
- The fix applied before peft is imported at all, and a fresh interpreter that
  does not inherit the patch but can apply its own.
- An unrelated decorator already wrapping the dispatcher: it must still run,
  and the degraded path must still read the arguments through it, since
  functools.wraps means inspect.signature follows __wrapped__ down to
  upstream's real parameter list.
- Repeated application never stacking wrappers, now five passes rather than
  two, because `import unsloth` can run more than once.
- The patched dispatcher round-tripping through pickle, which spawn workers
  need. Against the real peft: a dispatcher defined inside a test carries a
  <locals> qualname and could not show that upstream's still resolves.
- Why QLoRA never saw this bug, as peft's real dispatch loop rather than an
  assertion about it: a dispatcher matching ahead of dispatch_torchao means
  the torchao one is never called, and with nothing matching earlier it is.
  _custom_modules occupies that short-circuiting slot without needing
  bitsandbytes, which has no wheel on every platform unsloth runs on.
- Mixed module types, where only some targets reach the torchao dispatcher.
- Both torchao peft fixes active at once, since the stale-version one patches
  the is_torchao_available this one calls.
- That torchao 0.18 keeps AffineQuantizedTensor only as an object subclass.
  That is what makes the degraded path answer None for every weight this
  torchao can actually build, so the honest behaviour is an ordinary LoRA
  layer, not TorchaoLoraLinear. Pinned so a torchao that restores a real
  tensor subclass under that name fails the test loudly.

Also skip rather than fail the real-peft tests when peft is not importable for
reasons that have nothing to do with this fix. pytest.importorskip only counts
a missing module as a skip, but peft 0.17 against transformers 5 raises
"cannot import name 'HybridCache'", which was reported as a failure of the
pre-existing test_real_plain_lora_survives_this_torchao.
@danielhanchen

Copy link
Copy Markdown
Member Author

Simulation and compatibility pass

I ran this against real installs rather than reasoning about it, on Windows ARM64 / Python 3.13 / torch 2.14.0, CPU only. One venv, swapping only peft and torchao inside it. torchao publishes py3-none-any wheels, so 0.17.0 and 0.18.0 both install here.

Result: no defect found. The fix behaves as described on every combination I could execute, so the only commit this pass adds is test coverage (d5c23c4).

Executed matrix

before is plain 16-bit LoRA with the fix not applied, after is the same with it applied. Every cell also checked that an earlier-matching dispatcher still short-circuits ahead of the torchao one (the reason QLoRA escapes), and that applying the fix a second time is a no-op.

peft torchao before after fix fires resolved layer torchao-quantized weight
0.17.1 absent ok ok no, calls through lora.Linear n/a
0.17.1 0.17.0 ok ok no, calls through lora.Linear AffineQuantizedTensor
0.17.1 0.18.0 ImportError ok yes, once lora.Linear Int8Tensor
0.18.0 absent ok ok no lora.Linear n/a
0.18.0 0.17.0 ok ok no lora.Linear AffineQuantizedTensor
0.18.0 0.18.0 ImportError ok yes, once lora.Linear Int8Tensor
0.18.1 absent ok ok no lora.Linear n/a
0.18.1 0.17.0 ok ok no lora.Linear AffineQuantizedTensor
0.18.1 0.18.0 ImportError ok yes, once lora.Linear Int8Tensor
0.19.0 absent / 0.17.0 / 0.18.0 ok ok no, calls through lora.Linear as above
0.20.0 absent / 0.17.0 / 0.18.0 ok ok no, calls through lora.Linear as above

The failure on the three affected cells is exactly the one in the PR body:

ImportError: cannot import name 'LinearActivationQuantizedTensor' from 'torchao.quantization'

Also executed on transformers 5.17.0 with peft 0.18.1 and 0.20.0 against torchao 0.18.0 and absent. Identical results. That is expected: the dispatcher list is built entirely inside peft.tuners.lora.model, so transformers cannot reach it.

The full test file was then run green (58 tests, counting the sibling stale-torchao file) on peft 0.17.1, 0.18.0, 0.18.1, 0.19.0 and 0.20.0 crossed with torchao 0.17.0, 0.18.0 and absent.

What I theorised could break, and what happened

Theory Outcome
The sweep only sees modules already in sys.modules, so a bare import peft might leave peft.tuners.lora.model unpatched while .torchao looks fine Holds. import peft pulls the LoRA tuner in, both copies get the same wrapper. Now tested in a child interpreter, since a fake peft cannot show this
peft 0.19 renamed the third parameter lora_config to config Handled. Arguments are read by position. Confirmed peft 0.19 also switched to a single TorchAOBaseTensor import, so it never reaches the degraded path anyway
functools.wraps confusing peft introspecting its own dispatchers No introspection in the dispatch loop. Signature and name survive, and inspect.signature follows __wrapped__
Double patching when import unsloth runs twice No-op, verified to five passes
Interaction with fix_peft_stale_torchao_import_error, which patches is_torchao_available Both active together works. The degraded path reads is_torchao_available from the defining module's live globals at call time, so it picks up the sibling patch
Pickling or deepcopy of a patched dispatcher Both fine. functools.wraps keeps upstream's __module__ and __qualname__, and the patch replaces the attribute those name, so pickle's by-reference lookup lands back on the wrapper
Subprocess or spawn dataloader workers re-importing The patch is per-process and is not inherited, which is correct. A child that imports unsloth re-applies it. Dataloader workers never call get_peft_model
torchao present but broken rather than newer Still raises. A bad .so message is not swallowed
torch.compile or dynamo tracing through the wrapper Not reachable. get_peft_model runs before any compile
The wrapper changing exception type or traceback It does not. A non-matching ImportError, and any non-ImportError, propagate unchanged
An unrelated decorator already wrapping dispatch_torchao The foreign decorator still runs and the degraded path still reads arguments through it
Dispatcher ordering, the claim that QLoRA escapes Confirmed against peft's real dispatch loop: with a dispatcher matching earlier the torchao one is called zero times, with nothing matching earlier it is called once per target

One honest correction to the PR body

The commit message says the degraded path means "a weight of a surviving subclass still gets peft's TorchaoLoraLinear". That is true as written but vacuous on the only version that triggers it. On torchao 0.18.0, AffineQuantizedTensor survives only as a backwards-compatibility stub:

AffineQuantizedTensor.__bases__ == (object,)

It is not a torch.Tensor subclass, so no weight torchao 0.18 can actually build is an instance of it. quantize_(..., Int8WeightOnlyConfig()) produces Int8Tensor. So on peft <= 0.18 plus torchao 0.18 the degraded path answers None for everything and every weight gets an ordinary LoRA layer.

I am leaving that behaviour as is, deliberately. Widening the check to TorchAOBaseTensor, which is what peft 0.19 switched to, would match Int8Tensor and build peft 0.18's TorchaoLoraLinear, which then raises TypeError: TorchaoLoraLinear.__init__() missing 1 required keyword-only argument: 'get_apply_tensor_subclass'. That would trade a working plain LoRA for a crash. Declining is the right answer, and the warning already tells the user to pin torchao<0.18 if they need those weights. I pinned the stub's shape in a test so a future torchao that restores a real tensor subclass under that name fails loudly instead of silently.

Separately, TorchaoLoraLinear requiring get_apply_tensor_subclass on peft <= 0.19 is a pre-existing upstream limitation. It reproduces identically with and without this patch, and is unrelated to this PR. peft 0.20.0 resolves Int8Tensor to TorchaoLoraLinear cleanly.

Primary sources

So: 0.18.0 is the torchao release that drops it, and peft 0.17.1 through 0.18.1 carry the old import. Both match the PR body.

Test changes in d5c23c4

Nine new cases covering the simulations worth keeping, plus one fix to a pre-existing test. pytest.importorskip only treats a missing module as a skip, so test_real_plain_lora_survives_this_torchao was reporting a failure when peft 0.17 met transformers 5 and raised cannot import name 'HybridCache'. That now skips. Baseline before my commit was 47 passed, after is 58 passed, with no pre-existing failures in a consistent environment.

Not verified

Being explicit about what this pass does not cover:

  • Linux, macOS and WSL. Nothing was run on them. Windows ARM64 only.
  • Real QLoRA. bitsandbytes has no Windows ARM64 wheel. The short-circuit claim was exercised through peft's real dispatch loop using _custom_modules, which occupies the same position ahead of dispatch_torchao that dispatch_bnb_4bit does, but it is a stand-in and I have not run an actual 4-bit model.
  • GPU. Everything was CPU only, deliberately.
  • Older torch. torch 2.14 only. Older torch wheels are not available for Windows ARM64, which is a real constraint of this host, not a skipped step.
  • TRL. Not executed. Code search across huggingface/trl at 0.22.2 and 1.13.0 returns zero hits for dispatch_torchao, _create_new_module and LinearActivationQuantizedTensor. TRL calls get_peft_model and never touches the dispatcher list, so its version cannot influence this path. I skipped it rather than burning the bandwidth.
  • A real end-to-end training run. The matrix builds LoRA models and checks the resolved layer classes and a forward pass, not a full fine-tune.

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 17, 2026
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 17, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

Simulation report

#11168 | issue: REAL | PR as submitted: CORRECT, 0 fixed by me | merge: YES, after #11167

Took this one over and ran the full simulation. Nothing needed changing, so the branch is untouched.

Before and after

Reproduced with the real torchao 0.18.0+cu130 and peft 0.18.0 installed side by side and put ahead of the venv's 0.20.0. One process per cell.

arm result
main ImportError: cannot import name 'LinearActivationQuantizedTensor' from 'torchao.quantization'
branch ok, layer peft.tuners.lora.layer.Linear, forward (2, 8) requires_grad True

REAL. get_peft_model dies on main for a model that has nothing to do with torchao, and works on the branch with the warning naming the cause once.

The part that actually needed proving

The risk here is not "does plain LoRA work again", it is "does a real torchao weight still get TorchaoLoraLinear". So I called the dispatcher directly with the kwargs peft/tuners/lora/model.py passes, comparing unpatched peft 0.18 with LinearActivationQuantizedTensor restored (that is, torchao 0.17 behaviour) against this branch on the real torchao 0.18:

weight upstream, both classes branch, one class
plain nn.Linear weight None None
AffineQuantizedTensor TorchaoLoraLinear TorchaoLoraLinear
LinearActivationQuantizedTensor TorchaoLoraLinear None

Identical except the third row, which is the unavoidable residue: on torchao 0.18 that class does not exist, so no weight can be an instance of it and the row is unreachable in reality.

One apparent divergence I chased down and cleared. Through get_peft_model, an AffineQuantizedTensor weight fails on the branch with TypeError: TorchaoLoraLinear.__init__() missing 1 required keyword-only argument: 'get_apply_tensor_subclass'. Control run: unpatched peft 0.18 with both classes present fails with the identical TypeError. That is upstream's own behaviour for that setup, not something this PR introduced.

No-op on peft 0.19 and 0.20

On the venv's real peft 0.20.0: wrapper installed, zero warnings, every dispatch result identical to unpatched. Those versions import a single TorchAOBaseTensor, so the wrapper never sees a failure and calls straight through, as the body says.

Enumeration

Full cross product of what the wrapper reads: the original's failure mode (5) x which classes this torchao ships (4) x weight kind (4) x target wrapped in BaseTunerLayer (2) x is_torchao_available (2) = 320 cells.

CALLED_THROUGH       64
DECLINED            112
RAISE:ImportError   128
TORCHAO_LAYER        16

by what the original dispatcher did:
  none               CALLED_THROUGH 64
  missing_laqt       DECLINED 56, TORCHAO_LAYER 8
  missing_aqt        DECLINED 56, TORCHAO_LAYER 8
  torchao_absent     RAISE:ImportError 64
  broken_extension   RAISE:ImportError 64

The 128 re-raises are the number that matters: an ImportError that is not about those two class names is never masked, so a missing torchao and an _C extension built against another torch still surface exactly as before.

Differential and mutation

40 passed on the branch. On merge-base f6cf06dec the file does not even collect, because the symbols are not there, so that arm is vacuous as behavioural evidence and the A/B tables above are what carries the claim.

Mutation: 8 mutants, 8 killed. The regex widened to mask unrelated ImportErrors, the re-raise removed, the isinstance check dropped, the weightless-target guard dropped, is_torchao_available ignored, the BaseTunerLayer unwrap dropped, the sys.modules sweep narrowed to the defining module, and the call removed from _gpu_init.py. Nothing survived.

Worth recording because it nearly produced a false finding: the sweep guard if not mod_name.startswith("peft") or mod is None: appears twice in import_fixes.py, the first occurrence being in the older fix_peft_stale_torchao_import_error. A single-occurrence replace mutates that one instead and reports a survivor. Anchored properly, the mutant dies.

Cross-platform staging

Run off the org queue on four runners, including the two the change does not touch:

runner result
ubuntu-latest success
ubuntu-24.04-arm success
windows-latest success
macos-15 success

Merge order with #11167

Both add a function to unsloth/import_fixes.py and a call plus two dels to unsloth/_gpu_init.py. Different regions of both files, so no textual conflict, but whichever lands second wants a rebase of the _gpu_init.py import list. #11167 is the one I had to change, so merge that first and rebase this. Neither fix can affect the other: one runs before torch, one after peft.

What I could not prove

  • No real torchao-quantized weight was trained. The AffineQuantizedTensor cases use a genuine tensor subclass standing in for the 0.18 stub, which is what torchao 0.17 and earlier shipped and what peft's check was written against, but it is a stand-in.
  • peft 0.19 was not installed. The parameter-rename handling is covered only by this branch's own test, not against the real 0.19.
  • The gemma-3-270m and Qwen3-0.6B runs in the body were not re-run; my reproduction is at the get_peft_model level on a two-layer module.

… header

Opening comment-reduction pass: comment and docstring lines introduced by this
change go from 211 to 120. The section banners in the test file are gone, the
dispatch-order explanation is stated once in the module docstring instead of
three more times, and the measured version sweeps move to the PR description.

The new test file also carried the Apache-2.0 header copied from an older test;
new files in this repo take the AGPL-3.0 SPDX line.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 17, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 2 commits September 17, 2026 12:06
The name match is on the ImportError MESSAGE, so a failure raised elsewhere in
the dispatcher that happens to mention one of the two classes reached the
degraded path with nothing actually missing. Reproduced: both classes present,
the dispatcher raising

    cannot import name 'quantize_' from
    'torchao.quantization.linear_activation_quantized_tensor'

after it had already started building, and the wrapper swallowed that error and
re-ran the dispatch, so construction happened twice and the real failure never
surfaced. With the guard the original propagates and the dispatcher runs once.

This is what the design already stated: only a genuinely missing class earns
the degraded path.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: d0c8b079f0

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

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 17, 2026
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 17, 2026
pre-commit's ruff-format-with-kwargs splits a signature that carries a spaced
default, which the dispatcher stub in the new test does.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen
danielhanchen merged commit fff6ee6 into main Sep 17, 2026
3 of 28 checks passed
@danielhanchen
danielhanchen deleted the fix-peft-torchao-import branch September 17, 2026 12:41
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 0dcde4ce35

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

shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
* Stop a missing torchao class from killing plain LoRA

torchao 0.18.0 deleted LinearActivationQuantizedTensor outright, and peft 0.18
still imports it inside dispatch_torchao to run a single isinstance check.
peft's LoRA dispatch table takes the first dispatcher that returns a module, so
a dispatcher that raises ends get_peft_model for models that never touch
torchao. QLoRA never sees this because dispatch_bnb_4bit matches and returns
first; plain 16-bit LoRA falls through to the torchao dispatcher and dies at
step 0 with "cannot import name 'LinearActivationQuantizedTensor' from
'torchao.quantization'".

fix_peft_torchao_missing_tensor_subclass wraps the dispatcher. A torchao that
still ships both classes is untouched: the wrapper calls straight through and
only reacts to the import actually failing. When the import does fail over one
of the two class names, the wrapper redoes the dispatcher's own work against
whichever classes this torchao still ships, so a weight of a surviving subclass
still gets peft's TorchaoLoraLinear and only a weight matching nothing gets an
ordinary LoRA layer. Answering None for everything would have been a quieter
version of the same bug, since AffineQuantizedTensor is still importable.

Only the two tensor subclass names peft imports are treated as removals: a
torchao that is broken rather than newer, or absent entirely, still raises.
The degraded path reads the dispatcher's arguments by position, because peft
0.19 renamed the third parameter; peft 0.19 also replaced the two imports with
a single TorchAOBaseTensor one, so only peft 0.18 and older can reach that path
at all. peft.tuners.lora.model imported the dispatcher by value, so every peft
module holding it gets the same shared wrapper and the warning is emitted once.

Wired into _gpu_init.py next to the other peft fixes, and covered by
tests/test_peft_torchao_missing_tensor_subclass.py.

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

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

* Widen the torchao dispatcher tests to what the version matrix exercised

Ran peft 0.17.1/0.18.0/0.18.1/0.19.0/0.20.0 against torchao 0.17.0, 0.18.0 and
no torchao at all, on torch 2.14 and transformers 4.57.6 and 5.17.0. The fix
held everywhere: the three peft versions that still import
LinearActivationQuantizedTensor fail plain 16-bit LoRA on torchao 0.18.0 and
are repaired, peft 0.19+ calls straight through, and no combination regressed.
No defect surfaced, so this only turns the simulations that were worth keeping
into tests.

New coverage, each one a case the suite could not previously have caught:

- A bare `import peft` is enough for the sweep to reach
  peft.tuners.lora.model, which is where the dispatch list is really built. A
  fake peft cannot show this, so it runs in a child interpreter.
- The fix applied before peft is imported at all, and a fresh interpreter that
  does not inherit the patch but can apply its own.
- An unrelated decorator already wrapping the dispatcher: it must still run,
  and the degraded path must still read the arguments through it, since
  functools.wraps means inspect.signature follows __wrapped__ down to
  upstream's real parameter list.
- Repeated application never stacking wrappers, now five passes rather than
  two, because `import unsloth` can run more than once.
- The patched dispatcher round-tripping through pickle, which spawn workers
  need. Against the real peft: a dispatcher defined inside a test carries a
  <locals> qualname and could not show that upstream's still resolves.
- Why QLoRA never saw this bug, as peft's real dispatch loop rather than an
  assertion about it: a dispatcher matching ahead of dispatch_torchao means
  the torchao one is never called, and with nothing matching earlier it is.
  _custom_modules occupies that short-circuiting slot without needing
  bitsandbytes, which has no wheel on every platform unsloth runs on.
- Mixed module types, where only some targets reach the torchao dispatcher.
- Both torchao peft fixes active at once, since the stale-version one patches
  the is_torchao_available this one calls.
- That torchao 0.18 keeps AffineQuantizedTensor only as an object subclass.
  That is what makes the degraded path answer None for every weight this
  torchao can actually build, so the honest behaviour is an ordinary LoRA
  layer, not TorchaoLoraLinear. Pinned so a torchao that restores a real
  tensor subclass under that name fails the test loudly.

Also skip rather than fail the real-peft tests when peft is not importable for
reasons that have nothing to do with this fix. pytest.importorskip only counts
a missing module as a skip, but peft 0.17 against transformers 5 raises
"cannot import name 'HybridCache'", which was reported as a failure of the
pre-existing test_real_plain_lora_survives_this_torchao.

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

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

* Cut the comment volume in this change, and fix the new file's licence header

Opening comment-reduction pass: comment and docstring lines introduced by this
change go from 211 to 120. The section banners in the test file are gone, the
dispatch-order explanation is stated once in the module docstring instead of
three more times, and the measured version sweeps move to the PR description.

The new test file also carried the Apache-2.0 header copied from an older test;
new files in this repo take the AGPL-3.0 SPDX line.

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

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

* Re-raise when the message names a class that is still there

The name match is on the ImportError MESSAGE, so a failure raised elsewhere in
the dispatcher that happens to mention one of the two classes reached the
degraded path with nothing actually missing. Reproduced: both classes present,
the dispatcher raising

    cannot import name 'quantize_' from
    'torchao.quantization.linear_activation_quantized_tensor'

after it had already started building, and the wrapper swallowed that error and
re-ran the dispatch, so construction happened twice and the real failure never
surfaced. With the guard the original propagates and the dispatcher runs once.

This is what the design already stated: only a genuinely missing class earns
the degraded path.

* Apply the kwarg-spacing hook to the new test

pre-commit's ruff-format-with-kwargs splits a signature that carries a spaced
default, which the dispatcher stub in the new test does.

---------

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant