Skip to content

Studio: defer optional GPU startup work - #8564

Merged
oobabooga merged 5 commits into
unslothai:mainfrom
wasimysaid:studio/lazy-idle-gpu-startup
Aug 12, 2026
Merged

oobabooga merged 5 commits into
unslothai:mainfrom
wasimysaid:studio/lazy-idle-gpu-startup

Conversation

@wasimysaid

@wasimysaid wasimysaid commented Aug 12, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Studio currently initializes two optional GPU consumers even when the user has not loaded a model or started any work:

  • the Unsloth Zoo/Xet integration during the coordinated torch warm;
  • the RAG sentence-transformer (unsloth/bge-small-en-v1.5) from the post-warm worker.

This PR removes those eager edges and uses the existing lazy boundaries instead:

  • read-only Hub capability checks remain Zoo-free; Unsloth Zoo/Xet initializes on the first actual download decision/watchdog operation;
  • the RAG backend initializes on the first ingestion, retrieval, ranking, or linked-folder job that actually needs embeddings.

Hardware detection, model metadata warmup, MLX self-repair, linked-folder scheduling, and Whisper/STT behavior remain unchanged.

Cold-idle measurements

Measured 15 seconds after launching a release AppImage, with no model selected and no chat, training, inference, RAG, or audio operation. Host: NVIDIA RTX PRO 6000 Blackwell, driver 610.57.04. PSS is the useful RAM comparison because RSS double-counts shared pages.

Process / metric Before After Change
Python backend RSS 1,253 MiB 1,064 MiB -190 MiB
Python backend PSS 1,237 MiB 1,046 MiB -191 MiB
Python backend private RAM 1,232 MiB 1,040 MiB -192 MiB
Python backend VRAM 630 MiB 0 MiB -630 MiB (100%)
Whole app RSS 2,367 MiB 2,188 MiB -179 MiB
Whole app PSS 1,864 MiB 1,704 MiB -161 MiB
Whole app private RAM 1,761 MiB 1,594 MiB -166 MiB
Whole app VRAM 630 MiB 0 MiB -630 MiB (100%)

Process-level PSS values (Tauri/WebKit fluctuate naturally between launches):

Component Before PSS After PSS VRAM before VRAM after
Python backend 1,237 MiB 1,046 MiB 630 MiB 0 MiB
Tauri shell 137 MiB 143 MiB 0 MiB 0 MiB
WebKit renderer 461 MiB 484 MiB 0 MiB 0 MiB
WebKit network process 22 MiB 24 MiB 0 MiB 0 MiB

What caused the idle allocation

Controlled startup-stage traces separated the two costs:

Eager startup consumer Idle VRAM before Idle VRAM after New activation point
Unsloth Zoo/Xet import and CUDA context ~550 MiB 0 MiB First Hub download/watchdog operation
unsloth/bge-small-en-v1.5 RAG embedder ~80 MiB 0 MiB First operation requiring embeddings
Whisper/STT 0 MiB 0 MiB Unchanged; explicit audio use only
Total avoidable idle allocation 630 MiB 0 MiB On demand

UX impact

Cold launch/login is lighter and leaves the GPU unallocated. The trade-off is a one-time initialization delay on the first use of the affected feature:

  • first Hub download initializes Zoo/Xet;
  • first RAG ingestion/retrieval/ranking operation loads the embedding backend.

Subsequent operations are unchanged because these components remain cached in the process. Training, inference, model catalog behavior, hardware verdicts, MLX repair, linked-folder scheduling, and audio flows are not changed.

First-use verification

Separate offline/cached smoke traces confirmed the costs moved rather than functionality being dropped:

Trace stage PSS VRAM Result
Import Xet shim 12 MiB 0 MiB unsloth_zoo absent from sys.modules
First cached Hub wrapper call 892 MiB 550 MiB Zoo loaded and file resolved
Import RAG facade 28 MiB 0 MiB No model/backend constructed
First embedding encode 1,729 MiB 764 MiB (1, 384) vector produced with sentence-transformers

Absolute first-use values include each fresh process's framework/CUDA context; the important contract is zero allocation at import/startup and successful activation from the real operation.

Tests

  • 195 passed across:
    • test_startup_defers_torch.py
    • test_startup_defers_stack_dependent_work.py
    • test_warm_window_review_fixes.py
    • test_hf_xet_fallback.py
    • test_hub_download_transport_auto.py
    • test_rag_embeddings.py
  • Ruff passed for all touched Python files.
  • Frontend production build passed.
  • Tauri release .deb build passed.
  • Rebuilt AppImage launched and shut down cleanly; cold profile reported no Studio backend process in nvidia-smi.

@wasimysaid

Copy link
Copy Markdown
Collaborator Author

Addressed the review finding in b50ec6201:

  • Hub capability reads now use cached Xet health only and cannot import unsloth_zoo.
  • The actual download decision still activates Zoo/Xet on demand.
  • Added a regression for opening Hub without loading Zoo.
  • Corrected stale startup comments that still mentioned the removed Zoo warm stage.
  • Verification: 195 focused tests passed; Ruff and git diff --check passed; fresh-process smoke confirmed zoo_after_browse=False and Zoo activation at the first download decision.

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

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

@wasimysaid

Copy link
Copy Markdown
Collaborator Author

Addressed the Codex P1 finding in 2683e1ef1. The review was correct: the frontend uses probe=1 to resolve Auto and then submits a concrete xet/http transport. The endpoint now uses cached health for ordinary Hub browsing (probe=False) but loads and probes Xet health for the first-download Auto decision (probe=True). Added a regression covering cached browse -> loading probe -> HTTP resolution. Verification: 195 focused tests passed, Ruff passed, and a fresh-process smoke confirmed browsing stays Zoo-free while the download-start probe activates Zoo health.

@wasimysaid

Copy link
Copy Markdown
Collaborator Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 2683e1ef14

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

@oobabooga

Copy link
Copy Markdown
Member

Reviewed the design and affected first-use paths. Deferring Zoo/Xet avoids eager CUDA initialization while Studio is idle, while preserving health checks and fallback behavior when a download begins. RAG embeddings similarly load on first use, with linked-folder and MLX behavior left intact.

The coverage verifies cold startup, first-use activation, and shutdown behavior. The remaining Backend CI failures are also present on the exact base commit, while the relevant startup, platform, lint, and security checks pass. This is a worthwhile idle memory and VRAM improvement that moves work to first use rather than dropping it.

@oobabooga
oobabooga merged commit 3c590a5 into unslothai:main Aug 12, 2026
47 of 52 checks passed
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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants