Skip to content

Diagnose torch and triton version skew at import time - #11023

Merged
danielhanchen merged 25 commits into
mainfrom
pr/import-time-floors
Sep 17, 2026
Merged

danielhanchen merged 25 commits into
mainfrom
pr/import-time-floors

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 15, 2026 •

Copy link
Copy Markdown
Member

Summary

Three reports with one shape: pip installs a combination it has no specifier to reject, and the
user sees an error from the wrong layer. Each is named where the version is actually known.

  • #8933: a transformers newer than the installed torch ended import unsloth with a bare
    AttributeError: module 'torch' has no attribute 'float8_e8m0fnu'. It now raises
    UnslothTorchTooOldError, naming the installed torch, the installed dependency, the
    attribute, the torch release that added it, and the upgrade command.
  • #3130: one temporary patch raised a SyntaxError and took import unsloth down with it,
    because _run_temporary_patches tolerated only ValueError and TypeError. The patch itself
    is fixed in Guard the generated quantizer import and skip CCE on the broken triton unsloth-zoo#1230; this is the second layer, so that no optional patch
    can end an import again.
  • #2760: a triton whose CUDA driver shim includes Python.h without defining
    PY_SSIZE_T_CLEAN fails at the first kernel launch with
    SystemError: PY_SSIZE_T_CLEAN macro must be defined for '#' formats. A check at import reads
    the shipped shim and names it, on the Python versions that require the macro. This is a
    partial answer and the section below says exactly which part.

Root cause

#8933. transformers reaches for torch dtypes at module scope. In 5.10.x,
transformers/integrations/finegrained_fp8.py:45 is _UE8M0_SF_DTYPE = torch.float8_e8m0fnu
with no guard, and that dtype first exists in torch 2.7.0, measured absent in 2.6.0 and present
in 2.8.0 and added by pytorch/pytorch#146427. Nothing stops the pair being installed:
transformers declares torch>=2.2 through torch>=2.5 depending on the release, well below
what its own modules touch, so there is no floor for the resolver to enforce. A static
transformers-to-torch table here would be no better, because it would have to be wrong
somewhere: torch 2.6.0 with transformers 4.57.6 is a supported combination that works.

#3130. _run_temporary_patches wrapped the signature probe and the call in one
except (ValueError, TypeError), so a patch that raised ValueError was silently re-run
without its argument, and a patch that raised anything else escaped into import unsloth.

#2760. The shim's loadBinary parses its arguments with the format "ss#ii" into a
Py_ssize_t, and CPython below 3.13 raises SystemError for a # format unless the extension
was compiled with PY_SSIZE_T_CLEAN defined before Python.h. Two things are worth stating
plainly, because they point away from the obvious fix:

  • Raising the triton>=3.0.0 floor would not have helped. Every triton on PyPI from 3.0.0 to
    3.8.0 already defines the macro in backends/<backend>/driver.c, checked against the wheels
    and against the upstream tags, so no floor separates a working triton from a broken one here.
  • It also cannot be raised. torch pins triton exactly, and the oldest supported torch, 2.6.0,
    requires triton==3.2.0 on Linux x86_64, so a floor above that makes torch 2.6.0
    unresolvable rather than safe, and a PEP 508 marker cannot be written against another
    distribution's version.

What is real is a rebuilt or repackaged triton whose shim lost the macro, which is what the
conda-forge feedstock had to backport and what one reporter fixed by adding the line and
rebuilding. That is the case this check names. It is a static read of the C source triton
compiles at run time, so it cannot see a shim whose source is correct but whose compiled
artefact is not, and for an environment in that state it stays silent.

Changes

unsloth/import_fixes.py

  • UnslothTorchTooOldError, an AttributeError subclass, and
    patch_torch_missing_attribute_error(), which wraps torch's module-level __getattr__. The
    interpreter calls that function only after normal lookup has already failed, so a successful
    attribute access costs nothing. Only an access made from a frame belonging to a package
    unsloth imports is re-raised; the same error from user code, or from torch asking itself, is
    left exactly as torch wrote it. The message keeps torch's original wording first, so anything
    already matching on it, and anyone searching for it, still finds what they expect. Idempotent,
    functools.wraps, and the original stays reachable as __unsloth_original__.
  • check_triton_py_ssize_t_clean() and _triton_driver_shims_missing_py_ssize_t_clean(), which
    read triton/backends/*/driver.c and warn when it includes Python.h without the macro while
    using a # format. Inert on Python 3.13 and later, where CPython no longer requires it, so
    those interpreters never read the file. Warns rather than raises: nothing has failed yet, and
    a run that launches no Triton kernel never will. UNSLOTH_SKIP_TRITON_SHIM_CHECK=1 silences
    it.

unsloth/_gpu_init.py calls the diagnosis ahead of every other fix and of import unsloth_zoo,
because those are what import transformers; it calls the triton check next to
check_transformers_dependency_versions(), and deletes both names like the rest.

unsloth/models/_utils.py splits the signature probe from the call in _run_temporary_patches,
and logs a patch that raises rather than letting it end the import.

pyproject.toml records why the Linux triton floor stays at 3.0.0, next to the pin, in the
same style as the diffusers floor above it. That is the only change to that file.

Compatibility

Version matrix, CPU lane, import sanity plus this PR's own steps, each cell before to after
where before is current main in both repos and after is this branch:

step mA mB mC mD mX2
import-sanity pass to pass pass to pass pass to pass pass to pass pass to pass
zoo-imports-under-spoof pass to pass pass to pass pass to pass pass to pass pass to pass
extended-module-imports pass to pass pass to pass pass to pass pass to pass pass to pass
tests-unsloth-import-time-floors skip to pass skip to pass skip to pass skip to pass skip to pass
tests-zoo-import-time-floors skip to pass skip to pass skip to pass skip to pass skip to pass
tests-unsloth-import-fixes-drift fail to fail pass to pass pass to pass pass to pass pass to pass
tests-zoo-temporary-patches-exhaustive pass to pass pass to pass pass to pass pass to pass pass to pass
repro-8933-torch-older-than-transformers fail to pass fail to pass fail to pass fail to pass fail to pass
repro-3130-empty-quantizer-import fail to pass fail to pass fail to pass fail to pass fail to pass
zoo-dynamic-exec-allowlist pass to pass pass to pass pass to pass pass to pass pass to pass
zoo-exec-literals-baseline pass to pass pass to pass pass to pass pass to pass pass to pass
venv python torch transformers trl peft triton
mA 3.10.19 2.6.0+cu124 4.57.6 0.22.2 0.18.0 3.2.0
mB 3.13.12 2.8.0+cu128 5.0.0 0.27.2 0.19.1 3.4.0
mC 3.13.12 2.11.0+cu130 5.5.0 1.0.0 0.20.0 3.6.0
mD 3.13.12 2.14.0+cu130 5.17.0 1.13.0 0.20.0 3.8.0
mX2 3.13.12 2.11.0+cu130 4.57.6 1.13.0 0.19.1 3.6.0

tests-unsloth-import-fixes-drift fails identically before and after on mA, on
ImportError: cannot import name 'transformers_weight_conversion' from 'peft.utils'. That is
PEFT 0.18.0 against transformers 4.57.6 in that corner and is unrelated to this change; it is
reported rather than hidden. mA is also the corner where all 18 of the new tests run, since it
is the Python 3.10 one and the triton probe is inert from 3.13 on.

One more corner was built for this PR alone, Python 3.10.19 with torch 2.6.0+cu124 and
transformers 5.10.4, which is the reporter's skew and the only combination where the
float8_e8m0fnu access is both present and unguarded:

corner before after
torch 2.6.0 + transformers 5.10.4 AttributeError: module 'torch' has no attribute 'float8_e8m0fnu', raised from torch/__init__.py, no version named UnslothTorchTooOldError naming torch 2.6.0+cu124, transformers 5.10.4, torch 2.7.0 and the pip command

The traceback in that corner is the reporter's, frame for frame: unsloth/_gpu_init.py to
import unsloth_zoo to temporary_patches/utils.py to transformers.processing_utils to
finegrained_fp8.py:45. After the change the frames below the raise are identical and torch's
own error is kept as the __cause__, so nothing is hidden. The new message reads:

module 'torch' has no attribute 'float8_e8m0fnu'

Unsloth: transformers==5.10.4 uses torch.float8_e8m0fnu, and the installed torch==2.6.0+cu124
does not have it, so this environment holds a transformers newer than its torch.
torch.float8_e8m0fnu first appears in torch 2.7.0.

Upgrade torch, which leaves transformers where it is:
    pip install --upgrade "torch>=2.7.0"

Installing a transformers that matches this torch works too. Pip allowed the pair because
transformers declares a lower torch floor than its own modules actually touch, so there was
nothing for the resolver to reject.

Tests

tests/test_import_time_floors.py, 20 tests. On Python 3.10 all 20 run and pass; on 3.13, 19
pass and one skips, the drift check on the installed triton, which is inert there by design.

python -m pytest tests/test_import_time_floors.py -q
19 passed, 1 skipped

Against main the same file is 8 failed, 7 errors, 1 passed, 1 skipped. The one that passes on
both is a regression guard for a callable with no readable signature. Alongside it,
tests/test_import_fixes_drift.py, tests/test_transformers_dependency_floor.py,
tests/test_allow_cpu_import_driverless.py, tests/test_torchaudio_cuda_mismatch.py,
tests/test_broken_torchvision_probe.py and tests/test_version_single_source.py are
120 passed, 6 skipped.

The new file covers the diagnosis and its floor, the generic path for an attribute the table
does not name, user and torch frames being left alone, hasattr and getattr with a default
being unaffected, idempotence, a torch without a module-level __getattr__, the install
happening before import unsloth_zoo, the triton shim probe on a shim with the macro, without
it, and with no # format, Python 3.13 not reading the file at all, the installed triton not
being flagged, and the three _run_temporary_patches cases.

Two of those twenty are about the cost of the wrapper rather than its wording. The module
__getattr__ only runs when normal lookup has already failed, so a successful attribute
access is untouched, measured at 0.036 microseconds before and after. A FAILED one is a
different matter: hasattr(torch, name) and getattr(torch, name, default) are how these
same libraries feature probe, and both arrive here. Building the diagnosis called
importlib.metadata.version, which walks sys.path and costs about 850 microseconds, so a
failed probe attributed to one of the named packages went from 0.8 microseconds to about
750. Each distribution version is now resolved once per process, which brings the same
probe to about 2.4 microseconds with the message unchanged. The tests count the lookups
rather than timing them, and check that a distribution with no readable metadata still
reports the word unknown. For reference, a model build plus three backward passes on
transformers 4.57.6 with torch 2.6.0, on 5.0.0 with 2.8.0 and on 5.17.0 with 2.14.0 reaches
this path zero times, so the cost only ever mattered on the skewed installs the diagnosis
is for.

Gates: ruff check unsloth unsloth_cli studio tests cli.py unsloth-cli.py passes,
python -m compileall passes, scripts/lint_exec_literals.py is ok: 72 dynamic-execution call site(s), all recorded, and pytest --collect-only tests/ collects 24282 tests with one
pre-existing tests/studio/test_mlx_context_platform_matrix.py collection error that is already
present on main in an environment without mlx.

Cross-platform CI

Both branches were run together on owned staging infrastructure rather than the org queue, with
unsloth_zoo installed from this pair's zoo branch, so each leg exercises both changes. Linux,
Apple Silicon macOS and Windows, Python 3.12 on all three, triton present on all three, so the
PY_SSIZE_T_CLEAN probe is active rather than inert on every leg:

runner result tests
ubuntu-latest, torch 2.12.1, triton 3.8.0 success 56 passed
macos-15, Apple Silicon success 56 passed
windows-latest, triton-windows 3.8.0.post28 success 56 passed

Counts are read out of each leg's log, not inferred from the badge: the generated workflow
treats "no tests ran" as green, and none of these legs did that. 56 is this PR's 18 tests plus
the two other files the generated workflow selects for the changed paths.

An earlier round failed on Windows, and it is worth recording why it was not a regression:
unsloth/_gpu_init.py imports triton at module scope, on main as much as here, and the first
round's dependency list did not include triton-windows, so import unsloth could not complete
on that runner at all. Adding triton as a per-platform optional dependency made the leg a real
gate, which is the round in the table.

Known limitations

  • The diagnosis fires on the access, not ahead of it. There is no eager assertion, because the
    only rot-free gate is the access itself; a transformers-to-torch table would have to be wrong
    for at least one supported corner.
  • It keys off the module of the frame that made the access, so a dependency that reaches
    torch.<missing> through a helper defined in another package is attributed to that helper's
    package.
  • It needs torch to keep a module-level __getattr__. Without one,
    patch_torch_missing_attribute_error() returns False and changes nothing; every torch from
    2.6.0 to 2.14.0 has one.
  • torch.float8_e8m0fnu specifically is unguarded only in transformers 5.10.x; 5.0 to 5.9 do
    not have the access and 5.11 onwards guard it with hasattr. The value here is the next
    unguarded dtype access, not this one.
  • The triton check answers the repackaged-shim half of [Bug] SystemError: PY_SSIZE_T_CLEAN macro must be defined for '#' formats #2760 and not the half where the source
    is correct and the compiled artefact is not, and it does not run on Python 3.13 and later.
  • Linux and CUDA only for the measurements, with CUDA_VISIBLE_DEVICES="" on the CPU lane.
    Nothing here is platform specific; cross-platform staging results are in the PR thread.

Overlap

#11016 also edits pyproject.toml, at the transformers specifiers on lines
206 and 853. The only change here is the comment above the triton extra on line 178, so the
two do not touch the same lines and either can merge first.

Fixes #8933
Refs #2760


Review round: two probes that answered for the wrong reason

The reinstall command named the wrong distribution. triton-windows,
pytorch-triton-rocm and pytorch-triton-xpu all provide the triton import name, all of which
this repository supports, so importlib.metadata.version("triton") raises on them (that was the
unknown in the message) and pip install --force-reinstall triton would have put a CUDA build
over a platform-specific one or found no wheel at all. The owning distribution is now resolved
with importlib.metadata.packages_distributions(), which is the only mapping that answers this
without guessing from the platform, and both the reported version and the command use it.

The macro check accepted a macro that is not in effect. CPython's requirement is positional:
PY_SSIZE_T_CLEAN must be defined BEFORE Python.h is included, and 3.13 dropped the need
entirely. The substring test called four ineffective shapes fixed. The check now finds the
Python.h include and the last #define / #undef PY_SSIZE_T_CLEAN directive before it, so a
mention in a comment, one in a string literal, an #undef, and a define placed after the include
are all still reported.

Six parametrised cases plus two for the distribution resolution; five fail against the substring
test and the plain-triton control passes either way.

Pre-existing CI failures, named rather than fixed here

unslothai/unsloth main is itself red on Repo tests (CPU, studio) and (Python 3.13, rest)
(run 35060623218). The same two jobs fail on this PR and on several unrelated ones in the same
batch, with the same tests:
tests/multi_account/test_chat_shared_resident.py (3 tests, {"detail":"Failed to get status"})
and tests/studio/test_chat_preset_load_config.py::test_preset_sheet_reacts_to_a_reasoning_budget_change.
Neither touches anything this PR changes, so they are recorded here and left to their owner
rather than fixed inside an unrelated PR.

A transformers newer than the installed torch ended `import unsloth` with a
bare `AttributeError: module 'torch' has no attribute 'float8_e8m0fnu'`, with
no version in the message and nothing for the user to act on (#8933). Pip
cannot reject that pair: transformers declares `torch>=2.2` through
`torch>=2.5` depending on the release, well below what its own modules touch.
A static table here would be no better, because torch 2.6.0 with transformers
4.57.6 is a supported combination that works.

Probe the behaviour instead. torch answers a missing attribute through a
module-level `__getattr__`, which the interpreter calls only after normal
lookup has already failed, so wrap that one function: an attribute error
raised from a frame belonging to a library unsloth imports becomes
UnslothTorchTooOldError, naming the installed torch, the installed
dependency, the attribute, the torch release that added it and the upgrade
command. It subclasses AttributeError, so `hasattr` and `getattr` with a
default behave exactly as before, and the same error from user code is left
exactly as torch wrote it.

Two more floors that used to surface as something else:

- A repackaged triton whose CUDA driver shim includes Python.h without
  defining PY_SSIZE_T_CLEAN fails at the first kernel launch with
  `SystemError: PY_SSIZE_T_CLEAN macro must be defined for '#' formats`
  (#2760). Every triton on PyPI from 3.0.0 to 3.8.0 defines it, and the
  `triton>=3.0.0` floor cannot be raised anyway, since torch pins triton
  exactly and torch 2.6.0 requires `triton==3.2.0`, so check the shipped
  shim and say so on Python below 3.13, where the macro is required.

- `_run_temporary_patches` caught ValueError and TypeError around both the
  signature probe and the call, so a patch that raised ValueError ran twice
  and a patch that raised anything else ended the import (#3130). Probe the
  signature separately and log a failing patch rather than letting it out.
@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-16T15:05:08.016173Z 353505c 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 added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 15, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 15, 2026
danielhanchen and others added 3 commits September 15, 2026 23:26
The torch module __getattr__ wrapper runs on every attribute access that
normal lookup missed, and a missed lookup is not always fatal: hasattr and
getattr with a default are how transformers, peft and trl feature probe, and
both arrive here. Building the diagnosis called importlib.metadata.version,
which walks sys.path and costs about 850 microseconds, so a failed probe from
one of those packages went from about 0.8 microseconds to about 750. Resolve
each distribution version once per process instead, which brings the same probe
back to about 2.4 microseconds with the message unchanged.

Two tests: the version is resolved once across fifty failed lookups, and an
unresolvable distribution still reports the word unknown rather than raising.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 16, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 16, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

Second pass over this branch, twenty-four cases across the venv matrix. One real defect found and fixed.

The defect is cost, not correctness. The torch module __getattr__ wrapper sits on the path the interpreter takes for EVERY attribute access on torch that normal lookup missed, and a missed access is not always fatal: hasattr(torch, name) and getattr(torch, name, default) are how the very packages in the named list feature probe, and both arrive here. Building the diagnosis called importlib.metadata.version, which walks sys.path. Measured on this workspace at 848 microseconds per call, so a failed probe attributed to transformers, peft, trl, accelerate, torchao, diffusers, vllm, xformers or the zoo went from

0.8 microseconds  ->  748 microseconds   (torch 2.14)
0.8               ->  885                (torch 2.8)
1.0               ->  1202               (torch 2.6)

Each distribution version is now resolved once per process. The same probe costs 2.4 microseconds and the message is byte for byte what it was. Two tests, both failing without the change: the lookup count across fifty failed accesses is one, and a distribution with no readable metadata still reports the word unknown rather than raising.

For scale, this was worth fixing but was never hot in practice: a model build plus three backward passes on transformers 4.57.6 with torch 2.6.0, on 5.0.0 with 2.8.0 and on 5.17.0 with 2.14.0 reaches the slow path zero times. The cost only ever appeared on the skewed installs the diagnosis exists for, which is where a thousandfold on a feature probe would have been least welcome.

What else was checked on the wrapper. torch has a module-level __getattr__ to wrap on 2.6.0+cu124, 2.8.0+cu128, 2.10.0+cpu, 2.11.0+cu130 and 2.14.0+cu130, including the CPU-only build. A successful attribute access is unchanged at 0.036 microseconds either way, because the interpreter only calls the hook after lookup has already failed. Installing twice gives the same function object and a wrapper chain of depth one, and restoring the original then re-patching works, which is the reload case. hasattr returns False and getattr with a default returns the default from a transformers frame, since the error subclasses AttributeError. e.name still carries the attribute name, same as torch's own. A user frame and torch's own frames get a message byte-identical to torch's, and not the subclass.

On the zoo half (unslothai/unsloth-zoo#1230). The version cases covered nightly local versions but not the .postN form the triton-windows distribution carries, which is the one Windows users actually have. Added both ends: 3.3.0.post1 and 3.3.1.post19 rejected at compute capability 7.5, 3.4.0.post28 kept. The gate was then swept over eight capabilities crossed with seventeen version strings: it fires only at 7.5 and only inside [3.3.0, 3.4.0), never on 7.0, 8.0, 8.6, 9.0, 10.0, 12.0 or 6.1, and an unparseable version is treated as no evidence of a defect.

Cross-platform, rerun for this pass on danielhanchen/unsloth-staging-2, scoped to this PR's own changed test files, with CPU torch, the paired zoo branch and transformers installed explicitly: ubuntu-latest 58 passed, macos-15 58 passed, windows-latest fails during collection on

unsloth\_gpu_init.py:406: import triton
ModuleNotFoundError: No module named 'triton'

That is the pre-existing hole rather than anything here. PyPI publishes no triton wheel for Windows, so on this branch import unsloth cannot complete there and no test in the file gets to run. It is an independent third measurement of the defect #11037 guards, and on that branch the same import walks past the line. Recorded rather than made green by narrowing what the leg runs.

Also run: tests/test_import_fixes_drift.py and the neighbouring floors and probe suites, 61 passed 5 skipped together; the zoo security lint gates after the allowlist and baseline hashes moved, 126 passed; ruff and the repository's own run_ruff_format.py at the pinned 0.6.9; and an 8-step LoRA on Llama-3.2-1B, which trains to the same loss as main to three decimals.

One thing to keep in mind rather than change: _run_temporary_patches now logs and continues on ANY exception from a patch, where before only ValueError and TypeError were tolerated. That is the point of the change, and it does mean a genuinely broken patch degrades silently instead of ending the import. The warning names the patch and the exception type, which is what makes that survivable.

danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Sep 16, 2026
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Sep 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 16, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 16, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 880a2b1142

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

Comment thread unsloth/import_fixes.py
Comment on lines +2105 to +2110
package = requester.split(".", 1)[0]
if package not in _TORCH_ATTRIBUTE_DEPENDENTS:
raise
raise UnslothTorchTooOldError(
_torch_too_old_message(name, package, exception)
) from exception

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Restrict the too-old diagnosis to known additive attributes

When one of these dependencies accesses a symbol that was removed or renamed in a newer torch—for example, an older dependency referencing a retired torch API—this condition treats the missing attribute as proof that torch is too old. _TORCH_ATTRIBUTE_FLOORS is only used to format the message, so even unknown attributes raise UnslothTorchTooOldError and recommend upgrading torch, which is the opposite remedy for a dependency older than torch and also misdiagnoses ordinary dependency typos or failures inside torch's lazy __getattr__. Only attributes with a known introduction floor should receive the upgrade diagnosis; unknown names should preserve the original error or use version-neutral wording.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct on the direction, and that is the half worth fixing: an absent attribute is not evidence that torch is the older one, since an older dependency reaching for a retired torch API lands in the same branch and an upgrade is the opposite remedy there. Kept the diagnosis for unknown names, because a dtype added after this release must still be named rather than left as a bare AttributeError, but the no-floor branch is now direction neutral: it says the attribute is either newer than this torch or removed by it, points at the torch docs to decide which, and offers both moves without prescribing either. A known floor still proves the direction and still prescribes the upgrade, which a negative control pins. The requester gate is unchanged, so user code and torch's own frames keep torch's exact error.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 353505c740

ℹ️ 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 added a commit to Imagineer99/unsloth that referenced this pull request Sep 16, 2026
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Sep 16, 2026
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Sep 16, 2026
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Sep 16, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

Performance of the import-time diagnostics

Measured on this host (8x NVIDIA B200, torch 2.14.0+cu130, Python 3.13.12), three arms
selected by PYTHONPATH so nothing is edited in place: base is the merge base 1286590,
head is this PR, and ctl is a second independent checkout of the same merge base, which
is the negative control. Arm order is rotated every rep, and each rep is a fresh subprocess,
because import cost is a once-per-process cost and measuring it in-process only measures
sys.modules.

import unsloth, 9 reps per arm plus a discarded warm-up per arm

arm median mean sd min max
base 11.0176 s 10.9616 s 0.2158 10.5317 11.2421
head 10.9187 s 10.9796 s 0.3232 10.6337 11.6006
ctl 10.7303 s 10.7123 s 0.1746 10.4889 10.9433

head minus base: -98.9 ms (-0.90%). Control minus base: -287.3 ms (-2.61%).

The control, which is the same code as base, differs from base by three times as much as the
PR does, and in the same direction. So the import cost of these diagnostics is below what
this harness can resolve, and the apparent speedup is noise rather than a claim.

The two new import-time steps

check_triton_py_ssize_t_clean() is the one that could have been expensive, since it can read
backends/*/driver.c out of the triton install. It returns before doing any of that when
triton is absent or the environment opts out, and where it does run it reads a handful of small
C files once. It is inside the number above, which is why the number is the answer rather than
the reasoning.

The torch.__getattr__ wrapper, which is the part that survives the import

patch_torch_missing_attribute_error() wraps torch's module-level __getattr__, so it is the
only part of this PR that can still cost anything after import. Two questions: what does one
call cost, and how many calls are there.

Per call, 200k iterations by 15 repeats, median of per-call time:

path unpatched patched delta
direct call, missing attribute 242.1 ns 725.7 ns +483.6 ns
through real module lookup, hasattr(torch, missing) 251.6 ns 726.6 ns +475.1 ns

There is no success-path row because there is nothing to put in it: on torch 2.14 every name
probed that torch could answer through its module __getattr__ was already in torch.__dict__,
so the wrapper's success path was never reached. Every call through it is a miss, and a miss
costs about 475 ns more, which is the frame read and the set membership test.

A first version of this microbenchmark reported +0.15 ns, which was wrong: it imported the
helper from the unsloth package, and that import runs _gpu_init and installs the wrapper, so
the "unpatched" arm was already patched. The baseline above is the wrapper's own
__unsloth_original__, swapped back into the module, so both arms go through identical machinery.

Call counts, counted rather than estimated, by wrapping whatever __getattr__ is installed and
tallying:

window calls who
import unsloth 66 all from unsloth.import_fixes (__module__ 54, _inductor 8, _dynamo 2, _linalg_eigvals 2)
generate, 3 x 64 tokens, Llama-3.2-1B-Instruct 4bit 0 nothing reaches torch's module __getattr__

66 calls at 475 ns is about 31 microseconds, once, at import. Generation reaches the wrapper
zero times, so the steady-state cost is not small, it is nil.

Verdict: performance is not impacted. The import delta is below the harness floor and smaller
than the same-code control, and the only piece that outlives import is never called during
generation.

@danielhanchen

Copy link
Copy Markdown
Member Author

Is this a regression for all torch attribute access? No. Only for lookups that already failed.

Asked because +475 ns on a path sounds alarming until you know which path it is. Measured on
2 x Xeon Platinum 8559C, Python 3.13.12, torch 2.14.0+cu130. Both arms in one process: patched is
the installed wrapper, unpatched is its own __unsloth_original__ swapped back into
torch.__dict__["__getattr__"], arm order flipped every odd repeat.

Ordinary attribute access never reaches the wrapper

Proved with a counter, not with an argument about CPython's attribute protocol. The installed
__getattr__ was replaced by a counting wrapper, then torch.float16, torch.nn, torch.Tensor,
torch.zeros, torch.float32, torch.matmul, torch.cat and torch.no_grad were each read
100,000 times:

value
accesses performed 800,000
__getattr__ invocations counted 0
counter liveness, re-checked with one deliberate miss fires
statement patched unpatched delta
torch.float16 19.95 ns 19.87 ns +0.08 ns
four names in one statement 71.07 ns 70.36 ns +0.71 ns

Both deltas are far inside the spread (sd 1.7 and 8.4 ns). Zero, and this time zero for the right
reason.

A correction to my earlier comment

I wrote that no name on torch 2.14 is answered lazily through the module __getattr__. That is
wrong. torch/__init__.py:3363-3412 answers has_cuda, has_mps, has_cudnn, has_mkldnn,
set_vital, and the lazy modules _dynamo, _inductor, _export, onnx. Timed on
torch.has_cuda, the delta changes sign between framings, because torch itself calls
warnings.warn on every deprecated-attr hit and that costs about 6.5 us, three orders of magnitude
more than the wrapper. Isolating the wrapper shape against a cheap callee, 200k by 15:

median spread
wrapped 36.14 ns 34.21 to 39.42, sd 1.36
bare 20.30 ns 19.99 to 22.27, sd 0.65

So a success that really traverses __getattr__ costs +16 ns, which is 0.24% of what such a
lookup already costs here.

The failed-lookup figure, reproduced on an independent harness

path patched unpatched delta
direct call, try/except 706.2 ns 245.6 ns +460.7 ns
hasattr(torch, missing) 710.3 ns 259.1 ns +451.2 ns
getattr in try/except AttributeError 980.8 ns 520.9 ns +459.9 ns

Call it +461 ns, all of it inside the except AttributeError handler: sys._getframe(1), the
f_globals read, the split, the set test.

How many such calls a real process makes, training included

Counter installed before import unsloth, so the wrapper sits on top of it. Llama-3.2-1B-Instruct
4bit, LoRA r=16 on 7 projections, bsz 2 x grad accum 2, 8 steps, then 3 x 64 generate:

phase calls names
import unsloth 66 __module__ x54, _inductor x8, _dynamo x2, _linalg_eigvals x2
from_pretrained plus get_peft_model 1 privateuseone
SFTTrainer construction 1 privateuseone
trainer.train(), 8 steps 8 all in step 1; steps 2 to 8 make zero
generate, 3 x 64 tokens 0
total 76 62 misses, 14 successes

62 x 461 ns plus 14 x 16 ns = 28.8 microseconds for the whole process, effectively all of it
during import, none per step, none per token.

Could 461 ns ever land somewhere hot

65 hasattr(torch, ...) sites across transformers, trl, peft, accelerate and unsloth_zoo. The ones
in a per-forward path are 16 transformers models probing get_autocast_dtype and peft's
lora/layer.py:2222 probing all five UPCAST_DTYPES. Every one of those names is in
torch.__dict__ on 2.14, so they never reach the wrapper. Every probe that genuinely misses
(npu, musa, hpu, sdaa, neuron) is in an @lru_cached one-time setup.

One honest caveat: on a torch old enough to lack get_autocast_dtype or one of the float8 dtypes,
those per-forward sites would become per-forward misses at 461 ns each. That is precisely the
too-old-torch case this PR exists to diagnose, and it could not be tested without installing a
second torch.

Verdict: not a regression for ordinary attribute access, +461 ns only on a lookup that has already
failed, and about 29 microseconds per process in total.

One conflict, a docstring in studio/backend/tests/test_diffusers_prewarm.py that
#11020's comment reduction shortened on main while this branch still carried the
long form. Resolved by taking main. This branch's only other edits to that file
were pre-commit line wrapping with no semantic content, so the file is taken from
main whole.
pre-commit.ci reported the branch as modified by its hooks. This is the
formatting it wanted, produced by the repo's own scripts/run_ruff_format.py.
@danielhanchen
danielhanchen merged commit b07e466 into main Sep 17, 2026
50 of 61 checks passed
@danielhanchen
danielhanchen deleted the pr/import-time-floors branch September 17, 2026 12:08
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
* Diagnose torch and triton version skew at import time

A transformers newer than the installed torch ended `import unsloth` with a
bare `AttributeError: module 'torch' has no attribute 'float8_e8m0fnu'`, with
no version in the message and nothing for the user to act on (unslothai#8933). Pip
cannot reject that pair: transformers declares `torch>=2.2` through
`torch>=2.5` depending on the release, well below what its own modules touch.
A static table here would be no better, because torch 2.6.0 with transformers
4.57.6 is a supported combination that works.

Probe the behaviour instead. torch answers a missing attribute through a
module-level `__getattr__`, which the interpreter calls only after normal
lookup has already failed, so wrap that one function: an attribute error
raised from a frame belonging to a library unsloth imports becomes
UnslothTorchTooOldError, naming the installed torch, the installed
dependency, the attribute, the torch release that added it and the upgrade
command. It subclasses AttributeError, so `hasattr` and `getattr` with a
default behave exactly as before, and the same error from user code is left
exactly as torch wrote it.

Two more floors that used to surface as something else:

- A repackaged triton whose CUDA driver shim includes Python.h without
  defining PY_SSIZE_T_CLEAN fails at the first kernel launch with
  `SystemError: PY_SSIZE_T_CLEAN macro must be defined for '#' formats`
  (unslothai#2760). Every triton on PyPI from 3.0.0 to 3.8.0 defines it, and the
  `triton>=3.0.0` floor cannot be raised anyway, since torch pins triton
  exactly and torch 2.6.0 requires `triton==3.2.0`, so check the shipped
  shim and say so on Python below 3.13, where the macro is required.

- `_run_temporary_patches` caught ValueError and TypeError around both the
  signature probe and the call, so a patch that raised ValueError ran twice
  and a patch that raised anything else ended the import (unslothai#3130). Probe the
  signature separately and log a failing patch rather than letting it out.

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

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

* Resolve a dependency version once when diagnosing a torch skew

The torch module __getattr__ wrapper runs on every attribute access that
normal lookup missed, and a missed lookup is not always fatal: hasattr and
getattr with a default are how transformers, peft and trl feature probe, and
both arrive here. Building the diagnosis called importlib.metadata.version,
which walks sys.path and costs about 850 microseconds, so a failed probe from
one of those packages went from about 0.8 microseconds to about 750. Resolve
each distribution version once per process instead, which brings the same probe
back to about 2.4 microseconds with the message unchanged.

Two tests: the version is resolved once across fifty failed lookups, and an
unresolvable distribution still reports the word unknown rather than raising.

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

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

* Reword the new test docstring so it does not open with a quote

* Name the distribution that owns Triton, and require the macro to be in effect

* Declare the AGPL-3.0 SPDX identifier on the new test file

* Keep the repair commands on the accelerator and Triton version already installed

* Name the accelerator index for a torch upgrade rather than pinning one that may not carry the release

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

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

* Ignore directives inside C comments, and send a conda torch to conda

* Find the Triton provider on Python 3.9, and diagnose torch on the MLX path too

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

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

* Name the Triton provider that ships the offending driver shim

* Move the torch companions with torch, and route the renamed XPU Triton to its index

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

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

* Name the renamed ROCm Triton provider, and judge the parse format on live code

* Keep a vendor Radeon torch and Triton on their own source, and read only live parse calls

* Configure the ROCm table before torch, and repair a conda Triton through conda

* Settle a driver file two providers both claim by torch's own backend

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

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

* Settle a rename leftover by the Triton torch itself requires

* Prescribe a direction only where a floor proves one

* Apply the repo formatter to the new test file

pre-commit.ci reported the branch as modified by its hooks. This is the
formatting it wanted, produced by the repo's own scripts/run_ruff_format.py.

---------

Co-authored-by: danielhanchen <[email protected]>
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Failed to import ML libraries: module 'torch' has no attribute 'float8_e8m0fnu'

2 participants