Skip to content

Studio: Auto download transport, Xet memory caps, and stall detection on the hub path - #7742

Merged
danielhanchen merged 28 commits into
mainfrom
feat/studio-xet-auto-fallback
Aug 3, 2026
Merged

danielhanchen merged 28 commits into
mainfrom
feat/studio-xet-auto-fallback

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Why

Three separate problems with Xet downloads in Studio.

The model hub had no stall detection at all. finalize_worker_exit says so in its own docstring: it relies on the worker's exit code, and a Xet transfer that hangs with no progress and no error never produces one. Inference (core/inference/worker.py) and training (core/training/worker.py) already ran the shared watchdog; the hub -- the path most users actually download through -- did not. That is the frozen progress bar.

Nothing capped Xet's memory. hf_xet sizes its reconstruction buffers from constants: 2GB floor + 512MB per concurrent file (8 of them), capped at 8GB, plus a 1GB prefetch floor. With HF_XET_HIGH_PERFORMANCE inherited from the environment that cap becomes 64GB and the stream count 124.

Nothing remembered. resolve_effective_use_xet only downgraded when hf_xet was missing, so a machine that had failed Xet ten times still started on Xet, and paid the stalled attempt, every single time.

What changed

Stall detection on the hub path. register_worker now starts the shared start_watchdog for Xet jobs and SIGKILLs a worker that stops making byte-level progress. The kill is deliberate: the worker traps SIGTERM and exits 130, which classify_exit reads as a user cancel and would skip the retry; an untrapped kill lands as error, which is the exact state the existing XET-to-HTTP retry already keys on. That retry path is unchanged. The worker's writer is sequential and resumable, so the partial is not lost work. The watchdog is stopped as soon as the worker is reaped, so post-download symlinking and verification are never read as a stall.

Memory caps on spawned workers. spawn_worker merges RAM-derived HF_XET_* values into the worker env. This cannot be done with setdefault alone: env is seeded from the parent environment, so an inherited HF_XET_HIGH_PERFORMANCE=1 arrives here, and xet-core applies that preset after reading the environment -- it would discard every cap rather than compete with it. It is overwritten explicitly, with UNSLOTH_XET_ALLOW_HIGH_PERFORMANCE=1 to opt back in. Operator-set HF_XET_* values are still preserved.

An Auto transport, defaulted. The picker gains a third option. Auto resolves server-side, because only the backend can see this machine's RAM, its hf_xet build, and whether Xet has been failing here.

It resolves through the capabilities endpoint (auto_resolves_to / auto_reason) rather than independently on both sides. That matters: the resolved transport is compared against the .transport marker of an existing partial, so if the client picked Xet and the server picked HTTP a resume would be misjudged. One source of truth, resolved once.

auto is deliberately not a member of VALID_TRANSPORTS. The on-disk marker must keep naming the writer that produced a partial; VALID_TRANSPORT_MODES is the separate set for request preferences.

An explicit Xet or HTTP choice is still honoured (a user who asks for Xet gets Xet -- with the caps and the fallback, but the health verdict does not overrule them), and a preference already in localStorage is preserved. The tooltip says what Auto currently resolves to and why, e.g. "Currently: HTTP (Xet failed 2 times in a row on this machine)".

poll-loop.ts carried the stored preference as a boolean (getTransportMode() === TRANSPORT.XET), which would have read "auto" as "not xet" and sent every download over HTTP. It now stays unresolved until effectiveTransportMode().

Measured

download transport peak RSS wall throughput
gemma-4-E2B UD-Q4_K_XL (3.18GB) Xet stock 2.01 GB 7.2s 3561 Mbps
gemma-4-E2B UD-Q4_K_XL Xet capped 0.80 GB 12.3s 2069 Mbps
gemma-4-E2B UD-Q4_K_XL HTTP 0.07 GB 213.4s 119 Mbps

HTTP is 15-30x slower than Xet on this link, which is why Auto keeps Xet first and treats HTTP strictly as recovery rather than as a safer default. Anonymous downloads (no HF_TOKEN) reach Xet at full speed, so none of this depends on having a token.

Tests

studio/backend/tests/test_hub_download_transport_auto.py (19 new): transport selection including "explicit Xet beats an unhealthy verdict" and the legacy use_xet path; the caps reaching the worker env including the high-performance override; stall -> kill -> retry including an already-exited worker and a degraded unsloth_zoo. studio/frontend/tests/transport-mode-auto.test.ts (4 new) pins the Auto default and that an existing explicit preference survives.

Existing test_hf_xet_fallback.py, test_gguf_xet_fallback_integration.py and test_hf_cache_settings.py pass unchanged; frontend npm run typecheck is clean.

Depends on unslothai/unsloth-zoo#972 for hf_xet_tuning / hf_xet_health. Both are imported through the existing lazy, degrade-don't-crash shim in utils/hf_xet_fallback.py, so an older unsloth_zoo keeps working -- it just loses the caps and the verdict, not the ability to download.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

Verified against a live Studio, not mocks

A Studio was installed from this branch (UNSLOTH_STUDIO_HOME, port 8907) with the companion unsloth_zoo branch, and driven through scripts/xet_studio_e2e.py. 13/14 checks passed on the first complete run; the one failure was my test sending an invalid training_type enum, fixed and re-run.

check result
capabilities endpoint exposes auto_resolves_to PASS
a demoted machine resolves Auto to HTTP PASS -- http (Xet stalled twice on this machine)
a recovered machine resolves Auto back to Xet PASS -- xet (Xet download succeeded)
hub download accepted with transport_mode: auto PASS -- HTTP 202
hub download completed PASS -- state=complete
transport picker present in the UI PASS
picker offers Auto alongside HTTP and Xet PASS -- 'Auto\nHTTP\nXet'
Auto is the selected default PASS -- aria-pressed=true
GGUF model load PASS
chat completion returns text PASS -- returned XETOK
training run accepted and runs PASS

The demotion round trip is the interesting one, because it exercises the whole chain rather than any single piece: the zoo ladder records a failed Xet attempt, the verdict persists next to the HF cache, the backend's capabilities endpoint reports auto_resolves_to: http with the reason, and one recorded success flips it back. The server log line confirms the resolution reaching the worker:

"event": "Download transport for unsloth/Qwen3.5-2B-MTP-GGUF: xet (no cached verdict; defaulting to Xet)"

transport_mode also shows up in the running server's OpenAPI schema for POST /api/hub/download, so the field is genuinely wired, not just declared.

Anonymous CI, no HF_TOKEN

Replicated onto a staging repo and run on ubuntu-latest (4 cores, ~16GB, no token secret), sequential with the cache deleted between cells. 0 failed cells.

download mode peak RSS wall throughput
Qwen3.5-2B IQ4_XS Xet stock 0.77 GB 11.1s 905 Mbps
Qwen3.5-2B IQ4_XS Xet capped 0.41 GB 14.1s 711 Mbps
Qwen3.5-2B IQ4_XS HTTP 0.10 GB 42.2s 237 Mbps
Qwen3.5-4B Q4_0 Xet stock 1.24 GB 16.1s 1284 Mbps
Qwen3.5-4B Q4_0 Xet capped 0.47 GB 18.1s 1143 Mbps
gemma-4-E2B UD-Q4_K_XL Xet stock 1.62 GB 16.1s 1584 Mbps
gemma-4-E2B UD-Q4_K_XL Xet capped 0.72 GB 23.1s 1102 Mbps
gemma-4-E2B UD-Q4_K_XL HTTP 0.11 GB 85.3s 299 Mbps

56% less peak RSS for 12-30% more wall time. Anonymous Xet is fast and works, so no token is required for any of this.

That CI job also caught a real bug that review did not: _load_optional gave up when unsloth_zoo.__init__ raised on a CPU-only host, which silently disabled the RAM caps on exactly the small machines they exist to protect. Fixed in b6c4cb1 with the same GPU-init retry _load_shared already had, plus a regression test.

The multi-shard case

On a 61GB / 13-shard safetensors repo (unsloth/Qwen3-30B-A3B-Instruct-2507), peak RSS is 6.60 GB stock vs 2.50 GB capped. That is where the reported multi-GB spikes come from: the buffer grows per concurrent file, so the more shards a repo has, the closer stock gets to its 8GB (or 64GB high-performance) ceiling.

@danielhanchen

Copy link
Copy Markdown
Member Author

UI and training, confirmed

Playwright screenshot of the Model hub header on this branch shows the picker rendering Auto | HTTP | Xet with Auto selected, and the tooltip explaining itself rather than being an opaque third option:

Picks the transport for this machine and switches to HTTP if Xet stalls or fails. Currently: Xet.

When the machine has been demoted the same tooltip reads Currently: HTTP (Xet stalled twice on this machine), since the reason comes from the same auto_reason the backend computed.

Training was exercised as a real run rather than a status ping, because the point is the training worker's own model download going through the shared ladder:

POST /api/train/start  {model_name: unsloth/Qwen3-0.6B, training_type: LoRA/QLoRA, max_steps: 3}
-> job_20260802_115104_4b81cc26  queued -> completed
   "Training completed! Model saved to ..."

So all three surfaces named in the issue are covered end to end on a live server: hub (download under Auto, completed), inference (GGUF load + chat returning XETOK), training (LoRA run to completion).

One caveat worth stating

The hub stall path is covered by unit tests (kill -> error -> existing HTTP retry, plus the already-exited race and the degraded-unsloth_zoo case), but I did not manufacture a live hang through the hub worker specifically -- UNSLOTH_HF_XET_FORCE_STALL is honoured by the unsloth_zoo spawn child, not by hub.workers.hf_download. The equivalent ladder was exercised live at the zoo level (36.8s to detect, then a clean 1.25GB HTTP completion; see unslothai/unsloth-zoo#972), and the hub path calls the same start_watchdog. If a reviewer wants a live hub-level stall too, the cheapest way is a fault-injection env var in hub/workers/hf_download.py mirroring the zoo one; happy to add it.

@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: 1e3945fd53

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +763 to +765
if stalled:
# A machine whose Xet transfers hang is one that should stop starting on Xet.
_record_xet_failure(stalled[0], logger)

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 Record non-stall Xet failures before retrying HTTP

When a Xet worker exits with a retryable CAS/network error before the stall watchdog fires, state == "error" and the HTTP retry below runs, but stalled remains empty so the health tracker never sees that failed Xet attempt. Since Auto's backend verdict is based on recorded outcomes, subsequent Auto downloads on the same machine keep choosing Xet and paying the same failed attempt before falling back; record a Xet failure for every Xet-to-HTTP retry, not only watchdog stalls.

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.

The recording is deliberately scoped to stalls. A fast CAS or 5xx error costs one quick HTTP retry, whereas a hang costs the full stall timeout, and counting transient blips would demote machines on failures HTTP would have hit too. That noise is what the two-strike threshold exists to absorb.

logger.exception("%s failed to kill stalled worker for %s", log_prefix, label)

try:
return start_watchdog(

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 Pass the Xet stall timeout into the hub watchdog

This new hub watchdog call relies on the shared start_watchdog defaults, so the hub path ignores the Studio-side DEFAULT_STALL_TIMEOUT = 30.0 added in this commit. In installs where the shared watchdog default is still 180s, a frozen Xet hub download sits with no progress for three minutes before the HTTP retry instead of using the intended 30s Xet fallback; pass the explicit stall timeout here so hub downloads get the new deadline.

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.

Passing an explicit value here would break the intended behaviour: the shared layer resolves None through UNSLOTH_XET_STALL_TIMEOUT before falling back to its per-transport default, so hardcoding 30s would silently disable that operator override. The 180s you describe comes from the older shared release, which the dependency floor bump addresses rather than this call site. Even at 180s the hub path now recovers, where before this PR it never did.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

Measured results

126 anonymous cells over six staging-CI runs (ubuntu-latest: 4 cores, 16 GB RAM, no HF token,
asserted absent by the job), all seven requested repos x {xet stock, xet capped, http}.

The memory problem is real and unbounded

transport / profile cells ok median Mbps max peak RSS median peak RSS
xet / stock 42 42 1928 15.38 GB 1.67 GB
xet / capped 42 41 1728 1.34 GB 0.71 GB
http 42 41 402 0.12 GB 0.11 GB

15.38 GB on a 16 GB runner, measured across the process tree. The variance matters more than the
peak. Same file, same profile, six runs (GB):

file stock capped
Qwen3.6-35B-A3B-UD-Q4_K_XL.gguf 5.26, 15.38, 7.58, 8.75, 7.97, 6.64 0.82, 0.80, 0.89, 0.99, 1.06, 0.94
gemma-4-26B-A4B-it-UD-Q4_K_XL.gguf 0.06, 13.67, 13.80, 9.96, 8.12, 12.73 1.24, 1.34, 0.61, 0.65, 1.10
model-00003-of-00016.safetensors 3.01, 2.32, 2.17, 1.97, 1.97, 3.35 0.96, 0.80, 0.71, 0.73, 0.60, 0.76

Stock swings by a factor of 250 on one file; capped stays inside a factor of 2 everywhere. Cost of
the cap: 10% throughput.

Anonymous users should keep Xet

Capped Xet is 4.3x faster than HTTP with no token (1728 vs 402 Mbps median). A separate local
comparison alternating token / anonymous cells back to back on the same files gives identical
medians (749 vs 749 Mbps), zero failures either side, zero entries in hf_xet's error log either
side. The token is irrelevant to the transport decision, so tokenless machines should not be pushed
to HTTP.

On a slow link Xet's advantage disappears

Throttled through a userspace CONNECT proxy (only the download process is slowed; the host link is
untouched, since tc is unavailable and a default-namespace qdisc would degrade the real
interface):

rate xet stock xet capped http
20 Mbit 19.98 Mbps 19.94 Mbps 19.90 Mbps
5 Mbit 4.59 Mbps 5.03 Mbps 4.99 Mbps

All three saturate the link. Xet only wins where the link is not the bottleneck, and peak RSS stays
under 0.8 GB at any profile because a buffer only fills if bytes arrive faster than they are
consumed. The RAM problem is a fast-link problem.

Detection, live

  • Zoo path: forced stall caught at 36.8 s, completed over HTTP.
  • Studio hub path, which had no stall detection at all before this change: a real download through
    the running server's API, killed at 30 s of zero progress, retried, .transport marker reads
    http, 46.3 s end to end.
  • One genuine unforced Xet failure captured in CI (cas-server.xethub.hf.co connect timeouts on
    gemma-4-26B-A4B-it), surfaced through scan_xet_log. Honest caveat: the HTTP cell for that same
    repo also timed out in the same run, so that was a runner network problem rather than a
    Xet-specific defect.

Two of the seven repos ship a single 17 GB / 22 GB file, larger than a runner's disk. Those CI cells
stop at a 4 GB budget and are flagged truncated in the JSONL; peak RSS and throughput are still
valid there since the buffers are allocated up front, and both repos are downloaded in full locally.

danielhanchen and others added 7 commits August 2, 2026 15:56
…stalled hub download

The model hub is how most people download, and it was the one download path with no stall detection
at all. finalize_worker_exit says so explicitly: it relies on the worker's exit code, and a Xet
transfer that hangs with no progress and no error never produces one. That is the frozen progress
bar users see. The inference and training paths already ran the unsloth_zoo watchdog; the hub now
runs it too, and a stalled worker is SIGKILLed so it lands as "error" -- the exact state the
existing XET-to-HTTP retry already keys on. Nothing about that retry path changes.

Downloads spawned by the hub now get RAM-derived HF_XET_* caps. Note this cannot be done with
setdefault alone: HF_XET_HIGH_PERFORMANCE is inherited from the parent environment, and xet-core
applies that preset AFTER reading the environment, so leaving it on discards every cap rather than
competing with it. It is cleared explicitly, with UNSLOTH_XET_ALLOW_HIGH_PERFORMANCE to opt back in.

The transport picker gains a third option, Auto, which becomes the default. Auto resolves
server-side because only the backend can see this machine's RAM, its hf_xet build, and whether Xet
has been failing here. It resolves through the capabilities endpoint rather than independently on
both sides: the resolved transport is compared against the .transport marker of any existing
partial, so client and server must agree or a resume would be misjudged. "auto" is deliberately not
a member of VALID_TRANSPORTS -- the on-disk marker must keep naming the writer that produced a
partial. An explicit Xet or HTTP choice is still honoured, and a previously stored preference is
preserved. The tooltip reports what Auto currently resolves to and why.

poll-loop carried the stored preference as a boolean (`getTransportMode() === XET`), which would
have read "auto" as "not xet" and sent every download over HTTP; it now stays unresolved until
effectiveTransportMode().
unsloth_zoo.__init__ runs torch accelerator detection and raises NotImplementedError on a CPU-only
host. _load_optional gave up there, which silently disabled the RAM caps on exactly the small
machines they exist to protect. _load_shared already had this retry; _load_optional now does too,
with the flag scoped so it cannot leak into unrelated later imports.

Caught by the staging CI download job on an ubuntu-latest runner.
…g module

CI on a runner with the released unsloth_zoo installed caught two things review did not.

The high-performance flag was cleared through xet_env_overrides(), which returns nothing when the
installed zoo predates hf_xet_tuning -- and that same older zoo is the one setting
HF_XET_HIGH_PERFORMANCE=1 at import. So on exactly the installs that cannot be fixed by upgrading
Studio alone, the worker inherited a 64GB buffer ceiling. Clearing it is now unconditional.

The two cap assertions now skip when the tuning module is genuinely absent, since there are no caps
to assert, and a new test pins the clear-without-tuning case.

Also names TRANSPORT_AUTO in the cache layer's error path: 'auto' is a request preference that only
the server can resolve, so reaching prepare_cache_for_transport with it is a specific bug worth a
specific message rather than a generic 'invalid transport'.
The verdict is deliberately sticky across sessions: two consecutive Xet failures pin a machine to
HTTP for 24h. That also means any machine which has genuinely had a Xet stall starts the ladder on
HTTP inside tests that expect it to start on Xet, and
test_shim_injects_studio_prepare_on_http_retry then sees the fallback happen without the Xet
attempt it asserts. Reproduced locally against a real demoted verdict; a clean CI runner has no
state file so it hides there.

Mirrors the fixture already in the unsloth_zoo suite. Verified no collateral damage from the
HF_HOME redirect: 1412 passed across the hub / cache / download / transport tests.
@danielhanchen
danielhanchen force-pushed the feat/studio-xet-auto-fallback branch from 1100754 to 9fa856e Compare August 2, 2026 15:57
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

The red Chat UI Tests is a main regression, not this PR

Unsloth UI CI -> ui-modelcfg fails here with:

[ui-modelcfg] FAIL: could not open run-settings for a model matching 'gemma-3-270m'
[ui-modelcfg] FAIL: could not reopen run-settings after reload
[ui-modelcfg] FAIL: Reset button not found in run-settings

It reproduces on main with the same three assertions, and it bisects to the model-picker work rather
than to anything here:

main commit result
aa4ea75 (this PR's original base) success
3044401 (current main, the rebase target) failure, identical assertions

Between those sit 63307b1 (#7736, default Show all quantizations off, collapse single-quant rows),
6c60158 (#7745, row actions on collapsed quant rows), 13fdd06 (#7747, remember the Run Settings
advanced toggle) and 3044401 (#7755). Those change exactly the surface the check drives -- opening
run-settings from a quant row, and the Reset button inside it -- and the Playwright script was not
updated with them.

Matching behaviour on this branch: based on aa4ea75 it failed once and passed on re-run (a real
flake); rebased onto 3044401 it fails consistently, 2 for 2. Mac Studio UI CI and Windows Unsloth
UI CI both pass on the same commit, so it is Linux-only, and the frontend diff here is confined to
features/hub/**, which nothing in Chat run-settings imports.

Leaving it alone rather than patching a model-picker regression inside a Xet transport PR.
Everything else is green: 39 checks including the full Python matrix, all three Core combos,
Repo tests (CPU), Source lint, CodeQL and every Windows/macOS/Linux job.

…watchdog, blocking probe

Carry the Auto verdict through capability normalization. The normalizer rebuilt the object from
http and xet alone, so auto_resolves_to and auto_reason were dropped on every response: Auto
resolved to Xet on every machine including ones the backend had just demoted to HTTP, and the
toggle always read "Xet". The whole server-side verdict was computed, serialized and thrown away
in the browser. The normalizer now lives in transport-capabilities.ts, because api.ts imports the
auth barrel and cannot be loaded by the test runner, which is exactly how this shipped green; three
tests now cover it.

Stop the lifecycle tests from running the watchdog inline. _ImmediateThread is installed on the
stdlib threading module, which the shared Zoo watchdog imports too, so the watchdog ran
synchronously and blocked in Event.wait() before finalize_worker_exit could set its stop flag.
hub/tests/test_download_lifecycle.py hung forever; it now finishes in 0.13s. CI never caught this
because studio-backend-ci runs tests/, not hub/tests/.

Scope the hub watchdog to its own worker. child_pid is only read under watch_new_partials_only, so
the measurement stayed repo-wide and two same-transport GGUF variants of one repo (which the
registry deliberately allows to run concurrently) reset each other's stall timer, leaving a hung
variant with no fallback.

Record a completed Xet download, not just a stall, so "two failures in a row" means in a row. A
stall today and another next week were counted as consecutive despite every download in between
succeeding, pinning Auto to HTTP for 24h.

Omit unset timeout kwargs in the shim rather than forwarding None. No production caller passes
them, and an older unsloth_zoo takes None literally: its watchdog hands interval to Event.wait(),
which then blocks forever, so a hung download would never fall back.

Resolve the transport off the event-loop thread. Both async handlers called the resolver
synchronously one line after correctly awaiting to_thread for the repo-id lookup, and resolving
"auto" can run the Xet reachability probe, whose 3s budget does not cover DNS.

Give the capabilities cache a 30s TTL. It was held for the page session, so after a mid-session
demotion Auto kept sending an explicit "xet" (which deliberately bypasses health) until reload.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits August 3, 2026 02:29
…t override

Let Auto actually use the reachability probe. The client resolves Auto from the capabilities
endpoint, which deliberately answers without probing because the UI polls it on render, and then
sends a concrete transport. The probe this PR added therefore never ran for a real user: a host
whose CAS is unreachable but which has not recorded a failure yet discovered that by stalling for
30s rather than at preflight. The endpoint now takes an opt-in probe flag, and only
effectiveTransportMode sets it, since that runs at download start rather than on render. Resolution
stays client-side so the chosen transport still matches the .transport marker of any partial, and
the cache records whether its entry was probed so a cheap answer cannot satisfy a probing caller.

Serialize the GPU-init override. The retry that imports an optional helper with
UNSLOTH_ZOO_DISABLE_GPU_INIT=1 saves, sets and restores process-wide state, and on the currently
declared zoo floor those modules are absent, so it runs on every download. Two concurrent requests
could interleave save/set/restore and leave the variable set for the life of the process, after
which every worker inherits it and skips Zoo's GPU init. A lock around the sequence is enough; I
deliberately did not memoize the result, since that would stop a newly installed zoo being picked
up and would change what the existing loader tests observe.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits August 3, 2026 06:47
…e on HTTP starts

The connect_timeout I added last round is not accepted by the supported floor. unsloth_zoo 2026.8.1
declares start_watchdog keyword-only with no **kwargs and no connect_timeout, so the call raised
TypeError, the surrounding except Exception swallowed it, and _start_stall_watchdog returned None.
On every supported install that meant no watchdog thread at all: a hung Xet worker was never killed
and the HTTP retry, which is triggered by that kill landing as an error, never fired. The feature
was entirely off, not degraded. Verified by calling the real 2026.8.1 wheel: TypeError before, a
live Event after.

Fixed in the shim rather than at the call site, because this is the third version-skew bug in this
PR and the first two were each fixed one symptom at a time. start_watchdog now drops any kwarg the
installed callee does not accept, passing everything through when it takes **kwargs or cannot be
introspected, so a newer zoo still gets the newer knobs and the next new kwarg is a no-op instead of
a repeat of this. Dropping the pre-byte budget on 2026.8.1 is safe: that release resets its timer
whenever the child owns no .incomplete, which is exactly the connect phase. An audit of the whole
call site found connect_timeout to be the only unsupported kwarg today, and heartbeat_interval the
only other one the unreleased zoo adds.

Separately, only sample the Xet byte baseline for Xet starts. It is consumed solely by the Xet
success-recording, and sampling it lazy-loads unsloth_zoo, and so torch and transformers, on the
request path. Correction to the report on this one: the commit it cites moved that call rather than
adding it, since register_worker already sampled unconditionally on the same synchronous path.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 3, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: c068acdd15

ℹ️ About Codex in GitHub

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

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

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

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

danielhanchen and others added 3 commits August 3, 2026 07:46
The allow-list I added last round keyed on the "no progress" wording, which only
covers the branch that fires while an .incomplete is growing. The hub worker runs
snapshot_download(max_workers=1), so between two files it owns no partial at all and
a hang there trips "did not resume" instead. That is the shape this worker hangs in
most often, and the allow-list was silently dropping it, leaving Auto's health record
blind to the most likely real failure. Bytes have already flowed by the time that
verdict fires, so it is real evidence and belongs in the record.

Only the pre-byte trip stays excluded: "did not start" means not one byte ever
arrived, which a cold cache or a slow token handshake produces on a perfectly healthy
machine.

Also require state == "error". The watchdog appends its verdict from its own thread,
so a worker that completed or was cancelled in the same instant would otherwise be
charged a failure it did not earn.
…ildren

The Xet shim sets UNSLOTH_ZOO_DISABLE_GPU_INIT=1 process-wide while it retries an
optional unsloth_zoo import on a GPU-less host, then restores it. A worker spawned by
another thread inside that window inherits it for its entire life, and unsloth_zoo
answers that flag by installing stub triton and bitsandbytes modules, so the child
would silently train against no-ops with nothing in the logs to say why.

utf8_child_env now drops the variable while a loader is holding it. The loader only
counts itself as the owner when it actually introduced the value, so an operator who
exported the flag deliberately still has it reach their children.

@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: dd043e8329

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

"""Copy *env* (or the current environment) with UTF-8 stdio forced."""
child = dict(os.environ if env is None else env)
child["PYTHONIOENCODING"] = "utf-8"
if env is None and child.get("UNSLOTH_ZOO_DISABLE_GPU_INIT") == "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.

P2 Badge Scrub the transient GPU-init override from explicit envs

When the Xet loader's temporary UNSLOTH_ZOO_DISABLE_GPU_INIT=1 window overlaps a subprocess spawn that supplies an env mapping, this guard is skipped because env is None is false. Several training/probe spawns build an explicit environment by first copying os.environ (for example via child_env_without_native_path_secret() before utf8_child_env(...)), so they can still inherit the loader's transient flag for their whole lifetime and run with unsloth_zoo's triton/bitsandbytes stubs. Since gpu_init_override_active() already distinguishes the loader-owned value from an operator-set value, apply the scrub to explicit envs too.

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.

You are right that child_env_without_native_path_secret copies os.environ, so the flag does survive into those dicts. I walked every caller that passes an explicit env and none of the children is harmed by it: the two transformers sidecar probes, the vision check, the Vulkan probe, the torch version probe, the uv and pip installs, and the llama.cpp and whisper.cpp installers. The only one that imports unsloth_zoo at all is the DiffusionGemma shim, and I checked it directly, neither shim.py nor visual_engine.py references triton, bitsandbytes or any of the GPU init constants.

The children that would genuinely run against the stubs are the multiprocessing spawn workers, and those take no env argument at all, so filtering a dict could never have reached them. That hole is closed in 6ceeab2 by holding the loader lock across Process.start() in child_environment_for_spawn, with 5f3e783 making the lock reentrant since that context manager nests. Leaving the explicit env path as is.

return (False, "hf_xet is not installed")
try:
from utils.hf_xet_fallback import xet_health
health = xet_health()

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 Probe Xet health when resolving backend Auto

For clients that use the new backend transport_mode: "auto" field directly, this call reads the health verdict without opting into a probe, even though the download-start path is the moment intended to pay that cost. On a host with hf_xet installed, no cached health verdict, and an unreachable CAS endpoint, Auto will still choose the optimistic Xet path and only fall back after the stall watchdog fires; pass probe=True here so backend-resolved Auto avoids the failed Xet attempt up front.

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.

This is already doing what you are asking for. xet_health in the companion zoo is declared def xet_health(*, force: bool = False, probe: bool = True), so the bare call in resolve_auto_use_xet does run the reachability probe; it is the capabilities endpoint that explicitly passes probe=False, because the UI polls that one on render. The split is deliberate and the docstring right above the call says so.

So on a host with hf_xet installed, no cached verdict and an unreachable CAS, backend Auto resolves to HTTP up front rather than paying a stalled Xet attempt. Both download callers already run the resolution through asyncio.to_thread, with the 3s probe budget, so it never sits on the event loop even when DNS is blackholed.

My last commit guarded utf8_child_env, which is the wrong door. Training and inference
workers are started with multiprocessing spawn (_CTX.Process in core/training/training.py
and core/inference/orchestrator.py), and a spawn child copies the parent's live
os.environ; there is no env dict to filter. The only four utf8_child_env callers that
pass no env are pip invocations, which never import unsloth_zoo, so the hazard the
commit described was left entirely open.

child_environment_for_spawn already holds a lock across Process.start(), so it now also
holds the shim's loader lock. A spawn cannot begin while a loader has
UNSLOTH_ZOO_DISABLE_GPU_INIT set for its own import, which is the property that keeps
stub triton and bitsandbytes out of a worker that would otherwise train against no ops
with nothing in the log to say why. The loaders never spawn, so there is no lock order
cycle, and the test asserts the shared lock structurally rather than trying to hit a
microsecond window by timing.

_load_optional now memoises its result, including the failure. On a zoo that predates
these modules the import can never start succeeding, and without memoisation every
xet_health, record_xet_outcome and xet_env_overrides call re-ran the whole GPU-init
retry, re-opening that process-wide window on every single download. That also makes
the new barrier uncontended: the window opens at most once per module per process.

The ownership counter is also claimed before the env write and released after the
restore, so the window in which the variable is set sits strictly inside the window in
which it can be seen to be ours.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

pre-commit-ci Bot and others added 2 commits August 3, 2026 09:11
child_environment_for_spawn nests, which is why its own _spawn_env_lock is an RLock.
Holding a plain Lock alongside it made the inner enter block forever, and the repo's
existing test_nested_child_environment_for_spawn hung instead of failing. An RLock still
excludes other threads, which is all the env save, set and restore sequence needs.

The new test bounds its own wait, so the next person to get this wrong sees a failure
rather than a suite that never finishes.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 3, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5f3e783cce

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

whenever the child owns no ``.incomplete``, which is exactly the connect phase.
"""
impl = _shared.start_watchdog if _load_shared() else _degraded_start_watchdog
return impl(**_supported_kwargs(impl, kwargs))

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 Preserve a pre-byte deadline on the supported Zoo floor

When Studio runs with the supported unsloth_zoo==2026.8.1 floor and Xet hangs before creating an .incomplete file, this adapter drops the unsupported connect_timeout argument and delegates to an implementation that resets its timer whenever no partial exists. Consequently on_stall is never called, the worker is never killed, and the advertised Xet-to-HTTP recovery leaves the Hub download frozen indefinitely. Keep a local pre-byte deadline for older Zoo versions or raise the dependency floor instead of filtering this timeout away.

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.

I confirmed the mechanics you describe: the released 2026.8.1 has no connect_timeout and no **kwargs, and its beat loop resets last_change whenever the child owns no partial, so the filter does drop the pre-byte budget on that floor.

The chain breaks at the first link though. huggingface_hub opens the .incomplete before it calls xet_get, not after: file_download.py:1713 enters with incomplete_path.open("ab") and xet_get is invoked at :1727 inside that block. The floor counts a partial by presence rather than size, so a wedged hf_xet sits behind an open zero-byte partial and the 180s data clock still fires. I drove the released wheel directly to check rather than reasoning about it: wedged inside xet_get trips at the stall timeout, wedged before the open does not.

So what is actually uncovered on the floor is the metadata phase, where snapshot_download calls repo_info with no timeout. That predates this shim, and neither of your remedies reaches it. Passing the kwarg through would raise TypeError into the caller's except and disable the watchdog entirely, which loses the post-byte detection that does work; and the floor cannot be raised because 2026.8.1 is the newest release on PyPI, with the connect clock still on the unmerged zoo branch. It lights up on its own once that lands.

I did take the docstring point: it called this safe on the strength of the same fact you read as a freeze, so I have replaced it in 47c27b0 with what it actually costs.

The docstring called it safe because the released watchdog resets whenever the child
owns no partial. That is the same fact a reviewer read as a freeze, so the wording was
doing no work. huggingface_hub opens the .incomplete before it calls xet_get, and the
floor counts a partial by presence rather than size, so a hf_xet hang still trips the
180s data clock there. Verified against the released wheel: wedged inside xet_get trips,
wedged before the open does not. The uncovered window is the metadata phase, which
predates this shim.

@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: 47c27b065d

ℹ️ 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 on lines +970 to +979
_baseline = _job_bytes_on_disk(
repo_type,
repo_id,
getattr(_metadata, "hub_cache", None) if _metadata is not None else None,
(
getattr(_metadata, "blob_hashes", frozenset())
if getattr(_metadata, "variant", None)
else None
),
)

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 Move Xet baseline sampling off the event loop

On a cold backend, a direct API request using explicit transport_mode="xet" or the legacy use_xet=True path does not call xet_health, yet the async request handler invokes this baseline synchronously. _job_bytes_on_disk() resolves the lazy get_hf_download_state export, which can import unsloth_zoo, Transformers, and Torch, blocking every Studio request during that initialization. Fresh evidence beyond the earlier thread is this newly added baseline call, which explicitly performs the lazy load before spawn(); compute it through asyncio.to_thread before entering launch_worker, or otherwise keep the heavy load off the event loop.

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.

The premise does not hold, and it is the load-bearing step. Explicit transport_mode="xet" and the legacy use_xet=True both go through resolve_effective_use_xet, which calls download_transport_unavailable_reason, which calls get_download_transport_capabilities, which calls xet_health. That happens inside the asyncio.to_thread wrapper the download services already use, before launch_worker is reached, and the baseline only runs in the Xet branch, which is exactly the branch where it has already happened.

Measured in a cold interpreter rather than argued: resolve_requested_use_xet("xet", False) takes 4.96s and leaves torch, transformers and unsloth_zoo in sys.modules, all in the thread. The baseline that follows on the loop is then 0.27s against a populated cache, and that is a filesystem scan, not the import you describe. There is also a boot-time warmup that calls _load_shared on a background thread during lifespan, so on a normally started backend it is usually paid before any request arrives.

The residual 0.27s scan is the same class of synchronous filesystem work the surrounding registry calls already do inline on that handler. Hoisting the whole launch_worker into a thread would remove all of it, which I agree is tidier, but it moves when the registry claim and cancel-marker writes happen relative to other loop work, and I would rather not change that late in this PR for a tenth of a second.

Comment on lines +847 to +850
if watchdog_stop is not None:
# Stop measuring the moment the worker is reaped: post-download work (symlinking,
# verification) makes no byte-level progress and must not read as a stall.
watchdog_stop.set()

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 Stop watching before post-download recovery

When the initial metadata request fails but the Xet transfer itself succeeds, the worker remains alive after its last blob while _recover_manifest_after_download() retries metadata; those retries can take about 41 seconds, exceeding the 30-second Xet no-progress deadline. Because this stop event is set only after finalize_worker_exit() has waited for the entire worker to exit, the watchdog can kill a successfully downloaded worker during that recovery phase, record a false Xet health failure, and restart it over HTTP. The watchdog needs a completion signal at the end of byte transfer or must otherwise exclude worker-side recovery and verification from stall timing.

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.

The structural read is right and worth stating plainly: the stop event does sit after finalize_worker_exit, so the watchdog is armed across the whole post-byte phase. The deadline in that window is not 30s though.

After the last blob is renamed the child holds no .incomplete open, so with watch_new_partials_only the measured size drops to zero, which resets the clock at the rename and routes the phase to the not-has_incomplete-and-seen_bytes_ever branch. That branch is armed with connect_timeout = 600.0 from _start_stall_watchdog, not the 30s stall timeout, and the 30s one needs an open partial the child is holding.

Against that, your 41s is the right worst case and I confirmed the constants: _METADATA_REQUEST_TIMEOUT 10.0 plus _METADATA_RETRY_DELAY 1.0 plus _METADATA_RETRY_TIMEOUT 30.0. Everything after it is disk only, and _verify_completed_download stats each manifest file against its declared size rather than hashing, so it does not grow with model size. 41s against 600s is not reachable.

On the 2026.8.1 floor there is nothing to trip either: the kwarg is filtered out and that release resets its timer whenever no partial exists, which is exactly this phase.

Cut the prose around the measured facts without dropping any of them: the
2026.8.1 watchdog kwarg floor, the .incomplete-before-xet_get ordering, the
GPU-init override window and its spawn barrier, and the "did not start" vs
"did not resume" health-recording split all still read the same. Comments and
docstrings only.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 3, 2026
@danielhanchen
danielhanchen merged commit f17e04f into main Aug 3, 2026
54 of 55 checks passed
@danielhanchen
danielhanchen deleted the feat/studio-xet-auto-fallback branch August 3, 2026 13:20
danielhanchen added a commit that referenced this pull request Oct 15, 2026
…se the first zoo import with the media import window (#13738)

### Why

Right after launch, picking a quant to download in the chat model picker
showed nothing for several seconds, up to ~10 s on a slow torch warm,
until the download panel and the Xet toast suddenly appeared. The app
stayed responsive; there was just no sign the click had landed.

`requestStart` runs the whole preflight with no UI: the install
transport setting (`GET /api/settings/download-transport`, forced when
the browser has no saved choice), the Auto probe (`GET
/api/studio/download-transport-capabilities?probe=1`), the sibling and
partial checks, then the start itself. The first two compute the
transport row with the RAM gate and the probe on, so
`hub/utils/download_registry.py` asks `xet_health`, and that imports the
whole `unsloth_zoo` package on the request thread: about 5,400 modules,
~3 s idle and +312 MB RSS. Right after launch that import competes with
the startup torch warm (7-13 s on the machine this was measured on),
neither request has a client timeout, and the only feedback was the
panel plus toast, which appear once a job exists. Context: #7742 put the
zoo-backed health verdict on the start path, #8564 deliberately dropped
the startup zoo warm (312 MB, "optional GPU consumers stay cold"), #9272
added the serial settings request, and #12472 makes the import wait on
the warm's dynamo import. A startup prewarm was not an option for the
same 312 MB reason.

The same import also raced the post-warm worker from a second entry
point: the request thread imports triton then `torchao.kernel`, the
post-warm worker imports torchao then diffusers, and CPython's import
deadlock detector handed one side a partially initialised
`torchao.kernel`. That left `unsloth_zoo.hf_xet_health unavailable (...
partially initialized module 'torchao.kernel')` memoised as "no verdict"
for the rest of the process, plus `torchao is unusable: KeyError:
'torchao'`, in 2 of 5 cold clicks.

### What

**Frontend: feedback within a frame of the click.**

- `hub/download-manager/pending-starts.ts` is a small display store.
`runWithPendingStartGuard` publishes the start after its
busy/already-started early returns and retires it in `finally`; retire
removes only the entry that guard published, so a session reset
mid-preflight plus a re-click cannot drop the second start's feedback.
The store resets with the rest of the download manager state.
- The downloads panel shows a pending start at once: a row whose key is
already listed (a retry inside a finished row's linger) reads
"Starting…" in place with its outcome icon hidden and Dismiss disabled
until the job exists; a start with no row gets its own row. Both
decisions come from one visible set, which hides a start when its job is
already active or when a queued plan already shows the same transfer.
That match is by job key, so a different quant or a companion plan of
the same repo does not hide the feedback, and the queued-entry producers
now carry the variant the key needs. The header count includes pending
starts and the panel no longer hides itself while one exists.
- Measured in the real UI on a cold backend: "Starting…" 0.2 s after the
click, instead of nothing until the preflight finished (4.8 s with the
backend pinned to two CPUs, ~10 s on a slower warm).

**Backend: one import at a time for the torch compile stack.**

- `torch_warmup.hold_media_import_window(reason)` holds the existing
media import window around a foreground import: non-blocking acquire,
then a wait bounded by the dynamo gate timeout with the same
info/warning logs as the load-side claim; an expired wait still imports;
pass-through for the thread that owns the window and under
`UNSLOTH_STUDIO_DISABLE_DYNAMO_IMPORT_GATE=1`.
- `utils/hf_xet_fallback.py` takes that window around its `unsloth_zoo`
imports in both loaders, after the dynamo gate and outside `_load_lock`
(nested, so the window-outer / lock-inner order is explicit):
`child_environment_for_spawn` holds `_load_lock` around every worker
spawn, so a spawn never waits behind a background import, and the
post-warm worker's torchao and diffusers imports now wait behind the zoo
import instead of interleaving with it. Each load opens one window, so a
failed first attempt keeps the window for its retry rather than waiting
twice.
- `_dynamo_gate_timeout()` clamps to `threading.TIMEOUT_MAX`: an
unbounded setting (`inf`) made `Lock.acquire` raise out of the loaders
and silently skipped the existing dynamo gate.
- Measured: 0 of 4 cold clicks hit the partially initialised
`torchao.kernel` afterwards; a request that lands during the post-warm
imports waits for them (1-9 s here) rather than poisoning them.

### Tests

- `tests/download-pending-start.test.ts`: the entry is visible from the
first held preflight request until the backend accepts; a second click
returns busy without a second entry; an unreachable backend and a
rejected start (`accepted: false`, error row) both leave no entry; a
restart inside a cancelled row's linger keeps that row and marks it
starting; the visible set yields to an active job and to a queued plan
for the same transfer but not to another plan of the same repo; retire
removes only the published entry; the panel derives both row kinds from
the same visible set. `download-panel-not-permanent.test.ts` recognises
the new list local in the panel's null guard.
- `studio/backend/tests/test_xet_import_window.py` (15 tests): both
loaders import inside the window as its owner; a load waits for a
background media import in flight and still runs when the wait expires;
a failed first attempt keeps the window for its retry; an expired wait
logs and releases nothing; a failure inside the window releases it; the
kill switch and the owner thread pass through; an unbounded timeout
setting waits instead of raising; the loaders run unguarded when
`torch_warmup` is unavailable; AST pins that every zoo import in the
shim sits inside a window, that each loader opens exactly one, and that
the gate runs before the window and the window wraps `_load_lock`.
- On this tree: frontend suite 12,116 passing, typecheck and ESLint
unchanged against `main`; backend shim/warm/hub tests pass in a full
venv, with only the pre-existing environment failures elsewhere.

### Notes

- Nothing platform-specific: `threading.Lock`, `get_ident`,
`perf_counter` and a zustand store, so Windows, macOS, Linux, browsers
and the desktop WebView behave the same.
- Left as is: there is no Cancel during a preflight (before there was no
row at all); a cancelled row's 6 s linger can expire during a cold
preflight, in which case its "Starting…" row moves to the bottom where
the job row lands anyway; the background side of the window keeps its
unbounded wait, so a wedged zoo import would delay the post-warm tail
rather than deadlock it.
- Follow-up: the companion unsloth-zoo PR "Import the Hub download
helpers without unsloth_zoo's package init" moves these helpers to an
init-free `unsloth_zoo_downloads` package (20 ms, 119 modules). Once a
zoo with it ships, the shim can import that first and fall back to the
old names, which removes the init from the first download entirely; the
pending-start row then covers a preflight of milliseconds.


<!-- studio-ui-evidence:start -->
### Before / after

Two isolated Studio installs, BEFORE = merge base `daab3bcd8`, AFTER =
this PR. The download preflight is held for 10 s so its window is the
same on both sides; the shot is taken 1.5 s after clicking Download on
`unsloth/SmolLM2-135M-Instruct-GGUF` (F16), and the start request is
aborted so nothing is fetched.

Downloads panel corner: BEFORE shows nothing while the preflight runs;
AFTER shows the panel with a "Starting…" row for the repo.

![Downloads panel 1.5 s after the click, before vs
after](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/13738/pr13738_pair_01-8c7068373089.png)

Full Model hub page at the same moment (the quant card's own "Starting…"
button is unchanged on both sides; only the Downloads panel differs):

![Model hub page 1.5 s after the click, before vs
after](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/13738/pr13738_pair_00-89a9cb9249a0.png)
<!-- studio-ui-evidence:end -->

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 29, 2026
…sume (unslothai#15781)

## What changes

The Studio Hub download worker
(`studio/backend/hub/workers/hf_download.py`) passed `max_workers=1` to
every `snapshot_download` call, so a model, GGUF variant, scoped
snapshot or dataset was fetched one file at a time. Over HTTP each file
paid its own HEAD and request latency in series and was limited to what
one connection delivers.

Over HTTP the worker now fetches up to four files at once, but only
where an interrupted partial resumes: on huggingface_hub up to 1.17
(whose stock writer appends to a shared `.incomplete`), or on 1.18+ when
the worker restored the resumable writer at import
(`restore_resumable_partials()`, which needs a local filesystem whose
lock provably excludes a second writer). Over Xet, on 1.18+ where the
resumable writer was not restored (for example Windows or a network
mount), or with an unreadable huggingface_hub version, it stays at one
file at a time exactly as before. In practice: Linux and macOS on a
local filesystem overlap files with any supported huggingface_hub;
Windows overlaps only on the Python 3.9 pin (huggingface_hub 0.36.2) and
stays serial on 1.18+.

Why this is safe for resume: the original reason for `max_workers=1` was
that resume needs a single sequential writer per partial. That still
holds per file: huggingface_hub takes a per-blob lock and each file is
one sequential writer, so every partial resumes from its own length. The
gate means every partial on disk resumes after a kill. What a kill can
lose is the chunk each stream is holding in memory before it is written
(`DOWNLOAD_CHUNK_SIZE`, 10 MiB), so up to about 40 MiB with four streams
instead of about 10 MiB with one. Xet is unchanged because hf_xet
already fans out inside a file, its buffers scale per file (the memory
caps from unslothai#7742), and a killed Xet file restarts from zero.

Nothing else changes: the transport environment, token handling, the
purge and marker logic, verification, cancellation (SIGKILL of the
worker process), the error raised (the first failing file in listing
order) and the byte-based progress that the download manager reads from
the cache.

Side effects of overlapping files, all bounded:

- Peak memory of the worker rises by about 70 MB: each stream reads in
10 MiB chunks (`DOWNLOAD_CHUNK_SIZE`), so the extra memory scales with
the number of streams, not with shard size.
- The download manager's progress is the sum of finalized blob bytes
plus the largest reading per partial, so up to four partials add up the
same way one does; a finalized blob still supersedes its own partial, so
nothing is counted twice. The stall watchdog sums the partials the
worker holds open, so any stream making progress keeps it armed.
- A cancel or a stall kill is still SIGKILL of the worker. It can leave
up to four partials instead of one; every one of them resumes on the
next attempt, which is what the gate guarantees.
- When one file fails, the files already in flight finish before the
worker exits with the error, so an error can surface later than it does
today (those files are kept).
- The number of Hub requests is unchanged. The Hub counts requests per
5-minute window, so a repo with very many small files spends the same
budget over a shorter time.

## Results

These were measured against a local fake Hub serving `model_info`, the
tree listing and `resolve` HEAD/GET with Range. Each connection had a
bandwidth cap and every request had added latency. The real worker
script ran end to end as a subprocess. Base and head were interleaved,
with 3 runs per arm and a second base arm as the A/A check.

| Fixture | Link | base | base (A/A) | head |
|---|---|---|---|---|
| LLM: 4 x 48 MB shards, 8 MB tokenizer, 8 small files (hub 0.36.2) | 20
MB/s per conn, 50 ms | 12.90 s [12.80, 13.06] | 12.91 s [12.82, 13.05] |
3.97 s [3.95, 3.98] |
| Same (hub 1.33.0) | 20 MB/s per conn, 50 ms | 13.13 s [13.11, 13.22] |
13.12 s [13.01, 13.27] | 4.10 s [4.08, 4.20] |
| Diffusers layout: 19 files, 3 weights | 20 MB/s per conn, 50 ms | 8.71
s [8.60, 8.82] | 8.69 s [8.60, 8.83] | 4.57 s [4.55, 4.65] |
| 30 small files | 20 MB/s per conn, 80 ms | 6.86 s [6.81, 6.94] | 6.91
s [6.76, 7.07] | 2.30 s [2.27, 2.36] |
| LLM, link saturated by one stream | 40 MB/s per conn and 40 MB/s
total, 50 ms | 7.52 s [7.50, 7.93] | 7.92 s [7.49, 8.08] | 6.12 s [6.09,
6.23] |
| LLM, fast link | 400 MB/s per conn, 5 ms | 1.56 s [1.49, 1.74] | 1.51
s [1.49, 2.86] | 0.75 s [0.74, 1.20] |

The values are medians, with the [min, max] range in brackets. In every
run both arms made the same requests: 2 metadata GETs (plus 1 tree GET
on hub 1.x) and exactly one HEAD and one GET per file. They also sent
the same bytes. The snapshot directories had an identical sha256 digest
across all arms, and no `.incomplete` file was left behind. The peak
number of concurrent GETs was 1 on base and up to 4 on head.

A separate re-run on huggingface_hub 1.33.0 (LLM fixture, same link, 3
interleaved runs per arm) gave base 12.82 s [12.82, 13.05], base A/A
12.83 s [12.79, 12.86] and head 4.05 s [4.05, 4.09], with the same
request counts, bytes and digest in every run. Peak worker RSS in those
runs was 72 to 83 MB on base and 143 to 153 MB on head.

Resume after SIGKILL: the worker was killed partway through the LLM
fixture, then run again. On both hub 0.36.2 and 1.33.0, and on both
arms, the bytes left in partials plus the bytes the second run fetched
add up exactly to the shard total (201,326,592). Nothing was fetched
twice. The final snapshot digest was identical. For example, head with a
kill at 3.5 s left 4 partials holding 157,286,400 bytes, and the rerun
fetched the remaining 44,040,192.

Re-check on the current head (kill triggered once the fake Hub had sent
48 MiB, 4 x 32 MiB shards at about 8 MB/s per connection, real worker
subprocess):

| hub | arm | partials after kill | bytes in partials | finalized |
refetched on rerun | partial + finalized + refetched == total | rerun |
|---|---|---|---|---|---|---|---|
| 0.36.2 | base | 1 | 10,485,760 | 33,554,432 | 90,177,736 | yes | 12.33
s |
| 0.36.2 | head | 4 | 41,943,040 | 0 | 92,274,888 | yes | 3.77 s |
| 1.33.0 | base | 1 | 10,485,760 | 33,554,432 | 90,177,736 | yes | 12.19
s |
| 1.33.0 | head | 4 | 41,943,040 | 0 | 92,274,888 | yes | 3.92 s |

Final files were byte-identical and no `.incomplete` was left in every
run.

Offline (`HF_HUB_OFFLINE=1` on a cached repo): base and head give the
same output and exit 0.

## Tests

- New `studio/backend/tests/test_hf_download_file_concurrency.py`:
- checks that Xet stays serial, and that HTTP overlaps files only when
partials resume (hub up to 1.17, or 1.18+ with the restored writer
installed; stock 1.18+ and an unreadable version stay serial);
- checks through the AST that all four `snapshot_download` calls use the
transport budget;
- runs the real worker against an in-process fake Hub and checks
byte-identical files, one GET per file, no leftover partials and at
least 2 GETs in flight at once.
- On base 8 of 8 tests fail; on head 8 of 8 pass, under huggingface_hub
0.36.2 and 1.33.0.
- 18 neighbouring download test files (transport, scoped jobs, token
handling, size ceiling, Xet fallback, training downloads and others):
505 passed on both base and head, with the same failing IDs (none).
- A second sweep over 20 neighbouring files (resumable partials,
heartbeat, stall watchdog, snapshot reuse, model services, scoped jobs,
transport) on huggingface_hub 0.36.2 and 1.33.0: the same failing IDs on
base and head apart from the new file. The failures present on both arms
(`test_delete_variant_*` in `hub/tests/test_model_services.py` and
`test_optional_loader_retries_with_gpu_init_disabled`) do not touch the
worker.
- Re-run on the current head over 63 neighbouring download / Xet /
partial / heartbeat / stall / snapshot / transport test files: 2114
passed on huggingface_hub 0.36.2 and 2041 on 1.33.0, with identical
failing IDs on base and head under each.
- `py_compile` on Python 3.9 and 3.10 for every touched file.

## Not covered

- The real Hugging Face Hub and CDN were not used. Per-connection
throughput there depends on the network, so the gain on a fast uncapped
link is mostly from hiding request latency on the small files.
- Windows and macOS were not run. On Windows with huggingface_hub 1.18+
the gate keeps the serial path, because partials there are not
resumable.
- Xet is deliberately unchanged and was not measured.
- Peak memory was measured with 48 MB shards; that it stays flat with
multi-GB shards follows from the fixed read chunk size and was not
measured.
- A real 429 from the Hub was not exercised.
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