Repository navigation
Fall back to HTTPS when hf_xet is installed but cannot be imported - #11167
Conversation
huggingface_hub decides whether to use the Xet transport with is_xet_available(), which only asks importlib.metadata whether the hf_xet distribution is installed. It never asks whether hf_xet actually imports. So an hf_xet that is present but unloadable is still routed to, the import inside file_download.xet_get raises, and transformers' cached_files turns that into "To use optimized download using Xet storage, you need to install the hf_xet package. Try pip install hf_xet", which names the one remedy that cannot work, because hf_xet is already installed. I hit this on Windows on ARM, where an x86-64 hf_xet wheel (Tag: cp37-abi3-win_amd64, hf_xet.pyd with PE machine 0x8664) ended up in an ARM64 CPython, so every Hub download died with "DLL load failed while importing hf_xet: %1 is not a valid Win32 application" and a QLoRA run never got past step 0. fix_broken_hf_xet_wheel now reads the installed hf_xet's wheel platform tags, compares them against this interpreter's CPU family, and when they disagree (or the package has no compiled extension at all) confirms the diagnosis with a real import before setting HF_HUB_DISABLE_XET=1 and logging one line that names the actual cause. Downloads then take the plain HTTPS branch: same files, same cache, only the Xet transport is skipped. It stays out of the way everywhere else. An hf_xet that is absent is left alone, since huggingface_hub already downgrades to HTTP for that case. An HF_HUB_DISABLE_XET the user set is never overridden in either direction. Metadata that cannot be read, a universal2 wheel, and an unknown machine all read as "cannot tell" rather than as a mismatch, and hf_xet is only ever imported for an install already proven suspect, so a healthy environment pays one small metadata read. It is wired into the first block of _gpu_init.py rather than down with the late fixes because huggingface_hub freezes HF_HUB_DISABLE_XET into constants.py at import time, so setting it after the Hub is imported would reach nobody. Note that unsloth_zoo.hf_xet_fallback does not cover this. That one is a Xet to HTTP stall fallback for a transfer that hangs, it only guards downloads routed through its own wrappers, and the training path that broke here went straight through transformers' cached_files.
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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6c87e0399a
ℹ️ 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".
| except Exception as error: | ||
| failure = f"{type(error).__name__}: {error}" | ||
|
|
||
| os.environ["HF_HUB_DISABLE_XET"] = "1" |
There was a problem hiding this comment.
Update the cached Hub flag when Hub is already imported
If the caller imports huggingface_hub (or transformers, which imports it) before Unsloth, huggingface_hub.constants.HF_HUB_DISABLE_XET has already been frozen as false. Setting only the environment variable here therefore does not disable Xet, so the affected wrong-architecture installation still fails every download despite emitting the fallback warning. The existing _gpu_init.py ordering only protects imports performed by Unsloth itself; this path should also update the already-loaded Hub constant or otherwise handle a pre-imported Hub.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 17e4364. You are right, and I reproduced it before changing anything: huggingface_hub 1.31.0 with transformers 5.17.0 imported first, a win_arm64 hf_xet in a win-amd64 interpreter, env HF_HUB_DISABLE_XET=1, constants.HF_HUB_DISABLE_XET still False, is_xet_available() still True, the transfer went through xet_get and raised the misleading "you need to install the hf_xet package". So the warning printed while every download still failed.
The fix now also rebinds the in-memory flag when huggingface_hub is already in sys.modules. That works because file_download.py reads constants.HF_HUB_DISABLE_XET as a module attribute at call time rather than copying it into a local. The environment variable is still set, and still set first, since that is what child processes and download workers inherit.
Rather than hardcoding constants.py I walk every loaded huggingface_hub module and only rewrite an attribute that already exists. I scanned 0.24.7, 0.30.2, 0.33.5, 0.34.4, 0.36.2 and 1.31.0 with transformers loaded: huggingface_hub.constants is the only binding that exists today, every other reference goes through constants.X, and utils/_xet.py holds no copy. The scan means a future from .constants import HF_HUB_DISABLE_XET copy would be covered too. Nothing is created on versions that never had the variable: 0.24.7 and 0.30.2 predate it, and 0.31 to 0.33 read os.environ per call, so those are left exactly as they were.
Verified with real downloads in six venvs. Hub-first ordering on 1.31.0 and 0.36.2 now gives constants.HF_HUB_DISABLE_XET True and http_get; 0.33.5, 0.30.2 and 0.24.7 still have no such attribute afterwards; the normal unsloth-first ordering is unchanged. The existing guards are untouched, so an explicit user setting still wins and a healthy or absent hf_xet still changes nothing. Added named regression tests for the pre-imported Hub case, for the multi-binding scan, and for not inventing the attribute on older hubs; the file is at 67 tests, all passing.
There was a problem hiding this comment.
This is already handled, one line below the anchored line: _disable_xet_on_already_imported_huggingface_hub() runs right after the env var is set, and rebinds the frozen HF_HUB_DISABLE_XET attribute on every already-imported huggingface_hub module (not just constants.py, so a future from .constants import ... copy is covered too).
Verified live rather than by reading. One of the scenarios in the simulation matrix is exactly this ordering, huggingface_hub imported BEFORE the fix runs, on a broken install:
| scenario | main routes to Xet | branch routes to Xet |
|---|---|---|
| hub imported first | yes, ValueError | no |
The question asked in both arms is huggingface_hub's own: is_xet_available() and not constants.HF_HUB_DISABLE_XET. On the branch it answers False, so the download goes over plain HTTPS. The env var alone would not have done it, which is why the helper exists.
|
Adding a limitation I want recorded on this PR, plus links to related reports. Trade-off: files over 50 GBDisabling Xet is not entirely free. # constants.py
MAX_HTTP_DOWNLOAD_SIZE = 50 * 1000 * 1000 * 1000 # 50 GB
# file_download.py
elif expected_size and expected_size > constants.MAX_HTTP_DOWNLOAD_SIZE:
# Any files over 50GB will not be available through basic http requests.
raise ValueError(
"The file is too large to be downloaded using the regular download method. "
...
)So on a host with a broken The real resolution for those users is a correctly built Related reports
|
…f_xet check
Three defects found simulating this against real hf_xet wheels and real
huggingface_hub versions on a Windows on ARM box.
1. platform.machine() is the wrong question on Windows. CPython asks WMI for
the PHYSICAL processor there (platform._get_machine_win32), so an emulated
x86-64 interpreter on Windows on ARM answers "ARM64" while being win-amd64.
Measured: every x86-64 venv on this box reports platform.machine() ==
"ARM64" beside sysconfig.get_platform() == "win-amd64". That got the verdict
backwards in both directions. A healthy win_amd64 hf_xet read as a mismatch
(harmless, but it bought a pointless `import hf_xet` at every startup), and,
worse, a genuinely unloadable win_arm64 hf_xet in an x86-64 interpreter read
as healthy, so the fix never fired on the install it exists for. Ask
sysconfig.get_platform() instead, which reports what the interpreter was
BUILT for, and keep platform.machine() only as the fallback for the builds
sysconfig cannot name a CPU for (macOS universal2).
2. A leftover hf_xet-*.dist-info with no package directory beside it was
skipped, because find_spec() returned None and that was read as "not
installed". huggingface_hub never asks find_spec: is_xet_available() ->
is_package_available("hf_xet") -> importlib.metadata.version(). Verified
against huggingface_hub 1.31.0 with the package directory deleted and the
metadata left: is_xet_available() returned True, so every download still
went down the Xet branch and still died in `from hf_xet import XetFileInfo`.
3. An hf_xet whose WHEEL metadata is unreadable (vendored, repackaged, trimmed
dist-info) gave no verdict at all, so a wrong-architecture extension sitting
right there was let through. Fall back to the machine id in the .pyd/.so
header itself, which is the fact that actually decides whether the import can
work. Parser checked against the real PE, ELF and Mach-O binaries out of the
hf_xet 1.4.2 wheels for win_amd64, win_arm64, manylinux2014_x86_64,
manylinux_2_28_aarch64 and macosx_11_0_arm64.
None of these can disable Xet on their own: a suspicion is still confirmed by a
real import before anything is set, and an explicit HF_HUB_DISABLE_XET is still
never overridden in either direction. Re-checked that a healthy x86-64 Linux
install is untouched.
Also require fix_broken_hf_xet_wheel() to be the FIRST import fix called in
_gpu_init.py rather than merely earlier than fix_huggingface_hub(). Confirmed
by measurement that huggingface_hub freezes HF_HUB_DISABLE_XET into
constants.py from 0.34.0 onward, so any fix added later that reaches the Hub
first would silently make this one a no-op.
Simulation and compatibility passI put this branch through a real version matrix and a scenario battery before calling it done. Three defects came out of it, all now fixed in 885f950. Everything below labelled EXECUTED was actually run on this box (Windows on ARM, Python 3.13.15, both a native ARM64 interpreter and an emulated x86-64 one, venvs built with uv). Anything I only reasoned about is labelled as such. I did not run Linux, macOS or WSL and I am not claiming coverage there. What I expected might break, before building anything
Defect 1:
|
| Interpreter | Installed hf_xet 1.4.2 wheel | Truth | Old verdict | New verdict |
|---|---|---|---|---|
x86-64 emulated (win-amd64) |
win_amd64 |
healthy | mismatch | healthy |
x86-64 emulated (win-amd64) |
win_arm64 |
broken | healthy | mismatch |
native ARM64 (win-arm64) |
win_amd64 |
broken | mismatch | mismatch |
native ARM64 (win-arm64) |
win_arm64 |
healthy | healthy | healthy |
Row 1 was merely wasteful, the confirm-by-import step caught it and nothing got disabled, but it bought a real import hf_xet on every startup on every emulated interpreter. Row 2 is the one that mattered: a genuinely unloadable hf_xet read as healthy, so the fix never fired on an install it exists for, and nothing downstream would have caught it.
Fix: ask sysconfig.get_platform(), which reports what the interpreter was built for. platform.machine() stays only as the fallback for builds sysconfig cannot name a single CPU for, chiefly macOS universal2, where it is the right answer.
Cross-checked against the user's three live Studio sidecars, read only. All three carry hf_xet 1.4.2 at Tag: cp37-abi3-win_amd64 with hf_xet.pyd PE machine 0x8664, next to huggingface_hub 1.8.0:
| Sidecar | ARM64 interpreter | x86-64 emulated interpreter |
|---|---|---|
.venv_t5_510 |
fires, sets =1 |
correctly silent |
.venv_t5_530 |
fires, sets =1 |
correctly silent |
.venv_t5_550 |
fires, sets =1 |
correctly silent |
Defect 2: a dist-info with no package beside it was skipped (EXECUTED)
find_spec("hf_xet") returning None was read as "not installed, the Hub handles that". The Hub does not ask find_spec. is_xet_available() goes to is_package_available("hf_xet") to importlib.metadata.version(). Verified against huggingface_hub 1.31.0 with the package directory deleted and the dist-info left in place:
metadata.version(hf_xet) = 1.4.2
find_spec(hf_xet) is None = True
is_xet_available() = True <- still routes every download to Xet
import hf_xet = ModuleNotFoundError
So a half removed or half copied install stayed broken. Now: if the import system cannot see it but importlib.metadata still can, that is a suspicion, and the confirm-import settles it. A genuinely absent hf_xet has no metadata either and is still left alone.
Defect 3: unreadable WHEEL metadata gave up too early (EXECUTED)
A wrong-architecture extension with its WHEEL file gone (vendored, repackaged, trimmed dist-info) produced no verdict, so nothing fired, while is_xet_available() still returned True. Now the machine id in the .pyd / .so header is read as the fallback, which is the fact that actually decides whether the import can work.
Parser validated against the real binaries inside the real PyPI wheels, which is how I got ELF and Mach-O coverage without those OSes:
| Wheel | Extension | Format | Parsed |
|---|---|---|---|
hf_xet-1.4.2-cp37-abi3-win_amd64.whl |
hf_xet.pyd |
PE | x86_64 |
hf_xet-1.4.2-cp37-abi3-win_arm64.whl |
hf_xet.pyd |
PE | arm64 |
hf_xet-1.4.2-cp37-abi3-manylinux2014_x86_64...whl |
hf_xet.abi3.so |
ELF | x86_64 |
hf_xet-1.4.2-cp37-abi3-manylinux_2_28_aarch64.whl |
hf_xet.abi3.so |
ELF | arm64 |
hf_xet-1.4.2-cp37-abi3-macosx_11_0_arm64.whl |
hf_xet.abi3.so |
Mach-O | arm64 |
huggingface_hub version matrix (EXECUTED)
Real venvs, real installs, each given a healthy hf_xet 1.4.2. is_xet_available() observed three ways.
| hub | HF_HUB_DISABLE_XET in constants.py |
no var | var set BEFORE import | var set AFTER import |
|---|---|---|---|---|
| 0.24.7 | absent | no Xet at all | no Xet at all | no Xet at all |
| 0.30.2 | absent | True |
True |
True |
| 0.33.5 | absent, read per call | True |
False |
False |
| 0.34.4 | present, frozen | True |
False |
True |
| 1.31.0 | present, frozen | True |
False |
True |
This matches the upstream history exactly. HF_HUB_DISABLE_XET was added in 0.31.0 by #3039, read per call in utils/_runtime.py through 0.33.5, and moved into constants.py as an import-time constant by #3206, first shipping in 0.34.0. Still frozen in 1.31.0. Upstream hit the same thing in #3266.
Two things follow.
First, the placement argument in this PR is not theoretical. The last two rows are the versions everyone is on, and for those, setting the variable after the Hub is imported does nothing at all.
Second, on the versions that ignore the variable, the fix degrades to a silent no-op rather than appearing to work: nothing breaks, the bug is simply not fixed. 0.24.7 has no Xet to disable. 0.30.2 has Xet but predates the variable. Both are below our own floor of huggingface-hub>=0.34.0, so no supported configuration is left in that state.
transformers (EXECUTED)
| transformers | hub | Result |
|---|---|---|
| 4.57.6 | 0.36.2 | no fire on a healthy install, correct verdicts |
| 5.17.0 | 1.31.0 | full chain reproduced and fixed |
The misleading message actually originates in huggingface_hub as a ValueError from file_download.xet_get; transformers/utils/hub.py cached_files re-raises it verbatim as OSError. Reproduced on 5.17.0. I have corrected the failure chain in the PR body accordingly.
Scenario battery (EXECUTED)
Real interpreters, real hf_xet 1.4.2 wheels placed by hand, real huggingface_hub.
| # | Scenario | Before | After | Want |
|---|---|---|---|---|
| A | ARM64 interpreter + win_amd64 wheel (the original bug) |
fires | fires | fires |
| B | x86-64 emulated + win_arm64 wheel |
silent | fires | fires |
| C | x86-64 emulated + win_amd64 wheel (healthy) |
silent, wrong verdict | silent, right verdict | silent |
| D | ARM64 + win_arm64 wheel (healthy) |
silent | silent | silent |
| E | package present, compiled extension deleted | fires | fires | fires |
| F | dist-info only, no package directory |
silent | fires | fires |
| G | WHEEL metadata deleted, wrong-arch extension |
silent | fires | fires |
| H | hf_xet absent entirely |
silent | silent | silent |
| I | user set 0 / 1 / false / yes / banana |
preserved | preserved | preserved |
| I | variable set to whitespace only | overridden to 1 |
overridden to 1 |
overridden |
| J | subprocess inheritance | child sees =1 |
child sees =1 |
inherited |
| K | offline (HF_HUB_OFFLINE=1) |
fires | fires | fires |
| L | redirected / read-only HF cache | fires | fires | fires |
| M | called twice | idempotent, second call 0.009 ms | same | idempotent |
hf_xet importable but broken only at call time is out of reach by construction: the import succeeds, so we stand down and leave Xet on. That is the intended behaviour, not a gap I can close from here.
Non-regression: healthy x86-64 Linux must keep Xet (SIMULATED)
This is the case I was most worried about, so I ran the whole cross product. What is faked is exactly three inputs, sysconfig.get_platform(), platform.machine() and the WHEEL tags, and the tags are read verbatim out of the real PyPI wheels. Everything else is the real code path. Seven simulated hosts times five real wheels, 35 verdicts:
| Before | After | |
|---|---|---|
| Wrong verdicts | 5 of 35 | 0 of 35 |
All five wrong ones were the emulated x86-64 on Windows on ARM row. Healthy linux-x86_64 with the real manylinux2014_x86_64 wheel gives mismatch = False both before and after, so a Linux user never loses Xet. I want to be plain that this is simulation, not a Linux run.
Cost (EXECUTED)
Cold, five fresh processes each:
| Install | Cost | Sets the variable |
|---|---|---|
healthy hf_xet present |
about 26 ms | no |
hf_xet absent |
about 12 ms | no |
| broken, first call | about 37 ms, includes the real import attempt | yes |
| any second call | 0.009 ms | already done |
Adding 200 bogus entries to sys.path did not make the negative find_spec measurably worse. Theory 4 dismissed.
Import ordering (EXECUTED)
The old test only asserted this runs before fix_huggingface_hub(). Given how completely the variable is frozen from 0.34.0 on, that is too narrow: any fix added later that reaches transformers or the Hub first would silently void this one with nothing failing to say so. The test now requires fix_broken_hf_xet_wheel() to be the first import fix invoked in _gpu_init.py, full stop.
Old installs
- Existing unsloth installs: unaffected. The fix is inert unless
hf_xetis both installed and unimportable, and an explicitHF_HUB_DISABLE_XETis still never touched. - Studio: the three live sidecars behave correctly under the fixed code, shown above. The Studio hub download path is unchanged by this PR and still has the gap already listed in the follow-ups,
download_registry.pydecidingxet_availablefromfind_specalone anddownload_lifecycle.pywritingHF_HUB_DISABLE_XET=0into the worker environment, which this PR deliberately respects. That is a pre-existing gap, identical before and after, and it needs the separate fix.
Upstream facts worth recording
hf_xetdoes publish Windows ARM64 wheels, from 1.3.1 onward, via xet-core#662 closing xet-core#588. 1.4.2 shipshf_xet-1.4.2-cp37-abi3-win_arm64.whl. So the remedy the warning points at genuinely exists, and the PR body's account of how the wrong wheel got installed stands.- There is no open upstream issue about wrong-architecture
hf_xetwheels orDLL load failed while importing hf_xetin eitherhuggingface/xet-coreorhuggingface/huggingface_hub. - Worth flagging: huggingface_hub's own dependency marker is
platform_machine=='x86_64' or ... =='amd64' or ... =='AMD64' or ... =='arm64' or ... =='aarch64'. Markers are case sensitive and Windows on ARM reportsARM64, sopip install huggingface_hubdoes not pullhf-xetthere at all. Anyhf_xeton such a host arrived some other way, which is consistent with what we found.
On preserving an explicit HF_HUB_DISABLE_XET=0
Asked and answered deliberately: yes, we keep it, and yes, that means Xet stays on even when we can see it is broken. The escape hatch has to be an escape hatch, our suspicion is heuristic, and a user who typed 0 outranks us. The one uncomfortable consequence is that Studio writes 0 programmatically, which is precisely why the download_lifecycle.py follow-up is a real item and not a nicety.
What I could not test here
- Linux, macOS and WSL as running systems. Those rows are simulated, as labelled.
- 32-bit Python on 64-bit Windows, and ARM64EC. No interpreter available. Reasoned only:
sysconfig.get_platform()returnswin32there and the mapper handles it, but I did not run it. - Real Xet-backed transfers. The test repos I reached served plain HTTPS, so I proved the chain by driving
file_download.xet_getdirectly and by observingis_xet_available()flip, rather than by watching a Xet download fail. - The full repo test suite.
tests/conftest.pyimports unsloth, which needs torch, and another job has the GPU on this box. I rantests/test_hf_xet_broken_wheel.py(58 passed),tests/test_broken_torchvision_probe.py(50 passed, 4 skipped) andtests/test_collection_hygiene.py(2 passed, 1 skipped) in a CPU-only venv with theunslothpackage namespace stubbed soimport_fixesloads without the heavy__init__. The module under test is the genuine one, nothing about it is stubbed. The three pre-existing Windows-specific failures reported in the PR body are unchanged by this commit.
… environment Setting HF_HUB_DISABLE_XET=1 only helps a process that has not imported the Hub yet. huggingface_hub >= 0.34 evaluates the variable exactly once, at import time, in constants.py, and file_download.py then reads constants.HF_HUB_DISABLE_XET on every call. So a user whose script starts with `import transformers` before `import unsloth` has already frozen it to False, and the fix was printing its warning while every download still routed to Xet and still died on the unimportable hf_xet. Placing the call first in _gpu_init.py only covers imports unsloth itself triggers; it cannot help someone who reached the Hub first. I now rebind the in-memory flag as well when huggingface_hub is already in sys.modules. Because readers go through the module attribute and never copy it into a local, that takes effect for the rest of the process. The environment variable is still set, and still set first, since that is what child processes and download workers inherit. The scan walks every loaded huggingface_hub module and only rewrites an attribute that already exists, so a later `from .constants import HF_HUB_DISABLE_XET` copy would be caught too, while huggingface_hub < 0.31, which never had the variable, and 0.31 to 0.33, which read os.environ per call, are left exactly as they were. The existing guards are untouched: an explicit user setting still wins, and a healthy or absent hf_xet still changes nothing. Verified with real downloads on huggingface_hub 0.24.7, 0.30.2, 0.33.5, 0.34.4, 0.36.2 and 1.31.0.
…circuit Two mutants survived the existing suite: - Every no-fire test stubs _hf_xet_distribution_is_installed, so a helper that reported an uninstalled hf_xet as installed kept the suite green while a user with no hf_xet at all got the warning and HF_HUB_DISABLE_XET=1 in their environment. The new test leaves the helper alone and makes importlib.metadata raise PackageNotFoundError. - Deleting the early return for an hf_xet already in sys.modules changed no assertion, because the follow-on lookup fails closed inside the existing except Exception. The new test records the lookups instead and asserts there were none.
The module docstring says these tests run everywhere, so Linux and macOS CI exercise the paths Windows on ARM would. They did not: `from unsloth import import_fixes` runs unsloth/__init__.py, which needs torch and an accelerator, so on a stock ubuntu, macos or windows runner collection ended at "ImportError: Unsloth: torch not found" and nothing in the file was exercised. Seen on four cross-platform staging legs. import_fixes.py imports only stdlib and packaging at module level, so loading it by path is enough. Verified by running the suite with torch made unimportable: 69 passed.
Simulation report
Took this one over and ran the full simulation. Three commits pushed to the branch, up to Before and afterMeasured against huggingface_hub 0.36.2 and hf_xet 1.2.1, in a throwaway venv copied per cell so no cell inherits another's damage, one process per cell, with
"error" is the user's actual failure, verbatim: which is the misleading part: hf_xet is installed, it simply is not loadable, and reinstalling the same wheel cannot fix it. REAL. Four broken shapes fixed, and the fix fires on exactly those four. Healthy, absent, user-set and already-imported are untouched, which is the half that decides release safety. EnumerationFull cross product of every input the gate reads: env value (5) x hf_xet in It warned in exactly the cells where it disabled, all 960. Invariants that held in every cell: a user-set CostFive fresh processes each, same venv with and without hf_xet: Neither sets the variable. The body claims about 26 ms present and 12 ms absent; I cannot reproduce that, it is roughly 5x and 3x what I measure here. The claim errs conservative so nothing depends on it, but those numbers are wrong for this box and are worth correcting in the description. Differential69 passed on the branch, 69 failed on merge-base Mutation, and the three things I fixedSix mutants against the branch as submitted: 4 killed, 2 survived. The first one I proved live rather than argued. With The second changes nothing observable on a healthy install, but it defeats the "makes repeat calls free" claim, and raising from
After those, 6 of 6 mutants killed. Cross-platform stagingOff the org queue, on the platforms the PR does not touch as well as the one it does:
Before the third commit above, windows-latest, windows-11-arm, ubuntu-24.04-arm and macos-15 all failed at collection with The remaining windows-11-arm failure is not this PR. It never reaches the tests: the install step dies building pyarrow from source, because there is no pyarrow wheel for Windows ARM64 on PyPI and the build fails at Blast radiusOne gate plus eight private helpers in What I could not prove
|
Opening comment-reduction pass. Added comment and docstring lines across the three files: 256 to 101. The 33-line header banner above the cpu tables keeps only the three facts a reader needs (metadata, not importability, decides routing; the constant is frozen at import, hence the _gpu_init placement; and unsloth_zoo.hf_xet_fallback is a different mechanism). Measured numbers, version sweeps and the quoted upstream traceback belong in the PR description, not the source.
A user who imports transformers first and only then sets HF_HUB_DISABLE_XET=1
asked for Xet off, and got Xet on: the variable is read by nobody once the Hub
has frozen it, and the early return skipped the helper that exists precisely to
unfreeze it. Reproduced on huggingface_hub 0.36.2:
env 1 | frozen constant False | is_xet_available True | routes to Xet True
and after the change:
env 1 | frozen constant True | is_xet_available False | routes to Xet False
Only truthy values are carried through, matched against the Hub's own
ENV_VARS_TRUE_VALUES, so an explicit HF_HUB_DISABLE_XET=0 still opts back in and
the constant is left alone.
|
Codex Review: Didn't find any major issues. 🚀 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". |
# Conflicts: # unsloth/_gpu_init.py
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7f34120701
ℹ️ 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".
| importlib.import_module("hf_xet") | ||
| return |
There was a problem hiding this comment.
Verify the API that Hugging Face imports
When a damaged installation leaves hf_xet-*.dist-info and an empty hf_xet/ directory without __init__.py or the compiled extension, find_spec returns a namespace-package spec and _hf_xet_extension_is_missing correctly marks it suspicious, but this bare import succeeds and returns early. Hugging Face still considers Xet available from the distribution metadata, then from hf_xet import XetFileInfo fails on every download. Confirm the symbols Hugging Face imports rather than merely importing the package.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Genuine, and reproduced. This landed in the same minute the PR merged, so it went untriaged here; the fix is now up as #11205.
An hf_xet/ directory with no __init__.py and no extension, beside an intact dist-info, is a namespace package. The suspicion was raised correctly, and then thrown away, because a namespace package always imports. Against huggingface_hub 0.36.2 with the package contents deleted and the directory left:
find_spec namespace
extension_is_missing True
bare import succeeds
routes_to_xet True
user_error ImportError: cannot import name 'PyXetDownloadInfo' from 'hf_xet' (unknown location)
which is exactly the misleading failure this change exists to prevent.
I took the general form of your suggestion rather than the literal one. Pinning the symbol list would tie us to a particular huggingface_hub (file_download wants PyXetDownloadInfo, download_files, _commit_api wants upload_bytes, upload_files, _xet_progress_reporting wants two more, and that set has moved before). A namespace package has __file__ None and no code at all, so no symbol the Hub asks for can exist; requiring a real __file__ covers every one of those imports without tracking them. Same scenario after: routes_to_xet False.
* Reject an hf_xet that is only an empty namespace package Follow-up to #11167. An hf_xet/ directory with no __init__.py and no extension in it, beside an intact hf_xet-*.dist-info, is a NAMESPACE package. The suspicion was raised correctly (the extension really is missing), but the confirm step imported the package, that import succeeded because a namespace package always does, and the fix cleared itself and did nothing. huggingface_hub does not import the package, it imports names out of it (from hf_xet import PyXetDownloadInfo, download_files), so it still routed every download to Xet. Reproduced against huggingface_hub 0.36.2 with the package contents deleted and the directory left behind: find_spec namespace extension_is_missing True bare import succeeds routes_to_xet True user_error ImportError: cannot import name 'PyXetDownloadInfo' from 'hf_xet' (unknown location) which is the exact misleading failure the original change exists to prevent. A namespace package has __file__ None and carries no code, so requiring a real __file__ is enough to tell it from an installed one, without pinning a symbol list that moves between huggingface_hub versions. Same scenario after: routes_to_xet False, and the shell is dropped from sys.modules rather than left for the next importer. The healthy, wrong-tag, already-imported and absent scenarios were re-run against a real huggingface_hub and are unchanged. The stand-in for a successful import in the test helper returned a bare object(), which has no __file__; it now returns a module, which is what a real import gives. * Check a cached hf_xet too, not just a freshly imported one huggingface_hub's own `from hf_xet import PyXetDownloadInfo, download_files` leaves hf_xet in sys.modules even when those symbols are missing: the PACKAGE imported fine and only the attribute lookup failed. So for a user whose first download happens before `import unsloth` (a notebook cell ordering, or any script that reaches the Hub first), the shell was already cached and the `if "hf_xet" in sys.modules: return` short circuit skipped every check. Reproduced against huggingface_hub 0.36.2, Hub used first: hub attempt ImportError: cannot import name 'PyXetDownloadInfo' from 'hf_xet' (unknown location) cached True, __file__ None env (unset) routes_to_xet True A cached module is not proof of a working one, so the cached object gets the same test as a freshly imported one and the shell is evicted rather than trusted. Same scenario after: env 1, routes_to_xet False. The test that pins the short circuit used a bare types.ModuleType as its stand in for a working hf_xet, which has no __file__ and is therefore exactly the shell this rejects; it now models a real module. The healthy, wrong-tag, already-imported and absent scenarios were re-run against a real huggingface_hub and are unchanged.
…nslothai#11167) * Fall back to HTTPS when hf_xet is installed but cannot be imported huggingface_hub decides whether to use the Xet transport with is_xet_available(), which only asks importlib.metadata whether the hf_xet distribution is installed. It never asks whether hf_xet actually imports. So an hf_xet that is present but unloadable is still routed to, the import inside file_download.xet_get raises, and transformers' cached_files turns that into "To use optimized download using Xet storage, you need to install the hf_xet package. Try pip install hf_xet", which names the one remedy that cannot work, because hf_xet is already installed. I hit this on Windows on ARM, where an x86-64 hf_xet wheel (Tag: cp37-abi3-win_amd64, hf_xet.pyd with PE machine 0x8664) ended up in an ARM64 CPython, so every Hub download died with "DLL load failed while importing hf_xet: %1 is not a valid Win32 application" and a QLoRA run never got past step 0. fix_broken_hf_xet_wheel now reads the installed hf_xet's wheel platform tags, compares them against this interpreter's CPU family, and when they disagree (or the package has no compiled extension at all) confirms the diagnosis with a real import before setting HF_HUB_DISABLE_XET=1 and logging one line that names the actual cause. Downloads then take the plain HTTPS branch: same files, same cache, only the Xet transport is skipped. It stays out of the way everywhere else. An hf_xet that is absent is left alone, since huggingface_hub already downgrades to HTTP for that case. An HF_HUB_DISABLE_XET the user set is never overridden in either direction. Metadata that cannot be read, a universal2 wheel, and an unknown machine all read as "cannot tell" rather than as a mismatch, and hf_xet is only ever imported for an install already proven suspect, so a healthy environment pays one small metadata read. It is wired into the first block of _gpu_init.py rather than down with the late fixes because huggingface_hub freezes HF_HUB_DISABLE_XET into constants.py at import time, so setting it after the Hub is imported would reach nobody. Note that unsloth_zoo.hf_xet_fallback does not cover this. That one is a Xet to HTTP stall fallback for a transfer that hangs, it only guards downloads routed through its own wrappers, and the training path that broke here went straight through transformers' cached_files. * Read the interpreter's own architecture, not the machine's, for the hf_xet check Three defects found simulating this against real hf_xet wheels and real huggingface_hub versions on a Windows on ARM box. 1. platform.machine() is the wrong question on Windows. CPython asks WMI for the PHYSICAL processor there (platform._get_machine_win32), so an emulated x86-64 interpreter on Windows on ARM answers "ARM64" while being win-amd64. Measured: every x86-64 venv on this box reports platform.machine() == "ARM64" beside sysconfig.get_platform() == "win-amd64". That got the verdict backwards in both directions. A healthy win_amd64 hf_xet read as a mismatch (harmless, but it bought a pointless `import hf_xet` at every startup), and, worse, a genuinely unloadable win_arm64 hf_xet in an x86-64 interpreter read as healthy, so the fix never fired on the install it exists for. Ask sysconfig.get_platform() instead, which reports what the interpreter was BUILT for, and keep platform.machine() only as the fallback for the builds sysconfig cannot name a CPU for (macOS universal2). 2. A leftover hf_xet-*.dist-info with no package directory beside it was skipped, because find_spec() returned None and that was read as "not installed". huggingface_hub never asks find_spec: is_xet_available() -> is_package_available("hf_xet") -> importlib.metadata.version(). Verified against huggingface_hub 1.31.0 with the package directory deleted and the metadata left: is_xet_available() returned True, so every download still went down the Xet branch and still died in `from hf_xet import XetFileInfo`. 3. An hf_xet whose WHEEL metadata is unreadable (vendored, repackaged, trimmed dist-info) gave no verdict at all, so a wrong-architecture extension sitting right there was let through. Fall back to the machine id in the .pyd/.so header itself, which is the fact that actually decides whether the import can work. Parser checked against the real PE, ELF and Mach-O binaries out of the hf_xet 1.4.2 wheels for win_amd64, win_arm64, manylinux2014_x86_64, manylinux_2_28_aarch64 and macosx_11_0_arm64. None of these can disable Xet on their own: a suspicion is still confirmed by a real import before anything is set, and an explicit HF_HUB_DISABLE_XET is still never overridden in either direction. Re-checked that a healthy x86-64 Linux install is untouched. Also require fix_broken_hf_xet_wheel() to be the FIRST import fix called in _gpu_init.py rather than merely earlier than fix_huggingface_hub(). Confirmed by measurement that huggingface_hub freezes HF_HUB_DISABLE_XET into constants.py from 0.34.0 onward, so any fix added later that reaches the Hub first would silently make this one a no-op. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Also disable Xet in an already-imported huggingface_hub, not just the environment Setting HF_HUB_DISABLE_XET=1 only helps a process that has not imported the Hub yet. huggingface_hub >= 0.34 evaluates the variable exactly once, at import time, in constants.py, and file_download.py then reads constants.HF_HUB_DISABLE_XET on every call. So a user whose script starts with `import transformers` before `import unsloth` has already frozen it to False, and the fix was printing its warning while every download still routed to Xet and still died on the unimportable hf_xet. Placing the call first in _gpu_init.py only covers imports unsloth itself triggers; it cannot help someone who reached the Hub first. I now rebind the in-memory flag as well when huggingface_hub is already in sys.modules. Because readers go through the module attribute and never copy it into a local, that takes effect for the rest of the process. The environment variable is still set, and still set first, since that is what child processes and download workers inherit. The scan walks every loaded huggingface_hub module and only rewrites an attribute that already exists, so a later `from .constants import HF_HUB_DISABLE_XET` copy would be caught too, while huggingface_hub < 0.31, which never had the variable, and 0.31 to 0.33, which read os.environ per call, are left exactly as they were. The existing guards are untouched: an explicit user setting still wins, and a healthy or absent hf_xet still changes nothing. Verified with real downloads on huggingface_hub 0.24.7, 0.30.2, 0.33.5, 0.34.4, 0.36.2 and 1.31.0. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Test the absent case against real metadata and the sys.modules short circuit Two mutants survived the existing suite: - Every no-fire test stubs _hf_xet_distribution_is_installed, so a helper that reported an uninstalled hf_xet as installed kept the suite green while a user with no hf_xet at all got the warning and HF_HUB_DISABLE_XET=1 in their environment. The new test leaves the helper alone and makes importlib.metadata raise PackageNotFoundError. - Deleting the early return for an hf_xet already in sys.modules changed no assertion, because the follow-on lookup fails closed inside the existing except Exception. The new test records the lookups instead and asserts there were none. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Load import_fixes by path so the suite really does run on every OS The module docstring says these tests run everywhere, so Linux and macOS CI exercise the paths Windows on ARM would. They did not: `from unsloth import import_fixes` runs unsloth/__init__.py, which needs torch and an accelerator, so on a stock ubuntu, macos or windows runner collection ended at "ImportError: Unsloth: torch not found" and nothing in the file was exercised. Seen on four cross-platform staging legs. import_fixes.py imports only stdlib and packaging at module level, so loading it by path is enough. Verified by running the suite with torch made unimportable: 69 passed. * Cut the comment volume in this change roughly in half Opening comment-reduction pass. Added comment and docstring lines across the three files: 256 to 101. The 33-line header banner above the cpu tables keeps only the three facts a reader needs (metadata, not importability, decides routing; the constant is frozen at import, hence the _gpu_init placement; and unsloth_zoo.hf_xet_fallback is a different mechanism). Measured numbers, version sweeps and the quoted upstream traceback belong in the PR description, not the source. * Carry an explicit disable to an already imported Hub A user who imports transformers first and only then sets HF_HUB_DISABLE_XET=1 asked for Xet off, and got Xet on: the variable is read by nobody once the Hub has frozen it, and the early return skipped the helper that exists precisely to unfreeze it. Reproduced on huggingface_hub 0.36.2: env 1 | frozen constant False | is_xet_available True | routes to Xet True and after the change: env 1 | frozen constant True | is_xet_available False | routes to Xet False Only truthy values are carried through, matched against the Hub's own ENV_VARS_TRUE_VALUES, so an explicit HF_HUB_DISABLE_XET=0 still opts back in and the constant is left alone. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…1205) * Reject an hf_xet that is only an empty namespace package Follow-up to unslothai#11167. An hf_xet/ directory with no __init__.py and no extension in it, beside an intact hf_xet-*.dist-info, is a NAMESPACE package. The suspicion was raised correctly (the extension really is missing), but the confirm step imported the package, that import succeeded because a namespace package always does, and the fix cleared itself and did nothing. huggingface_hub does not import the package, it imports names out of it (from hf_xet import PyXetDownloadInfo, download_files), so it still routed every download to Xet. Reproduced against huggingface_hub 0.36.2 with the package contents deleted and the directory left behind: find_spec namespace extension_is_missing True bare import succeeds routes_to_xet True user_error ImportError: cannot import name 'PyXetDownloadInfo' from 'hf_xet' (unknown location) which is the exact misleading failure the original change exists to prevent. A namespace package has __file__ None and carries no code, so requiring a real __file__ is enough to tell it from an installed one, without pinning a symbol list that moves between huggingface_hub versions. Same scenario after: routes_to_xet False, and the shell is dropped from sys.modules rather than left for the next importer. The healthy, wrong-tag, already-imported and absent scenarios were re-run against a real huggingface_hub and are unchanged. The stand-in for a successful import in the test helper returned a bare object(), which has no __file__; it now returns a module, which is what a real import gives. * Check a cached hf_xet too, not just a freshly imported one huggingface_hub's own `from hf_xet import PyXetDownloadInfo, download_files` leaves hf_xet in sys.modules even when those symbols are missing: the PACKAGE imported fine and only the attribute lookup failed. So for a user whose first download happens before `import unsloth` (a notebook cell ordering, or any script that reaches the Hub first), the shell was already cached and the `if "hf_xet" in sys.modules: return` short circuit skipped every check. Reproduced against huggingface_hub 0.36.2, Hub used first: hub attempt ImportError: cannot import name 'PyXetDownloadInfo' from 'hf_xet' (unknown location) cached True, __file__ None env (unset) routes_to_xet True A cached module is not proof of a working one, so the cached object gets the same test as a freshly imported one and the shell is evicted rather than trusted. Same scenario after: env 1, routes_to_xet False. The test that pins the short circuit used a bare types.ModuleType as its stand in for a working hf_xet, which has no __file__ and is therefore exactly the shell this rejects; it now models a real module. The healthy, wrong-tag, already-imported and absent scenarios were re-run against a real huggingface_hub and are unchanged.
On Windows ARM64,
hf_xetcan end up installed as an x86-64 wheel inside an ARM64 interpreter.import hf_xetthen fails at the DLL level, and every Hugging Face download that routes through Xet dies. What the user actually sees is this, which is actively misleading:hf_xetIS installed. Reinstalling the same wheel cannot help, because the problem is the architecture of the wheel, not its absence. This blocked a QLoRA training run ofunsloth/Qwen3.5-2Bat step 0 on an NVIDIA RTX Spark N1X box.The failure chain:
What this does
Adds
fix_broken_hf_xet_wheel()tounsloth/import_fixes.py. Whenhf_xetis installed but cannot be imported, it setsHF_HUB_DISABLE_XET=1so downloads transparently use plain HTTPS, and logs one warning that names the real cause.The guard order matters, so to be explicit:
HF_HUB_DISABLE_XETis already set, in either direction, the user's choice wins and we do nothing.hf_xetis already insys.modulesit demonstrably works, so we do nothing.huggingface_hubis absent, orhf_xetis absent with no distribution metadata left behind either, we do nothing. The Hub already handles a genuinely missinghf_xetcorrectly.hf_xet. If it imports fine, we leave Xet on. Suspect means one of: the wheel platform tag names a CPU family this interpreter is not, the compiled extension header names one (used when theWHEELmetadata is unreadable), the compiled extension is missing outright, orimportlib.metadatastill sees anhf_xetdistribution that the import system cannot find.Confirming by import rather than trusting the tag means a healthy install never pays for this and never gets the variable set, and a misread tag corrects itself.
Placement
This is wired into the first block of
unsloth/_gpu_init.py, not next to the otherhf_xetpatch further down.huggingface_hub/constants.pyfreezesHF_HUB_DISABLE_XETinto a module constant at import time, and by the later blockdisable_broken_vllm,check_fbgemm_gpu_versionandfix_huggingface_hubhave all already pulled the Hub in. Setting it there would have been a no-op. There is a test asserting the ordering so this does not regress.Evidence
Before, on ARM64 CPython 3.13.15 with the affected sidecar:
After, same interpreter, real end to end
import unsloth:The download log shows a plain
HEADthenGETthroughhttp_get, with no Xet branch.Verified no-fire cases, each in a real process: healthy
win_arm64wheel, awin_amd64tag whose module nevertheless imports fine,hf_xetabsent entirely, and user-setHF_HUB_DISABLE_XET=0and=1both preserved verbatim.Cost on a healthy install, once per process, measured cold across five fresh processes on this box: about 26 ms with
hf_xetpresent and about 12 ms with it absent. Nothing is imported on that path; it isfind_specplus oneimportlib.metadatascan.Tests
tests/test_hf_xet_broken_wheel.py, 58 tests: tag parser table, mismatch verdicts, fires-on-mismatch with one log line, idempotency, does-not-fire when the import succeeds despite a mismatched tag, healthy wheel, absenthf_xet, three user-override values, the_gpu_initordering assertions, host-CPU resolution preferringsysconfig.get_platform()overplatform.machine(), the ELF / PE / Mach-O header parser, and the metadata-only and unreadable-WHEELinstall shapes. All fakes, no network, platform independent.See the simulation report in the comments for the full executed matrix.
Wider run across
test_import_fixes_drift,test_enforce_kwargs_spacing,test_lint_duplicate_definitions,test_collection_hygiene,test_public_api_surface,test_version_single_source,test_python39_compatibilityandtest_source_read_encoding: 148 passed, 9 skipped, 3 failed. All 3 failures are pre-existing and Windows specific, confirmed identical with these changes stashed on a clean tree.How the wrong wheel got there
Worth recording, because the install path itself is not at fault. PyPI does publish
hf_xet-1.4.2-cp37-abi3-win_arm64.whl, and reproducing the install today resolves correctly:The sidecars were created at a time when the resolving interpreter was an emulated x86-64 CPython, so all three (
.venv_t5_510,_530,_550) carryhf_xetandtiktokenatwin_amd64.What makes it permanent is validation rather than installation. The sidecar scan checks extension tags for the Python version only and never inspects the platform half, so
cp313-cp313-win_amd64passes as current, the wipe and reinstall never fires, and an x64 sidecar is reused forever by an ARM64 interpreter.Follow-ups, not in this PR
WHEELtag againstsysconfig.get_platform(), and treat a mismatch as damage so the sidecar rebuilds. That would have self-healed all three sidecars here.download_registry.pydecidesxet_availablefromfind_spec("hf_xet") is not None, which has the identical blind spot, and it causesdownload_lifecycle.pyto writeHF_HUB_DISABLE_XET=0explicitly into the download worker environment. This PR deliberately respects an explicit setting, so Studio hub downloads on such a host need that separate fix.