Skip to content

Fall back to HTTPS when hf_xet is installed but cannot be imported - #11167

Merged
danielhanchen merged 11 commits into
mainfrom
fix-hf-xet-arm64-wheel
Sep 17, 2026
Merged

danielhanchen merged 11 commits into
mainfrom
fix-hf-xet-arm64-wheel

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 17, 2026 •

Copy link
Copy Markdown
Member

On Windows ARM64, hf_xet can end up installed as an x86-64 wheel inside an ARM64 interpreter. import hf_xet then 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:

OSError: To use optimized download using Xet storage, you need to install the hf_xet package.
Try `pip install "huggingface_hub[hf_xet]"` or `pip install hf_xet`.

hf_xet IS 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 of unsloth/Qwen3.5-2B at step 0 on an NVIDIA RTX Spark N1X box.

The failure chain:

huggingface_hub/file_download.py xet_get -> from hf_xet import XetFileInfo
  -> ImportError: DLL load failed while importing hf_xet: %1 is not a valid Win32 application.
  -> huggingface_hub raises ValueError("... you need to install the hf_xet package ...")
  -> transformers/utils/hub.py cached_files re-raises it verbatim as OSError

What this does

Adds fix_broken_hf_xet_wheel() to unsloth/import_fixes.py. When hf_xet is installed but cannot be imported, it sets HF_HUB_DISABLE_XET=1 so downloads transparently use plain HTTPS, and logs one warning that names the real cause.

The guard order matters, so to be explicit:

  1. If HF_HUB_DISABLE_XET is already set, in either direction, the user's choice wins and we do nothing.
  2. If hf_xet is already in sys.modules it demonstrably works, so we do nothing.
  3. If huggingface_hub is absent, or hf_xet is absent with no distribution metadata left behind either, we do nothing. The Hub already handles a genuinely missing hf_xet correctly.
  4. Only if the install looks suspect do we confirm by actually importing 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 the WHEEL metadata is unreadable), the compiled extension is missing outright, or importlib.metadata still sees an hf_xet distribution that the import system cannot find.
  5. Only a genuine import failure sets the variable.

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 other hf_xet patch further down. huggingface_hub/constants.py freezes HF_HUB_DISABLE_XET into a module constant at import time, and by the later block disable_broken_vllm, check_fbgemm_gpu_version and fix_huggingface_hub have 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:

constants.HF_HUB_DISABLE_XET = False
import hf_xet -> ImportError: DLL load failed while importing hf_xet: %1 is not a valid Win32 application.
cached_files(...) -> OSError: ... you need to install the hf_xet package ...

After, same interpreter, real end to end import unsloth:

BEFORE import unsloth: HF_HUB_DISABLE_XET = None
AFTER  import unsloth: HF_HUB_DISABLE_XET = 1
cached_files -> ...\snapshots\fffbc0d8...\tokenizer.json   (19,989,343 bytes)

The download log shows a plain HEAD then GET through http_get, with no Xet branch.

Verified no-fire cases, each in a real process: healthy win_arm64 wheel, a win_amd64 tag whose module nevertheless imports fine, hf_xet absent entirely, and user-set HF_HUB_DISABLE_XET=0 and =1 both preserved verbatim.

Cost on a healthy install, once per process, measured cold across five fresh processes on this box: about 26 ms with hf_xet present and about 12 ms with it absent. Nothing is imported on that path; it is find_spec plus one importlib.metadata scan.

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, absent hf_xet, three user-override values, the _gpu_init ordering assertions, host-CPU resolution preferring sysconfig.get_platform() over platform.machine(), the ELF / PE / Mach-O header parser, and the metadata-only and unreadable-WHEEL install 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_compatibility and test_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:

DEBUG Selecting: hf-xet==1.4.2 [compatible] (hf_xet-1.4.2-cp37-abi3-win_arm64.whl)

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) carry hf_xet and tiktoken at win_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_amd64 passes 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

  • The sidecar scan should compare the platform component of extension tags and the dist-info WHEEL tag against sysconfig.get_platform(), and treat a mismatch as damage so the sidecar rebuilds. That would have self-healed all three sidecars here.
  • download_registry.py decides xet_available from find_spec("hf_xet") is not None, which has the identical blind spot, and it causes download_lifecycle.py to write HF_HUB_DISABLE_XET=0 explicitly into the download worker environment. This PR deliberately respects an explicit setting, so Studio hub downloads on such a host need that separate fix.

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.
@chatgpt-codex-connector

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

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-17T12:41:36.106567Z 7f34120 Manual request
🔒 Security Review ✅ Completed 2026-09-17T02:03:54.452918Z 6c87e03 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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: 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".

Comment thread unsloth/import_fixes.py
except Exception as error:
failure = f"{type(error).__name__}: {error}"

os.environ["HF_HUB_DISABLE_XET"] = "1"

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

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.

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.

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.

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.

@danielhanchen

Copy link
Copy Markdown
Member Author

Adding a limitation I want recorded on this PR, plus links to related reports.

Trade-off: files over 50 GB

Disabling Xet is not entirely free. huggingface_hub refuses plain HTTP downloads above MAX_HTTP_DOWNLOAD_SIZE:

# 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 hf_xet, this fix turns a total download failure into a working one for every file up to 50 GB, but a single file larger than that will still fail, now with a different message. That is strictly better than the status quo, where nothing downloads at all, and it is unreachable for the overwhelming majority of weights and shards. It is worth knowing about for very large single-file GGUFs.

The real resolution for those users is a correctly built hf_xet, which is the sidecar-rebuild follow-up described in the PR body rather than anything this change can do.

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.
@danielhanchen

Copy link
Copy Markdown
Member Author

Simulation and compatibility pass

I 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

# Theory Outcome
1 Hub versions predating HF_HUB_DISABLE_XET entirely: we set a variable nobody reads Confirmed, and harmless. See the hub matrix
2 Hub versions reading it lazily rather than frozen at import Confirmed, 0.31.0 to 0.33.5 read it per call
3 Another import fix starts pulling the Hub in earlier and silently voids this Real risk, now guarded by a test
4 Negative find_spec cost on a long sys.path Measured, not a problem
5 Frozen / zipimport / PyInstaller shape with no WHEEL metadata Real defect. Fixed
6 dist-info missing, or the package vendored Two cases. Metadata gone entirely is safe; metadata present with no package is a real defect. Fixed
7 platform.machine() values the mapper does not know (aarch64 vs arm64 vs ARM64, x86_64 vs AMD64, universal2) Mapper was fine. The source was not. Real defect, fixed
8 A healthy x86-64 Linux user must not lose Xet Holds, before and after
9 Subprocess inheritance of the variable Works
10 Explicit HF_HUB_DISABLE_XET=0 must survive Holds. See the note at the end on whether that is right

Defect 1: platform.machine() is the wrong question on Windows (EXECUTED)

This is the big one, and it was live on the exact platform class this PR targets.

CPython's platform.machine() on Windows asks WMI for the physical processor (platform._get_machine_win32), not the architecture of the running interpreter. So on Windows on ARM, an emulated x86-64 CPython answers ARM64.

Measured on this box, every x86-64 venv:

sysconfig.get_platform() = win-amd64      platform.machine() = ARM64

The verdict function was keyed off platform.machine(), so it was wrong in both directions:

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_xet is both installed and unimportable, and an explicit HF_HUB_DISABLE_XET is 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.py deciding xet_available from find_spec alone and download_lifecycle.py writing HF_HUB_DISABLE_XET=0 into 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_xet does publish Windows ARM64 wheels, from 1.3.1 onward, via xet-core#662 closing xet-core#588. 1.4.2 ships hf_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_xet wheels or DLL load failed while importing hf_xet in either huggingface/xet-core or huggingface/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 reports ARM64, so pip install huggingface_hub does not pull hf-xet there at all. Any hf_xet on 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() returns win32 there 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_get directly and by observing is_xet_available() flip, rather than by watching a Xet download fail.
  • The full repo test suite. tests/conftest.py imports unsloth, which needs torch, and another job has the GPU on this box. I ran tests/test_hf_xet_broken_wheel.py (58 passed), tests/test_broken_torchvision_probe.py (50 passed, 4 skipped) and tests/test_collection_hygiene.py (2 passed, 1 skipped) in a CPU-only venv with the unsloth package namespace stubbed so import_fixes loads 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.

pre-commit-ci Bot and others added 4 commits September 17, 2026 02:50
… 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.
pre-commit-ci Bot and others added 2 commits September 17, 2026 11:12
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.
@danielhanchen

Copy link
Copy Markdown
Member Author

Simulation report

#11167 | issue: REAL | PR as submitted: DEFECTIVE, 3 fixed by me | merge: YES

Took this one over and ran the full simulation. Three commits pushed to the branch, up to 1920f6f1e; the fix itself is unchanged.

Before and after

Measured 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 HF_HUB_DISABLE_XET scrubbed out of the child environment so the parent cannot leak it in. Ten scenarios, two arms.

scenario main routes to Xet branch routes to Xet fix fired
healthy yes yes no
metadata only, package dir gone yes, error no yes
compiled extension deleted yes, error no yes
extension header says AArch64 yes, error no yes
WHEEL tag says win_amd64, extension loads yes yes no
hf_xet fully uninstalled no no no
broken install, user set HF_HUB_DISABLE_XET=0 yes, error yes, error no
broken install, user set HF_HUB_DISABLE_XET=1 no no no
hf_xet already imported yes yes no
huggingface_hub imported before the fix runs yes, error no yes

"error" is the user's actual failure, verbatim:

ValueError: To use optimized download using Xet storage, you need to install the hf_xet
package.  [raised because: ModuleNotFoundError: No module named 'hf_xet']

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.

Enumeration

Full cross product of every input the gate reads: env value (5) x hf_xet in sys.modules (2) x huggingface_hub importable (2) x hf_xet spec (2) x metadata installed (2) x architecture verdict (3) x extension missing (2) x confirm-by-import result (2) = 960 cells.

DISABLE       42     no spec + metadata present 18
                     architecture mismatch      12
                     extension missing          12
LEAVE_ALONE  918

It warned in exactly the cells where it disabled, all 960. Invariants that held in every cell: a user-set HF_HUB_DISABLE_XET never loses, hf_xet already in sys.modules never disables, an unimportable huggingface_hub never disables, and a successful import hf_xet never disables.

Cost

Five fresh processes each, same venv with and without hf_xet:

hf_xet present: 4.37 4.53 4.57 4.91 5.23 ms   (median 4.57)
hf_xet absent : 3.77 3.78 3.82 3.83 4.09 ms   (median 3.82)

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.

Differential

69 passed on the branch, 69 failed on merge-base f6cf06dec, all AttributeError because the symbols do not exist there. That arm is vacuous as behavioural evidence and I am not counting it as any. The ten-scenario matrix above is what carries the claim, because it asks huggingface_hub's own routing question on both arms.

Mutation, and the three things I fixed

Six mutants against the branch as submitted: 4 killed, 2 survived.

SURVIVED  a genuinely absent hf_xet is treated as installed
SURVIVED  hf_xet already in sys.modules no longer short-circuits

The first one I proved live rather than argued. With _hf_xet_distribution_is_installed forced True, a user who has no hf_xet at all gets the full "hf_xet is installed but cannot be imported" warning and HF_HUB_DISABLE_XET=1 exported to every child process. The suite stayed green because every no-fire test replaces that helper with a lambda, so the real one was never exercised.

The second changes nothing observable on a healthy install, but it defeats the "makes repeat calls free" claim, and raising from find_spec does not expose it either because that lookup sits inside except Exception: return.

  1. 2fa22198c test_absence_is_decided_by_real_metadata_not_by_a_stub: leaves the helper alone and makes importlib.metadata raise PackageNotFoundError.
  2. 2fa22198c test_an_imported_hf_xet_short_circuits_before_any_lookup: records the lookups and asserts there were none.
  3. 1920f6f1e The file's docstring says it runs on every OS so Linux and macOS CI exercise the Windows-on-ARM paths. It did not. from unsloth import import_fixes runs unsloth/__init__.py, which needs torch and an accelerator, so on stock runners collection ended at ImportError: Unsloth: torch not found and nothing in the file was exercised. I saw this on four cross-platform staging legs. import_fixes.py imports only stdlib and packaging at module level, so it is now loaded by path. Verified by running the suite with torch made unimportable: 69 passed.

After those, 6 of 6 mutants killed.

Cross-platform staging

Off the org queue, on the platforms the PR does not touch as well as the one it does:

runner result
windows-latest success
ubuntu-24.04-arm success
windows-11-arm failure, see below
ubuntu-latest, macos-15, macos-13 still queued at the time of writing

Before the third commit above, windows-latest, windows-11-arm, ubuntu-24.04-arm and macos-15 all failed at collection with ImportError: Unsloth: torch not found. They pass now.

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 find_package. That is the exact gap the signed Windows-on-ARM wheelhouse addresses, and it is the reason a public ARM64 Windows runner cannot install this repo today.

Blast radius

One gate plus eight private helpers in unsloth/import_fixes.py, called once from unsloth/_gpu_init.py. Symbol audit across unsloth and unsloth_zoo: no collisions, the only references to any new name are the three intended lines in _gpu_init.py. The only globally visible effect is setting HF_HUB_DISABLE_XET=1, on 42 of 960 cells. No new dependency, no pin change, no installer change, nothing imported on the healthy path.

What I could not prove

  • I have no Windows-on-ARM box. Every architecture-mismatch case is faked at the three sources the code reads: sysconfig.get_platform(), the WHEEL tags, and the ELF, PE or Mach-O header. What is proven is that the code reads those sources correctly, not that a real ARM64 interpreter with a win_amd64 hf_xet behaves as modelled.
  • The cost numbers in the description, as above.
  • No file went on the wire. The matrix asks huggingface_hub's own routing question, is_xet_available() and not constants.HF_HUB_DISABLE_XET, it does not perform a download.
  • huggingface_hub 1.x. I measured 0.36.2 only; the description cites 1.31.0 for the metadata-only case and I did not re-run that version.

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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen added a commit to Datta0/unsloth-staging-3 that referenced this pull request Sep 17, 2026
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.
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: 222c3b8998

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

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

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@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: 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".

Comment thread unsloth/import_fixes.py
Comment on lines +1677 to +1678
importlib.import_module("hf_xet")
return

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 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 👍 / 👎.

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.

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.

@danielhanchen
danielhanchen merged commit 6ed7f22 into main Sep 17, 2026
3 of 28 checks passed
@danielhanchen
danielhanchen deleted the fix-hf-xet-arm64-wheel branch September 17, 2026 12:41
danielhanchen added a commit that referenced this pull request Sep 17, 2026
* 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.
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…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>
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant