Repository navigation
Survive a torchao that does not match the installed torch - #7856
danielhanchen wants to merge 11 commits into
Conversation
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d26556d88e
ℹ️ 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".
| os.makedirs(directory, mode = 0o700, exist_ok = True) | ||
| if hasattr(os, "getuid"): | ||
| info = os.lstat(directory) | ||
| if stat.S_ISLNK(info.st_mode) or info.st_uid != os.getuid(): |
There was a problem hiding this comment.
Reject a pre-existing writable hook directory
If this fixed per-user temp directory already exists with group- or world-write permissions, os.makedirs(..., mode=0o700, exist_ok=True) leaves its existing mode unchanged, while the subsequent check accepts it as long as the victim owns it. Another account with write access can then replace sitecustomize.py, which will be executed automatically by every Python child after this directory is added to PYTHONPATH; verify or repair the directory's permission bits before trusting it.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The ownership and symlink cases are already checked at import_fixes.py:3512-3517, and the path is per-uid (3507), so an attacker cannot create a directory owned by the victim; if they pre-create it under their own uid the lstat check refuses it. /tmp is sticky, so they cannot replace a victim-owned one either. That leaves the victim having previously created that exact path world-writable, which nothing does.
torchao is an optional dependency that unsloth never pins tightly, so the
version a notebook resolves is whatever the index serves that day. Several
recent torchao releases broke `import unsloth` outright, each in a different
place. This collects the fixes.
1. An old torchao aborts LoRA creation that never uses it.
`peft.import_utils.is_torchao_available` returns False when torchao is
absent, but raises when it is installed and older than peft's minimum:
ImportError: Found an incompatible version of torchao. Found version
0.10.0, but only versions above 0.16.0 are supported
peft calls it from `dispatch_torchao` for every LoRA layer, so one stale
optional dependency ends `get_peft_model` for a model that has nothing to
do with torchao. Kaggle ships torchao 0.10.0 preinstalled, so the
difference between pass and fail was one `pip install` line in a notebook.
`fix_peft_stale_torchao_import_error` answers False and warns once, naming
the upgrade. Only the version complaint is caught; any other ImportError
still propagates. Both binding sites are patched, since
`from peft.import_utils import is_torchao_available` copies the original
into peft.tuners.lora.torchao, the actual caller.
2. torchao 0.18 imports torch symbols that torch below 2.10 does not have.
0.17 guarded the import behind `torch_version_at_least("2.10.0")`; 0.18.0
left it at module level:
ImportError: cannot import name 'ScalingType' from 'torch.nn.functional'
It surfaces while importing transformers, so it reaches the user as a bare
Exception naming neither torchao nor torch, and kills `import unsloth`.
`fix_torchao_torch_symbol_skew` supplies placeholders that import cleanly
and refuse to be used: 0.17 simply left these names undefined on old torch,
so anything wanting them already raised, and a stub impersonating a real
enum could hand a float8 path a meaningless value. The symbol list comes
from the whole installed package, not one file:
grep -rh "from torch.nn.functional import" torchao/
which is how scaled_grouped_mm got in. Reading only mx_formats/mx_tensor.py
gives ScalingType and SwizzleType and misses the one on the path of a plain
`import torchao`. scaled_dot_product_attention exists on every supported
torch, and the loop skips anything torch already provides.
3. torchao 0.18 also wants an aten op that torch below 2.8 does not have.
It registers a float8 handler at module scope with
`@implements([aten._grouped_mm.default])`, and the attribute lookup raises
before the decorator is applied. Sibling of the symbol skew but a different
lookup: that one goes through torch.nn.functional, this one through
torch.ops, so supplying the functional names does nothing for it. The
schema is registered and nothing else, as a FRAGMENT into aten, and calling
it raises: torchao only wants somewhere to hang a handler this torch will
never dispatch to, and a plausible-looking grouped matmul would be worse
than the crash it replaces.
4. The in-process fix does not reach vLLM. vLLM inspects model architectures
in a separate process which imports torchao itself, so with
fast_inference = True the run still died, and the user saw only
"Model architectures ['...'] failed to be inspected".
`propagate_torchao_fix_to_subprocesses` stages a sitecustomize on
PYTHONPATH, which children inherit. It chains to any other sitecustomize on
sys.path rather than shadowing it, guarded so a broken one elsewhere cannot
become a startup crash for every subprocess. The logic is inlined rather
than importing unsloth, which would pay the full import cost at the start of
every subprocess on the machine and could recurse. Writes via os.replace so
a concurrent run cannot expose a truncated file, and uses os.pathsep for
Windows.
5. torchao 0.18.0 moved torchao/dtypes/nf4tensor.py to
torchao/quantization/quantize_/workflows/nf4/nf4_tensor.py. torchtune still
imports the old path and xcodec2 imports torchtune, so TTS work died with
ModuleNotFoundError one cell after a green install. `fix_torchao_nf4tensor_move`
appends a meta path finder after the real finders, so an older torchao that
still ships the module always wins, and the loader returns the relocated
module itself rather than a hand-copied stub, so it cannot rot as symbols
are added. Resolution is lazy, so `import unsloth` does not pay for a
torchao import nobody asked for.
Every fix is gated on torchao being installed, the version actually having the
bug, and the torch symbol genuinely being absent. On a healthy pair none of
them do anything, so nothing is masked. The symbol fix is also called from the
MLX branch of __init__.py, which never reaches _gpu_init.
Tests: 84 across five files. They build real package trees and import them in
subprocesses rather than stubbing sys.modules, since appended-versus-inserted
finders and PYTHONPATH inheritance only mean anything to the real import
machinery. 82 pass here; 2 skip because this machine has torchao installed and
a torch that already provides the symbols.
d26556d to
18ae443
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 18ae443403
ℹ️ 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".
|
|
||
| _ATEN_LIBRARY = None | ||
|
|
||
| _chain_to_the_real_sitecustomize() |
There was a problem hiding this comment.
Apply the compatibility patch before chaining sitecustomize
In the generated subprocess hook, an existing sitecustomize.py is executed before _apply(). If that customization imports transformers, torchao, or another module that reaches the incompatible torchao import, it encounters the exact symbol-skew failure this hook is meant to prevent; the exception is then swallowed by _chain_to_the_real_sitecustomize, so the child continues but the existing customization never completes or gets retried. Apply the compatibility fix before invoking the chained customization.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The ordering is as you read it and is asserted deliberately (tests/test_torchao_subprocess_fix.py:56), but the harm needs a third-party sitecustomize that imports torch or torchao at interpreter startup. Both sitecustomize files on this machine avoid exactly that, since importing torch there costs every process on the box about 1.2s, and without our file site.execsitecustomize would truncate the same customization anyway, just noisily.
| import torch | ||
| import torch.nn.functional as F |
There was a problem hiding this comment.
Avoid importing torch in every Python child
Once this hook is staged, it runs for every Python subprocess inheriting PYTHONPATH, including helpers that never import torchao, and _apply() eagerly imports the full torch package during interpreter startup. On affected torchao/torch environments this adds torch's substantial startup time and memory cost to unrelated Python commands and worker processes; defer the patch until a child actually begins importing torchao rather than importing torch unconditionally from sitecustomize.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
_apply() returns before importing torch unless torchao is installed and at least 0.18 (import_fixes.py:3563-3571), and PYTHONPATH is set through os.environ at 3716, so this reaches descendants of the unsloth process rather than every Python on the machine. Measured here at 1.16s versus 0.03s for those children: a startup cost in an already-broken environment, not wrong behaviour.
| if "torchao" not in message.lower(): | ||
| raise |
There was a problem hiding this comment.
Restrict suppression to PEFT's version error
The wrapper claims to suppress only PEFT's stale-version complaint, but this condition accepts every ImportError whose text happens to mention torchao. If PEFT or a custom integration reports a real torchao import failure such as a missing symbol or native extension, this converts it to False; for a torchao-quantized base layer, PEFT then skips its torchao dispatcher and proceeds as though the dependency were merely absent, hiding the actual incompatibility and potentially selecting the wrong layer path. Match the specific incompatible-version error rather than the package name alone.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
peft never imports torchao in is_torchao_available: every version from v0.14.0 through main uses importlib.util.find_spec plus importlib_metadata.version, so the stale-version complaint is the only ImportError that can reach import_fixes.py:3242. In the case this PR targets, torchao 0.18 with torch 2.9, the raw ImportError comes from dispatch_torchao's own torchao.utils import, outside this wrapper entirely.
_gpu_init.py calls fix_torchao_torch_symbol_skew() immediately before
propagate_torchao_fix_to_subprocesses(). The first adds a placeholder to
torch.nn.functional for every symbol torch is missing and registers the
aten::_grouped_mm schema; the second then asked hasattr(F, n) and
_torch_op_is_missing("aten", "_grouped_mm") and read both as healthy. So it
returned before staging anything, in exactly the environments it exists for.
Measured on torch 2.9.1: the fix places all three symbols, propagate returns
None, nothing is written and PYTHONPATH is untouched. vLLM's architecture
inspector child therefore still died with the original ImportError, which is
the whole reason for that half of the change.
The gate now asks whether TORCH provides the symbol rather than whether one is
merely present, using the __unsloth_placeholder__ marker the placeholder
already carries, and treats a registered _aten_grouped_mm_library as proof the
op was missing. Reordering the two calls in _gpu_init.py would also work today
but leaves the same landmine for the next reorder.
The decisive symbol test never ran. Its skip predicate was any(hasattr(F, n)
for n in _TORCHAO_TORCH_SYMBOLS), and that tuple contains
scaled_dot_product_attention, which the test above it asserts exists on every
supported torch, so it was unconditionally true. It skipped on every machine,
including this one, which is genuinely missing ScalingType and SwizzleType. Now
gated on the two symbols the reproduced import line actually names, and it
passes.
The nf4 alias is installed on the MLX path too. _gpu_init.py was its only
caller and the _IS_MLX branch never reaches it, so an Apple Silicon user whose
audio work reaches xcodec2 and torchtune still hit the ModuleNotFoundError this
fix exists for. It sits next to the symbol fix already called there.
The alias loader no longer corrupts the relocated module's specification.
create_module returns the real module, and module_from_spec then overwrites its
__spec__ with the old-name one, because importlib/_bootstrap.py assigns
__spec__ unconditionally while guarding every other attribute. find_spec for
the new name reported the old one, and reload ran the alias loader's no-op
exec_module instead of the file. exec_module now restores it.
Tests: 90 pass, 1 skip, over the five torchao files. 4 new, each failing
without its fix.
unsloth is Apache-2.0 (LICENSE, and pyproject license = "Apache-2.0"), and 303 of its 314 test files carry no header at all while 10 carry the Apache one. The new files here went in with an AGPL-3.0 notice attributed to Unsloth Zoo, which is the wrong licence, the wrong project and against the convention here.
CI now installs torchao 0.18.0, which broke two premises. test_the_real_environment_is_left_alone decided "this machine has the old layout" from find_spec, but by then the session had imported unsloth and the alias answers that query, so a new-layout runner looked like an old-layout one and the assert fired. Ask the filesystem instead, in a child, like every other case in that file. test_it_does_nothing_when_torchao_is_absent shadowed torch on PYTHONPATH but could not un-install torchao, and importlib.metadata is what the hook reads, so the runner's real torchao made "absent" false. Run that child in a venv without system packages.
…wn placeholders
The rebuild dropped empty components. An empty component is an import
location, not padding: it is what PYTHONPATH="$PYTHONPATH:/opt/lib" leaves
behind when PYTHONPATH was unset, and CPython reads it as the cwd (3.11+
absolutises every component in Modules/getpath.py and abspath("") is the cwd;
3.10 puts the literal "" on sys.path and site.removeduppaths() absolutises
it). Dropping them took an import location away from every descendant. The
opposite case still has to be handled: a set-but-empty PYTHONPATH is ignored
by CPython, so splitting it would ADD the cwd. Hence the 'if current' guard
rather than dropping the filter outright.
Two test probes had the mirror-image bug. conftest.py imports unsloth, so on
the environment these fixes exist for the placeholders are already on
torch.nn.functional before any test runs, and a plain hasattr reads that as a
healthy torch. Use _torch_really_has, and drop the placeholders first in the
two tests that need to observe the 'before' state.
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
pre-commit.ci's ruff-format-with-kwargs hook reported "files were modified by
this hook" and could not push the result back, so the check stayed red.
Applied locally instead.
Three source-asserting tests had to be made robust rather than re-pinned,
since the reformatting is legitimate and will happen again:
- test_the_flag_is_recorded_beside_the_dtype counted the literal
"self._autocast_enabled = (", which the formatter collapsed onto one line.
Now pairs each _autocast_dtype initialiser with a nearby flag assignment by
position, so it still catches a genuinely missing one.
- test_the_original_error_is_still_reported anchored on a whole f-string
literal, which the formatter merged with the hint that follows it. Anchors
on the message text alone now; either shape satisfies the intent.
- test_the_source_beats_the_version_fallback exposed a real fragility rather
than a test problem: the detector matched the literal "kw_only=True", so any
whitespace in transformers' own source would have read an install that needs
nothing as one that needs patching. Made whitespace-tolerant.
|
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". |
|
@codex review |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2c231f3dce
ℹ️ 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".
| cand = os.path.join(entry, "sitecustomize.py") | ||
| if not os.path.isfile(cand): |
There was a problem hiding this comment.
Preserve package-form sitecustomize hooks
When an existing customization is installed as a package (sitecustomize/__init__.py), CPython imports it normally, but this chain only probes for a sitecustomize.py file. Because the Unsloth hook directory is prepended to PYTHONPATH, those environments now run only this generated hook and silently skip their existing startup customization in every child process; use the normal import machinery for each remaining path entry so package/pyc forms are chained too.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in af51c70.
Reproduced against a real child interpreter. The chain probed os.path.join(entry, "sitecustomize.py") with os.path.isfile, so only the flat-file form was ever found:
| PYTHONPATH | child output, before |
|---|---|
other/ alone (CPython baseline, package form) |
PACKAGE SITECUSTOMIZE RAN |
hook/:other/ |
nothing, silently skipped |
hook/:plain/ |
PLAIN SITECUSTOMIZE RAN |
hook/:pyconly/ (sitecustomize.pyc, no source) |
nothing, silently skipped |
So both the package form and a bare .pyc lost their startup customization in every child we spawn, exactly as you describe.
It now uses PathFinder.find_spec("sitecustomize", [entry]), the same machinery CPython would use, which covers .py, package, .pyc and zipimport forms; namespace hits are skipped. Two details that turned out to matter:
- the module is registered as
sys.modules["sitecustomize"]only for the duration ofexec_moduleand restored in afinally, otherwise a package-form hook doingfrom . import extraraises, because the parent name insys.moduleswas our own hook module with no__path__. - entry comparison is
os.path.normcase(os.path.abspath(entry)), so the self-skip holds on case-insensitive Windows and WSL paths.
Failure handling is now split rather than uniform: an exception while probing an entry continues to the next, while an exception from a chained hook's own code still breaks, which matches CPython and keeps the existing contract that someone else's bug must not stop the interpreter starting. Still stdlib-only with no heavy imports, since this runs at startup in every child.
Three new subprocess tests, including a package hook that does from . import extra so discovery and package-relative imports are both covered, and a broken package hook that must not kill the process. With the fix stashed: 2 failed. With it: all pass. 103 passed across the files this PR touches.
The generated hook probed each sys.path entry for a sitecustomize.py file, so an existing sitecustomize installed as a package or shipped as a bare .pyc was skipped in every child process. Use PathFinder.find_spec instead, which is what CPython itself would have done.
|
@codex review |
|
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". |
…r/torchao-import-survival
|
Closing as superseded. This work is already on main in a more developed form, so merging the branch would be a net regression rather than a gain. Comparing this branch's
Both overlapping test files conflict add/add because main already carries them, and main's are larger ( Four test files here are genuinely absent from main ( |
|
Correction to the note above: the four test files are not absent from main. All four are on main already, at the same paths: The contents differ, but the coverage exists on main, so there is nothing to port and no risk of losing it. Ignore that last paragraph. The rest of the rationale holds, re-verified against
So closing as superseded stands. |
Five failures, one cause: a
torchaowheel built against a newer torch than the one installed. Colab and Kaggle images pair them independently, so this happens to users who never asked for either package by name.1.
torch.nn.functionalsymbol skewtorchao 0.18.0 imports
ScalingTypeand friends fromtorch.nn.functional. On torch 2.8 they are not there, andimport unslothdies before anything else can happen:The missing names are shimmed in before
unsloth_zoois imported. Version-gated, and existing symbols are never overwritten.2.
aten::_grouped_mmThe same skew one layer down: torchao registers against an aten op this torch does not define. Detected and handled the same way, with
scaled_grouped_mmcovered too since the original symbol list was short.3. The fix did not reach vLLM
fast_inference = Truehas vLLM inspect model architectures in a separate process, which imports torch and torchao itself and sees none of the in-process patching. The run still died, and the message named neither package:with the user shown only "Model architectures ['Qwen3ForCausalLM'] failed to be inspected". Observed on Colab after the in-process fix had reported success, so the parent looked healthy right up to the failure.
A
sitecustomizeonPYTHONPATHis the hook that reaches a process we do not launch. Three things this had to get right:sitecustomizeis a single global name and other things legitimately install one; replacing it would silently disable whatever it does for every subprocess.PYTHONPATHis executed by every subprocess and the temp dir is shared, so a fixed name there would be code execution for whoever creates it first. The path is scoped by uid, created 0700, and a directory this user does not own is refused.Only the symbol fix is propagated. The other fixes in the module were checked and do not need a child; the reasoning is recorded in the source so the next one is not added by reflex.
4. peft aborted on a torchao it never uses
An old torchao made LoRA construction fail even though nothing in that path touches torchao. It no longer does.
5.
torchao.dtypes.nf4tensor0.18.0 moved the module.
torchtunestill imports the old path, which is how the Llasa TTS notebooks break. Aliased.Tests
Five files, 85 passed, 2 skipped. The two skips are environment gates, reported by
-rs: one wants torchao absent, the other wants a torch that lacks the symbols. Neither is available on a machine that has both.The subprocess tests spawn real interpreters against a fake torch and a fake torchao 0.18 that reproduces the exact import error, and assert the hook reaches a grandchild, that an existing
sitecustomizestill runs, and that a broken existing one does not kill the process.