Skip to content

Studio: wait for the torch warm's dynamo import before a load's first download - #12472

Merged
danielhanchen merged 6 commits into
mainfrom
studio/dynamo-warm-race
Oct 2, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
studio/dynamo-warm-race

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Problem

On a slow CPU, an image or video load sent right after Studio starts can leave torch._dynamo half-initialised for the life of the process. Every later load then fails with partially initialized module 'torch._dynamo' has no attribute 'utils' until a restart. On a 4-vCPU Kaggle T4 VM, 7 of 8 loads failed this way. Waiting for the "torch warm finished" log line before loading cleared every failure.

Studio already imports torch._dynamo on one thread (ensure_dynamo_imported in utils/torch_warmup.py), and the load path calls it right before import diffusers. But a load downloads before that call:

  • _run_load fetches files (_prefetch_files, _fetch_denoiser_prequant) before load_pipeline, and video loads do the same.
  • Those download helpers go through utils/hf_xet_fallback._load_shared(), which imports unsloth_zoo.hf_xet_fallback.
  • unsloth_zoo enters the torch._dynamo / torch._inductor import cycle from the inductor side, while the background torch warm enters it from the dynamo side.
  • The two threads take the two package locks in opposite order. CPython's import deadlock check hands one of them the half-built module, and the leftovers in sys.modules keep every later import broken.

The failing Kaggle logs show exactly this order:

  1. unsloth_zoo.hf_xet_fallback unavailable (cannot import name 'IndentedBuffer' from partially initialized module 'torch._inductor.utils')
  2. torch._dynamo is not importable
  3. the has no attribute 'utils' load failure.

Change

  • utils/torch_warmup.py: new gate_torch_stack_import(reason, log).
    • It waits on the same lock the warm holds while importing torch._dynamo, with a timeout.
    • When it has to wait, it logs <reason>: waiting for another thread to finish importing torch._dynamo, then ready after waiting N s, or a warning on timeout.
    • Once dynamo is imported it returns immediately, so a normal start is not slowed.
    • ensure_dynamo_imported gains optional log, reason and timeout; existing callers behave as before.
  • utils/hf_xet_fallback.py: _load_shared and _load_optional call the gate before importing unsloth_zoo. This covers every download path on any thread.
  • diffusion.py and video.py: the gate runs at the top of _run_load, before any download.
  • Kill switch: UNSLOTH_STUDIO_DISABLE_DYNAMO_IMPORT_GATE=1 turns the new gates off. UNSLOTH_STUDIO_DYNAMO_IMPORT_GATE_TIMEOUT sets the wait limit (default 600 s).
  • The existing gate before import diffusers and the dynamo_partial_init_message toast are unchanged and stay as the fallback.

Results

Real race, no monkeypatching: the real background warm, the real unsloth_zoo and a real GPU, pinned to 4 CPUs with taskset -c 0-3. The download thread starts 0 to 0.05 s after the warm begins its dynamo import. 20 runs per arm:

arm download failed process left broken
main 16 / 20 7 / 20
this PR 0 / 20 0 / 20
this PR, kill switch on 8 / 20 5 / 20

The failures on main are _DeadlockError on torch._dynamo and the IndentedBuffer partially-initialised error, the same as on Kaggle.

Tests

  • New test_dynamo_import_race.py runs real torch in a fresh subprocess.
    • The warm thread is held inside import torch._dynamo until the download thread is blocked. A stand-in unsloth_zoo imports torch._inductor.utils, as the real one does.
    • On main, the race test fails 3 of 3 times with KeyError('torch._dynamo') and then partially initialized module 'torch._dynamo' has no attribute 'utils'. Here it passes.
    • The other three tests cover the kill switch, the timeout and its log lines, and that both load threads call the gate before their first download. All four fail on main and pass here.
  • The warm, dynamo, xet, startup, diffusion, video and hub download suites (169 files): 7070 passed here against 7066 on main. The same 40 failures and 1 error appear on both sides, all from datasets and fastmcp missing in that venv.

Not covered

  • Studio was not run over HTTP with a load fired right after start; the reproduction drives the warm thread and the download helper directly.
  • No re-run on the 4-vCPU Kaggle VM.
  • Request-thread imports of torchao or unsloth outside these load and download paths are not gated.

… unsloth_zoo import

A media load that arrives while the background torch warm is inside
import torch._dynamo reaches unsloth_zoo through its first download
(utils/hf_xet_fallback). unsloth_zoo enters the torch._dynamo /
torch._inductor import cycle at torch._inductor, the warm at
torch._dynamo, so the two threads take the package locks in opposite
order. CPython's import deadlock detector then hands one of them a
half-built module and the leftovers keep every later load failing with
"partially initialized module 'torch._dynamo'" until a restart.

The existing gate sat in front of import diffusers, after the download
had already lost the race. Gate the unsloth_zoo imports in
hf_xet_fallback and the top of the image and video load threads on the
same lock the warm holds, with a bounded, logged wait.
UNSLOTH_STUDIO_DISABLE_DYNAMO_IMPORT_GATE=1 turns the new gates off;
UNSLOTH_STUDIO_DYNAMO_IMPORT_GATE_TIMEOUT bounds the wait (600 s).
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 1, 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-10-02T08:44:50.179499Z e3bbb1d Manual request
🔒 Security Review ⚠️ Failed 2026-10-01T21:59:32.288260Z e130e58 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

Repo tests (CPU, rest) on head 5950fd93 fails on the test file this PR adds:

FAILED tests/test_source_read_encoding.py::test_checked_in_file_reads_name_an_encoding[4] - ... Pass encoding = "utf-8": ['studio/backend/tests/test_dynamo_import_race.py:202: read_text()']

studio/backend/tests/test_dynamo_import_race.py:202 calls read_text() on a checked-in file without an encoding. Adding encoding = "utf-8" there should clear it; the rest of the shard passed.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: e3bbb1da3d

ℹ️ 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
danielhanchen merged commit 923b8f4 into main Oct 2, 2026
@danielhanchen
danielhanchen deleted the studio/dynamo-warm-race branch October 2, 2026 10:26
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant