Repository navigation
Stop a removed torchao class from killing plain LoRA - #11168
Conversation
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.
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. |
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.
Simulation and compatibility passI 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 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
The failure on the three affected cells is exactly the one in the PR body: 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 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
One honest correction to the PR bodyThe commit message says the degraded path means "a weight of a surviving subclass still gets peft's It is not a I am leaving that behaviour as is, deliberately. Widening the check to Separately, 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 d5c23c4Nine new cases covering the simulations worth keeping, plus one fix to a pre-existing test. Not verifiedBeing explicit about what this pass does not cover:
|
Simulation report
Took this one over and ran the full simulation. Nothing needed changing, so the branch is untouched. Before and afterReproduced 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.
REAL. The part that actually needed provingThe risk here is not "does plain LoRA work again", it is "does a real torchao weight still get
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 No-op on peft 0.19 and 0.20On the venv's real peft 0.20.0: wrapper installed, zero warnings, every dispatch result identical to unpatched. Those versions import a single EnumerationFull 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 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 Differential and mutation40 passed on the branch. On merge-base 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, Worth recording because it nearly produced a false finding: the sweep guard Cross-platform stagingRun off the org queue on four runners, including the two the change does not touch:
Merge order with #11167Both add a function to What I could not prove
|
… 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.
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.
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. 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". |
pre-commit's ruff-format-with-kwargs splits a signature that carries a spaced default, which the dispatcher stub in the new test does.
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
* 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>
Plain 16-bit LoRA dies at
get_peft_modelon torchao 0.18.0:torchao 0.18.0 removed
LinearActivationQuantizedTensoroutright. It was not moved: no module in the package defines the name any more, andgrep -rnacross the installed package returns zero hits. peft 0.18 still imports it insidedispatch_torchao, purely to run oneisinstancecheck.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:
This is why the failure looks selective. QLoRA never reaches it, because
dispatch_bnb_4bitmatches and breaks out first. Plain LoRA falls all the way through todispatch_torchaoand dies. On the machine this was found on, a QLoRA run ofunsloth/Qwen3-0.6Btrained fine while a 16-bit LoRA run ofunsloth/gemma-3-270m-itfailed at step 0.Scope
Only peft 0.18 and earlier. I read
dispatch_torchaoin 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 singleTorchAOBaseTensorfromtorchao.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()tounsloth/import_fixes.py, wired intounsloth/_gpu_init.pynext to the existingfix_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
BaseTunerLayerunwrap, thehasattr(weight)guard,is_torchao_available(), the isinstance check, thenTorchaoLoraLinear. 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
Noneon the ImportError, which fixes plain LoRA but would silently downgrade a real torchao user fromTorchaoLoraLinearto 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_availableandBaseTunerLayerare resolved from the original function's own__globals__first, so the wrapper uses the very objects upstream would have, including anis_torchao_availablealready patched by the sibling fix.inspect.signature(original).bind(...)and read by position, because peft 0.19 renamed the third parameter fromlora_configtoconfig.sys.modulesrather than patching only the defining module.peft/tuners/lora/model.pydoesfrom .torchao import dispatch_torchao, which copies the function object, so patching the definition alone would leave the real caller raising.torchao, a missing submodule, or an_Cextension built against another torch must not be masked.A correction worth recording
AffineQuantizedTensorstill imports on torchao 0.18.0, but it is no longer a real class.torchao/dtypes/__init__.pycarries# 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 soisinstance()returns False without errors. Its bases are(object,)and it is not atorch.Tensorsubclass, 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:
After, same snippet:
With a weight that really is an
AffineQuantizedTensor, old revision against new:QLoRA is unaffected: a
bnb.nn.Linear4bittarget still resolves topeft.tuners.lora.bnb.Linear4bitand 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,BaseTunerLayerunwrap, 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.pyand the broader import-fix suite: 168 passed, 25 skipped, 2 failed. Both failures are pre-existing and Windows specific (test_lint_duplicate_definitionsnon-ascii path,test_torchao_subprocess_fixown-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.