Skip to content

Studio: bring the login screen up before the ML stack loads - #7607

Merged
danielhanchen merged 99 commits into
mainfrom
lazy-torch-startup
Aug 2, 2026
Merged

danielhanchen merged 99 commits into
mainfrom
lazy-torch-startup

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Jul 29, 2026 •

Copy link
Copy Markdown
Member

unsloth studio on a GPU box spends its first six seconds importing torch
before the socket exists. Nothing is listening, so the browser gets a connection
refused and the user watches a blank tab. None of that import is needed to draw
the login screen.

uvicorn binds the listening socket only after import main and the lifespan
have both returned, so every module either of them touches is time the UI does
not exist. scripts/profile_startup.py from #7553 put import main at 5.4-6.0s
on this host, and the profile blamed four eager edges, none of which any request
needs before it is asked for:

file edge
utils/models/model_config.py _build_detection_sets() at module scope, which reads the transformers registry
routes/models.py from core.inference import get_inference_backend
core/inference/orchestrator.py from utils.hf_xet_fallback import DownloadStallError
utils/datasets/raw_text.py from datasets import Dataset, for an annotation

Plus detect_hardware() in the lifespan, which imports torch to enumerate
devices.

What this does

All four edges become lazy, hardware detection moves off the lifespan, and a new
utils/torch_warmup.py re-imports the whole stack on a background thread as the
last statement of the lifespan. The socket binds the moment that returns, so the
login screen is up while torch, transformers, datasets and unsloth_zoo load
behind it. Nothing is dropped: every package import main used to leave in
sys.modules is still loaded by the time the warm finishes, in the same order,
through the same call sites.

Numbers

scripts/profile_startup.py --import-only, same interpreter, 3 runs per tree:

main this branch
import main 5.966 / 5.365 / 5.468s 1.043 / 1.040 / 1.046s

Real unsloth studio cold start, driven by Chromium against the actual UI. Two
installs built by the same install.sh --local run of the same machine, so both
venvs carry the identical torch 2.11.0+cu130; 3 runs each, medians:

main this branch
launch to socket bind 6.484s 1.477s
launch to a login form you can type in 8.190s 4.172s
torch .so mapped in the server at bind all 6 only libtorch_global_deps.so
POST /api/auth/login during the window 27ms 64-166ms
GET /api/health (waits for detection) 163ms 1779ms
/api/liveness polled every 25ms, non-200 0 0
/api/liveness p50 / p99 1ms / 27ms 2ms / 270ms
4xx or 5xx seen by the browser none none

Warm stages on a fresh install of this branch: hardware 1.4s, transformers 1.9s,
datasets 0.3s, unsloth_zoo 1.5s.

During one such cold start the server answered 43 requests before the warm
finished, all 200: GET / (205ms), POST /api/auth/login (66ms),
/api/models/list (17ms), /api/inference/status (62ms),
/api/system/gpu-visibility (100ms), /api/system/hardware (18ms),
/api/health (1610ms, the deliberate wait), and /api/liveness throughout at
0.6-11ms. Loading unsloth/Qwen3-0.6B (safetensors, so the torch worker, not
llama.cpp) and chatting with it works: 16s to load, reply in 3.48s.

Mechanism, and what is guarded

The warm runs off the event loop. It is a plain thread, started from the last
line of the lifespan so it never competes with the work that binds the socket.
The endpoints that read DEVICE / CHAT_ONLY now block on hardware detection
while that thread holds it, which on an async def handler stalls every other
request for the length of the torch import (measured at 1547ms on an
/api/liveness that touches nothing). Every first-paint and polled route on that
path goes through asyncio.to_thread, and an AST test asserts it stays that way
for each of the six.

Detection happens exactly once. detect_hardware() resets CHAT_ONLY at
entry, so two overlapping runs would let a reader observe "chat only" on a GPU
host. Detection is now under a re-entrant lock, and callers that only want the
result use ensure_hardware_detected(), which collapses the warm thread and any
early request into a single run. A caller arriving mid-detection waits instead of
starting a second one. Same guarantee for the lazily-built registry sets, under
a double-checked lock.

A failed warm is reported, not swallowed. Stages are isolated; a failure logs
a warning and leaves that stage cold rather than killing the process. A failed
detection degrades to CPU + chat-only with CHAT_ONLY_REASON = "detection_failed" rather than leaving DEVICE unset, because unset means every
later request retries the same broken import and /api/health, which waits on
it, answers 500.

Half-imported packages get purged, except when that would abort the process.
When package/__init__.py raises, CPython drops only the parent from
sys.modules and keeps every submodule it already executed, so the next import
re-runs __init__ with its from .x import y served from that cache and ends up
missing pieces (the bitsandbytes case in #7580). The warm makes that reachable,
since it imports on a thread and swallows the failure, so the retry belongs to
somebody's request. purge_partial_import() clears exactly that signature
(parent gone, submodules present) and leaves a concurrent, still-running import
alone.

It also refuses outright once any submodule is a loaded C extension. Evicting one
does not undo its module init, it only makes the next import run that init again,
and pybind11 answers a duplicate type registration with std::terminate:

import torch
saved = sys.modules.pop("torch")
purge_partial_import("torch")      # evicts all 708 torch.* entries
sys.modules["torch"] = saved
import torch._C
-> terminate called after throwing an instance of 'std::runtime_error'
     what():  generic_type: type "GradBucket" is already registered!

_has_torch() calls the purge on any failed import torch, so a torch that
raises after torch._C has loaded would have taken the backend down mid-request
instead of degrading to CPU. A zombie torch missing attributes is bad; SIGABRT is
worse. Found by running the full backend suite, which died at 90% on this branch
and not on main.

The warm reproduces the eager import rather than approximating it. The
unsloth_zoo stage goes through utils.hf_xet_fallback, not a bare import unsloth_zoo, because the edge it replaces was orchestrator.py's
DownloadStallError import and that shim retries under
UNSLOTH_ZOO_DISABLE_GPU_INIT=1 when unsloth_zoo's GPU init raises. A bare
import skips the retry: on a host whose bitsandbytes cannot find libcudart it
fails where startup used to succeed. Caught by diffing the two trees' end state,
not by a test.

UNSLOTH_STUDIO_DISABLE_TORCH_WARM=1 turns the warm off entirely; the deferred
imports then happen on first use.

Equivalence

A probe boots the real app through its lifespan on each tree under one
interpreter, waits for the warm, and dumps everything a deferred import could
have changed. Identical across both trees:

  • CUDA enumeration: 4 devices, same names, same compute capabilities, same UUIDs,
    same get_backend_visible_gpu_info() payload and ordinal-to-physical mapping
  • torch globals: default dtype and device, thread and interop-thread counts,
    grad mode, float32_matmul_precision, anomaly and deterministic flags, every
    torch.backends cudnn/matmul/mkldnn flag
  • utils.hardware: DEVICE, CHAT_ONLY, CHAT_ONLY_REASON, IS_ROCM,
    export_capability(), get_gpu_utilization() shape
  • the environment the process ends up with, PYTORCH_CUDA_ALLOC_CONF included
  • the lazily-built VLM and audio-only registry sets
  • the /api/health body
  • the set of top-level modules imported

The repo sets no torch.set_* globals, so there is nothing to re-order there;
CUDA_DEVICE_ORDER=PCI_BUS_ID is still set at the top of main.py, before any
import can create a CUDA context.

Honest limits

  • First paint is slower even though the login screen arrives sooner. Bind to
    a fillable login form goes 1.648s to 2.692s, because the SPA's first paint now
    competes with the torch import for the GIL. Launch to that same point is still
    8.190s to 4.172s.
  • Tail latency degrades during the warm window. /api/liveness p99 goes 27ms
    to 270ms and the worst sample 183ms to 1.86s, with Chromium loading the SPA at
    the same time; on an idle box the worst sample is 536ms. asyncio.to_thread
    moves the wait off the loop but cannot release the GIL that a C-extension
    import holds. p50 is unchanged. On main that window does not exist because the
    server does not either: the same seconds are spent with the port closed.
  • /api/health waits for detection, but only up to 1.0s. It prefers the
    measured chat_only over the pre-detection default, which would grey out Train
    and Export on a GPU host for the first second. The ceiling exists because the
    desktop launcher probes this endpoint with a 2s client timeout right after
    TAURI_PORT is emitted, and a timeout there is not a retry: it surfaces as
    "The desktop-owned Unsloth backend is still starting." When the budget expires
    the reply carries the pre-detection default plus a new additive
    hardware_detecting: true so a client can tell a provisional value from a
    measured one.
  • The 2s desktop probe deadline is not guaranteed, and cannot be from inside
    this process.
    With the budget in place, /api/health during the warm costs
    no more than /api/liveness -- three cold starts measured worst health samples
    of 1.832s / 1.717s / 2.161s against liveness worst samples of 1.817s / 1.740s /
    2.171s, i.e. the endpoint itself adds nothing and what is left is the
    process-wide stall in the row above. One of those three runs put a single
    sample past 2s. A backend-side budget cannot fix that; only moving the import
    out of the server process would. Holding the warm off for a 0.75s grace period
    was measured as a mitigation and did not remove the tail (worst health samples
    1.929s / 1.713s / 1.333s), so it is not taken here.
  • torch now finishes importing before transformers starts, where the eager
    order began transformers and reached torch through it. The end state measures
    identical, and unsloth_zoo still runs last so its transformers patches land the
    same way, but the intermediate ordering genuinely differs.
  • Measured on one Linux host, 4x B200, torch 2.11.0+cu130, warm page cache. No
    macOS or Windows numbers. The paths this touches trigger the Measure where Studio's startup time actually goes #7553 startup
    profile workflow, which runs on ubuntu, macos-14 and windows.
  • The warm is best-effort by design. On a host where a stage fails, the cost
    moves to the first request that needs it, exactly as it would have without the
    warm; warm_status() records which stage failed and why.

Tests

studio/backend/tests/test_startup_defers_torch.py, 25 tests, CPU-only, no
network, no GPU, no weights. A fresh interpreter asserts import main leaves
torch, transformers, unsloth_zoo, scipy, sklearn and sympy unimported, and that
each of the four modules imports clean on its own. The rest cover the PEP 562
shims still resolving the old names, single detection and single registry build
under an 8-thread barrier, the warm starting once and honouring its kill switch,
a failing stage being logged and not fatal, a failed detection degrading instead
of raising, a broken torch counting as no torch, purge_partial_import clearing
a pure-Python zombie while declining on a loaded extension and leaving a live
package alone, the unsloth_zoo stage going through the shim rather than a bare
import, the six routes staying off the event loop, and the stage list covering
every package import main used to pull.

Review follow-ups added four more files' worth of coverage:
test_inference_backend_singleton.py (the getter builds one orchestrator under
an 8-thread barrier, the warm path stays lock-free, AST guard on the with),
test_training_streaming_mlx_warm.py (the MLX streaming rejection survives the
warm window and does not become a blanket rejection),
test_health_answers_within_probe_budget.py (health answers inside the budget
with detection stubbed at 10s, still waits when detection is quick, and a
cross-language guard that parses preflight/backend.rs so the two timeouts
cannot drift), and one more case in test_startup_defers_torch.py (one torch
probe per detection pass).

Full backend suite, same host, same command, this branch against the merge-base
main: main 5 failed / 11418 passed, branch 5 failed / 11455 passed, failure sets
identical (all five pre-existing MCP and secure-tools failures). Collection is
append-only: 37 new ids, none removed.

shimmyshimmer and others added 9 commits July 29, 2026 05:33
Deferring torch moved hardware detection behind the port bind, so the routes
the SPA fetches on first paint now reach get_device() while the warm thread is
still importing torch. They were calling it inline from async def, which blocks
uvicorn's loop: a measured /api/liveness request, which touches nothing, took
1547ms right after the socket bound.

Move the five first-paint / polled call sites off the loop, make a broken torch
count as no torch, and cache a failed detection as CPU + chat-only so a raise
cannot make every request retry the import (or 500 /api/health).
A failed package import leaves its submodules in sys.modules with the parent
evicted, so the retry re-runs __init__ against cache hits and gets a package
that imports but is missing attributes. The warm makes that reachable: it
imports torch and unsloth_zoo on a thread and swallows the failure, so the
retry belongs to whichever request needs them next.
Two gaps found by diffing the modules, env vars and torch state a booted
backend ends up with against main, on this box:

The unsloth_zoo stage did a bare `import unsloth_zoo`. The edge it replaces
was orchestrator.py's `from utils.hf_xet_fallback import DownloadStallError`,
and that shim does more than import: when unsloth_zoo's GPU init raises it
retries under UNSLOTH_ZOO_DISABLE_GPU_INIT=1, which makes unsloth_zoo skip the
init and inject its triton/bitsandbytes stubs. A bare import skips the retry,
so on a host whose bitsandbytes cannot find libcudart the stage failed at
something startup used to complete. Reproduced here: bare import raises
"CUDA Setup failed despite GPU being available", the shim succeeds.

`datasets` was imported by utils/datasets/raw_text.py for an annotation and
is now deferred with nothing warming it, so its 0.3s moved onto the first
dataset operation instead of onto the warm thread. Add it as a stage, between
transformers and unsloth_zoo, which is where `import main` reached it.

With both fixed the two trees end with the same top-level module set, the same
env (PYTORCH_CUDA_ALLOC_CONF included), the same 4-device CUDA enumeration and
the same torch globals.
The full backend suite died with SIGABRT at 90%, deterministically, on this
branch and not on main. The cause is purge_partial_import().

Evicting a loaded C extension from sys.modules does not undo its module init,
it only makes the next import run that init a second time. pybind11 answers a
duplicate type registration with std::terminate. Reduced:

  import torch
  saved = sys.modules.pop("torch")
  purge_partial_import("torch")      # evicts all 708 torch.* entries
  sys.modules["torch"] = saved
  import torch._C
  -> terminate called after throwing an instance of 'std::runtime_error'
       what():  generic_type: type "GradBucket" is already registered!

_has_torch() calls the purge on any failed `import torch`, so a torch that
raises after torch._C has loaded would take the backend down mid-request
rather than degrade. Leaving the zombie gives a torch that is missing
attributes, which is the bad-but-alive outcome the purge was chosen over.

purge_partial_import() now declines, and says so in the log, as soon as any
submodule of the package is a loaded extension. Pure-Python zombies, which is
what the unsloth_zoo case actually is, still get cleared.

test_a_broken_torch_purges_its_own_zombie was the trigger: it left sys.modules
holding `torch` with every torch.* submodule evicted, so the next test that
touched torch aborted the pytest process. It now snapshots and restores the
whole torch slice and builds its zombie out of a pure-Python submodule.
test_desktop_auth patched CHAT_ONLY and CHAT_ONLY_REASON but left DEVICE unset,
which was consistent while detection ran in the lifespan and is not now:
/api/health waits on ensure_hardware_detected(), which re-detects while DEVICE
is None and so recomputes the value the test had just pinned. Pin DEVICE with
them; CPU plus "mlx_unavailable" is the state detection actually ends in on an
Apple Silicon host without a usable MLX stack. The assertions are unchanged.

test_the_unsloth_zoo_stage_goes_through_the_shim reached the shim as
`from utils import hf_xet_fallback`. test_hf_xet_fallback re-imports that module
and leaves the `utils` package attribute pointing at a different object than
sys.modules holds, so the patch landed on a module the code under test never
looks at. Resolve it through import_module, the way the code does.

While here: the failing-stage test asserted on capsys alone, which depends on
whether an earlier test rebound structlog to the stdlib handlers. Accept either
sink.

Full backend suite, this host: main 5 failed / 11418 passed, branch 5 failed /
11443 passed, failure sets identical. Collection is append-only: 25 new ids
(23 in the new file, 2 from test_text_io_encoding parametrising over sources),
none removed.

@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: 634f38c5a9

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

# degraded fallback is indistinguishable from success.
from utils.hf_xet_fallback import _load_shared

if not _load_shared():

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 Reset the shim's negative cache after a failed warm

If this proactive _load_shared() attempt fails transiently, utils.hf_xet_fallback sets _shared_available = False permanently. Purging unsloth_zoo from sys.modules does not reset that flag, so the later caller described by the comment never actually retries the import: every download helper immediately selects the degraded stub and the Xet stall watchdog remains disabled until restart. Either leave the shim unattempted after a failed warm or clear its negative cache safely so the first real download can retry.

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 behaviour is described accurately but it is neither new here nor safe to change, so I have not taken the suggested fix.

Not new: on main, core/inference/orchestrator.py has 'from utils.hf_xet_fallback import DownloadStallError' at module scope. That import runs the same _load_shared() during startup and pins _shared_available = False on the same failure. This PR only moves when that happens, from the eager import to the warm stage.

Not safe: DownloadStallError resolves through PEP 562 getattr on every import, so clearing the negative cache mid-process hands the real unsloth_zoo class to importers after the flip and the degraded stub to the ones before it. Checked directly -- raising the post-flip class is not caught by an 'except' bound to the pre-flip one, so a stall raised inside a download escapes the handler meant to catch it. A per-download retry buys a watchdog and loses the exception contract it exists to serve.

The other suggested alternative, leaving the shim unattempted after a failed warm, gives up the priming that is the whole point of the stage: the eager import primed it, and warming through the shim rather than a bare 'import unsloth_zoo' is what makes it succeed on hosts where unsloth_zoo's GPU init raises and the shim's UNSLOTH_ZOO_DISABLE_GPU_INIT=1 retry recovers.

The one real defect here was the comment, which read as though the purge re-arms the retry. Rewritten in 0bbe858 to say what the purge is for (the next direct importer of unsloth_zoo -- model loading, export, the MLX paths) and why the shim's cache is deliberately left alone.

get_inference_backend() was a bare check-then-set on a module global. That was
fine while the first caller was the lifespan, but first paint now reaches it
from three routes at once (routes/models.py:list_models,
routes/inference.py:get_status and get_api_monitor), each through
asyncio.to_thread, so the calls are genuinely parallel. The first construction
is slow -- InferenceOrchestrator.__init__ runs get_default_models(), which
calls hw.get_device() and so blocks on the torch warm -- and every thread that
enters that window observes None and builds its own. The last assignment wins;
orchestrator state is per-instance (its own subprocess handle, loading_models,
active_model_name), so a load started on a loser is invisible to every later
status or generation call.

Double-checked locking: the cheap read keeps the warm path lock-free, the
recheck under the lock decides who constructs. A plain Lock is safe here --
get_default_models() calls only get_device(), so the constructor cannot re-enter
the getter.

tests/test_inference_backend_singleton.py: 8 threads through a barrier into a
cold getter with the constructor stubbed to hold the window open. Against the
old getter: 8 orchestrators constructed, assert 8 == 1. With the lock: 1, and
every caller is handed the module global. Also covers that the warm path does
not serialize on the lock (a warm call from another thread returns while the
lock is held) and an AST guard that the construction stays inside the with.
/training/start rejects dataset_streaming on Apple Silicon by comparing
hardware.DEVICE against DeviceType.MLX. Detection used to run inline in the
lifespan, so that global was always set before the socket bound. It is filled in
by the warm thread now, so a start submitted in the first moment of serving
reads the pre-detection default (None), the comparison is False, and the
rejection is skipped. _build_training_worker_config() detects MLX only after
validation has passed, so the request runs on and hands a streaming dataset to a
loader that materializes the whole thing.

Force detection at the guard. Off the loop via asyncio.to_thread because
detection imports torch: inline it would stall every other request for that
import, which is the stall the deferred startup exists to remove. Same treatment
as /api/health and /api/system/gpu-visibility. Only the streaming branch pays
it, and only until the warm finishes -- after that ensure_hardware_detected()
returns the cached DEVICE.

tests/test_training_streaming_mlx_warm.py covers the behaviour: with DEVICE
still None on a pretend-Apple-Silicon host the start must be rejected 400 (it
returned 200 and called start_training before this change), the guard itself is
what moves DEVICE None -> MLX, and forcing detection must not become a blanket
rejection -- the same request on a CPU host still queues. The lexical half goes
in test_startup_defers_torch.py's _OFFLOAD_REQUIRED table so the call cannot
drift back onto the loop.
_detect_hardware_locked() called _has_torch() twice: once for the CUDA/ROCm
branch and again for the Intel-XPU fallback below it. On a host where the import
works that is a cheap sys.modules hit, but on the path that matters -- a wheel
whose CUDA libs do not resolve -- it is the whole failing import run twice.
purge_partial_import() cannot clean up after the first failure whenever a
compiled submodule is already loaded (evicting one makes the next import re-run
its init and pybind11 answers duplicate registration by aborting), so the
partial tree stays and the second probe re-runs torch/__init__ against those
cache hits: same seconds again, same declined purge, on a request that is
already degrading to CPU. It also need not fail the same way twice, so the two
branches could disagree about whether torch exists.

Hoist it: one probe, both branches read it.

Reproduced with a fake torch that fails after leaving a compiled submodule
behind: 2 import attempts and 2 "not purging torch" warnings before, 1 and 1
after. tests/test_startup_defers_torch.py::test_one_detection_pass_probes_torch_once
pins it (assert 2 == 1 against the old code).
/api/health awaited ensure_hardware_detected() with no ceiling. That is safe
only while detection has already run, which is what the old inline lifespan
detection guaranteed: TAURI_PORT is emitted after the lifespan returns, so by
the time the desktop launcher probed, health answered instantly. Detection is on
the warm thread now and TAURI_PORT comes first, so the probe lands on an
endpoint that is blocked on a cold `import torch`.

The launcher does not tolerate that. preflight/backend.rs builds its probe
client with a 2s timeout; on timeout probe_ownerless_spawned_backend() returns
Missing, choose_ownerless_spawned_preflight() falls through to
ExternalConflict/"desktop_owned_backend_starting", and use-tauri-backend.ts
renders it as setBackendError("The desktop-owned Unsloth backend is still
starting. Wait a moment, then try again.") -- terminal, not a retry.

Wait up to 1.5s and answer either way. When the budget expires, chat_only is
still published (the pre-detection default, i.e. the conservative direction --
Train/Export hidden, never wrongly offered) alongside a new hardware_detecting
flag so a client can tell a provisional value from a measured one. Every field
the launcher actually reads is correct either way; only the web UI reads
chat_only, and its first health call is the unauthenticated one behind the login
screen, which does not cache (fetched tracks device_type).

The wait polls DEVICE on the event loop rather than awaiting a to_thread:
asyncio.wait_for cannot cancel a to_thread, so a timed-out call would hold its
executor slot for the rest of the import and a polled endpoint would drain the
pool. start_background_detection() puts up at most one daemon thread so
detection still happens when the warm is disabled or already past its hardware
stage.

Measured with detection stubbed at 10s: 10.01s before, under the budget after.
tests/test_health_answers_within_probe_budget.py pins the deadline, that a
detection finishing inside the budget is still waited for (chat_only=False, no
flag), and -- as a cross-language guard -- that the budget stays under whatever
timeout backend.rs sets, with headroom.
The comment read as though purging unsloth_zoo re-arms the retry, which it does
not: utils.hf_xet_fallback pins _shared_available = False on a failed
_load_shared() and nothing here clears it. That is deliberate, so say so.

Clearing it would be a bug, not a fix. DownloadStallError resolves through PEP
562 __getattr__ on every import, so flipping the cache mid-process hands the
real unsloth_zoo class to importers after the flip and the degraded stub to the
ones before it. Verified: raising the post-flip class is not caught by an
`except` bound to the pre-flip one, so a stall raised inside a download escapes
the handler that was meant to catch it.

The stickiness is also not new -- on main, core/inference/orchestrator.py
imports DownloadStallError at module scope, which runs the same _load_shared()
at startup and pins the same flag on the same failure. This change only moves
when that happens.

The purge still earns its place: it is for the next *direct* importer of
unsloth_zoo (model loading, export, the MLX paths), which would otherwise re-run
__init__ against the submodules the failure left behind.

Comments only: docstring-blanked AST and comment-stripped token stream are both
identical to the parent commit.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Measured the 1.5s budget against a real cold start: the first /api/health, fired
the instant the socket bound, came back in 1.742s. Inside the 2s the desktop
launcher allows, but only just.

The overrun is the budget doing what it can rather than a bug. The wait polls on
the event loop, and a C-extension import holds the GIL for stretches in which
the loop does not run at all, so the reply lands late by however long the
current stretch is -- 0.24s here, and this host has a warm page cache. 1.0s buys
that margin back. The cost is one more provisional reply: the health poll shows
the very next sample, ~0.3s later, already carrying the measured chat_only.

Comment says so, and the headroom the cross-language guard demands goes from
0.4s to 0.9s.
The bounded wait publishes a provisional chat_only when detection has not
finished, flagged with hardware_detecting. The authenticated reply carried
device_type alongside it, and that is exactly the field the frontend uses to
decide the response is authoritative: config/env.ts sets
`fetched = data.device_type !== undefined`, and every later non-forced
fetchDeviceType() short-circuits on fetched. So one authenticated health request
inside the warm window pinned chat_only=true for the rest of the SPA session --
Train hidden, /studio redirected to /chat, on a GPU host, until a reload. The
sidebar's recovery poll does not rescue it: that only runs for
chat_only_reason === "mlx_unavailable", and a provisional reply has no reason.

Omit device_type and chat_only_reason while the reply is provisional. fetched
stays false, the next fetch re-reads, and the measured values land. Nothing the
launcher reads is affected -- version, studio_version and every capability bit
are still there, since none of them depend on detection.

tests/test_health_answers_within_probe_budget.py: with detection stubbed at 10s
the authed reply must not carry device_type or chat_only_reason (it did before
this change) and must still carry version; with detection at 0.3s both come back.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Two things still imported the ML stack ahead of the socket bind, so the login
screen waited on them.

start_mlx_autorepair_if_needed() ran inline on the lifespan thread, and its
mlx_stack_available() probe imports mlx.core, mlx_lm, mlx_lm.sample_utils and
mlx_vlm whenever the installed versions are acceptable. That is the healthy
Apple Silicon case, so a normal Mac got no benefit from deferring torch at all:
uvicorn binds only once the lifespan yields. The probe cannot be reduced to a
metadata check, because importing after the version gate is exactly what lets a
version-satisfying but broken install be detected and repaired.

_warm_rag_embedder started on a thread early enough to race the coordinated
warm. With RAG_EMBED_BACKEND=auto a GPU host selects sentence-transformers, so
embeddings.warm() pulls sentence-transformers, transformers and torch while the
lifespan is still working toward yield, contending for the GIL and the import
locks and bypassing the warm's hardware-first ordering and its purge-on-failure
handling.

Both now run on one post-warm thread that joins the coordinated warm first, so
the stack is imported once, in the intended order, and they run against a warm
module cache.

tests/test_startup_defers_stack_dependent_work.py: the lifespan must reference
neither entry point, the post-warm function must join before doing either piece
of work, and something must actually start the thread. All four fail if either
call is moved back.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

get_inference_backend() builds the orchestrator on first call, and that runs
get_default_models() -> hw.get_device(), so the first caller waits for the
background warm. Fourteen async handlers still called it inline, including
/v1/chat/completions, generate_stream, unload_model and the OpenAI model
routes, so any of them landing in the warm window held the event-loop thread
for the whole torch import and stalled login, liveness and the deadline-bound
desktop health probe. Only the three first-paint polling routes were covered.

The offload stays at the call site, handing the route module's own
get_inference_backend to a thread, matching what routes/inference.py:7072 and
routes/models.py:1750 already do. An async accessor in orchestrator.py was
tried first and reverted: it resolves that module's global, so callers and
tests that patch routes.inference.get_inference_backend were silently
bypassed, and test_orchestrator_unload_cancel hung on a load gate that never
opened. tests/test_async_singleton_access.py records that, so the accessor is
not reintroduced as an optimisation.

test_openai_tool_passthrough's cancel test replaces to_thread with a stub that
cancels every hop except one it names as running "before the row opens". The
singleton resolution is a second such hop, so it joins the same carve-out; the
assertions on the finalized monitor row are unchanged.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 3 commits July 29, 2026 14:14
The existing checks are lexical: they assert the lifespan no longer reaches for
the MLX probe or the RAG warm. They would all still pass if the deferred work
never ran at all, which would quietly end MLX self-healing and leave the RAG
embedder cold on every launch. Deferring must not become dropping.

Two runtime tests: the post-warm function joins the warm and then runs both
stages in that order, and a failing MLX probe does not strand the RAG warm
behind it. Removing the deferred _warm_rag_embedder() call fails both.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

Three paths still paid the cold build or a heavy import on the loop.

_loaded_satisfies calls get_inference_backend() inline and runs four lines
above the offload added for _reject_unservable_model, so on the
llama-not-loaded path the singleton was still built on the loop. It is a sync
def, and the guard sweep only walked async def bodies, so nothing caught it.
Offloaded at all three call sites, and the sweep now follows sync helpers too.

ModelConfig.from_identifier() runs in validate_model, _load_model_impl and
get_model_config. Its first call builds the vision/audio detection registry,
importing transformers or blocking on _DETECTION_SETS_LOCK while the warm
thread imports it. All three are offloaded; the _load_model_impl one takes the
_hf_offline_if_dns_dead guard to the worker with it, since that DNS probe is a
network round trip that does not belong on the loop either.

The health wait treated DEVICE going non-None as "detection finished". It is
not: the branches assign it partway through and keep probing -- the XPU branch
sets DEVICE and CHAT_ONLY=False before torch.xpu.get_device_name(0), and if
that raises, ensure_hardware_detected degrades the host to CPU/chat-only. A
waiter keyed on the assignment publishes training-enabled for that host, and
config/env.ts caches it for the SPA session. Added DETECTION_COMPLETE, set only
where a final value is guaranteed and deliberately not in a finally: a raise
leaves the partial assignment in place, which is exactly what must not be
published. The health test stubs replace ensure_hardware_detected, so they now
honour the same protocol rather than signalling completion by assigning DEVICE.

The sweep also found 19 more sites reaching the singleton through five sync
helpers across the OpenAI, Responses, monitor and unload paths. Rather than
offload all of them, the warm builds the orchestrator in its own stage after
hardware detection, so the getter is a plain dict read before any of them run.
Those five are a frozen baseline in the test: the set must not grow. This is
containment, not a cure -- a request arriving between the bind and that stage
still pays the build, correctly under the lock but not quickly.

@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: 2cf488c8b3

ℹ️ About Codex in GitHub

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

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

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

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

Comment thread studio/backend/main.py Outdated
"timestamp": datetime.now().isoformat(),
"service": "Unsloth UI Backend",
"chat_only": _hw_module.CHAT_ONLY,
"chat_only": snapshot[0] if snapshot is not None else _hw_module.CHAT_ONLY,

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 Keep provisional health verdicts conservative

When UNSLOTH_STUDIO_DISABLE_TORCH_WARM=1 and a first-use operation is actively detecting hardware, snapshot remains None but _detect_hardware_locked() can already have changed CHAT_ONLY to False before detection settles (for example, before the XPU name probe, which can still fail and fall back to CPU). This response is marked hardware_detection_deferred, and hardware-verdict.ts deliberately stores data.chat_only for deferred replies, so a concurrent health refresh can temporarily enable Train/Export from an unfinished verdict. Use the conservative True fallback whenever no settled snapshot exists rather than reading the mutable global.

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.

Good catch, fixed in 4799e3a. Every accelerator branch of _detect_hardware_locked assigns CHAT_ONLY = False before the probe that can still raise and degrade the host to CPU, and DETECTION_COMPLETE stays clear across that whole window, so a reply landing mid-pass published chat_only: false.

The fallback is now the literal True, which is what the adjacent comment already claimed the value was. New subprocess test test_an_unsettled_pass_is_never_published_as_training_capable models the XPU branch verbatim; restoring the global read fails it on exactly that assertion.

if self._top_models_started:
return
self._top_models_started = True
threading.Thread(target = self._fetch_top_models, daemon = True, name = "top-models").start()

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 Refresh the catalog after the lazy ranking fetch

When the Hugging Face ranking request takes longer than the frontend's single 1.2-second deferred inventory refresh, both /api/models/list responses are assembled before this new thread populates _top_gguf_cache and _top_hub_cache. The Chat page performs no subsequent automatic catalog refresh, so the fetched top models never appear until another user action or page reload happens; previously the fetch began during orchestrator construction and could complete before the first catalog read. Arrange a refresh when _top_models_ready is set, or otherwise ensure a later list read consumes the result.

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.

Checked this one against the tree and I do not think it holds.

list_models in studio/backend/routes/models.py constructs the orchestrator and reads default_models as adjacent statements in the same handler:

inference_backend = await asyncio.to_thread(get_inference_backend)
default_models = inference_backend.default_models

So before this PR the thread started during construction and the catalog was read microseconds later, in the same request. An HTTP round trip to huggingface.co could not complete in that window either. Nothing else constructs the orchestrator on the boot path: main.py never calls get_inference_backend on main or on this branch, and the other call sites (routes/inference.py _loaded_satisfies / _resolves_to_resident, export, data_recipe jobs, training_vram) are load/unload helpers behind a user action. The first constructor is the first /api/models/list in both cases, so the fetch start moves by one statement, not by a page load.

The behaviour you describe is the documented pre-existing design rather than a change here. The comment on default_models is unmodified by this PR and already says it:

# Never wait for the remote Hugging Face ranking during startup. Chat's
# first /api/models/list needs curated defaults immediately; the
# background fetch backfills extra choices on later calls.

There is also a third refresh beyond the two you counted. chat-page.tsx re-runs refreshDeferredModelInventories() on an effect keyed to the model selector opening, which re-issues /api/models/list, so the ranking lands at the moment it is actually rendered.

Every accelerator branch of _detect_hardware_locked sets CHAT_ONLY = False
before the probe that can still raise and degrade the host to CPU, and
DETECTION_COMPLETE stays clear across that window. /api/health fell back to a
bare CHAT_ONLY read whenever no settled snapshot existed, so a reply landing
mid-pass published chat_only: false. hardware-verdict.ts stores data.chat_only
verbatim for deferred replies, which flashes Train and Export on a host that
ends up chat-only.

Use the literal True instead. It matches what the surrounding comment already
claims the value is, and the shutdown reset becomes defence in depth rather
than the only guard.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 1, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Aug 1, 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: 4799e3ac48

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

# inline from async handlers. Building it here makes the getter a plain dict read.
# After hardware so it reuses this thread's detection.
from core.inference import get_inference_backend
get_inference_backend()

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 Carry the warm epoch into backend construction

Fresh evidence beyond the existing stage-boundary retirement fix is that shutdown can land after _warm() passes its pre-stage check but before this constructor reaches get_default_models() → get_device(). Because that nested detection receives no owning epoch, it adopts the post-shutdown epoch and republishes DEVICE; the successor warm then sees a cached verdict and skips the intended re-detection for the new lifespan. Bind this construction's hardware read to the warm epoch, rather than relying only on checks before and after the whole stage.

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.

Agreed, and the code had already half-admitted it: the comment on the post-stage check says later stages build the orchestrator, which reaches get_device() and would republish DEVICE after teardown cleared it. The guards just bracketed each stage rather than covering the inside of one.

Fixed by binding nested reads to the pass instead of threading an epoch through the constructor. hardware.py gains a thread-local _OWNING_EPOCH plus an owning_detection_epoch() scope, ensure_hardware_detected consults it before falling back to current_detection_epoch() (so behaviour is unchanged when no scope is held), and _warm wraps its whole stage loop in it. That covers any stage reaching hardware, not just inference_backend.

Tests: a reproduction of the mid-stage shutdown, a negative control that a live stage still publishes, a thread-isolation/nesting check, and an AST guard that the loop stays inside the scope.

danielhanchen and others added 3 commits August 1, 2026 21:26
The stage-boundary checks only catch a shutdown that lands between two stages.
_warm_inference_backend builds the orchestrator, whose constructor reaches
get_default_models() -> get_device(), and get_device() takes no epoch, so a
shutdown landing mid-construction let that nested pass adopt the epoch it was
being retired into and publish DEVICE over the teardown. The successor warm
then found a non-None DEVICE and skipped detection for the new lifespan.

Bind the read to the pass rather than thread an epoch through the constructor:
hardware.py gains a thread-local owning epoch and an owning_detection_epoch()
scope, ensure_hardware_detected consults it before falling back to the current
epoch, and _warm wraps its whole stage loop in it. Behaviour is unchanged when
no scope is held, and any stage reaching hardware is covered, not just this
one.
Three fixes from a fresh review pass over the branch.

detect_hardware() guards a shutdown landing mid-pass but read the current epoch
itself, so the MLX self-heal, whose repair is a pip install that can outlast the
lifespan, adopted the epoch shutdown moved to and published a verdict for a
lifespan that had ended. It now consults the owning epoch, and the repair thread
is bound to the epoch read before start() like the other background workers.

purge_partial_import() bailed correctly when another importer republished the
parent, then logged and returned the whole planned list, so the warm reported a
clean slate the next import would not get. It now reports what it removed.

health_check assigned _await_hardware_detection() to a local it never read,
which implied the boolean shaped the response when _hardware_snapshot() does.
@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: fb76d4dcc7

ℹ️ 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 +7595 to +7596
active_model, context_length = await asyncio.to_thread(
lambda: (_monitor_active_model(), _monitor_context_length())

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 Keep monitor polls from constructing the backend

When the API-monitor overlay is enabled (its default), the first /api/inference/monitor request during a cold or warm-disabled boot now runs this lambda off-loop but still calls _monitor_active_model(), whose non-GGUF branch constructs the inference singleton to answer “nothing loaded”. That construction reaches get_default_models() -> get_device(), so a read-only monitor poll can import/probe torch even with UNSLOTH_STUDIO_DISABLE_TORCH_WARM=1; use the existing non-constructing peek in _monitor_active_model() when no singleton exists.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed. _monitor_active_model() now uses the module's existing _peek_inference_backend(), which honours the injection seam the monitor tests rely on and returns None rather than constructing. _monitor_context_length() was already on the peek, so both monitor helpers are now consistent.

Comment thread studio/backend/routes/models.py Outdated
Comment on lines 2484 to 2486
try:
inference_backend = get_inference_backend()
inference_backend = await asyncio.to_thread(get_inference_backend)
loading_models = getattr(inference_backend, "loading_models", 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 Keep finetuned deletes hardware-silent without a backend

When deleting an exported or trained model before any standard inference backend exists, such as with the torch warm disabled or before any model has been loaded, this guard still constructs the singleton in a worker just to inspect loading_models and active_model_name. Construction calls get_default_models() -> get_device(), so a metadata-only delete can import/probe torch even though no singleton means no standard model can be active; peek the existing backend and treat None as not blocking deletion.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed. The guard peeks and skips when there is no orchestrator, since no singleton means no standard model can be loading or active. Kept as a conditional around the two checks rather than an early return: there is a second try block below that performs the actual deletion, and returning there would have skipped it.

Comment on lines +110 to +111
const spendWait = Boolean(token) && !hardwareWaitSpent;
const deadline = spendWait ? Date.now() + HARDWARE_DETECT_WAIT_MS : 0;

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 Skip the detection wait for stale tokens

When localStorage holds an expired or otherwise invalid access token, this treats the request as able to receive an authoritative device_type, but /api/health catches the auth failure and returns the unauthenticated body, which can never include device_type. On a cold boot while hardware is still detecting, root beforeLoad also runs for /login, so a stale token can block the first login screen for the full polling window even though the user is unauthenticated; stop polling once the response is still provisional but lacks authenticated-only fields, or validate/clear the token before spending this wait.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed. The loop now breaks when a provisional reply carries no version, which is authed-only, so a token the backend rejects stops immediately instead of polling out the full 5s against a body that can never contain device_type.

Chose the response-shape test over validating or clearing the token up front: it needs no extra request, and it also covers the case where the token is valid but authentication is failing for some other reason.

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines +7891 to +7894
# Otherwise report Unsloth backend status. Off-loop: the first call builds the
# singleton, which waits on detection, and the chat UI polls this from first
# paint.
backend = await asyncio.to_thread(get_inference_backend)

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 Avoid constructing the backend for empty status polls

When no GGUF or standard model is loaded, the chat UI's /api/inference/status poll from first paint now still constructs the standard inference singleton just to return an idle status. With UNSLOTH_STUDIO_DISABLE_TORCH_WARM=1, that constructor reaches get_default_models() -> get_device() and imports/probes torch from a read-only status request, defeating the kill switch until a real hardware-dependent operation runs; use the non-constructing peek here and return the empty status when no singleton exists.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed. The status handler peeks instead of building, and returns an empty InferenceStatusResponse when no singleton exists; every field on that model has a default, so the idle reply is well formed. The asyncio.to_thread hop went with it, since a peek is a plain global read.

The monitor overlay, the chat UI's status poll and a finetuned delete each built
the inference singleton just to report that nothing was loaded. Construction
reaches get_default_models() -> get_device(), so a read-only poll imported torch
even with UNSLOTH_STUDIO_DISABLE_TORCH_WARM=1, which is the one thing that
switch promises not to do. All three peek now, and the status handler returns an
empty InferenceStatusResponse when no singleton exists.

env.ts treated any stored token as one the backend would accept. A rejected
token gets the unauthenticated body, which never carries device_type, so the
wait could only ever time out while beforeLoad held /login. The loop now stops
as soon as a provisional reply lacks the authed-only version field.

The desktop probe guard read the client timeout out of a builder call that main
has since replaced with loopback_http::client(), so it matched nothing once
merged. It now reads the whole-seconds Duration inside the probe, which both
shapes share.

Three offload baselines move with the peeks: the floor drops to 13, the
sync-helper allowance is empty now that both monitor helpers peek, and
get_status leaves the first-paint offload list. test_async_singleton_access
gains a guard that the read-only paths never construct.
@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: 680469925c

ℹ️ 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 thread studio/frontend/src/config/env.ts Outdated
await new Promise((resolve) => setTimeout(resolve, HARDWARE_DETECT_POLL_MS));
res = await fetch(apiUrl("/api/health"), { headers });
}
if (spendWait) hardwareWaitSpent = true;

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 Preserve the wait for the first valid token

When localStorage contains an expired token, spendWait is true but the loop breaks immediately on the unauthenticated health body because version is missing; this assignment still consumes the once-per-page-load wait. If the user then signs in before hardware detection has settled, the first authenticated fetchDeviceType() in that same page load skips the client polling window and can leave the route guard/sidebar using provisional local defaults until another navigation or refresh. Only mark the wait as spent after an accepted-token poll actually waited, or leave it available when the break was caused by a rejected token.

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.

Correct, and a regression from the previous round's fix. Breaking on the rejected token still ran the unconditional claim, so the window was consumed without one ever being waited out.

Fixed in 3b8f50c: a tokenRejected flag records why the loop exited, and the claim is now if (spendWait && !tokenRejected). Signing in later in the same page load gets its window back.

Two existing guards anchored on the literal if (spendWait) hardwareWaitSpent = true; line and went stale; they now locate the claim by pattern rather than by exact text, so the assertions themselves are unchanged.

Breaking out of the wait on a rejected token still marked the once-per-page-load
window as spent, so a user who signed in before detection settled had the first
authenticated read of that page load skip its poll and leave the route guard and
sidebar on provisional local defaults until a navigation or refresh.

@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: 3b8f50c5ea

ℹ️ 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 +345 to +348
epoch = getattr(_OWNING_EPOCH, "value", None)
if epoch is None:
epoch = current_detection_epoch()
DETECTION_COMPLETE.clear()

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 Reject stale forced detections before clearing the current verdict

When an MLX autorepair from a previous lifespan finishes after a restarted lifespan has already published its hardware verdict, its epoch-bound call enters this forced-detection path with a stale epoch, snapshots the newer verdict, clears DETECTION_COMPLETE, probes again, and then _discard_detection_locked() clears the global state because the epoch mismatches. Fresh evidence beyond the earlier stale-waiter issue is that the MLX worker now calls this forced detect_hardware() path, which lacks the early stale-epoch rejection present in ensure_hardware_detected(); reject the stale owning epoch before clearing or probing so an old repair cannot erase the restarted lifespan's result.

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.

Agreed, and this one is a consequence of the previous round's fix rather than something that pre-dated it. Binding the MLX worker to its spawn epoch is what routes a late repair into this forced path with a stale epoch, and the sequence there is snapshot, clear DETECTION_COMPLETE, probe, then _discard_detection_locked(). Run over a restarted lifespan that has already published, that does not merely fail to add its own verdict, it erases the new one and drops the fresh lifespan back to provisional. Strictly worse than the behaviour before that fix.

ensure_hardware_detected() already had the early stale-epoch rejection; detect_hardware() did not. It now returns before clearing or probing when the owning epoch is already stale, so an old repair leaves the running lifespan untouched. Unchanged when no scope is held, so ordinary forced re-detects behave exactly as before.

Test asserts the retired pass neither probes nor disturbs DEVICE, CHAT_ONLY or the completion event; removing the early return fails it and nothing else.

Binding the MLX worker to its spawn epoch routes a late repair into
detect_hardware() with a stale epoch. That path snapshots, clears
DETECTION_COMPLETE, probes, then discards on the epoch mismatch. Run over a
restarted lifespan that has already published, the discard erases the new
verdict rather than merely failing to add its own, dropping the fresh lifespan
back to provisional.

ensure_hardware_detected() already rejected a stale epoch early; detect_hardware()
now does too, returning before it clears or probes. Unchanged when no owning
scope is held, so ordinary forced re-detects behave exactly as before.
@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: f342e44861

ℹ️ 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 +348 to +353
elif current_detection_epoch() != epoch:
# Retired before this pass began, so leave the running lifespan alone. Going
# on would clear DETECTION_COMPLETE over a settled verdict, probe, and then
# discard: an old repair finishing late would erase the verdict the restart
# had already published, not merely fail to add its own.
return DEVICE

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 Re-detect after a stale MLX repair succeeds

When a lifespan restarts while MLX autorepair is still installing, the successor warm can first publish mlx_unavailable; if the install then succeeds, the repair enters this branch with its retired epoch and returns without refreshing that successor verdict. Because the process-wide _attempted latch prevents another repair and health polling only reads the settled snapshot, Train and Export remain disabled until a process restart despite MLX now being usable. Preserve the newer verdict here, but arrange a detection owned by the current epoch after the successful repair.

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.

Agreed, and this is a regression from the previous round rather than something pre-existing. Declining the stale pass fixed the erasure but replaced it with a worse outcome: the pre-fix code accidentally self-healed here, because erasing the verdict forced a re-detect that eventually found the working mlx. Removing the harm removed the accidental recovery with it.

That also cuts against the reason I declined the MLX autorepair kill-switch item earlier in this review, which was that repair exists precisely to stop a Mac being permanently chat-only.

Fixed in f7f4fc8: when the scoped pass declines but attempt_mlx_repair() succeeded, re-detect under the live epoch. Only on a successful repair, so a no-op or failed one still cannot publish into a stopped lifespan.

Comment on lines +404 to +407
produced_here = DEVICE is None
if produced_here:
try:
_detect_hardware_locked()

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 Clear completion before replacing a torn verdict

When shutdown races a cached ensure_hardware_detected() waiter, the waiter can set DETECTION_COMPLETE after shutdown has cleared DEVICE, producing the event-set/DEVICE=None state that _await_hardware_detection() explicitly handles by starting a fresh pass. This produced_here path does not clear that stale event before _detect_hardware_locked() mutates DEVICE and CHAT_ONLY, so health can observe the first accelerator candidate as settled—for example XPU with chat_only=False before get_device_name() fails and detection falls back to CPU—and the frontend can cache that intermediate training-capable verdict. Clear DETECTION_COMPLETE before beginning any pass that produces a new verdict.

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.

Confirmed, and it is an asymmetry the tree already documents: detect_hardware() clears the event for the duration with a comment about health serving the intermediate state as settled, while the produced_here branch of ensure_hardware_detected() did not. The event-set-with-DEVICE-None state is reachable exactly as you describe, and _await_hardware_detection() already handles it explicitly, so the pass could start with a stale event set.

Fixed by clearing before the pass and republishing once the verdict is final. The test asserts the event is observably clear from inside _detect_hardware_locked() and set again afterwards; leaving the clear out fails it and nothing else.

Declining the stale forced pass fixed the erasure but introduced a worse
outcome: a successful MLX install whose repair outlived its lifespan left the
running one holding a verdict measured before mlx existed. _attempted is
process-wide, so no later repair revisits it, and a Mac that is now perfectly
capable stayed chat-only until a restart. When the scoped pass declines but the
install succeeded, re-detect under the live epoch.

ensure_hardware_detected() also has to clear DETECTION_COMPLETE before it
produces a verdict, the same way detect_hardware() already does. Shutdown
clearing DEVICE while a cached waiter goes on to set the event leaves it set with
DEVICE None, a state _await_hardware_detection() treats as detect-again, so the
pass could publish the XPU candidate as settled before the probe that falls back
to CPU.
@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: f7f4fc87ef

ℹ️ About Codex in GitHub

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

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

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

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

Comment thread studio/backend/main.py
# Last, so it never contends with the work above for the GIL: torch (via hardware
# detection), transformers, datasets, unsloth_zoo. The socket binds as soon as this
# returns, so the login screen is up while the stack loads.
start_background_warm()

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 Start the ML warm only after startup is signaled

On cold boots where a torch native-extension import holds the GIL, the newly started torch-warm thread can begin importing the ML stack here before this lifespan reaches yield; uvicorn cannot finish startup and bind its socket until that later yield, so the warm can still delay the login screen by the very import this change intends to move behind it. Synchronize the worker with completion of lifespan startup, or otherwise ensure its target cannot enter the import stages until the server is ready to accept requests.

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 mechanism is sound in principle, but I measured it and the magnitude is not there.

Only two statements sit between start_background_warm() and yield: _start_post_warm_thread() and the log call. I instrumented the real lifespan, ran it three times with the warm thread genuinely importing torch (asserted torch in sys.modules afterwards), and timed warm-start to yield:

warm_start_to_yield_ms: 0.84   post_warm_spawn_ms: 0.76   torch_imported_by_warm: true
warm_start_to_yield_ms: 1.02   post_warm_spawn_ms: 0.93   torch_imported_by_warm: true
warm_start_to_yield_ms: 0.98   post_warm_spawn_ms: 0.84   torch_imported_by_warm: true

Roughly 0.8ms of the ~1ms is the thread spawn itself, not GIL contention. The end-to-end numbers agree: time to a healthy /api/health went from 5.09s to 3.12s, which would not hold if the warm were still gating the bind.

The worst case you describe is bounded by a single GIL hold inside whichever dlopen is in flight, because the main thread needs the GIL once for about three bytecodes. That is a fraction of a second at worst against the roughly ten seconds this path removes, so it is not a regression, just a residual.

I also considered the suggested fix. Nothing inside the lifespan can observe uvicorn binding, so the achievable version is an event set immediately before yield and waited on by the warm. That buys about a millisecond and adds a failure mode worth avoiding: if lifespan startup raises before setting the event, the warm parks forever and every stage stays cold. Not worth it for this margin.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: f7f4fc87ef

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

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: b28d7e2fc7

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

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.

3 participants