Skip to content

PR #8264 real Tauri Playwright repro CI - #56

Closed
Imagineer99 wants to merge 207 commits into
mainfrom
fix/pr-8264-tauri-playwright-repro-ci
Closed

Imagineer99 wants to merge 207 commits into
mainfrom
fix/pr-8264-tauri-playwright-repro-ci

Conversation

@Imagineer99

Copy link
Copy Markdown
Owner

Disposable Windows WebView2/Tauri A-B validation for unslothai#8264. Do not merge.

danielhanchen and others added 30 commits August 6, 2026 07:01
… you are offline (unslothai#7829)

* Model hub: report why Hugging Face is unreachable, and fall back to the server

The Model hub could sit permanently on "You're offline" while flapping to
"Back online" and straight back, on machines that were online. Discovery is a
direct cross-origin browser fetch to huggingface.co, so anything blocking the
browser (DNS or content filter, TLS-inspecting antivirus, an extension, CSP)
produced an opaque TypeError that was reported as loss of internet.

Three problems, all fixed here.

1. Every failure looked identical. The first failed fetch blacklisted the
   origin for 30s, which disabled the search hook, which cleared the error that
   explained the failure, so the catalog fell back to a hardcoded
   "Discovery is unavailable while offline." The branch that would have shown
   the real cause was unreachable for connectivity failures.

   Failures are now classified (timeout / aborted / csp-blocked /
   browser-offline / network-opaque), survive the backoff window, and are
   rendered. A securitypolicyviolation listener names CSP blocks, the one class
   a browser will identify. Messages keep only the origin host, never the
   request URL, which carries the search query.

2. The flapping. A lapsed backoff was treated as proof the Hub was reachable,
   firing "Back online" and a retry that failed again. It now yields a probing
   state; only a successful response announces recovery. Retry also always
   re-probes instead of refusing while the backoff is open.

3. No way through. Added GET /api/hub/discovery/{models,datasets}, used only
   after a transport failure, never after a real HTTP status. The destination
   comes from hf_endpoint_url() server-side and cannot be influenced by the
   request, the query is rebuilt from an allowlist, redirects are refused, and
   size and timeout are bounded. Upstream 401/403 maps to 424: passing it
   through would hit authFetch's 401 handler and log the user out of Studio.

This also makes HF_ENDPOINT mirrors work. The frontend hardcoded huggingface.co
while the backend was endpoint-aware, so a mirror looked permanently offline.
hub_endpoint now ships in the authed /api/health payload and a non-official
endpoint uses the proxy from the first request, which is what lets mirrors work
on desktop, where the Tauri CSP is fixed at build time.

Tests: 16 new frontend (node:test), 31 new backend (pytest).

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix proxy fallback: model-info routing, pagination, offline marker, navigator veto

Five fixes from review of the discovery fallback.

Model-info requests were retargeted at the listing proxy. makeHfFetch is passed
to cachedModelInfo, and toProxyRequest kept only the query, so on fallback
/api/models/{repo}/revision/HEAD became the /api/models listing and the SDK
parsed an array as one repo, caching a model with no id. The transport now
proxies only URLs whose path is exactly /api/{resource}; anything else stays on
the direct route.

Proxy pagination stopped after one page. The Hub SDK's parseLinkHeader only
matches an http(s) target, so the relative Link the route emitted yielded no
next. The route now builds it from request.base_url, and isProxyUrl matches on
pathname so the absolute link is still recognised as already proxying.

A successful fallback left the Hub marked unavailable. fetchWithTimeout records
the direct failure before throwing and nothing cleared it, so the catalog
refused to paginate and rendered fallback results as a connection error. The
backend path now clears the origin's failure, but only when the response is ok,
so a failing proxy keeps the diagnosis.

browser-offline no longer vetoes the fallback. navigator.onLine is advisory and
reads false on WSL2 and some Tauri/WebKitGTK webviews, which network.ts already
documents; letting it gate the fallback made the one untrusted signal
authoritative.

The offline panel no longer echoes the raw SDK error. createApiError appends
"URL: <url>", which carries the user's search query.

Also bind the discovery_router re-export so the import-hoist verifier counts it
as used, matching routes/__init__.py.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix pagination dead end, mirror relative links, and the proxy-first error trailer

Preserved results could not retry. Keeping rows on screen when the Hub goes
unavailable left Load more gated on `online`, and the phase only leaves probing
on a success, so that footer was the only request the view could make and it
refused to make it. Load more now proceeds once the backoff has lapsed; the
unavailable window still blocks it.

A mirror emitting an RFC 8288 relative next target had its link dropped. The
same-origin check ran on the unresolved value, so an empty scheme and authority
never matched and mirror pagination stopped after the first page. The target is
resolved against HF_ENDPOINT first; an absolute off-endpoint link is still
rejected.

The proxy-first path leaked the SDK's URL trailer. With a mirror the listing
goes through the backend, so an upstream HTTP error records no classified
failure and the raw message, which ends in "URL: <full request url>", reached
both the toast and the catalog. It is now sanitized where it enters our state,
which covers every render path rather than one branch.

* Route mirror model-info through a path-preserving endpoint, bound stream reads

With HF_ENDPOINT set to a mirror, model-info still went to the public Hub. The
SDK builds those URLs on huggingface.co and the listing-only guard sent them
straight out, so a mirror user's repo ids and Authorization token reached the
wrong service, and if that origin is blocked the pinned and priority lookups
were silently dropped instead.

Adds GET /api/hub/discovery-info/{resource}, which keeps the repo path the
listing route discards. The repo is checked with is_valid_repo_id and the
revision against a conservative pattern, then both are re-encoded rather than
forwarded, and only expand is accepted so this cannot become a second listing
route. The transport uses it only when a mirror is configured or after a
fallback; otherwise model-info stays direct as before.

Also bound the streaming read. requests' timeout limits inactivity between
chunks, not total duration, so an upstream drip-feeding within the window could
hold a worker thread well past _REQUEST_TIMEOUT_SECONDS. The read loop now
tracks a monotonic deadline and returns 504.

The model-info test now asserts what it always meant, that such a request never
reaches the listing route, rather than that it never reaches the backend.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Sanitize the Hub error where every consumer reads it

The URL trailer was stripped in useDiscoverSearch, but useHubModelSearch and
useHubDatasetSearch feed the training and dataset pickers too, and those render
the hook error raw. On a proxied request Response.url is our own route carrying
the user's search query, so a blocked or mirror user could see it there.

Moved into useHubPaginatedSearch, at the single point the message becomes state.

* Track proxy availability separately from browser-origin reachability

Clearing the huggingface.co failure on a successful fallback said the browser
could reach the Hub when only the backend had. useOnlineStatus() then re-enabled
the direct clients, the README and owner-avatar fetches, which failed against the
still-blocked origin and marked it unavailable again, recreating the flapping in
exactly the environments the fallback exists for.

The transport now records that the backend is serving us and leaves the origin
state alone. getHubPhase reports available while that holds, so the catalog uses
the proxied feed, and isHuggingFaceOffline stays origin-based so the direct
clients remain suppressed. The hub page follows content availability rather than
browser reachability.

* Compare normalised authorities when accepting a pagination link

An HF_ENDPOINT written with a different case or an explicit default port is the
same origin, but the raw netloc comparison treated the mirror's canonical next
link as off-endpoint and dropped it, stopping proxy pagination after one page.
Scheme, host and effective port are compared instead.

* Route selection metadata through the mirror, drop malformed pagination links

Selection metadata bypassed the mirror. useSelectedModelMetadata called
cachedModelInfo without the mirror-aware transport, so opening a repo the
current listing had not primed, a deep link or a downloaded-inventory entry,
sent its id and the user's token to the public Hub and failed outright when that
origin is blocked. Added createModelInfoFetch as the one fetch every modelInfo
caller should use, and pointed this hook at it.

A malformed next-page link now drops the header instead of failing the request.
Reading .port raises on a nonnumeric or out-of-range authority, which turned a
good first page into a 500; the header is optional, so an unusable link is
simply not emitted.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Do not treat proxy-served availability as a direct reconnect

Two consequences of routing the catalog off content availability.

The reconnect branch fired when the backend started serving us, so a successful
fallback announced Back online and called retrySearch. That builds a fresh
transport with no per-iterator affinity, which re-attempted the known-blocked
direct request and duplicated the first page for exactly the users the fallback
helps. useHubAvailability now reports whether availability came from the proxy,
and reconnect requires the browser's own origin to have recovered.

The recommended searches in the model picker still gated on useOnlineStatus, so
the direct failure marked the origin offline, disabled the paginated hook, and
aborted the signal handed to the fallback that same failure had just started.
They follow content availability now, like the hub page.

* Report only a normalised Hub origin, and normalise before choosing proxy-first

HF_ENDPOINT may carry userinfo, and health returned it verbatim, so a mirror
configured as https://user:password@host handed those server-side credentials to
every authenticated Studio user. Only the normalised origin is reported now,
which is all the client needs to tell a mirror from the official Hub.

The client-side check was textual too, so an equivalent spelling of the official
origin, a trailing slash, different case, or an explicit :443, was read as a
mirror and gave up direct browser access for nothing. Scheme, host and effective
port are compared instead.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Defer the offline marking until the fallback has also failed

fetchWithTimeout marked the origin offline the moment the direct request failed,
before the transport could try the backend. That re-render disabled consumers
gated on availability, and their cleanup aborted the same signal the fallback was
using, so the retry could never finish or report that the server was serving us.
The picker could sit empty while the backend could reach the Hub perfectly well.

The transport now asks fetchWithTimeout not to record, and marks the origin
offline itself only once the backend attempt has failed too.

* Defer offline recording in the model and dataset fetch adapters too

Only the transport's default adapter passed recordFailure false; the model and
dataset adapters override direct and so kept recording, which still aborted the
fallback in the Recommended picker.

* Keep the mirror token off the public Hub, record failed fallbacks, widen deadline

A mirror user's README request went to a hardcoded huggingface.co URL carrying
their Authorization token and the repo name, so selecting a private mirror
result disclosed both to the public Hub. That request is now skipped when a
mirror is configured. Model cards for mirror repos are unavailable until the
README, avatar and dataset-size paths are routed through the endpoint, which is
a larger change than belongs here.

A non-OK fallback lost the diagnosis: authFetch resolves rather than throws on a
non-2xx, so the catch never ran, the panel had no classified cause, and no
backoff suppressed the next direct attempt. The saved direct failure is recorded
when the backend answers non-OK.

The upstream deadline now starts before the request rather than after headers,
so a mirror dripping header bytes cannot claim a full window of its own first.

* Guard the size lookups behind the mirror check, bound the socket timeout

fetchDatasetSize and fetchModelSize call hardcoded public services, so a mirror
user's token and repo name went to the wrong host exactly as the README fetch
did. Both are skipped when a mirror is configured.

requests' timeout is per read, so handing it the whole budget let headers spend
one window and a stalled body another. The socket timeout is half the window
now, which keeps the worst case at one.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Let the picker probe after backoff, and never back off on a caller abort

The picker exposes no Retry, so excluding probing left it stuck until some other
surface reached the Hub or the page reloaded. It counts as eligible now. This
does not reintroduce the loop the discover panel dropped: the picker fetches on
mount and user interaction, not on a timer.

A superseded query also put the Hub into backoff. Aborting the shared signal
rejected the pending fallback, and that was recorded as both routes being gone,
which could then disable the replacement request. An abort is no longer treated
as a proxy failure.

* Close the last public lookups on mirrors, and keep proxy state honest

Dataset splits and owner avatars were the remaining hardcoded public services.
The splits call carried the mirror token and dataset id to the public
datasets-server, and the avatar lookup disclosed private owner names to the
public Hub. Both are skipped in mirror mode; an avatar miss was already
non-fatal.

A rejecting backend left hubProxyServing true, so the Hub kept reporting as
available off a proxy that was gone. It is cleared on rejection, and since
affinity makes that the only path later pages take, the saved direct failure is
recorded there rather than only in the first fallback.

The direct failure is also retained for the transport's proxy lifetime, so a
later page failing non-OK still reports the diagnosed cause instead of nothing.

* Tighten comments in the hub discovery changes

* Scope the Hub failure diagnosis to the feed that recorded it

* Tighten the new comments

* Track Hub availability per feed so an auxiliary outage cannot pin the catalog

* Keep Load more working while the Hub is probing, and fix a bad hostLabel fallback

* Tighten the comments from the last review rounds

* Scrub URLs from proxy errors, file paged failures under the Hub, unblock Load more

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tag services by route, record mirror failures, fall back model-info, scrub hosts

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Name HTTP failures in the panel and suppress direct clients while the proxy serves

* Restart the feed on a manual retry: a failed page finishes the iterator

* Raise the proxy response cap: an ordinary text-generation listing is 9.9 MB

* Stamp proxy responses so an older backend's SPA 404 is not blamed on the Hub

* Serve the repo card through the backend so a mirror shows one at all

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Stamp proxy errors too: an upstream 404 must not look like a missing route

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Let the server's own answer name the failure, and diagnose direct HTTP statuses

Four fixes in the hub transport:

- A status the backend actually got (424, 429, 4xx) now outranks the saved
  direct failure. A 502 stays subordinate: it only means the server could not
  reach the Hub either, so the browser's cause is the more specific of the two.
- 424 and 502 are the backend's own remaps, so they are described rather than
  attributed to Hugging Face. A 424 was reading as "Hugging Face returned 424".
- A served model-info fallback marks the proxy as serving, which is what keeps
  the README and avatar clients off an origin this browser cannot reach. It
  promotes only, so a missing repo's 404 cannot retire a proxy the listing uses.
- A non-2xx the Hub answered directly is now recorded, so the status reaches
  the panel. It resolves as a Response and fetchWithTimeout clears the origin on
  any resolved response, so nothing else was recording it and the http branch
  was unreachable on the direct path. It is not a fallback trigger.

* Separate 'this browser is blocked' from 'the backend is serving the feed'

Follow-up to the previous commit, from re-reviewing it.

hubProxyServing forces getHubPhase to "available" and blanks getLastHubFailure,
so it means the catalog feed is coming through the proxy. A repo lookup does not
earn that: with the catalog down and its cause on screen, one proxied detail-pane
request would report the feed available and erase the diagnosis. Split out a flag
that only suppresses the direct clients (README, avatars, quant listings), which
is all a lookup proves, and clear it on any direct success so a single transient
timeout cannot strand it for the session.

Also from the same pass:

- A real HTTP status no longer opens a 30s backoff. It proves the origin is
  reachable, so backing off stalled Load more and pushed the direct clients into
  offline mode over a bad query or a stale token. The cause is still recorded.
- Only the Hub's own answer outranks the saved direct failure. The old test was
  on the kind, so a 503 from a proxy in front of Studio read as the Hub's and
  discarded an actionable csp-blocked cause. A 401/403 here is Studio's session,
  since the backend remaps an upstream one to 424.
- directHttpFailure files the failure under the origin it is keyed by, rather
  than pinning the official Hub while keying by the request's origin.
- The direct stub in the new test now clears the origin the way fetchWithTimeout
  does, so the ordering the fix relies on is actually exercised.

* Make the backend README path actually reachable, and stop it leaking to the public Hub

All four from the latest review, each confirmed against the code.

- The card's load effect was gated on `online`, which is false exactly when the
  proxy is serving, so the backend README route added in this PR could never run
  on a mirror. It now runs when that route is the one that works.
- readmeBaseUrl hardcoded huggingface.co, so a mirror card's relative images and
  links went to the public Hub, disclosing the repo path and 404ing every asset.
  It follows the configured endpoint.
- The README route caught only HTTPException, so a DNS, TLS or connection
  failure escaped as an unstamped 500 with an unscrubbed message. It now maps
  through the same helper as the search and info routes, and its two rejected
  query responses are stamped like everything else.
- A CSP violation record was consumed by the first failure that read it. The
  picker starts two listings at once, so the second was classified opaque and
  overwrote the more actionable diagnosis. The record lives out its TTL instead.

Backend 78 tests, frontend 399. The CSP correlation path had no coverage at all;
it does now, driven through a stubbed document rather than an injected kind.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Finish the blocked-browser detail path, and stop a concurrent failure pinning the phase

Four follow-ons from the last round, all in paths the previous two commits added.

- readmeViaBackend missed directHubBlocked, the flag those commits introduced.
  A deep link, pinned publisher or detail pane never runs a listing, so its own
  model-info fallback is the only proof the backend can reach the Hub; without
  it the card stayed unavailable until a catalog fallback happened.
- The README cache keyed only repo and token, so a direct attempt that failed
  before the backend was proven cached a 30s rejection that every later
  backend-capable retry got back. The route is part of the key now.
- The ttl=0 record could not shorten a live 30s window, and two concurrent
  listings can interleave so the other one's failure is marked between this
  response resolving and the status being recorded. The window is retired
  first, so an origin that answered is not left reported unreachable.
- The info route returned an older backend's unmarked 404 as a real missing
  repo. It now recognises the SPA catch-all the way the listing does.

Also tightened a source assertion that CodeQL flagged as incomplete URL
sanitization: it now rejects any literal scheme rather than one hostname.

Frontend 402, backend 78.

* Back out the backoff clear, and scope the card's second cache to the route too

Self-review of the previous commit.

The clearRemoteBackoff added there was over-fixing. fetchWithTimeout already
clears the origin on any resolved response, so a window opened before the answer
was gone before the status was recorded; the only windows the clear could reach
were ones opened after it, by any service, which is newer evidence than ours.
Retiring those resumed direct README and avatar fetches against an origin that
had just failed for them, and it defeated the backoff from the auto Load more
path, whose test greps use-discover-search.ts and so stayed green. The two cases
are now pinned separately: an earlier window is already gone, a newer one stays.

Scoping fetchReadme's key to the route also fixed nothing on its own, because
model-readme keeps a second cache holding the in-flight promise, keyed without
the route. A direct attempt still running when the browser turns out to be
blocked was handed straight back, so the backend route was never reached in the
ordering that actually happens: the info fetch fails fast, the README has a 10s
timeout. Both keys carry the route now.

Also gave the missing-repo info test its marker header. Without it the stub was
taking the new SPA-catch-all branch, so the case it names was not covered.

Frontend 404, backend 78.

* Scope the backoff window per feed, and keep a subpath mirror's prefix

- The backoff was keyed by origin while the failure it explains was keyed per
  feed, so a success on any other client deleted it. A block can be per-path:
  an avatar or dataset-size request can succeed while /api/models stays
  blocked, and that retired the catalog's backoff while its failure was still
  recorded, so Load more resumed probing a dead feed. The window is keyed like
  the failure now, getHubPhase reads its own feed's, and isRemoteNetworkOffline
  answers origin-wide by default so the direct clients keep their meaning.
  Retry still clears every feed on the origin, which is what a click means.
- readmeBaseUrl kept only the endpoint's origin, but the backend builds its
  URLs from the whole of HF_ENDPOINT, so a mirror mounted at a subpath had
  every relative image and link resolved one directory too high.

Frontend 407, backend 78.

* Report the endpoint's path, and refuse a redirected repo card

Both from the latest review, both real.

- /api/health reported scheme, host and port only, so the path never reached
  the frontend and the subpath-mirror fix in the previous commit could not
  work. The path is kept now; userinfo is still dropped, since that is the
  server's credentials, and query and fragment are dropped by construction.
  This supersedes the origin-only choice an earlier test pinned, because the
  frontend now resolves a card's relative assets against this value.
- The README route checked 404 and >= 400, so a 301/302/303/307/308 fell
  through. Redirects are refused rather than followed, and _fetch_upstream
  hands them back with an empty body, so the card shipped as a blank 200. It
  is a stamped 502 now, matching the search and info routes, and the status
  tuple they share is named rather than repeated four times.

Backend 85 in the hub suite, 115 with middleware. Frontend 407.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Let the asset clients ask about their own feed, and bracket an IPv6 endpoint

Self-review of the per-feed backoff change.

Keying the window per feed fixed a success on one feed retiring another's, but
it broke the mirror image: isHuggingFaceOffline still asked origin-wide, while a
success now clears only its own window, so under a per-path block a dead catalog
kept the repo card, owner avatar and quant clients in local-only mode and no
avatar success could release them. Every keystroke re-armed the catalog window,
so it lasted as long as the user kept searching rather than 30s. Those three
callers now ask isDirectHubOffline, which reads their own feed; the feed's own
view is unchanged, so Load more still respects the catalog backoff.

Also:

- The retry timer woke on the longest live window while the phase reads one
  feed's, so the panel could report a state it had already left. It wakes on the
  soonest now.
- urlsplit().hostname strips the brackets an IPv6 literal needs, so
  /api/health reported http://fd00::1:8080/hf. new URL() throws on that, and the
  frontend then resolved a mirror card's relative assets against the public Hub,
  which is the disclosure the backend README route exists to prevent.
- Two comments the re-keying had made false.

Frontend 409, backend 87.

* Point the direct asset clients at the window their own failures arm

The previous commit named the right problem and fixed the wrong call sites.

isDirectHubOffline reads the "other" window, but the clients switched to it
were chat-api and the inventory API, which fetch through our own backend and so
populate no window at all. Meanwhile the three clients that do fetch the Hub
directly, and are the only things that arm "other" (repo cards, owner avatars,
dataset sizes), were still gated on the origin-wide flag, so under a
discovery-only block they never fetched. The window could then lapse with
nothing able to re-arm it: while genuinely offline the quant picker stopped
sending offline=true and waited out a 5s upstream timeout per listing instead of
answering from cache. The model-readme switch was a no-op besides, since the
field it changed is overridden on the only path where the two predicates differ.

So the loop is closed properly now: the three direct fetchers gate on
useDirectHubOnline, which is the window they themselves arm, and the two pure
consumers go back to the origin-wide flag. The new test pins both halves,
because either one alone fails silently.

Frontend 412.

* Close the loop for dataset sizes too, and make the test that claims it real

Found reviewing the previous commit, which claimed more than it delivered.

The dataset-size hook fetches datasets-server, not the Hub, so its failures arm
a window on that origin while the gate read the Hub's. Same shape as the bug the
previous commit set out to fix: a client that can neither back off nor recover,
because nothing it does touches the window it reads. isDirectHubOffline and the
hook take the origin now, and that hook passes its own. The flags stay
origin-independent, since a browser that cannot reach the Hub at all is the same
block that would stop datasets-server.

The test I added to pin this was vacuous for two of the three clients: it looked
for fetchReadme and fetchDatasetSize in the gate file, which the import line
satisfies on its own, so flipping either module's service tag left it green. It
asserts on the module that actually calls fetchWithTimeout now, and on the origin
each gate reads.

Also corrected an assertion message the earlier revert had made half false: the
quant list is deliberately not on this predicate, since it is served by our own
backend, whose reachability a browser-side block says nothing about.

Frontend 412.

* Wake every backed-off origin, and stop the test passing off a sibling producer

Reviewing the previous commit found two faults in it and one older one.

- Gating dataset sizes on datasets-server gave them a backoff with no way out.
  getBrowserOfflineRetryDelayMs scanned the Hub's origin only, so nothing was
  scheduled to wake that window, and the gate it had shut was the only thing
  that could have reported the recovery. It scans every live window now, which
  is what the timer was always meant to express.
- The test meant to pin that was still vacuous for the one client it is about:
  dataset-size.ts hosts two producers, so flipping fetchDatasetSize's tag left
  it green off fetchModelSize. It reads one function's body now. My earlier bite
  test missed this because it replaced both occurrences at once.
- Nothing tied DATASETS_SERVER_ORIGIN to the host fetchDatasetSize calls, so
  renaming the constant would leave both checks green over a window nothing
  arms. That is now asserted directly.
- fetchModelSize tags its failures 'other' but the download card gated it on the
  origin-wide flag, so it stopped fetching under a discovery-only block and
  never re-armed. Same fault as the other three, and it is now covered.

Frontend 413.

* Close three assertions that could not fail

Mutation-audited every test this PR adds or reworks: apply the smallest edit
that should break each assertion, re-run, revert. 22 of 25 mutations were
caught. The three that were not:

- /needsRestart/ matched needsRestartRenamed, so renaming the thing it exists to
  pin left it green. Word-bounded now.
- The http panel branch asserted only that failure.status appears within it, and
  the ternary's own condition reads it, so dropping the number from the title
  passed. It asserts the interpolation now.
- Nothing pinned allow_redirects on the call that actually leaves the process:
  every redirect test stubs _fetch_upstream, so flipping the flag broke no test
  even though refusing the hop is what keeps a redirect off an internal address.

One apparent miss was mine, not the suite's: adding "http" to FALLBACK_KINDS
changes nothing, because classifyFetchFailure never returns that kind and a real
status resolves rather than throwing. Re-run with a mutation that does fall back
on a non-ok response, the existing test catches it.

Frontend 413, backend 88.

* Stop a proxied catalog speaking for the asset paths, and match cause to window

Three from the review on 3f04c1d, all correct.

- isDirectHubOffline inherited hubProxyServing, so once the catalog fell back to
  the backend every direct asset client reported offline for as long as the feed
  stayed proxied. A blocked listing is not evidence about /raw or an avatar,
  which is the whole premise of the per-service windows, so it no longer counts.
  directHubBlocked stays, but only for the Hub's own origin: what it records is
  a repo lookup there failing, which says nothing about datasets-server.
- markRemoteNetworkOffline took the newer cause even when it kept an older,
  longer window, so the panel could name a request that had answered while a
  different live failure was what held it unavailable. Cause and window move
  together now, and a first cause is still always taken.
- A filter can block only /raw, and neither proxy flag is set by that, so the
  README's own transport failure never reached the backend route this PR added
  and the card stayed unavailable. It falls back like the listing does.

The fourth, restarting picker searches on a probing transition, I disagree with
and have said why on the thread.

Frontend 417.

* Bound the proxy's wall clock, and stop a served feed forcing cache-only answers

Four from the review on 9a2c28c, all correct.

- The quant list read isHuggingFaceOffline, which hubProxyServing sets, so the
  moment discovery fell back the picker asked the backend for cache-only results
  and got 404 for every uncached repo. A serving proxy is positive proof the
  server can reach the Hub, so it now vetoes that request instead of causing it.
- A README served by the backend after a /raw block did not record that the
  backend is the working route, so the gate shut on the next card and none
  loaded until the direct backoff lapsed. It promotes now, like the info path.
- The socket timeout is per operation, so a stalled DNS lookup or OS proxy
  discovery was unbounded and held an executor thread well past the advertised
  window. The deadline is applied around the threaded call.
- A direct 401, 404 or 429 was folded into the offline branch, so an auth or
  rate-limit answer raised "Can't reach Hugging Face" and a later success
  announced "Back online" though nothing had been unreachable.

The deadline took two attempts. asyncio.wait_for around to_thread does not bound
the clock: it cancels the future then waits for that cancellation, and a thread
cannot be cancelled, so it blocks for the full stall. The test caught it. It
uses asyncio.wait and leaves the orphan to the socket timeout.

Frontend 420, backend 90.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Gate the GGUF update actions on the backend's reach, not the browser's

Same fault as the quant list, two call sites further on. The update button and
the remote variant refresh both run through our own API, but were gated on
useOnlineStatus, which hubProxyServing and directHubBlocked both force false. So
once discovery fell back or a card came from the backend, a downloaded row never
offered an update even though the server had just proved it could fetch one.

They ask useBackendHubOnline now, which is the same question the request itself
asks, so the gate and the call cannot disagree.

Frontend 421, backend 90.

* Merge main, and update the picker contract for the renamed predicate

tests/studio/test_model_picker_contracts.py pins the exact call text in
chat-api, and this branch predated that file, so the rename only failed once CI
merged with main. The contract is unchanged: the caller still hands its options
to the builder. What it names is now shouldPreferLocalCache, because the request
goes to our own backend and a proxy already serving discovery proves the server
can reach the Hub.

* Keep a card's fallback scoped to cards, and check what the proxy hands back

Six review findings from the last round.

Frontend:
- A README that fell back to the backend set the origin-wide directHubBlocked
  flag, so a filter on /raw pushed the listing, avatars and dataset sizes onto
  the proxy too. It now records a card-scoped flag instead.
- hubProxyFirst compared origins, so a mirror mounted on the Hub's own host
  (HF_ENDPOINT=https://huggingface.co/hf) was taken for the default and fetched
  direct, reading the wrong repo. The comparison now includes the path.
- The auto-fill kept pulling a generator that had already thrown. That pull
  returns done, which clears the error and drops hasMore, so the failure
  disappeared and the list silently ended. Only a restart resumes now.

Backend:
- Timed-out fetches are left running, since a thread cannot be cancelled. They
  ran on the loop's shared executor, where a stalled resolver starved every
  other asyncio.to_thread user in the process. They get their own bounded pool.
- The card proxy asked for application/json on a /raw path, which a
  content-negotiating mirror may answer with 406 or with JSON.
- A 200 whose JSON was the wrong shape (an error object, an SSO page) was
  passed on as a working feed and threw inside the SDK's iteration. Listings
  must be arrays and repo lookups objects.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Split the backend discovery proxy out of this PR

The proxy and the HF_ENDPOINT mirror support it carries are a separate change
from the diagnosis fix, and they are the part that keeps growing: every round
turns up another direct fetch that has to be routed through it. They go in a
follow-up so this PR is the state-machine and panel fix on its own.

Removes studio/backend/hub/routes/discovery.py and its tests, and restores
hub/routes/__init__.py, hub/dependencies.py and main.py to upstream.

* Split the frontend fallback transport and mirror support out of this PR

The other half of the same split. What is left is the diagnosis fix on its own:
the failure taxonomy, the CSP correlation, the per-feed backoff windows and the
phase machine that stops a lapsed window claiming the Hub is reachable, plus the
panel that names the cause.

Removes hub-transport.ts, hub-endpoint.ts, endpoint-key.ts and their tests, and
restores the search hooks, hf-readme, use-selected-model-metadata, env.ts,
use-hf-dataset-splits, hub-token-header and the picker contract to upstream.
The proxy-served flags come out of network.ts, so shouldPreferLocalCache and
useBackendHubOnline go back to isHuggingFaceOffline and useOnlineStatus.

The "http" failure kind goes with them: hub-transport was its only producer, so
keeping it would leave a branch in the panel that nothing can reach.
hf-readme keeps its service: "other" tag, which belongs to the panel half - a
filter can block /raw alone, and the card's failure must not name the catalog.

* Keep a repo lookup from speaking for the listing, and stop retrying our own recovery

Two findings from the round on the reduced diff.

cachedModelInfo runs in parallel with listModels and went through makeHfFetch,
which left it on the feed's own key. Its response, a 404 included, then called
markRemoteNetworkOnline and deleted the listing's failure and backoff: the panel
lost the classified cause and the phase read available while the listing was
still blocked, which is the generic-panel bug arriving by another door. A repo
lookup is not the listing, so it is tagged "other" like the card and the avatar.
makeSortFetch, which is what listModels is handed, keeps "discovery".

The reconnect effect refreshed the feed whenever availability was restored, but
the request that restores it is usually the feed's own retry. That fired a second
retrySearch, discarding the results that had just arrived and re-issuing the same
call. It now tracks whether this feed was the one probing and only refreshes when
another surface proved the Hub reachable. The announcement is unconditional.

* Give the repo lookup a key nothing gates on

Tagging cachedModelInfo "other" stopped it retiring the listing's diagnosis but
handed it the asset clients instead: a 15s timeout on the pinned-publisher
lookup blanked every card and avatar for 30s, over a request whose rejection
mergedModelIterator catches and nobody waits on.

It gets "info" of its own. Retry still sweeps it, since a window no reset can
touch would sit out its full TTL and keep delaying the wake timer, but the
origin-wide reachability question reads GATING_SERVICES and skips it: a lookup
no client is waiting on must not answer "can this browser reach the Hub".

* Cut this back to the reported bug

The proxy is out for good, and so is everything that only existed to keep it
honest. What is left is the two defects behind the report.

Dropped: the securitypolicyviolation listener and the "csp-blocked" kind, the
per-feed service keying and every gate built on it, the Load-more-while-probing
work, and the changes to the repo card, avatars, dataset sizes, dataset splits
and the model picker. Those files are back at upstream.

One consequence, stated rather than papered over: with a single window per
origin, a failed avatar or repo-card fetch can put a cause on the catalog panel
that came from an asset request. That same event renders "You're offline" today,
so it is not a regression, and the panel is still the more useful of the two.

* Keep a way back from every state the probing phase can leave you in

Making a lapsed backoff mean "probing" fixed the flapping, but "probing" only
clears when a listing succeeds, and a failed page leaves a closed generator
behind. Three things were stranded by that.

The selected model's metadata lookup and the cached feed each issue their own
request, and hub-page was gating both on the discovery phase. Neither can make a
listing succeed, and the Downloaded tab has no Retry, so metadata for an
on-device model never loaded. They are back on browser reachability, which is
what they actually ask about; the panel still reads the classified cause.

Load more stayed on screen after a failed page, since hasMore is deliberately
kept, but called a fetchMore that returned false forever. It now restarts the
feed rather than resuming a generator that is finished. Allowed while probing,
which is exactly when the next page should test the network, and never while the
backoff is live, so only the explicit Retry clears a window.

A cached feed substituted after a failed refresh rendered rows with hasMore
false, which skipped the footer and the panel alike: once the toast went there
was nothing saying the results were stale and nothing left to click. The footer
now survives an error and offers Try again.

* Let the backoff hold again, now that disabling no longer erases the cause

Ungating the search hook is what let the error reach the panel, but it also
meant a changed query, sort or channel built a new iterator and fired straight
away. Typing through an outage issued a request per debounce tick, each failing
and re-arming the 30s window, so it never elapsed. Automatic searches are gated
on the live backoff again, which is safe now only because the disabled path
stopped clearing `error`. Gated on "unavailable" alone, never on `online`: a
lapsed window has to be allowed to probe, and reaching "available" requires a
listing to have already succeeded.

The retained footer had the same shape of problem from the other direction. A
failed avatar or repo card marks the same origin, so the listing keeps its rows
and records no error of its own, and useHubInfiniteScroll is gated on `online`:
the Load more button rendered enabled and did nothing for the whole window. It
now offers a re-probe whenever it cannot fetch, not just after a failed page.

* Show the outage, and its cause, on the footer that outlives the toast

Two gaps in the retained footer from the last round.

The `failed` prop was reached only when `hasMore` or a `searchError` already put
the footer on screen. With pagination exhausted and the outage coming from an
avatar or repo card, neither holds, so there was no notice and no control at
all. `!online` joins the render condition, not just the prop.

And the footer reduced everything to "These results may be out of date". This is
the persistent surface once the toast closes, so that threw away the classified
cause, which is the thing this change exists to keep. It now shows the sanitized
failure text, with the generic line only as a fallback.

* studio: keep the outage notice, a bad row, and paused dataset rows from stranding recovery

The footer keyed on the 30s backoff TTL, which lapses on a timer with nothing
proven, so the notice and its Retry vanished while the phase was still probing.
Key it on the recorded cause, which only a successful request clears.

pullBatch called mapItem outside any guard, so a malformed row reached the catch
that marks the iterator dead. The item was already consumed and the generator
still usable, and every restart hit the same row again. A throw now skips the
row, like the null the mapper already returns for one.

useHubDatasetSearch's enabled also empties its results memo, so gating it on the
backoff blanked every rendered dataset row for the window. Split the two: enabled
still means the tab is showing, and a new paused holds only the request.

* studio: back off on connectivity failures only, not on any timeout

The avatar, README and dataset-size fetches all run a 10s timeout against
huggingface.co. Treating a timeout as evidence the origin is down meant one slow
optional endpoint armed the 30s window, which paused discovery and disabled the
metadata and download controls while the API itself was reachable. Timeouts are
per-request, so the caller keeps the classified failure and can retry at once;
only an opaque network error still backs the origin off.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
…thai#8022)

Both pass on a GPU-less CI runner with no Studio running, and fail on a developer box that
has either. Neither is testing the machine.

test_a_worker_spawned_during_the_gpu_init_retry_does_not_inherit_the_override asserts the shim
makes two import attempts, the second under UNSLOTH_ZOO_DISABLE_GPU_INIT. df5f139 gated that
retry on _gpu_present(), because the flag makes unsloth_zoo stub triton and bitsandbytes for the
whole process and that would turn a healthy GPU into 500s. So on a machine with an accelerator
there is one attempt, not two. Its two neighbours in the same file already pin _gpu_present for
exactly this reason; this one was missed.

test_a_corrupt_pid_file_does_not_abort_shutdown ends by asserting _remove_pid_file unlinks a
record holding its own PID. _legacy_heir scans the real Studio root and hands studio.pid to a
live sibling instead of deleting it, so with any server running on the machine the file is
rewritten and the assertion fails. Pinned to no heir, which is the case that assertion is about.

The handoff had no coverage of its own, so it has one now: the branch that broke the test above
is worth pinning rather than only working around.
…ic message (unslothai#8023)

* Do not let the default tool policy reject every plain Anthropic message

`unsloth studio run` resolves the server-side tool policy to on unless --disable-tools
(resolve_tool_policy: "tools default on for every bind", ce193c2). The permission gate added
in unslothai#7079 read that resolved policy as "this request selected server tools", so for an ordinary
tool-free POST /v1/messages it collected the whole catalog, found terminal in it, saw no
permission_mode, and returned 400. Every plain Anthropic chat request against a default server
answered:

    permission_mode 'ask' has no confirmation channel for Anthropic Messages server tools

A process-wide default is not a per-request selection. The gate now fires on an explicit ask
only, enable_tools/mcp_enabled or an Anthropic server-tool type in `tools`, and --disable-tools
still vetoes both. Everything the gate rejected because the request asked for something it
cannot confirm still rejects: enable_tools with ask or an omitted mode, a bare terminal/python
tool type, render_html, and ask for a safe-only selection.

Nothing caught it because the four e2e cases that exercise this path live in
tests/test_studio_api.py, which studio-backend-ci.yml ignores: they need a live model and a
2 GB GGUF download.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Route on the same predicate the permission gate uses

Lifting the gate off the process default fixed the rejection but not its twin: the tool
routing below decides server-tool mode from `_effective_enable_tools(payload)` too, so a
tool-free request on a default server still entered the local tool loop with the full
catalog, python/terminal/render_html included, and confirm_tool_calls unset. That is the
execution this channel has no way to confirm, which is what the gate existed to stop.

Deciding "did this request select server tools" twice is what let the two disagree, so both
now call `_anthropic_selects_server_tools`. A tool-free request takes the plain chat path,
an explicit enable_tools/mcp_enabled/server-tool type still routes to the loop under a mode
that permits it, and --disable-tools or enable_tools=false still vetoes.

* Drop mcp_enabled as a Messages-channel ask, and say where the CLI flag stops

AnthropicMessagesRequest is extra="allow", so `mcp_enabled: true` really does arrive and
pydantic serves it through __getattr__: reading it as intent routed such a request into a
loop holding ALL_TOOLS' terminal/python and not one MCP tool, since nothing on this route
loads MCP schemas. It is an ask on the OpenAI routes because those wire MCP discovery.
Before this branch it did nothing here, so dropping it restores that.

The CLI help and the tool_policy docstring said --enable-tools forces tools on for every
request. On /v1/messages it no longer does, deliberately: that channel has no confirmation
prompt, so the on direction has to come from the request. The off direction still applies
everywhere. Documented rather than left to be discovered.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
* Fix desktop window chrome

* Sync native window theme

* Match restore window icon

* Use restore glyph for maximize

* Shift mac fullscreen navigation

* Simplify mac fullscreen tracking

* Avoid mac titlebar overlap

* Remove mac fullscreen nav lag

* Differentiate maximize and restore

* Address desktop theme review

* Polish desktop update screen
…nslothai#8024)

Follow-up to the Mac consolidation, applying the resolution that came out of
reviewing the equivalent Windows change in unslothai#8013.

The installer carried an explicit 'if: ${{ !cancelled() }}' with a comment
explaining why: phase 1's environment and model cache ran before it, so under
the implicit success() a phase-1 GGUF download failure would skip the install,
skip assert-llama with it, and take phases 2 and 3 down. The gate bought that
independence, but at a price the comment did not mention: a failed setup-node
or setup-python no longer stops anything, the installer runs on a runner that
never got its pinned toolchain, assert-llama passes, and all three phases run
and fail somewhere unrelated.

Moving phase 1's block below the shared preamble is better than either gate,
because it makes the two failure classes structural rather than conditional.
Everything above the block is genuinely shared, everything below it belongs to
phase 1, and the installer can go back to the implicit success().

Phases 2 and 3 also gated every step on assert-llama alone, so a failed
download or a server that never came up still ran the test against it. Each
phase now chains on its own prerequisites, keeping assert-llama as the first
term so cross-phase independence is unchanged. Phase 3 additionally gates on
its SDK install, which only it needs.

Verified no coverage moved: every 'run:' body in the file is byte-identical
across the change, 24 before and 24 after, none lost and none added.
Twenty-one steps across eight workflows ran the same five-line body, varying
only in port, log filename and the name of the environment variable the pid
lands in. .github/scripts/boot-studio-api-only.sh takes those three as flags.

Three parts of that body are easy to get subtly wrong, which is the argument
for one definition rather than twenty-one:

  rm -rf, not `reset-password`. The boot only re-seeds a fresh
  .bootstrap_password when the auth directory is absent, so a caller that
  resets keeps the old password and the test authenticates against stale state.

  The pid has to reach $GITHUB_ENV, because the step that stops the server is a
  different step with a different shell.

  Both streams go to the log. The server writes startup diagnostics to stderr,
  so a redirect without 2>&1 leaves an empty log on exactly the failure someone
  needs it for.

Not folded into serve-unsloth-run.sh, despite the plan saying so. That script
boots `unsloth run --disable-tools` and its body is banner-key parsing and
/v1/models resolution; these boot `unsloth studio --api-only` with auth wiped
and no banner. The two share the word boot and nothing else, and each header
now says which is which.

Deliberately does not wait for health: the callers' waits differ, some polling
/api/health and stopping while others go on to rotate the password and load a
model in the same step.

Left alone: three boots inside Playwright retry loops, which re-boot mid-loop
and reassign the pid in the running shell, and three boot-briefly-and-kill
steps that keep the pid in a local variable rather than $GITHUB_ENV.

Each caller's paths filter gains the script, so an edit to it re-runs the
workflows that call it -- the trap unslothai#8015 hit when the install body moved out
from under those filters.
…othai#7547 pins (unslothai#8026)

* Fix the desktop clean-machine CI: asset patterns and the retired unslothai#7547 pins

The nightly has been red on main since 2026-08-05, all six legs, for two
unrelated reasons.

macOS and Windows died at the download with 'no assets match the file
pattern'. The patterns were Tauri's default bundle names, '*aarch64.dmg' and
'*setup.exe'. The release pipeline moved to its own scheme at
desktop-v0.1.512-beta, so the assets are now Unsloth-Desktop-<ver>-MacOS.dmg
and Unsloth-Desktop-<ver>-Windows.exe. The last green run, on 2026-08-04,
resolved desktop-v0.1.50-beta and downloaded
Unsloth.Studio.Desktop._0.1.50-beta_aarch64.dmg, which is the last release that
carried the old names. Matching on the extension instead removes the coupling
to a naming scheme; a release ships exactly one .dmg and one .exe, and the
arm64 assertion further down is what actually checks the architecture.

Linux died on its own tripwire, which fired exactly as designed:

  the bundled install.sh now carries unslothai#7547; delete this pin block and let the
  venv + torch assertions below run unconditionally

Both outcome pins are gone. macOS no longer accepts exit 1 plus the Xcode CLT
gate line, Linux no longer accepts exit 2 plus the NEED_SUDO optional set, and
all three legs now require the installer to exit 0, leave a venv and import
torch -- the assertion Windows already made.

* Let the early-exit branch actually print its diagnostic

The launch steps run under `bash -e`, so `wait "$APP_PID"` returning non-zero
aborted the step on that line and neither the ::error:: annotation nor the
tail of app-stdout.log ever printed. The failure surfaced as a bare 'Process
completed with exit code 1' with no annotation and no app output, which is
precisely the information the branch exists to produce.

Found while validating this PR on staging: with the download and pin fixes in
place the Linux legs reach the launch step for the first time, it fails, and
the log said nothing about why.

* Require a ready disposition on macOS and Linux, and unpin the dispatch default

Two things the pin retirement left behind.

The dispatch default for release_tag was desktop-v0.1.50-beta, a bundle that
predates unslothai#7547. With the outcome pins gone a manual dispatch that took the
default would fail all four POSIX legs at the installer step, on a bundle
nobody meant to test. Empty instead, which falls through to the same
newest-desktop-v* resolution the schedule already uses.

The ready-disposition assertion was Windows-only, and the reason given for
that was the install root. The source says otherwise: preflight/managed.rs
env_removes UNSLOTH_STUDIO_HOME and STUDIO_HOME unconditionally, not under a
cfg(windows), with a comment saying Tauri uses the legacy root regardless. So
all three platforms read the same root and the asymmetry was unjustified.

It also mattered more once the pins went: a post-unslothai#7547 bundle can install a
working venv and still have preflight regress to NotInstalled, and the app
then sits on the Install screen -- alive, log written, a disposition recorded,
and nothing it just built recognised. macOS and Linux accepted that. All four
staging legs record ManagedReady today, so this tightens the bar without
moving any leg from green to red.
* Desktop: center sheet header close buttons

* Studio: keep the centred sheet close buttons clear of the desktop window controls

The two sheets start at the top of the viewport, so on Windows and Linux their
header sits under the custom titlebar and its window-control toolbar, which
paint above at z-70/z-80. Centring the close button on the title row moves it
further into that band.

Offset both sheets below the titlebar. The variable is set on the wrapper div,
which portalled content cannot see, so mirror the titlebar heights onto <html>
as well. Resolves to 0px in the browser and on macOS, which use native chrome.

* Tidy comment wording for PR unslothai#7957

---------

Co-authored-by: danielhanchen <[email protected]>
* refactor(studio): make cloudflare tunnels runtime-managed

* feat(studio): add public access controls

* fix(studio): preserve public stop responses

* feat(studio): show public access settings

* fix(studio): report settings-managed public links

* fix(studio): respect launch tunnel ownership

* fix(studio): apply public runtime trust policy

* refactor(studio): rename public access to remote access

* feat(studio): serve web ui through desktop remote access

* feat(studio): set the remote password from desktop

The desktop app signs in with a local secret and never sees the seeded administrator password, which is only printed to a terminal. Remote access refuses to open a tunnel while that seeded password is still in place, so a desktop user had no way forward: the change-password flow needs a current password they do not have, and the General tab hides its password row on desktop.

Add a Remote password row to the Remote access section, desktop only. While the seeded password is pending it sets the first password through a new POST /api/auth/desktop-initial-password; once a password exists the same row changes it through the existing endpoint. The new route accepts only a desktop-issued JWT (web sessions and API keys are refused), applies only while the seeded credential is unchanged, and binds its write to the credential version it read so a concurrent web change or CLI reset is not overwritten.

Both password routes now keep the local desktop credential valid and mint desktop-flagged tokens when the caller is the desktop app, so auto-auth stays passwordless and the session survives the change it made. Browser callers keep their existing behavior: the credential is revoked and ordinary tokens are issued.

Remote access status reports password_pending on its own, independent of block precedence, so the row is correct even when another block hides the reason. Re-reading status after either operation clears the pending-password block and lets the tunnel start; remote browsers then sign in as unsloth with the new password.

The action reuses the account password dialog in an initial-password mode rather than adding a component, and adds no file.

* feat(studio): redesign remote access settings as a status card

The remote access controls rendered as flat settings rows, so the
feature read as hidden and the tunnel URL was squeezed into a
description cell. Rebuild remote-access-section.tsx as a bordered card:

- header with globe icon, title, live status dot plus state text and
  the start/stop action together
- online state gets a dedicated URL panel with a copy button, a QR
  button that opens a scannable code for phones (react-qr-code, svg,
  zero deps), and a note that the URL plus remote password grants
  sign in
- block reasons and tunnel errors render as their own strip,
  destructive styling on error
- shine sweep on the status text while starting or stopping
- password and auto start rows move below a divider inside the card

Polling and start/stop/auto-start logic are unchanged.

* fix(studio): stop tunnel dns wait from stalling on negative caches

Starting remote access took 45-48s while a manual tunnel came online in
about 8s. _wait_for_dns queried DoH immediately after the edge
connection registered, before the fresh trycloudflare hostname
propagated, and the resolver negative-cached the NXDOMAIN
(trycloudflare.com publishes a 1800s SOA negative TTL; 1.1.1.1 was
observed serving the stale negative for about 40s while the loop
re-asked it every 2s).

- delay the first lookup 3s so it cannot seed those negative caches
- ask two independent resolvers per round (cloudflare and google DoH)
- cap the dns wait at 20s so it can never starve the health probe,
  which is what actually gates advertising the URL

Start to online now measures about 12s end to end against a live
backend. The consecutive-error bailout for blocked DoH is unchanged.

* fix(studio): drop stale stopping status after a finished stop

A stop worker outlives its completed stop by up to about a second while
draining stop responses. During that window remote_access_status kept
reporting state stopping and forced can_start false, so a quick
stop-then-start flashed "Stopping" in the UI and the start request
could 409 as operation_in_progress.

Once the tunnel controller reports off with no pending stop handle the
stop is done, so a still-alive stop worker no longer masks the idle
state or a newly admitted start. Unconfirmed terminations
(stop_pending) keep reporting stopping so retry stays visible.

* fix(studio): resolve the tunnel hostname through one resolver

Asking a second DoH resolver in the same round cannot rescue the poll: both queries land milliseconds apart, so the round that seeds one resolver's negative cache seeds the other's too. It also disclosed the freshly issued hostname to a third party on nearly every start, where the provider that handed the name out already knows it.

The hold-off and the wait cap stay, which is where the measured speedup comes from. The cap trades one case away: a hostname that only propagates after 20s now meets the OS resolver while it is still missing, and because the tunnel has registered by then a failed probe ends the attempt instead of retrying over http2. In exchange every start whose record exists by 20s spends the rest of the deadline on probe attempts rather than a single one at 45s.

* fix(studio): report a stop only while its teardown is outstanding

A stop worker outlives the teardown it performed, so reporting stopping until that thread exits hid the tunnel already being off and refused a start that would have succeeded. The worker's recorded admission sits behind the control token once its teardown advanced the generation, but a start advances the generation the same way, so only that advance together with an off tunnel and no pending stop shows the teardown actually happened.

* fix(studio): keep the remote access card legible

The status text goes back to full opacity. The shimmer needs partly transparent glyphs, which put the transitional states below the contrast that same text had before, and a viewer who asked for reduced motion paid that cost with no sweep to show for it. The status dot already marks the transition.

The auto-start switch's accessible name matches its visible label again after the rename, and the block reason no longer borrows the error colour when a failed tunnel is not what it is reporting. Moving the URL panel and the block-reason strip out of the section body keeps the section at the complexity it had before the card, and SettingsRow drops labelAccessory along with the row that used it.

* perf(studio): verify a new tunnel at the edge instead of through DNS

Cloudflare routes quick tunnels by TLS SNI, so the edge serves a tunnel as soon as its connection registers, before the hostname resolves anywhere. Probing an edge address with the tunnel's name in SNI and Host takes that hostname's DNS off the startup path, along with the wait that existed only to keep an early lookup from caching the miss.

Measured over four fresh tunnels each: verification after registration falls from 10.97s to 6.61s on average, and a whole start from 22.9s to 16.8s. It also removes the case behind the slowest starts, where one DoH query sent before the record propagates is negative-cached, blinding the poll until its own cap expires and pushing a start past 30s.

The hostname path stays as the fallback for networks that block direct addresses or intercept TLS. It is entered as soon as the edge looks unreachable rather than merely unready: an error 1033 page is an answer, a failed connection is not.

* fix(studio): bound the edge probe and dial distinct frontends

Verifying a quick tunnel at Cloudflare's edge shipped with two defects. The wait checked the clock only after trying every address, so a full pass always ran: verify_public_url with a 0.05s timeout still took 12s, against 1.65s before the edge probe existed, and a pass of two real TLS handshakes overshot the 15s cap to about 19s, taken out of the hostname fallback's share of the same deadline. The clock is now read before every attempt, and no attempt is given more time than the deadline leaves.

The addresses were also not distinct. macOS reports the A records again as IPv4-mapped under AF_INET6, so taking one per family dialled a single frontend twice, as 104.16.230.132 and ::ffff:104.16.230.132. That doubled the cost of a pass, halved the poll rate, and let two dependent samples of one address exhaust the unreachable counter. Deduplicating by frontend yields 104.16.230.132 and 104.16.231.132 here.

An intercepting proxy answering with its own page is an answer rather than an unreachable edge, so it resets that counter exactly as error 1033 does and the wait ends at the cap instead. The comments claimed interception left through the early exit; they now describe what it does.

* fix(studio): clear the python floor, read encoding and locale parity gates

The tunnel test annotated a helper with `str | None`, which evaluates on the 3.9 floor that pyproject declares and pushed the studio union ratchet from 35 files to 36. Six new test reads took the platform default encoding, so they break on Windows the moment those files gain a non-ASCII byte. The remote password dialog's six new strings existed only in en, which strict locale parity rejects; they are now translated into every overlay.

* Fix settings-managed tunnels dying on Linux, and stop-during-retry orphans for PR unslothai#7875

PR_SET_PDEATHSIG is a parent-THREAD death signal, not parent-process: the kernel
fires it when the thread that forked the child exits. start_remote_access forks
cloudflared from a short-lived worker thread, so the connector was SIGTERMed
about a second after it came online, every time. Reproduced 3/3 on a real
install: the URL is logged, then state goes to error with "cloudflared exited".
Auto-start shares the same worker, so it was affected too.

Only Linux and WSL are hit. macOS arms no per-thread signal and Windows uses a
process-wide Job Object, so both were fine, as was the launch path, which forks
from the main thread.

Changes:

- process_lifetime: spawn_on_lifetime_thread() performs the fork on one
  process-lifetime daemon thread, so PDEATHSIG means "die with the parent
  process" again. Non-Linux spawns directly. Falls back to an inline spawn when
  no helper thread can be obtained, so it can never block.
- cloudflare_tunnel: spawn through that helper. The abort branch now tears the
  connector down instead of returning the URL of a process it just detached,
  which could leave a live public tunnel no later stop_studio_tunnel() could
  reach. Restore _tunnel_state to "starting" after attempt 1's teardown so the
  http2 retry no longer advertises "stopping", which made stop_studio_tunnel()
  early-return and stop nothing, and made the Settings Stop route a no-op.
- run.py: an explicit --cloudflare/--no-cloudflare/--secure on this invocation
  now beats an inherited _UNSLOTH_CLOUDFLARE_INTENT, so a stale export, Docker
  ENV or systemd Environment= cannot re-enable a tunnel the user opted out of.
  The marker still softens the compatibility --no-cloudflare into "unset".
- Add tests for remote-access-state.ts, which had no coverage. No bugs found
  there; the logic is correct, it simply was not exercised.

Verified: 701 passed in the focused backend slice (the one failure is a
pre-existing missing optional dep, and fails on main too), 347 frontend tests,
typecheck, biome and 80 simulation tests including a real-child-process tunnel
lifecycle and Chromium/Firefox/WebKit CORS runs.

* Surface the unstoppable-connector error, bound the Stop wait, unlatch polling for PR unslothai#7875

Follow-ups from reviewing the remote access flow on Linux. The tunnel lifetime
fix landed already; these are the smaller things around it.

- remote_access_status collapsed "cloudflared could not be stopped" into the
  generic "Cloudflare tunnel failed". That is the one error the user can act on:
  the connector's exit was never confirmed, so it still holds the runtime slot
  and Start stays disabled. Pass it through like the other known messages.

- The Stop worker waited on a live start worker with no deadline, polling at
  100 Hz. A start that never claims settings ownership (foreign owner, or one
  that bailed on admission) deferred the user's Stop for the full probe
  deadline, up to about 170s. Bound it at 5s and poll at 50 Hz.

- setPollEnabled(false) had no path back to true. It fires when you stop a
  tunnel from a browser connected through that tunnel, which is correct, but
  the section then stayed dark until it unmounted. Resume on any later action
  or on a password-change refresh, since both prove the origin is reachable.

- test_change_password_policy called change_password positionally, so the new
  is_desktop parameter defaulted to the Depends object, which is truthy. Harmless
  today because the assertions fire earlier, but it silently exercises the
  preserve-desktop-secret branch. Pass False explicitly.

Verified: 230 passed in the focused backend slice, 347 frontend tests, typecheck,
build, locale parity, and no new biome warnings. Re-checked on a real install:
auto-start brought a tunnel up at boot and it stayed online, and Stop through
that tunnel returned 200 in 0.07s. The one backend failure
(test_health_response_reports_desktop_capability_fields) is a pre-existing
environment gap and fails on main too.

* Correct streaming_supported, shorten the CORS preflight window, guard the spawner across fork for PR unslothai#7875

Findings from simulating the remote access paths across platforms, browsers and
upgrade scenarios. Three small fixes, each measured rather than reasoned.

- streaming_supported was a hardcoded True. Every tunnel Studio opens is a
  Cloudflare Quick Tunnel, and Cloudflare documents that Quick Tunnels do not
  support Server-Sent Events. Measured against a real tunnel: a local SSE
  endpoint delivers 6 events over a 5.0s spread, and the same endpoint through
  the tunnel answers 200 with text/event-stream and then delivers nothing at all
  before the read times out. Chunked non-SSE streaming was blackholed the same
  way, so no transport change works around it. The field now reports whether a
  tunnel is currently carrying the traffic, so it is true locally and false while
  a tunnel is live. Nothing branches on it yet, which is exactly why it should be
  right before something does.

- The CORS middleware inherited Starlette's 600s Access-Control-Max-Age.
  is_allowed_origin closes the instant the tunnel URL clears, but a preflight the
  browser already cached does not. Measured across four engines: after remote
  access was stopped, WebKit reused its cached preflight and the state-changing
  POST still reached the server, while Chromium, Firefox and Edge re-preflighted
  and were refused. Pinning max_age to 60 keeps preflight caching useful and
  makes revocation nearly as immediate as every other trust signal here.

- spawn_on_lifetime_thread keeps a module-level lock and a helper thread. A fork
  child inherits the lock in whatever state it was in, and a spawner whose thread
  does not exist in the child. Reproduced: forking while the lock is held
  deadlocks the child permanently. Not reachable today, since the backend only
  uses the spawn start method and the one fork start method lives in the training
  worker, which never imports the tunnel. Registering an at-fork reset is three
  lines and closes the class of bug rather than the instance.

Also verified and unchanged: no schema change in any store, so an old studio.db
with no remote_access_auto_start row reads as false and fail-closed on corrupt or
non-boolean values; the argument parser is byte-identical to main, so no launch
flag default moved; the PR touches no hardware, GPU or desktop files, and all
twelve OS x accelerator combinations produce an identical remote-access status.
Host and Origin are forbidden request headers in all four engines, so no page
script can forge the Cloudflare provenance gate.

Verified: 95 simulation cases, 41 adversarial cases, 109 in the directly affected
backend slice, 347 frontend tests, typecheck, build and locale parity. On a real
install: auto-start brought a tunnel up at boot and it stayed online, Stop through
that tunnel returned 200 in 0.09s, and the live status now reports max-age 60 and
streaming_supported false.

* Keep the desktop backend up without a dist, and settle self-origin Stop on off for PR unslothai#7875

The desktop spawns "studio --api-only" with no --frontend, and install.sh
--tauri skips the frontend build outright. The new desktop-owned branch made
_serve_frontend true for that launch, so an unresolvable studio/frontend/dist
raised SystemExit before TAURI_PORT was emitted and the app never got a
backend. The SPA only backs the optional remote web UI there, so warn and
carry on API-only; a web UI launch still aborts loudly.

A Stop sent from the tunnel's own origin is answered with a terminal off, then
polling restarts in perform()'s finally and the first poll can still land
inside the ~50ms teardown drain, where the backend reports "stopping". That
overwrote the terminal off, cloudflared then exited, and the card latched on a
permanent "Stopping" for a tunnel that was already down. Teardown frames no
longer overwrite it, while a poll that can still stop the connector proves
teardown was abandoned and takes the card back over.

---------

Co-authored-by: Maheswar Kumar <[email protected]>
Co-authored-by: danielhanchen <[email protected]>
* Add opt-in DSpark speculative decoding

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix lint blockers, retry-guard test and DSpark broken-build gate for PR unslothai#7968

Three fixes for the failing CI on this branch:

- Drop the unused `Literal` import from unsloth_cli/commands/chat.py and
  inference.py. The options are typed with `SpeculativeType`, so the added
  import was a leftover and tripped the import-hoist blocker.

- Make test_the_startup_retry_drops_the_mtp_the_extras_and_the_env_carry
  whitespace insensitive. The guard now names both drafters, so formatting
  wrapped the call and the literal substring assertion no longer matched.
  It asserts on both `_extra_args_requests_mtp` and
  `_extra_args_requests_dspark` now, so the DSpark half is covered too.

- Gate DSpark on the whole broken build window instead of one tag. The
  reshape regression is ggml-org/llama.cpp#26531 and the fix is #26577, so
  every prebuilt based on b10259 through b10268 aborts on a DSpark load,
  not only b10265-mix-89aa77b. Matching the base build number keeps source
  builds unaffected, since those carry no install marker.

* Probe DSpark support before downloading the sidecar

The ~11 GB DSpark sidecar was fetched at llama_cpp.py:8664 while the first
supports_dspark consumer sat ~480 lines later, so a binary that cannot run
draft-dspark paid for the whole download and then fell back without ever
opening the file. probe_server_capabilities is already called just above for
supports_kv_unified, so the answer is in scope and cached and the check costs
nothing.

This is the default path right now, not an edge case: the shipped
unslothai/llama.cpp prebuilt b10265-mix-89aa77b sits inside the known-broken
b10259..b10268 window, so supports_dspark is False on a standard install.

Also swaps the order of the first two DSpark fallbacks. Now that the fetch is
gated on the same answer, a gated binary leaves no sidecar, and checking the
drafter first reported "no matching dspark-*.gguf sidecar was found" and told
the user to place a file that was never the problem, while re-loading on every
Apply through the drafter_not_found dedup branch.

Adds three regression tests, all of which fail without this change.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Enforce fixed fit for pass-through DSpark, size split sidecars, correct the hint

Three fixes from the latest review round.

Extras that own --spec-type return from _build_speculative_flags before
_speculative_type is set, so the --fit strip keyed only on that field never
fired for a pass-through DSpark launch and a user --fit on survived. DSpark's
layout cannot be reshaped, so that aborts the load. The strip now also reads
the accumulated spec types, which covers both the flag and the env.

The training coexistence estimate sized the drafter with a bare stat(), while
the main weight beside it already used the split-aware helper. Discovery hands
back shard 1, so a split sidecar was counted at one shard and the guard could
admit a load that evicts the training run it exists to protect.

The Speculative Decoding hint promised "no accuracy hit" unconditionally, which
DSpark does not meet: on a quantized target its greedy output can differ from a
non speculative run (ggml-org/llama.cpp#25618). Measured here on
DeepSeek-V4-Flash-0731 UD-Q4_K_XL, where the same greedy conversation produced
10570 tokens without a drafter and 14687 with one. The claim now stays with
Auto, and DSpark carries its own caveat.

Both backend fixes have regression tests that fail without them.

* Pin fit off for pass-through DSpark, keep cached sidecars visible, reclaim them on delete

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Allow DSpark under --fit on: fitting only skips the sidecar reserve

* Gate the training-guard DSpark estimate on binary support, fix the picker contract marker

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Default Auto to DSpark when a sidecar is available, and stop the two reload loops it exposed

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Charge no drafter when forced DSpark is gated off by the binary

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Gate remote Auto DSpark sizing, retry only a failed sidecar fetch, refresh the Auto hint

* Apply ruff kwarg-spacing formatting

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
* fix studio responsiveness across desktop and mobile web

Dialogs had no height limit, so any dialog taller than the window clipped its
actions off screen with no way to scroll to them. DialogContent and
AlertDialogContent now cap at the viewport and scroll; call sites that manage
their own height still override both, since tailwind-merge treats a later
overflow-* as conflicting with the base overflow-y-auto.

On desktop the custom titlebar paints at z-70 over body-portaled dialogs, and
the chrome CSS variables live inline on a wrapper div that portaled content
never inherits from. A new WindowChromeTopInsetEffect publishes the titlebar
height on <html> as --studio-window-chrome-top, and dialogs subtract it from
their max height and centre below it. Web leaves the variable unset, so it
falls back to 0px.

The Images, Video and diffusion training panes docked a fixed 400-416px left
column inside an overflow-hidden parent, which is wider than a phone and left
the canvas unreachable. All three stack below 768px and keep their existing
classes from md: up. Onboarding centred a 620-660px card inside an
overflow-hidden container, so at the 900x600 minimum window the footer was cut
off and unreachable; the container scrolls now and the card uses my-auto.

Also in this change: 19 height rules move from vh to dvh so panels stop sitting
under mobile browser chrome; dialogs go full screen below 640px instead of
floating on a sliver of backdrop, with the close button fixed so it survives
scrolling; confirms stay centred cards but take the available width; seven
two-column grids stack on phones; the eight window resize strips get
pointer-events-auto, because Radix sets pointer-events none on the body while a
modal is open, which killed window resizing entirely; and top and bottom sheets
gain a height cap.

* keep viewport-sized dialog rules off container-portaled dialogs

The phone full-screen block sat in the shared base class string, so it also
applied to DialogContent with position="absolute". Recipe Studio portals its
config, import, processors and preview dialogs into a short overflow-hidden
editor container; there max-sm:h-dvh ran past the container and
max-sm:max-h-none dropped the callers' own max-h-[650px], clipping the lower
form controls. The full-screen and titlebar-offset rules now live in the fixed
branch only, and the close button keeps its absolute corner when the dialog is
container-portaled.

* bound the onboarding scroll container so it can actually scroll

The container only had min-height, so it grew to fit the card and
overflow-y-auto never created a scrollport. At the 900x600 minimum window the
md:min-h-[620px] card plus padding still overflowed the h-dvh overflow-hidden
chrome wrapper, leaving Continue clipped. It now takes the height that main
already pads for: __root.tsx redefines --studio-titlebar-height to the
hidden-route inset, so 100dvh minus that variable is exactly the area below the
titlebar.

* Keep the phone close button fixed and let a resize drag survive an open dialog

Three fixes on top of the responsiveness work, all verified in Chromium.

max-sm:translate-x-0/translate-y-0 compiles to `translate: 0px`, which is not
`none`, so the dialog stayed a containing block and the close button's
max-sm:fixed behaved like absolute inside the new scrollport: it moved the full
200px of a 200px scroll at 320, 390 and 639 wide. max-sm:translate-none drops
the containing block and the button now moves 0px, with the dialog box and
horizontal overflow unchanged.

The eight resize strips stopped propagation on mousedown, but Radix dismisses
modals on pointerdown, which fires first. Grabbing a window edge with a dialog
open started the resize and closed the dialog underneath it. Moving the handler
to onPointerDown keeps the resize and leaves the dialog open.

Below md the settings rail is no longer a scrollport, so pb-20 rendered as 80px
of blank space above the divider; it is now pb-6 with md:pb-20. On the same
containers an unset overflow-x computes to auto next to overflow-y-auto, so a
wide row could pan the whole page sideways on touch; overflow-x-hidden pins it.
md:overflow-hidden still wins from md up, so desktop is unchanged.

typecheck, 472/472 tests, i18n parity and build all pass.

* Keep phone-width dialogs below the desktop titlebar

The max-sm branch set top-0/h-dvh, dropping the --studio-window-chrome-top inset
the same class string had just applied, so a full-screen dialog rendered under the
z-70 titlebar. That breakpoint is reachable on desktop: MIN_WINDOW_WIDTH is 900
logical px while max-sm is a CSS-px query, and the two diverge under Windows text
scaling, which navbar.tsx:41-42 already accounts for.

It now starts at the inset and takes the remaining height. The variable is only
ever set inside TauriWrapper, so on web it resolves to 0px and the geometry is
byte-identical to before.

Measured in Chromium, Firefox and WebKit at 320x568, 390x844 and 639x600:
web unchanged (top 0, full height); with the inset at 34px the dialog moves to
top 34 with height reduced by 34. Close button drift stays 0px and no viewport
gains horizontal overflow. Primary action reachable in 144/144 probes.

* Restore mobile action clearance and chrome offsets for PR unslothai#8016

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…nslothai#8007)

* feat(studio): add isServedByMlx for MLX-only settings

Whether MLX will serve a model is not the same question as whether its repo name says MLX: on a Mac with a working MLX stack every non-GGUF model loads through MLX, including plain safetensors repos. Callers gating MLX-only behaviour need that distinction, and `!isGguf` alone would extend it to CUDA hosts.

Exported from the feature index so other features can import it without reaching past the barrel.

* feat(studio): honor MLX KV cache quantization with a load-time eligibility probe

Adds an MLX-native `mlx_kv_bits` load setting (8 or 4) applying KV cache quantization to the text, vision and audio generation paths on Apple Silicon. MLX takes a bit width rather than a llama.cpp dtype name, so this is a separate field from `cache_type_kv` and the GGUF path is untouched. Unset leaves generation byte-identical to before.

Eligibility is probed, not predicted. At load the backend builds the cache the runtime will build, runs a single-token forward, and attempts the real `to_quantized` conversion on each top-level entry. Deriving it from config vocabulary or class attributes is unreliable in both directions: a model can declare a head dimension it does not use for the cache, a sliding window can be spelled differently between implementations, and unrecognised vocabularies would refuse models that work. It also catches the case that matters most, since a sliding-window model such as Gemma 3 mixes plain and rotating entries and quantizing it raises mid-generation only after the leading entries have already been converted. The probe restores the random stream it borrows and releases its caches, so asking about a setting neither perturbs sampling nor retains memory.

The resolved value, its eligibility and any reason or caveat cross the worker and orchestrator mirrors into the load and status responses, and join the already-loaded check so changing the setting reloads the model. A model that cannot honor the setting reports why instead of appearing to apply it, including when an mlx-lm build cannot measure a quantized entry and cross-turn prompt-cache reuse is therefore unavailable.

Measured on Apple Silicon: KV bytes fall from 645.9 MB to 343.1 MB (46.9%) over a 5,410-token prompt on Qwen3-0.6B, while Gemma 3 270M is refused with its rotating-cache reason.

* feat(studio): expose MLX KV cache quantization in the UI

Adds an "MLX Advanced Settings" section offering the KV cache quantization width (off / 8-bit / 4-bit) for models served by MLX, and plumbs it through load requests, the runtime store, per-model config and presets. The backend already honored the width; until now nothing could set it from the UI.

The section keys on the backend that will serve the model rather than the repo name: on Apple Silicon a plain safetensors repo loads through MLX too, so `!isGguf` alone would offer the control to CUDA users and miss ordinary MLX repos. Hosts whose MLX stack cannot serve — Intel Macs, a broken install, or failed hardware detection — are excluded.

The editable width and the width the backend was last asked for are kept as separate state. They diverge as soon as the user stages an edit, and a refusal applies no width at all, so neither can stand in for the other: the refusal reason is shown only beside the request it actually answers, and staging a different width retires it. Status responses adopt this state when the tab takes up a model it was not already tracking, matching the surrounding load settings; a tab that missed that moment recovers on a later poll, but only when nothing would be lost. A non-MLX response retires the verdict while keeping the width itself, which is dormant on another backend rather than wrong, so a preset survives a round-trip through a model that cannot consume it. That dormant value is excluded where a model's own config is captured, so a GGUF model never compares unequal to its own defaults over a setting it does not show.

Two response boundaries needed the new fields. `ChatPresetLoadConfig` forbids unknown keys, so a preset carrying the width would have failed the whole chat-settings write; and the llama.cpp runtime projection raises on any field it cannot resolve, which would have turned every GGUF load and status poll into a 500. A llama.cpp backend now reports the MLX fields as absent, and a test exercises the real backend class rather than a stand-in, since a permissive fake proves nothing about the shipped one.

On vision models the control discloses that prompt-cache reuse may be reduced, worded conditionally because the effect depends on the model's cache mode.

* feat(studio): widen MLX KV widths and match the GGUF settings layout

Offers every KV cache width the runtime supports rather than 8 and 4. mx.quantize accepts 2, 3, 4, 5, 6 and 8, each verified round-tripping through QuantizedKVCache rather than through mx.quantize alone, since the cache does its own packing arithmetic. mlx-lm forwards --kv-bits without imposing a domain, so the earlier pair was this code's restriction and not the runtime's. The request schema, the preset schema and the API description widen with it, so a width the control offers cannot be rejected downstream.

Renames the control to "KV Cache Dtype" and its unset option to "Auto", matching the llama.cpp control users see in the same place. MLX still takes a bit width rather than a dtype name, but the two are never visible at once, so shared vocabulary reads better than a distinction that only makes sense to someone who knows both backends.

Moves the MLX section behind the "Advanced settings" toggle and puts the chat template inside it, so both backends present the same shape: base settings, an advanced block behind the switch, then the switch. Previously the MLX controls were always visible while their llama.cpp equivalents were tucked away. The toggle row is now one component shared by both branches; it was duplicated markup, which is how the two would drift.

Shortens the tip to the length of the one beside it. The vision-model caveat it used to carry is already attached to the load response and rendered under the control, so it appears when it applies instead of in a tooltip on every model.

* feat(studio): honor a chat template override on MLX models

Lets an MLX-served model be loaded with a custom chat template, which until now only llama.cpp accepted. The frontend already sent the value for these models; nothing received it.

The override is installed onto the objects that render, once, when the model loads. Every render site reads the template at call time and the backend keeps the same objects it renders with, so one install governs the text, vision and audio paths — including audio, which bypasses the shared rendering helper entirely and would need its own plumbing otherwise.

It replaces a template that already exists and never creates one. Two different selectors decide which object renders, and both choose by whether a template is present: giving one to an object that had none moves the render somewhere else, and on the vision side to an object that never selects a template's tool-calling variant. Replacing an existing template moves neither.

Six ways it cannot be honored are reported rather than left to look like success: the runtime supplies the template as code and prefers it over the attribute; the model ships a set of named templates, which flattening to one string would strip of its tool-calling variant; nothing holds a template to replace; the template cannot be replaced at all; the override does not render, which is how a hand-edited template usually fails and would otherwise raise on every generation instead of once at load; and it stops marking where audio goes, which would leave the model advertising an input it can no longer place. Anything already replaced is put back before the reason is reported.

The audio case is judged against the native template rather than in isolation. Several model families render without consulting the audio count at all, so an absolute check would answer the same for every template and refuse an override identical to the one the model shipped with.

The template reported to clients still means the one the model shipped with. It is captured before installing, because the capability classification and the settings editor's notion of "default" both read it, and because an override that drops tool markup would otherwise turn off tool support and with it the fallback that rescues tool rendering.

The value crosses both process boundaries in both directions. The backend runs in the load subprocess and the parent rebuilds its record from an enumerated set of keys at each hop, so a value not named at both never reaches the parent — which is what the status endpoint and the reload decision read. That decision compares the requested override rather than the honored one, so a refused template does not differ from itself on every request and reload forever.

* feat(studio): let MLX models take a custom chat template from the UI

Unlocks the chat template editor for MLX-served models, inside the MLX advanced settings where the control already lives, and surfaces the reason when the backend could not take the template it was given.

The editor's read-only test was "not a GGUF model", which lumped together two different backends: MLX, which now accepts an override, and CUDA safetensors, which does not. It keys on the serving backend instead, the same test the rest of that section uses. The copy no longer says overrides are a GGUF feature, since for two of the three backends they are not.

The reason travels the same route as the KV quantization verdict, across the response type, the shared response mapper, the runtime store and the status adoption. Each of those is an enumerated list that has to name the field, which is where every repeat defect on this branch has come from, so both status branches carry it: one to set it, one to retire it when the active model changes backend. It is shown only while the editor's template still matches the one the backend answered, so staging an edit retires the old verdict rather than leaving it under a template it never described.

* fix(studio): name the serving backend's load settings in the preset hint

The Preset hint listed llama.cpp's controls unconditionally, so an MLX model was told a preset stores context length, speculative decoding and GPU layers -- none of which that backend exposes -- while omitting max seq length, which it does store.

Resolve the list against the backend actually serving the model: GGUF keeps its existing text, MLX gets max seq length and KV cache dtype, and a non-GGUF model MLX cannot serve gets max seq length alone. The names match the panel's own labels so a user can find the controls the sentence promises.

* fix(studio): preserve MLX KV state across background autoloads

VISIBLE_MODEL_RUNTIME_KEYS is the sole input to snapshotVisibleModelState, and restoreVisibleModelState spreads its output back, so a key missing from the list is neither captured before a background autoload nor restored after it. The MLX KV width and its verdict were missing, leaving the background load's values attached to the restored visible model.

* fix(studio): stop per-model load settings following onto another model

Switching to a model with no staged or remembered config snapshotted the outgoing model's MLX KV width and chat template override and sent both in the new model's load payload, so it loaded quantized to a width whose eligibility was never checked for it, under a template written against another model's tokens.

Both are re-baselined in the existing per-model reset. The payload variables only: the store keeps its values, since off MLX the width is dormant state a preset carries, neither editable control has a rollback path that restores it, and a completed load rewrites each control and its baseline from the response.

* fix(studio): surface MLX KV settings the Advanced section was hiding

Advanced settings auto-open when a model carries a non-default advanced value, but the MLX KV width was never added to that check, so reopening a model whose only non-default setting was a remembered width showed the section closed and the active lower-precision setting hidden.

Applicability is read live rather than frozen with the rest of the decision: MLX can become available after the page mounts, and a width that starts applying then has to surface without waiting for a remount. The width snapshot itself stays frozen, so editing the field cannot reopen a section the user just closed.

The eligibility reason and the note beside it were also treated as alternatives, so a partial verdict on a vision model reported only that some layers are quantizable and dropped the note carrying the token offset where quantization begins -- promising savings on prompts too short to ever reach it. Both are rendered now.

* Carry the MLX KV width through server-side overrides, and revoke a template that drops the image marker

Three fixes on top of the branch.

mlx_kv_bits was persisted in browser storage but dropped by every stage of the
server-side override projection, so an OpenAI-API auto-switch loaded a
remembered MLX model at full precision while the picker honored the width. It
now travels beside kv_cache_dtype through toApiOverride, ModelOverridePayload,
normalize_model_override and model_override_load_kwargs, validated against the
same discrete set mx.quantize takes.

The load-time template probe rendered a text-only turn and rejected only an
empty result, so an override that renders text but emits no image placeholder
installed cleanly and failed later on the first image request. Vision now gets
the paired native-versus-override marker check the audio path already had,
sharing one revoke helper.

The native template was captured from the nested tokenizer while generation
renders through chat_render_target, so on a processor owning its own template
the editor showed the wrong default and saving it would install the tokenizer's
template over the processor. Capture follows the render target, falling back to
the tokenizer when that target holds no editable string.

Also binds _template_override in __init__ beside _kv_quant, so a load failing
before the install leaves the entry writer reading a dict rather than raising.

* Echo the requested MLX chat template in both load responses

/status already reports chat_template_override from the mirrored
chat_template_override_requested, but the fresh-load and already-loaded
responses set only the refusal reason, so an API client saw a reason next to a
null override and could read that as the model using its default. Only the MLX
backend records the requested key, so llama.cpp responses are unchanged.

* Pick the template target through chat_render_target, and measure a quantized entry with the fallback

_template_render_targets restated a looser version of chat_render_target: it
took the processor whenever one carried a template, while chat_render_target
also requires the processor to be able to render and otherwise hands the render
to the nested tokenizer. A processor with a template but no apply_chat_template
therefore had its eligibility judged, and the override installed, on an object
generation never reads, after a probe that rendered from the untouched native
tokenizer. It now defers to chat_render_target, which is the rule unslothai#7066
introduced for exactly this, and _native_template_source and
_image_marker_survives consume the same helper rather than a third copy.

The existing named-set case asserted against a processor fixture with no
apply_chat_template, which no real processor looks like, and that is what hid
the drift. The fixture now renders, and the non-rendering shape is asserted
separately as the veto it should be.

The eligibility probe also read quantized.nbytes directly while
_MLXPromptCacheHistory measures the same entry through _kv_entry_nbytes, which
exists to work around an mlx-lm whose QuantizedKVCache.nbytes raises. The probe
marked every entry non-retainable there and reported that cross-turn cache
reuse was off while insertion would have retained it.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Release the saved template targets once the media checks are done

The restore pairs hold the tokenizer and processor. unload_model nulls both and
runs gc.collect precisely to let them go, but the pairs kept them reachable
through self._template_override until the next load replaced the status, and
the worker outlives the model. Nothing reads them after the audio and image
revocation checks, so they are cleared there.

* Size cache entries the way the LRU does, and require a real image placeholder

Reverts the previous round's retainability change, which was wrong. Upstream
LRUPromptCache.insert_cache computes its own total with sum(c.nbytes for c in
prompt_cache), so an entry whose property raises can never be admitted however
well a local fallback measures it. Measuring it another way only dropped the
no-reuse caveat while every quantized turn still failed to insert.
_kv_entry_nbytes now reads the property that decides admission, which also
retires a workaround that could not work.

The image check accepted any difference between the image-bearing and
text-only probes, so a template rendering the image as prose, or emitting the
content dict, passed while placing nothing the processor can bind an image to.
It now also rejects a prompt _vlm_prompt_issue flags and, when the model names
an image_token, requires that placeholder to survive. A model naming none
keeps the difference test.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Declare chat_template_override on the shared runtime fields

The echo added earlier was inert: only InferenceStatusResponse declared the
field, so pydantic dropped it as an extra keyword from both load responses and
the client saw nothing, with no error to notice it by. Moved to
_InferenceRuntimeFields, which both responses inherit, so the declaration
cannot drift again.

The guard asserts every is_mlx / mlx_ / chat_template_override field status
reports is on the shared base, and round-trips the echo through a real
LoadResponse rather than trusting the constructor call to mean anything.

* Check the vision template override even when native rendering needs recovery, and keep the staged MLX width through a rollback

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten comments in the MLX KV quantization and chat template override paths

---------

Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
…othai#8074)

_llama_runtime_fields() returns one entry per field on _InferenceRuntimeFields
and get_status splats it. unslothai#8007 added chat_template_override to that model while
get_status was already passing the same keyword explicitly, so the call raised
TypeError: got multiple values for keyword argument 'chat_template_override'.

Every status poll with a GGUF loaded returned 500. The chat UI showed
'Failed to get status' plus 'Failed to refresh models', and the model picker
rendered empty, which is what took studio-windows-ui-smoke red on main.

Assign into the dict before splatting. Pinning the duplicate to None would not
help: two values for one keyword is a TypeError whatever the values are.

Adds a source-level contract so any future field added to _InferenceRuntimeFields
cannot collide with an explicit keyword at a splat site.
…dows (unslothai#8068)

The tree under hf-cache is byte-identical on all three runners, so the
runner.os prefix in the key only ever bought three copies of the same
254 MiB download. Drop it, bump v2 -> v3, and set enableCrossOsArchive
so Windows can join the same entry.

Also require hashFiles('hf-cache/**/*.gguf') != '' before saving: a
shared key means a bad save now poisons three OSes, not one.
…and Windows (unslothai#8069)

The Linux, macOS and Windows tool-calling phases download the same file
from the same repo into the same flat --local-dir layout, but the Linux
job used path gguf-cache while the other two used gguf-cache-tools, and
runner.os split the key three ways. Rename the Linux directory to match,
drop runner.os, and set enableCrossOsArchive.

The key goes v1/v2 -> v3 in the same commit as the path move: an entry is
identified by key AND a hash of path, so moving one without the other is
a permanent restore miss plus a refused save.

One-time cost: the first main run after merge re-downloads 1.22 GiB on
each of the three runners. Steady state drops from three copies to one.

Also require hashFiles('gguf-cache-tools/**/*.gguf') != '' before saving:
a shared key means a bad save now poisons three OSes, not one.
Repo tests (CPU) is red on every open PR, and none of it is the PRs.

- unslothai#8025 added Minus/Square/X to the titlebar's lucide-react import; the
  contract pinned the whole import line. Check the two icon names it
  actually cares about instead.
- unslothai#8007 added mlxRuntimeStateFrom to chat-adapter.ts; the autoload
  harness has no stub for it, so 16 scenarios died as ReferenceErrors.
  Stub mirrors the real one: a non-MLX response retires the verdict but
  leaves mlxKvBits absent, and returning {} would keep a stale width
  alive and pass for the wrong reason.
- model-config-page.tsx grew two raw text-[11px] utilities, which ignore
  the UI font size preference. Swapped for the text-ui-11 token.

Co-authored-by: danielhanchen <[email protected]>
Imagineer99 and others added 27 commits August 9, 2026 04:05
* fix(studio): show image GGUF quant in loaded models

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Report the video GGUF quant in loaded models too for PR unslothai#8238

* Upper-case the GGUF quant label so a lowercase filename reads the same for PR unslothai#8238

* Tighten the loaded-models quant comments for PR unslothai#8238

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
…lothai#8252)

tests/test_python39_compatibility.py is a hard gate in Core CI and it is
currently red on main for every open PR:

  studio/backend/vendor/truststore/_api.py:30: str | bytes (type alias)
  studio/backend/vendor/truststore/_api.py:31: str | bytes | ... (type alias)

Those unions cannot be reached on 3.9. truststore/__init__.py raises
ImportError below 3.10, and its only caller wraps the import in try/except,
so the package is gone before _api.py is ever loaded.

Skip files under a package whose __init__ declares a floor above ours,
keyed on the guard rather than the path so unguarded code added to the same
vendor directory is still scanned.
* Desktop: confirm quit during training on Cmd+Q

* Desktop: confirm Dock quit and logout during training

* Desktop: defer termination reply until quit confirmation resolves

* Desktop: keep overlapping macOS termination pending

---------

Co-authored-by: Etherll <[email protected]>
unslothai#8248)

* Fetch the llama.cpp validation model only when the smoke test reads it

An approved bundle proves integrity by sha256 and skips the staged smoke test,
so the tiny GGUF probe goes unread on the default install path. It was still
downloaded up front, which made huggingface.co a hard gate on every prebuilt
install: a 429 there raised PrebuiltFallback and forced a multi-minute source
build over a file nothing opens.

Fetch it lazily instead, at the one branch that reads it, memoised so the two
smoke steps share a single download.

test_install_prebuilt_does_not_skip_unhealthy_existing_install tripped on the
probe download as a proxy for reaching the normal install flow. That proxy is
gone on the default path, so it now trips on validate_prebuilt_attempts, which
is the behaviour it actually names.

* Cover the probe rate limit end to end over install_prebuilt

The unit tests pin validate_prebuilt_choice's behaviour, but the bug was that a
429 short-circuited the whole install before the release loop. Assert that over
install_prebuilt itself: with download_validation_model raising 429, the flow
must still reach validate_prebuilt_attempts rather than exit EXIT_FALLBACK.

Verified it fails against the pre-fix source.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Resolve the probe before the candidate loop when a plan will validate

validate_prebuilt_attempts catches Exception per candidate, so a probe download
failing inside that try read as a failure of the bundle itself: a transient 429
demoted a healthy GPU pick to the CPU asset or an older release, and because the
thunk memoises success but not failure, each further attempt re-downloaded after
extracting another bundle.

Hashless attempts always validate, so resolve the probe once before the loop
whenever any attempt will need it. Plans that skip validation never call the
thunk and stay lazy.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Resolve the probe before the release loop too

The per-release handler in install_prebuilt swallows PrebuiltFallback and moves
to an older plan, the same shape as the per-candidate handler one level down. A
probe failure raised inside it installed an older llama.cpp build over a
transient 429, and since the thunk memoises success but not failure, each plan
retried the download.

The probe does not depend on which release was picked, so resolve it once before
the loop whenever any plan will smoke-test.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…othai#8161)

* Make install.ps1 work with the user's PowerShell profile loaded

Installing from a normal console failed where the same install from a
console started with -NoProfile succeeded. A profile runs before
`irm https://unsloth.ai/install.ps1 | iex` does and shares its scope, and
that entry point has no script file to re-launch without it, so the
individual couplings are cut instead.

install.ps1, at the top of Install-UnslothStudio:

- Set-StrictMode -Off. The script tests environment variables that are
  legitimately unset and reads $script: state only some branches assign,
  both of which a profile's `Set-StrictMode -Version Latest` turns into
  terminating errors.
- $PSDefaultParameterValues is filtered down to proxy keys. An entry like
  'Start-Process:WindowStyle' silently rebinds cmdlets here and fails the
  install with an error naming none of it. Proxy entries are kept because
  they can only ever enable a download, and on a locked-down host may be
  the only route to python.org and the uv release.
- $PSNativeCommandUseErrorActionPreference = $false. With a profile
  turning it on, the "Stop" preference makes a failing native command
  throw out of the `unsloth studio setup` handoff instead of reaching
  Exit-InstallFailure, skipping rollback and the Tauri error record.

All three assign without a scope qualifier, so they apply to the
installer and everything it calls and leave the caller's session alone.

uv is resolved once through Resolve-UvExecutable, which uses
`Get-Command uv -CommandType Application -All` and falls back to the bare
token when nothing is on PATH. PowerShell ranks aliases and functions
above PATH, so a profile `Set-Alias uv ...` was answering the version
probe and ending the install at "uv could not be installed" on machines
that had a working uv. Test-UvVersionOk pins the executable that
answered in $script:UvExe, and the 27 install scriptblocks invoke that
path. $script:UvExe and $script:UvInstallDestDir are reset per
invocation, since $script: is the caller's session under irm | iex.

unsloth_cli/commands/studio.py passes -NoProfile to setup.ps1
unconditionally. It was only added when stdout was not a tty, which is
never the case for the console install this fixes, so setup.ps1 ran
under the profile with its own bare uv calls exposed.

tests/test_installer_profile_hardening.py runs the extracted prologue and
uv probe under a hostile profile and checks the caller's session is left
intact. The four existing tests that anchored on the literal
`uv venv $VenvDir` are re-anchored past the command token.

* Plant the real-profile fixture where pwsh actually looks

test_a_real_profile_reproduces_the_same_state failed on ubuntu-latest with
every probed setting at its default, meaning the planted profile never loaded.
It passed here and on macos-14.

PowerShell resolves $PROFILE from $XDG_CONFIG_HOME when that is set and only
falls back to $HOME/.config when it is not, and GitHub's ubuntu image writes
XDG_CONFIG_HOME into /etc/environment. The fixture redirected HOME alone, so on
a hosted runner the inherited value went on naming the real account and the
profile was written to a path pwsh never opened. Setting XDG_CONFIG_HOME to the
same directory HOME already implies reproduces the CI failure exactly on this
machine, and removing it makes the failure go away.

_hostile_env now redirects XDG_CONFIG_HOME alongside HOME, so the two rules
agree whichever one the host applies, and the test asks pwsh for the path
instead of hardcoding the fallback branch. The two guards are precise rather
than blanket: a machine-wide profile loads into the real leg only, and a
$PROFILE that lands outside the fixture cannot be planted into. Neither is
reachable on Linux or macOS with the redirect in place.

The other tests in the file never shared the premise; every other pwsh launch
there passes -NoProfile and dot-sources the profile explicitly.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Close the uv wrapper hole, harden winget the same way, and restore module autoloading

Validating the profile hardening against real pwsh turned up three things the
first pass missed. Six of the nineteen hostile-profile scenarios I exercised
are genuinely broken on main and genuinely fixed by this branch, so the shape
of the fix is right -- these are gaps in its coverage, not a change of
direction.

Resolve-UvExecutable still handed back the bare token when nothing named uv
was on PATH. That was meant to keep a working non-Application uv working, but
it reopens the exact hole the function exists to close: a profile
`function uv { Write-Output "uv 99.0.0" }` clears the version gate, gets
pinned into $script:UvExe, and then receives every install command the script
runs, with the user's torch, index URL and venv path as arguments. The
existing test missed it because its hostile alias reports no version at all,
and an alias to a missing file fails loudly. Follow an alias as far as an
Application and return that resolved path, since aliasing uv at a specific
build is a legitimate thing to do; return $null for anything else, which puts
the caller back on its install-uv branch and the gate re-probes against the
real thing.

winget had the identical defect and was left untouched. It is detected with a
bare Get-Command and invoked as a bare token at five sites, and it is what
installs both Python and uv -- so a `function winget` wrapper, which people
write to inject --accept-* or pin a source, owns the whole bootstrap. Same
treatment: resolve once to an Application and invoke through the path.

A profile setting $PSModuleAutoLoadingPreference to 'None' is fatal here and
was not covered. PowerShell 7 loads no modules at startup, so that one line
removes Test-Path, Write-Host, Select-Object, ConvertFrom-Json, Get-FileHash,
Invoke-WebRequest, Expand-Archive, Start-Process and Get-Content, and the
script dies on its first step naming a cmdlet the reader assumes is always
there. Windows PowerShell 5.1 preloads Utility and Management and survives,
which is exactly what makes this reproduce on one machine and not another.

Also: use [regex]::IsMatch in the defaults filter so it leaves no $Matches
behind; add -NoProfile unconditionally in _refresh_desktop_shortcuts, which
launches install.ps1 and had it gated on the hidden branch, so the visible
console path -- the one where a profile IS loaded -- was the one that missed
it; and record that the preserved proxy defaults do not reach setup.ps1,
which is launched with -NoProfile, along with why that trade is accepted.

Tests: the assertion that the bare token must come back now asserts the
opposite, and there are new ones for a convincing uv function, an alias to a
real uv, the winget call sites and the autoloading reset. The two new pwsh
tests execute against a genuinely planted profile rather than reading source.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Carry the profile proxy across the setup handoff, not just inside install.ps1

install.ps1 deliberately keeps proxy-shaped $PSDefaultParameterValues entries out of the
profile table it discards, because on a locked-down corporate host that entry can be the
only route out. Adding -NoProfile to the setup launch unconditionally then threw them away
one process later, and setup.ps1 downloads on its own: the VC++ runtime through
Invoke-WebRequest and the uv installer through Invoke-RestMethod.

A PowerShell variable does not cross a process boundary, so the kept entries travel as
JSON in _UNSLOTH_PS_PROXY_DEFAULTS and the child re-applies them before running setup.ps1.
Nothing else from the profile comes with them. A credential is left behind on purpose:
PSCredential does not survive ConvertTo-Json, and the environment is the wrong place for
one. A stale variable is cleared when there is nothing to hand off.

Three tests, one static and two driving real pwsh, covering the round trip, the credential
and non-proxy keys being dropped, and the prelude staying silent when the variable is
absent, empty or corrupt.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Harden the proxy handoff: ordering, key casing, uri values, scope, and the standalone update

Five follow-ups, all on the handoff added last round.

The handoff serializes with ConvertTo-Json, from Microsoft.PowerShell.Utility, and ran before
the module-autoloading reset. Under a profile's $PSModuleAutoLoadingPreference = 'None' a fresh
PowerShell 7 session therefore died right there, taking out the one configuration the handoff
exists to support. The reset moves to the front of the prologue.

The key filter was a case-sensitive .NET regex, but cmdlet and parameter names bind
case-insensitively, so 'invoke-webrequest:proxy' was dropped. And [uri] is the type the Proxy
parameter actually takes, so a careful profile assigns one; the serializer accepted only string
and bool, and it disappeared at the process boundary. Both are accepted now, a uri by its
AbsoluteUri. A PSCredential is still deliberately left behind.

Under "irm ... | iex" the prologue runs in the caller's own session, so writing the environment
variable there outlived the install on every path, early returns included, and a later
`unsloth studio update` from that console would reapply stale JSON over a proxy that had since
changed. The prologue now holds the value and it is published around the setup child only,
saved and restored beside the other child-scoped variables.

A standalone `unsloth studio update` has no installer above it, so there was nothing to
restore and -NoProfile left it with no route out. It now asks: a throwaway PowerShell that does
load the profile prints just the proxy-shaped defaults as JSON, validated before use, entirely
best effort. Same filter as install.ps1's.

Five tests, two driving real pwsh, including one against a profile with strict mode on,
autoloading off, a lowercase key and a uri value.

* Ask the profile the caller actually has, and follow a uv alias first

- the standalone update probed powershell.exe only, so a proxy living in the
  PowerShell 7 profile never reached the -NoProfile child; both editions are
  asked now, the caller's first, and their answers merged.
- Resolve-UvExecutable checked PATH before the alias, which is the reverse of
  PowerShell's own resolution and made the alias branch unreachable on any
  machine with some uv on PATH.
- the parity workflow did not run this suite when unsloth_cli/commands/studio.py
  changed, though the suite asserts that module directly. Its own path-filter
  parser also treated a comment inside the list as the end of it, which would
  have hidden the addition.

* Give the parity job the imports it needs, and fold proxy keys the way PowerShell does

Three tests in the profile-hardening suite import unsloth_cli.commands.studio to drive
the profile probe directly, and that pulls typer, pyyaml, pydantic and click. The job
installed pip and pytest only, so on a clean setup-python both matrix legs died with
ModuleNotFoundError before a single test ran. Installed, with a test that keeps the step
in step with what the suite imports.

$PSDefaultParameterValues keys are case-insensitive and a Python dict is not, so
"Invoke-WebRequest:Proxy" from the caller's own host and "invoke-webrequest:proxy" from
the other one both crossed over; the prelude then replayed them in order and the
lower-priority host's value landed last, reversing the earlier-host-wins rule this merge
exists for. Keys are folded now, first spelling seen wins, within one profile's answer
as well as across two.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Frame the proxy record, and quote the union so 3.9 can still import the CLI

The probe runs after the profile, and the profile is free to print: a MOTD, a "loading
personal and system profiles took 812ms" line, a corporate banner. With the record bare,
that arrived ahead of the JSON, the parse threw and the whole answer was dropped -- so
the locked-down host that needed the proxy handed the -NoProfile child nothing and every
download failed, which is worse than before, since the old visible-console path loaded
the profile itself. The record is emitted between two markers now and cut out of
whatever else was said.

And `str | list[str]` was evaluated at def time in a module with no postponed
annotations, so on the 3.9 this project still supports it raised TypeError and took the
whole CLI import with it. Quoted, with a test that walks every annotation in the module
for an unquoted PEP 604 union.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Let the uv gate move past a stale alias, and decode the probe output lossily

An alias pointing at a real but stale uv was the only binary the version gate ever
probed, so a current uv already on PATH -- or one winget or the pinned release had just
installed -- could not rescue the run and the install ended at "uv could not be
installed" on a machine that had one. The resolver hands back every candidate in the
order the bare token would pick them, alias first, and the gate walks them until one
passes, pinning the one that answered.

The profile probe decoded its child with text=True alone, which is the locale codec with
STRICT errors. A UTF-8 banner on an ANSI console then raised UnicodeDecodeError, which is
neither OSError nor SubprocessError, so it escaped the handler and took the update down
before the -NoProfile child ever ran -- and before the framing could discard the banner.
UTF-8 with replacement now; the record itself is ASCII.

rich is named in the parity job's install line too. It arrives through typer today, but
unsloth_cli imports it directly, and this suite's imports should not rest on somebody
else's dependency list.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Assert the proxy handoff by parsing it, not by substring

CodeQL reads the bare membership test as an incomplete URL sanitization, which
is a fair reading of the shape even though this is an assertion on a compressed
JSON payload rather than a check on untrusted input. Parsing it and comparing
the value exactly is the stronger assertion anyway.

* Read the caller edition by order, pin the probe's encoding, claim cmdlets whole

A machine can carry both PowerShell module trees on PSModulePath at once, so
inferring the caller from the absence of the other edition handed precedence to
the wrong profile and let its proxy override the console the command was typed
into. Each host puts its own module directory first, so the earliest tree names
the caller; neither present keeps the previous order.

Windows PowerShell 5.1 writes redirected output in the console code page while
this process decodes UTF-8, so a non-ASCII proxy value came back with
replacement characters, still parsed as JSON, and handed setup a proxy that does
not resolve. The probe pins its own output encoding first.

And the merge claims a cmdlet whole rather than filling missing companion
parameters from the other profile, which built a configuration neither host had
-- one profile's proxy with the other's credential forwarding.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Evaluate script-block proxy defaults, read the caller's host profile, drop the secret

A profile can set a dynamic default as a script block, which is PowerShell's
supported form and which Invoke-WebRequest evaluates per call. Both
serializers dropped it, so the caller downloaded fine and the -NoProfile
setup child got no proxy at all. Both now invoke the block and hand over the
resulting URI or string; executable code does not cross the handoff.

The probe spawns pwsh.exe or powershell.exe, which load the CONSOLEHOST
profile. A caller in the VS Code Integrated Console or the ISE keeps its
defaults in Microsoft.VSCode_profile.ps1 or Microsoft.PowerShellISE_profile.ps1
instead, so the probe reported no proxy on exactly the host that needed one.
It dot-sources the caller's other CurrentUser host profiles, from their own
directory, before reading the table.

And the prelude clears _UNSLOTH_PS_PROXY_DEFAULTS the moment it has read it.
A profile proxy routinely carries credentials, and every native process
setup.ps1 starts inherited the environment it was launched with.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Probe only the caller's own host profile, on one shared budget

Sourcing every Microsoft.*_profile.ps1 in the profile directory ran profiles
belonging to hosts nobody was using: they can overwrite the console's own
$PSDefaultParameterValues, have side effects, or exit before the framed
record is written. The probe now sources exactly one, named by
_UNSLOTH_PS_HOST_PROFILE, and only when the caller identifies itself (VS Code
does, via TERM_PROGRAM). A host we cannot name gets no extra profile rather
than someone else's.

install.ps1 removed the handoff variable when it had no proxy to pass, and
its absence is precisely how the CLI recognises a standalone update -- so an
installer launch, including one started with -NoProfile or by the desktop
app, went and reloaded the profiles it had deliberately discarded. It
publishes an explicit empty handoff instead, and the CLI keys on presence.

And the probe's timeout is one budget for the whole call rather than one per
host, so two installed editions with two hung profiles no longer cost twice
the documented best-effort delay before setup starts.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Run the proxy probe with -NoProfile and dot-source the caller's own two

Without -NoProfile the probe host loaded its own ConsoleHost profile before
the script ran, so an unrelated profile could print, rewrite
$PSDefaultParameterValues or exit before the record was written -- and it
still was not the profile a VS Code caller keeps its defaults in.

The child runs with -NoProfile now and dot-sources exactly the two the
caller's session would have loaded: $PROFILE.CurrentUserAllHosts and either
the host profile named in _UNSLOTH_PS_HOST_PROFILE or
$PROFILE.CurrentUserCurrentHost. $PROFILE is fully populated under
-NoProfile, since the paths are computed rather than loaded, so this is exact
rather than incidental.

Checked against pwsh with a fixture profile directory: a VS Code caller picks
up its own profile plus the all-hosts one and never runs the console
profile's banner, and a plain console caller picks up the console profile
plus the all-hosts one.

* Probe the all-users profiles too, and clear profile defaults before emitting

A machine-managed proxy commonly lives in AllUsersAllHosts on a domain-joined
box while the user's own profile never mentions it, so sourcing only the
current-user pair reported no proxy on exactly the host that has one. The probe
now walks PowerShell's own startup order, all-users first, so the user's profile
still gets the last word.

The profile's $PSDefaultParameterValues was also still active when the record
was serialized. ConvertTo-Json:AsArray = $true is a legitimate setting and turns
the payload into a JSON array, which the reader rejects for not being a
dictionary. $out already holds copies by then, so the table is cleared first.

* Harden the proxy probe against profile overrides, and drop the handoff copy

Five fixes from the review round:

install.ps1 kept the serialized proxy defaults in $script:, which under the
documented irm | iex path IS the caller's session scope, so an authenticated
proxy URI stayed readable in that console after the installer returned. Cleared
in the same finally that restores the environment handoff.

A profile setting [Console]::OutputEncoding overrode the probe's UTF-8 pin, and
the parent decodes that stream as UTF-8, so the framed record could come back
corrupted. Re-pinned after the last profile is sourced.

The record was emitted through bare Write-Output and ConvertTo-Json, which a
profile alias or function shadows; clearing $PSDefaultParameterValues does not
cover a command override. Both are module-qualified now.

TERM_PROGRAM=vscode is set by every VS Code integrated terminal, not only the
PowerShell extension's host, so substituting Microsoft.VSCode_profile.ps1 for
the current-host profile missed the proxy a plain pwsh terminal there actually
has. The named host profile is added rather than substituted, with the
current-host profile last.

The per-cmdlet ownership check compared command strings literally, so a wildcard
key from one host and a literal key for a matching cmdlet from the other were
both merged, which is how one invocation ends up configured from two profiles.
Overlap is matched in either direction now.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Hold the proxy handoff in the frame, and treat two wildcards as one family

Three fixes from the review round:

The serialized handoff lived in $script:, which under the documented irm | iex
path is the caller's session scope, and the only cleanup ran after the setup
child. Dozens of exits return earlier -- ShortcutsOnly, an argument error, lock
contention, a failed dependency install -- so an authenticated proxy URI stayed
readable in that console. It is a function-local now, which dies with the frame
on every path including a throw.

install.ps1 serialized that record through a bare ConvertTo-Json, which a
profile alias or function shadows exactly as it does in the probe. Module
qualified.

The cmdlet-ownership check compared two wildcard patterns as strings, and
Invoke-Web* and *-WebRequest both apply to Invoke-WebRequest while neither
matches the other. Two patterns are now assumed to overlap: the cost is a second
host's unrelated wildcard entry going unmerged, against handing setup a
credential setting from a profile that never asked for one.

* Tighten the profile-hardening comments

Comments, docstrings and whitespace only; no code changes. Each comment keeps
the reason it records and drops the retelling.

* Cut the profile-hardening comments down again

Comments, docstrings and whitespace only. The install.ps1 prologue and the
studio.py proxy probe kept one causal claim per decision, with the probe's
profile-loading essay split into a short note beside each line it justifies.

* Pin the probe's add-both profile order in its own test name

* Keep disjoint wildcard proxy families, and give each probed host its own module path

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
)

* Name a torchvision whose compiled ops do not match torch

torchvision_compatibility_check compares version metadata, and metadata
cannot see an ABI break. Running Gemma4_(E2B)_GRPO turned one up: its T4
branch installs vllm==0.9.2 beside Colab's torch, and torchvision came out
reporting a version the table accepts while its ops were built against a
torch that is gone. import unsloth then died with

    RuntimeError: operator torchvision::nms does not exist

raised from transformers/image_utils.py, naming neither torchvision nor
what to do about it. The vLLM half of the same breakage was already
handled: the run logged "Detected broken vLLM binary extension; disabling
vLLM imports and continuing".

So import torchvision on the path the table calls compatible, which is the
only blind spot, and turn the loader error into one that says which package
is broken and how to reinstall it. UNSLOTH_SKIP_TORCHVISION_CHECK=1 still
skips everything, and an import failure we cannot explain is left alone.

No extra import cost in practice: transformers imports torchvision from
image_utils as soon as anything touches processing_utils.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Shorten the comments on this PR

Comments and docstrings only. AST gate with --strip-docstrings passes on both
files; without it both report CODE CHANGED, which is expected since a docstring
is an AST node. Docstrings touched: the module docstring of
tests/test_broken_torchvision_probe.py and _probe_torchvision_binary's.

* Do not let the probe claim a loader failure it did not cause

The probe imports torchvision where nothing used to, so it can turn a latent
failure into a hard error on `import unsloth`. `undefined symbol` and
`cannot open shared object file` on their own are not enough: a CPU-only or
driverless box whose torchvision cannot load for an unrelated reason -- a
missing libcuda, a mismatched libjpeg -- would have imported unsloth fine
before and would now be told to reinstall torchvision.

Those two markers now also have to name torchvision or the torch libraries it
links. `torchvision::`, `torchvision.io.video` and `io._video` stay
unambiguous on their own. Anything else is left exactly as it was, which is
the point: the probe adds a diagnosis, it must not add a failure.

Three new cases; all three fail without the change.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Pin the torchvision repair command so it cannot replace torch

Every torchvision wheel requires an exact torch==X.Y.Z (0.24.1 requires
torch==2.9.1), so the unpinned `pip install --upgrade --force-reinstall
torchvision` the new message printed resolves the newest torchvision and then
pulls a new torch in to satisfy it. On a Colab or Kaggle image that is the
pinned torch every other wheel was built against, vLLM included, so following
the advice broke more than it repaired.

Pin to the companion release the compatibility table names, and pass --no-deps
so torch is never a candidate. The pin also covers the case where the version
gate passed on its lower bound: torch 2.4 accepts torchvision >= 0.19, so an
installed 0.20 reaches the probe, and 0.19 is what actually repairs that box.

pip's own docs: --upgrade selects the newest version and, under the default
only-if-needed strategy, upgrades a dependency that the newer package no longer
accepts; --force-reinstall reinstalls the whole resolved set.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Name the exact torchvision wheel the installed torch pairs with

The 0.<minor>.* range under-specifies the pair. torchvision 0.22.0 requires
torch 2.7.0 and 0.22.1 requires torch 2.7.1, both confirmed against PyPI, so on
a 2.7.0 host pip picks 0.22.1 and --no-deps then keeps the torch that does not
match it. Following the advertised repair rebuilt the mismatch it repairs.

torch's own patch is already in scope, and the two move together, so carry it
into the companion and name one wheel.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Point the torchvision repair at the index that carries torch's backend

* Stop advertising a pinned reinstall for a torch no public wheel pairs with

* Keep the CUDA family too, and detect every prerelease by parsing it

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Do not advertise a PyPI torchvision to a conda-installed torch

conda records the backend in the build string and leaves the version
plain, so a conda torch reaches the local-tag check looking exactly like
a PyPI one and gets the unqualified pin. --no-deps then keeps a conda
CPU or ROCm torch beside PyPI's CUDA-only torchvision, rebuilding the
mismatch the command exists to clear. Read conda's own ledger,
conda-meta/<name>-<version>-<build>.json, and fall back to the advice
that names no wheel.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: danielhanchen <[email protected]>
unslothai#8030)

* Diffusion: source the Qwen-Image-2512 companions from unsloth

A Qwen-Image-2512 GGUF, FP8 or bnb-4bit pick ships only the denoiser and reads
its VAE, text encoder, tokenizer and scheduler from the base. That base is named
by the base_model card tag on the artifact repo (Qwen/Qwen-Image-2512), not by
the family table, whose default is the older Qwen/Qwen-Image, so nothing in the
existing redirect touched it and every 2512 pick pulled 16.8 GB from the vendor.

unsloth/Qwen-Image-2512 is a complete mirror: all 14 weight files match upstream
by sha256, no file is missing, and it loads as QwenImagePipeline with all five
components. Apache-2.0 upstream, so the copy carries LICENSE and NOTICE.

The mirror table is no longer only about gating, so its comments say what it is
now for. The swap stays fetch-only: status(), saved configs and a trained
adapter's base_model tag still read the vendor id through canonical_base.

Two new tests: the 2512 pair specifically, since it is the one entry the family
table cannot reach; and a guard that no mirror is ever a companion-only repo,
because prefer_ungated_mirror also fires on a plain bf16 pipeline pick and a
mirror without a transformer would break it.

* Tighten the comments on the mirror change

* Mirror the remaining third-party diffusion bases into unsloth

Eight more complete mirrors, so that every image family Studio can load takes
its companions from unsloth/* rather than a vendor repo: Qwen-Image,
Qwen-Image-Edit-2511, FLUX.2-klein-4B, Z-Image-Turbo, Lumina-Image-2.0,
HiDream-I1-Full, stable-diffusion-xl-base-1.0 and sdxl-turbo.

All eight verified against upstream: every LFS weight file matches by sha256,
no upstream file is missing. Redistribution terms differ, so each mirror
carries the upstream licence text plus the notice its own licence prescribes:
Apache-2.0 for the five Qwen/BFL/Tongyi/Alpha-VLLM repos, MIT with its
copyright and permission notice for HiDream, OpenRAIL++ with Attachment A's
use restrictions flowed down for SDXL base, and for sdxl-turbo the Stability
AI Community License with the section IV(a) attribution sentence verbatim.

HunyuanImage-2.1 is deliberately NOT mirrored, and the table says so. The
Tencent Hunyuan Community License permits distribution only inside a Territory
that excludes the EU, the UK and South Korea, and a public Hub repo
distributes worldwide.

Three existing tests asserted a vendor id where the fetch now reads the
mirror. Updated to the mirror, and two of them now also assert that status
still reports the vendor id, which is the property the fetch-only swap is
supposed to preserve.

* Stop two tests deciding on the ambient HF cache

Both build a Z-Image cache fixture and then let prefer_ungated_mirror read the
REAL cache to decide whether the swap fires. On a machine that happens to hold
the upstream they pass, on a clean runner they fail, which is how they passed
locally for me and failed in CI.

The cross-root test pins UNSLOTH_DIFFUSION_NO_MIRROR, since its subject is
shard discovery across cache roots and not mirroring at all. The dense-builder
test pins _no_cache and asserts the mirror id, which is what the load reads now
that Z-Image is mirrored; which hub id it is was always incidental there, the
point being a hub id rather than the staged snapshot path.

* Tighten the mirror-table comments

* Mirror the three variant bases exact-id lookup was missing

The table named FLUX.2-klein-4B and HiDream-I1-Full but not the variants a
supported pick can actually resolve to, and lookup is by exact id:

  black-forest-labs/FLUX.2-klein-base-4B  <- what unsloth/FLUX.2-klein-base-4B-GGUF
                                             resolves to from its card tag
  HiDream-ai/HiDream-I1-Dev               <- offered directly, 63 GB bf16 pipeline
  HiDream-ai/HiDream-I1-Fast              <- offered directly, 63 GB bf16 pipeline

So those picks kept fetching from the vendor while the change claimed to have
stopped that, and claimed Hunyuan was the only deliberate exception.

All three upstreams are ungated and permissively licensed (apache-2.0 and MIT),
so redistribution rests on the same basis as the existing ungated mirrors. Each
new mirror is a complete copy, verified file-by-file against upstream: 25/25,
36/36 and 36/36 files with no missing entries and no size mismatches.

The new test reads the catalog rather than restating the table, so a newly
offered vendor bf16 pipeline fails here instead of quietly bypassing the
mirrors. It is scoped to IMAGE_CATALOG, matching this change's scope; the video
bases are ungated and a separate call. Verified load-bearing: dropping the two
HiDream rows fails it and names them.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten two mirror-test comments

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
* fix(studio): infer splits for metadata-free cached datasets

* Match datasets split inference for PR unslothai#8144

Skip datasets' FILES_TO_IGNORE basenames so a metadata-only cache stays empty,
apply its sharded split grammar and fail closed on a name it rejects, and drop
snapshots whose splits infer different builder modules.

* Make inferred splits case-exact and reuse the shared split grammar

fsspec globs with a plain regex and no normcase, so datasets matches file
names case-sensitively on Windows and macOS too. Match keywords, extensions
and the sharded data/ prefix the same way, stop skipping __ filenames since
datasets only skips __ directories, and drop the local sharded pattern now
that main's HF_DATASET_SPLIT_NAME_PATTERN is datasets' own _split_re.

* Mirror the loader's metadata and module rules in split inference

Merge .huggingface.yaml over the card the way datasets does, keep declared
config names when only the fallback produces splits, and stop inferring at all
when the card's YAML fails to parse, since datasets raises there instead of
loading. Let files datasets loads but training cannot use join a split so a
snapshot whose split modules disagree offers nothing, and sample each split's
module from its first 200 files in sorted order like the loader.

* Pick split patterns over every file, like the loader does

datasets chooses its split-pattern family before it filters extensions, so a
file it cannot train on still decides which stage wins and can leave a split
with nothing to build. Scan every non-ignored name, carry datasets' own
extension table, and offer only splits that hold a trainable file, dropping the
snapshot when a split has no data, when the modules disagree, or when a zip
would decide one, since its module lives inside the archive. Keep tsv apart
from csv for its sep kwarg, rank folder metadata last in the tie-break, infer
each declared config under its own data_dir, and fail closed on a truncated
scan. Names are no longer resolved during the walk, only for the splits that
end up offered, which is what makes the much larger scan limit affordable.

* Count extensions and validate configs the way the loader does

Carry datasets' full per-builder extension table so the media families stay
apart, count every suffix under its own lowercase name instead of the first one
that resolves, and finish the tie-break on the extension string. A file that
matches two keyword patterns of one split now lands in it twice, as the loader
resolves each pattern separately.

On the metadata side, refuse a card whose configs datasets could not build,
take the last of duplicate config names, drop a config whose data_dir would
have to be rewritten rather than silently widening it to the snapshot, and
infer per config so an explicit sibling no longer suppresses the rest.

A split is offered only when every file its builder would read stays in the
cache: datasets loads them all, so one safe file among them proved nothing.

* Settle one module per dataset and tighten the metadata gates

datasets infers a single packaged module before it builds any config, so a
config it has to infer patterns for is built with the module the declared ones
produced; a pending config whose own module differs is no longer offered. A
config is only inferred when data_files is genuinely absent, an empty configs
list means undeclared again, an absolute data_dir is refused rather than
stripped to a relative one, and front matter that is not a mapping or a
dataset_infos.json that will not decode suppress inference the way the loader
raises on them.

Membership now uses the same all-suffix rule as the counting, so a file like
records.txt.jsonl is no longer dropped from the split its own extension won.
Keyword patterns resolve in the loader's order rather than sorted, which is
what the first 200 files are sampled from, and one scan per data_dir serves
every config that shares it.

Compression is limited to what fsspec can actually decompress here: zstd and
lz4 are named by datasets but need codecs Studio does not ship, so they raise
on read and .zst had been offering a dead split since the first commit.

* Validate what the builder keeps, and stop over-reading the card

Zips are kept for every module and folder metadata for its own builders, so a
split holding one that points outside the cache is no longer offered on the
strength of its other files.

Card handling was both too strict and too lax after the last round. A null
front matter block is empty metadata to DatasetCard.load, not a broken card, so
that snapshot infers again; a scalar standalone yaml, a card too large to read,
and two configs both marked default all suppress inference instead, because the
loader raises on each. Only the plural dataset_infos.json is opened by the
local factory, so a malformed singular file no longer hides valid data.

A declared pattern with no extension leaves the dataset module unsettled, so a
sibling config is no longer offered against a module we guessed. A sharded name
that only validates after trimming is rejected rather than trimmed, and a file
matching two synonyms of one split now sits at each synonym's own position,
which is where the loader resolves them.

* Flatten list-valued declared paths and tighten declared-config gates

* Match the loader on defaults, empty declarations and repeated keyword globs

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Follow RepoCard's grammar and collapse configs the way the loader does

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Settle the builder from the first config, and match the pinned card parser

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Resolve declared paths and reject metadata shapes the loader refuses

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Resolve declared globs against the snapshot instead of reading their text

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Follow the loader when a declared glob matches nothing

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Skip what the picker cannot show without hiding the rest

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Weigh every suffix, and take the card apart the way the loader does

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Index declared resolution, and keep config-local failures local

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Read features by role, and glob what the loader globs

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Follow the loader through blob directories, and refuse what fsspec refuses

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Match the dtype grammar, and keep what the card already stated

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten dtype grammar, data_dir walking and truncated-walk literals for PR unslothai#8144

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Model dataset_info verification, builder parameters and empty files for PR unslothai#8144

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Validate feature classes, versions and split formats for PR unslothai#8144

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Match loader metadata precedence and data dir handling for PR unslothai#8144

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Validate feature arguments and compressed payloads for PR unslothai#8144

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Check declared payloads, parameter ranges and unmatched data dirs for PR unslothai#8144

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Validate feature and metadata fields the loader reconstructs for PR unslothai#8144

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Align value aliases, csv headers and compression handling for PR unslothai#8144

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Reject unsafe declarations and normalise the settled builder for PR unslothai#8144

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Bound compression layers, csv ranges and snapshot reach for PR unslothai#8144

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Validate builder enums, nullability and unsafe directory links for PR unslothai#8144

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Reduce PR unslothai#8144 to the split-inference fallback and its tests

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Match the loader's module sampling and payload checks for PR unslothai#8144

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Suppress a config whose sibling split is empty for PR unslothai#8144

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Only stand down for metadata that names a config for PR unslothai#8144

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Follow the loader at the metadata boundaries for PR unslothai#8144

* Match the loader on metadata it cannot read for PR unslothai#8144

* Ignore dangling snapshot links when grouping splits for PR unslothai#8144

* Drop rowless splits and skip file checks for untrainable builders for PR unslothai#8144

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Reject empty JSON containers and legacy lzma streams for PR unslothai#8144

---------

Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…ter (unslothai#8158)

* Studio: check FLUX.2 GGUF/base compatibility before the download, and validate the model catalog against the Hub

Two things a user hit by hand.

A FLUX.2 GGUF only carries the transformer, so its inner_dim has to agree with
the companion diffusers base the loader assembles around it.
assert_flux2_gguf_matches_base already said so, legibly, but it opens the
DOWNLOADED checkpoint: it fires from inside load_pipeline, after the prefetch
pulled ~19 GB of base shards and after _unload_locked freed the pipeline the
user was working with. The pick was never valid; they paid for both to be told.

diffusion_compat answers the same question from metadata alone -- one HTTP range
request for the first 256 KiB of the GGUF, which is where its tensor table
lives. That is cheap enough to run at selection time, so the check now happens
in three places instead of one:

  * POST /images/download-plan, reported in the envelope as incompatible_reason
    rather than raised. The images page falls back to /images/load on ANY plan
    failure, so a 400 here would start the very download this prevents; carried
    in the response, the picker refuses before the user commits.
  * preflight_base_access, beside the gated-repo refusal, so the route rejects
    the pick before it takes the GPU from chat.
  * _run_load, before _prefetch_files and before load_pipeline, so a direct
    begin_load (a saved config, the deploy path) is covered too.

The loader's own guard stays exactly where it was, as the backstop.

Fail-open is the whole contract, so it is enforced at the parser: the
header-only reader REFUSES a read past the prefix rather than zero-filling it.
Reading the table field by field means a prefix cutting between a tensor's name
and its dims would otherwise hand back shape 0 -- a wrong answer, not a missing
one, and one that refuses a valid pick. It also skips the base class's per-tensor
data views, which for a prefix would allocate the whole declared checkpoint
(tens of GiB, charged against the pagefile on Windows). Anything unreadable, any
base outside the size table, an offline host, or a server that ignores Range all
yield no opinion and today's behaviour.

Same header closes the sibling hole: sd_cpp_text_encoders_for picked the
FLUX.2-klein 9B text encoder by string-matching the repo id and filename, which
a renamed checkpoint defeats silently (the wrong encoder fails deep inside
sd-cli). It now prefers the checkpoint's own inner_dim, keeping the string match
as the fallback, and the committed dim is carried on _SdState so the delete
guard reconstructs the same pick without re-probing under the lock.

Catalog: unsloth/LTX-2.3 was never published. It was only a grouping key, but an
`unsloth/*` id that is not an artifact clears both the picker's owner guard and
the backend's, so a pick reaching the fall-through loaded as a pipeline and died
at the Hub. Keyed on Lightricks/LTX-2.3, which is a real artifact in the same
group; the retired id still resolves through the GGUF's suffix-stripped key.

To stop the next one, catalog:check gains an opt-in --network mode that HEADs
every declared repoId and filename anonymously (what a fresh install sees) and
asserts each `gated` flag matches what the Hub reports. Opt-in and scheduled,
never on pull_request: it depends on huggingface.co being up, and an
indeterminate answer is a warning, never a failure.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Arm the GGUF header read's deadline instead of only testing it

The whole-body deadline the previous commit added did not work. It was
only evaluated BETWEEN chunks, but iter_content(chunk_size=65536) blocks
inside urllib3 until the full 64 KiB chunk has arrived, and every dribbled
byte resets requests' per-socket timeout. Against a server trickling four
bytes a second the loop body is not reached for 4.6 hours, and the picker
sits there: measured on a loopback socket, the read was still blocked at
60s with the deadline claiming 15s.

This is on the pre-eviction path, so the symptom is an /images/load that
never answers. No lock is held, so it is a hang rather than a deadlock,
but the mitigation the comment described was inert.

Arm it on a timer that half-closes the socket. response.close() is not
enough: it drops the file object while the socket stays readable, so the
parked read stays parked. urllib3's HTTPResponse.shutdown() is the only
thing that wakes it, with a guarded fallback to close() so an older
urllib3 is no worse than today.

Whatever arrived is kept rather than discarded. A merely slow link still
leaves the tensor table in hand, and the parser is truncation-safe: a
short prefix is answered or ignored, never guessed at. The happy path is
unchanged at 1.1ms for 256 KiB; chunk_size stays at 64 KiB because
dropping it to 1 costs 912ms on every pick.

* Bound the header read without depending on urllib3, and stop a Hub blip disabling the local probe

Three fixes to the range-read preflight, found reviewing the branch against old installs.

The whole-body deadline works by half-closing the socket, which is the only thing
that wakes a read parked inside iter_content. HTTPResponse.shutdown landed in
urllib3 2.3.0; below that the watchdog degrades to Response.close(), which leaves
the socket readable and the read parked. Measured against a trickling loopback
server on urllib3 2.2.3, the reader was still alive after 40 s, and this read sits
on the /images/load route thread. The drain now runs on a worker the caller
abandons, so the bound holds whatever urllib3 is underneath, and requirements
floors urllib3 at 2.3.0 for new installs as defence in depth.

A memoised "no opinion" was consulted before the on-disk read, so a transient Hub
failure -- or simply a probe that ran before the download finished -- permanently
disabled the free local read for that pick and left the guard silent on a file
sitting in the cache. The negative now only suppresses the network half.

The native backend probed the header before the lock but still on the route
thread, and begin_load returns at once by contract. It is offline-only there now;
the worker re-probes with the network and publishes the real encoder repos before
fetching a byte, so the delete-cached guard still names them.

Five tests, each checked against a mutation of the fix it covers.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Key the header memo on the file and the credential, and bound the catalog fetch

Four review findings, all reachable.

The memo keyed on (repo, filename, has-token). A checkpoint swapped in place under the same
name kept the same key, so the old dim answered for the new file: a valid 9B pairing refused,
or the 4B text encoders handed to the native backend, until the process restarted. And every
non-empty token was one key, so a first probe with an expired credential cached its miss and
the working token pasted afterwards inherited it for the session, with the preflight silently
off for that pick. The key now carries a non-reversible token fingerprint and the local file's
(path, size, mtime). That also subsumes the earlier download-completion case: the file
arriving is a new key, so a miss taken before it landed re-probes off disk for free.

The catalog network check had no per-attempt deadline, so a peer that accepted the request and
then stalled never reached the retry or the fail-open path, and the scheduled job died on its
own 10-minute timeout as a red run for a transient stall. Each attempt now carries an
AbortSignal.timeout, and the body is read under that same deadline rather than by the caller,
where an abort would have been reported as unreadable JSON, which is a catalog failure.

Rejecting an incompatible pick reverted the quant label but not the steps and guidance the
pick had already applied, so the still-resident previous pipeline would run its next
generation at the rejected model's settings. All three revert together now, on the poll path
as well as the start path.

Three tests for the memo, each confirmed against a mutation of the key.

* Bound the whole network catalog pass, not just each request

Per-attempt deadlines fixed the hang but not the budget. The batches are serial: about 53 repos
at four per batch is 14 of them, and a peer that stalls every request costs three 20-second
attempts plus 1.5 seconds of backoff each, so a fully stalled Hub takes roughly 14.3 minutes to
fail open while the workflow kills the job at 10. That is the red run the retry logic exists to
avoid, arriving by a different route.

An overall seven-minute deadline is armed when the network pass starts, and every request past
it short-circuits to "no opinion" without reaching the socket, so the check still prints its
warnings and exits 0. Measured against a server that accepts and then stalls every request: a
scaled 53-repo run takes 7.5 seconds with the deadline and 105 without, all 53 failing open
either way.

The test reads the budget out of the source and the timeout out of the workflow, so raising one
without the other fails.

* Bound the header probe from the first byte, and stop stale picks rolling back

- requests' timeout is an inactivity timeout, so a peer trickling response
  HEADERS never reached the bounded body reader; the request now runs on the
  same abandonable worker as the drain, under one wall-clock deadline.
- the offline probe bailed before consulting the memo, so begin_load fell back
  to the filename heuristic right after a plan-time probe had answered, and
  published the 4B encoder repos for a renamed 9B checkpoint.
- picking a second model while the first plan request was in flight let the
  older rejection restore its own steps and guidance over the newer, accepted
  pick; a rollback now applies only if its selection is still current.

* Advance the selection token on curated picks, and mirror urllib3 into the extra

The curated non-GGUF branch applied its defaults and returned without touching the
selection token or the pending revert, so it was the one accepted selection the token
mechanism did not cover: an earlier GGUF pick whose plan came back incompatible still
matched its own token and restored ITS quant, steps and guidance over the curated model
that was already loading. It now follows the same optimistic-then-revert contract as the
other three branches, and the test counts token bumps against branches that apply a
model's defaults, so a fifth branch cannot opt out either.

urllib3>=2.3.0 went into studio.txt only, which left pip install "unsloth[studio]"
without the floor the range-read preflight's socket shutdown needs, and failed
test_studio_extra_matches_requirements.py.

* Do not replay a pick's settings over an edit the user made while it was pending

Staging an undownloaded model deliberately leaves `busy` unset for as long as the
download takes, so Steps and Guidance stay live the whole time. The pending revert holds
the values captured before the pick, and every rollback path replayed them
unconditionally, so a staged load that later failed or was cancelled silently undid the
user's own edit. The selection token cannot cover this: it moves on another pick, not on
a slider.

The sliders go through handlers that mark the settings edited, every settings restore is
behind that flag, and arming a fresh pick clears it so one edit cannot disarm every later
pick. The quant label rollback is unchanged: that one is still about the pick.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Let the merged plan test see the compatibility field in the envelope

origin/main's test asserts the download plan dict exactly, and this branch adds
incompatible_reason to it, so the two only collided once they were in the same tree.

* Confirm the Hub revision before refusing a pick from a cached header

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…unslothai#8228)

* Realign the desktop release tests with the post-publish VirusTotal job

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tie the release contract tests to what they are meant to guard

Checkpoint of in-progress work, mutation testing still outstanding.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Scope the release wait and scan assertions to the mechanism they guard

The wait checks searched the whole step, so a one-shot jobs API read beside an
unrelated loop passed; they now run against the poll loop body and also require
a break. The scan job's condition was accepted on a success() substring, which
let a disjunction through; it now has to require success() conjunctively. And
the scan's directory was compared by leaf between two download steps, so moving
both under a new parent, or repointing the script argument, scanned an empty
directory and still reported clean; the argument the step passes is now
compared against the download path.

* Tighten the comments on the release contract tests

* Reject any job-level condition on the scan and require a live poll loop

Accepting a condition that merely opened with success() let success() && false
through, which skips the sweep after a publication that succeeded, so no
job-level if: is accepted at all now: reaching virustotal-scan is needs:'s
decision alone. The wait helper likewise selected a loop by shape, so turning
while :; do into while false; do kept every assertion green while the shell
skipped the API reads and fell through to a download that races the matrix; the
helper now only selects an unconditional poll.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…tates (unslothai#8231)

* GRPO: wrap the model that owns the head when falling back to hidden states

TRL builds GRPO's ref_model with a plain architecture.from_pretrained(model_id),
so on every non-PEFT run the hidden-states fallback has to catch a bare
*ForCausalLM. _grpo_hidden_states_wrap_target walked ("base_model", "model")
looking for an adapter's wrapped model and landed on that model's decoder body,
which returns no .logits, so the head above it ran untouched and the wrapper
became a silent no-op. The reference logprob path then received [B, T, vocab]
where it expects [B, T, hidden] and died in the lm_head matmul.

Descend only into a child that still owns an output head.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* GRPO hidden-states fallback: survive accelerate rebinding the wrapped forward

Wrapping the head owner puts the fallback forward where accelerate can see it.
extract_model_from_parallel(keep_fp32_wrapper = False), which the GRPO loop calls
on every step, rebinds an instance-level forward as MethodType(forward, model),
so the wrapper is re-entered with the module as its leading positional argument
and the head owner passes it on as input_ids. Drop a leading argument that is the
target module.

Also make the regression tests real: build the tiny config locally instead of
fetching it from the Hub, drop the CUDA gate so they run in the CPU job that
collects tests/, and pin the switch per block so a process that starts with
UNSLOTH_RETURN_HIDDEN_STATES=1 does not read hidden states as the reference.

* Tighten the comments on the GRPO hidden-states wrap target

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…unslothai#8018)

* Diffusion: allow fp8 on Qwen-Image again, and split the training deny

_FAMILY_SCHEME_DENY refused fp8 on qwen-image / qwen-image-edit because the
family rendered every frame black. That cause is gone. It was torchao's
_choose_scale_float8 having no eps clamp: qwen's text stream emits all-zero
token rows through a run-varying set of txt_mlp.net.2 linears, so the per-row
scale went to 0 and the qdata to NaN. _make_quant_config now floors it with
activation_value_lb = 1e-12, and the deny was left behind on its old
justification.

Re-measured on B200 with the floor, on BOTH paths the deny governs, since it
gates select_transformer_quant_scheme rather than one loader:

  prequant checkpoint, full 28-pair gate:
    28/28 PASS, SSIM 0.87-0.99, LPIPS 0.027-0.228, CLIP delta <= 0.019
  on-the-fly quantize_, the gate's own simple_object prompt and seeds:
    LPIPS 0.048 / 0.033 / 0.027 / 0.063  (gate checkpoint: 0.050 / 0.048 / 0.033 / 0.027)

against pre-floor plain fp8 at LPIPS 0.712, SSIM 0.016, mean luma 0. The bar
is 0.10. Keeping the deny cost speed: it pinned qwen to int8 at 1.10x bf16
when compiled fp8 measures 1.21x.

mxfp8 and nvfp4 stay denied. Those failures were activation outliers and the
4-bit noise floor, not the zero-row bug, and nothing here touches them.

The deny table has a second consumer: core/training/diffusion_train_common.py
filters the Train UI's precision list and hard-rejects a run through
_family_denied. All the evidence above is rendering evidence. It says a frozen
fp8 forward reconstructs the bf16 image, not that a LoRA converges when its
frozen linears are fp8, and nobody has run that. So training gets its own
_FAMILY_TRAIN_SCHEME_DENY and keeps refusing qwen fp8, via a
_family_train_denied helper that is a strict superset of the inference rule.
A test pins that direction, because training being more permissive than
inference is the one way this split could go wrong.

* Reject an fp8 prequant checkpoint built without the activation floor

Lifting the qwen fp8 deny lets a pre-floor artifact load. Its serialized
activation quantiser still carries hp_value_lb=None, so it reproduces the
black frames the deny existed for, and neither existing guard catches it:
_validate_checkpoint checks fp8_granularity but nothing about the floor, and
the smoke probe exercises a NEWLY BUILT config rather than the loaded tensors.

These artifacts are real, not hypothetical. Auditing every transformer_fp8.pt
on this box, four carry hp_value_lb=1e-12 and one, built before the fix,
carries None.

Checked on the loaded TENSORS rather than metadata, deliberately. The floor is
serialized per tensor as act_quant_kwargs.hp_value_lb, so it can be read
directly; a pre-floor checkpoint predates any metadata field that could be
stamped; and every metadata check around this one accepts an absent field for
back-compat, which is exactly the wrong default here. Reading the tensors is
fail-closed and needs no format bump. Verified against both artifacts on disk:
the pre-floor one is rejected, the floored one accepted, and a rejection falls
through to the dense re-quantise path that applies the floor.

A dense tensor has no act_quant_kwargs, and an unwalkable state dict raises,
so both are treated as "not evidence of a missing floor" and left to the
scheme and granularity checks. Failing closed there would reject every int8
checkpoint too.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Let auto fall back to a scheme that has a hosted prequant

Lifting the qwen fp8 deny changed what auto picks, and that has a consequence
beyond quality. auto now returns fp8 for qwen-image, but the family publishes
only an int8 DiT checkpoint, so usable_prequant_source(fp8) is empty and the
loader must size the ~40 GB dense fp8 build. On a host that rejects that
transient the dense-fit check set dense_declined and the pick fell through to
GGUF, losing the int8 prequant that auto reached before this change. A machine
that used to load a fitting checkpoint would have started loading GGUF instead.

select_transformer_quant_scheme returns only the winner, which is all the load
needs until the winner has no published checkpoint AND cannot fit dense. So
auto_scheme_candidates exposes the whole ladder, built from the same tiers,
deny list and smoke probe as the selector's auto branch, and a test asserts the
selector's answer is always the head of that list so the two cannot drift.

_auto_prequant_retry_scheme then walks the rungs BELOW the winner for one with
a usable prequant and pins transformer_quant to it. Strictly below: a higher
rung was already rejected by the ladder, so offering it back would hand the
loader a scheme auto itself would refuse. Only for auto, since an explicit
scheme is honored or refused and never swapped, and not when a LoRA is baked,
which takes the dense path regardless.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Make the auto retry cached-only and reachable from the offload path

Two follow-ons to the retry, both consequences of putting it in one branch and
not re-reading the policy it has to live under.

Cached-only. For a GGUF pick with auto, a hosted prequant is used only when
already cached: fetching one means downloading a SECOND multi-GB denoiser for a
pick that already has its GGUF. _uncached_prequant_repo enforces that, but it
runs select_transformer_quant_scheme, which only ever returns the WINNER, so it
inspected fp8 alone. A retry handing back an uncached int8 repo went straight
past it. The retry now applies the same rule: a repo source must be cached, a
local override is the operator's own file and costs no bytes.

Reachable from the offload path. The retry sat only in the else branch, the one
taken when the GGUF plan does NOT offload. When it does, the branch above
replans auto's winner alone; if that replan still offloads, quant_plan stays
unset and the gate below skips the dense/prequant load entirely, so a cached
lower rung that WOULD have fit was never looked at. The retry now also runs when
that branch produces no resident plan, re-resolving the candidate and replanning
at the lower scheme before anything falls back to GGUF.

The existing test needed updating rather than replacing: it stubbed
usable_prequant_source with a bare string, which no longer satisfies the source
contract. It now covers cached repo (retry), uncached repo (no retry) and local
override (retry regardless).

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Hoist the replan helper out of the candidate guard

The offload-path retry rebinds `candidate` and calls `_replan_candidate`, but that
closure was defined inside `if candidate is not None:`. The retry is reached
precisely when the first resolve returned None (the free-disk gate skips auto's
winner while a lower cached prequant still passes), so the name was unbound
exactly where it is needed and the load raised UnboundLocalError under the load
lock instead of loading the cached rung.

The closure reads `candidate` at call time, so hoisting it changes nothing for
the callers that already worked.

Regression test asserts both resolves run, and fails with UnboundLocalError when
the definition is nested again.

* Make the resident retry reachable, sized, and honest about provenance

Three review findings on the resident-plan branch.

The retry sat under 'if dense_mib > 0', but dense_mib is zero exactly when the
prefetch capacity gate declined the base transformer/ shards, which is the
fresh Qwen cache this PR was written for: fp8 wins, only int8 is published,
so the load ran fp8 with no prequant and no dense fallback and dropped
straight back to GGUF. Zero staged shards is not missing information, it means
the dense build cannot run, so the retry now covers that case too.

The retry also pinned a rung on existence alone. An int8 checkpoint can
outweigh the Q4 GGUF that planned resident, so a host that fits the GGUF need
not fit the rung retried into; the load would move it onto CUDA after eviction
under a GGUF-sized budget. It is now resolved and replanned like the offload
branch, and taken only when that plan is resident.

Pinning the retry also overwrote the user's 'auto' request, and
build_resolved_record calls anything but None/''/'auto' explicit, so status
badged a backend decision as the user's own choice. The request is frozen
before any retry and that is what provenance reads.

Tests: the retry fires with zero staged shards; a rung that does not plan
resident is declined and the GGUF stands; an auto pick that retried is still
badged auto while a real int8 request is not relabelled. The first two fail
against the previous shape.

* Spare a cached checkpoint from the space gate, and check an override's scheme

Two problems the fp8 lift exposed.

1. resolve_dense_quant_candidate ran its download-space gate unconditionally,
   even though its own comment says a cached re-download is a no-op. The auto
   retry only ever proposes a rung whose checkpoint is ALREADY cached, so on a
   low-disk or moved-cache install the gate discarded exactly the candidate the
   retry exists to find and the pick fell back to the GGUF. Skip the gate when
   the prequant source is cached; an uncached one still trips it.

2. resolve_prequant_source returns a path source for ANY override without
   looking at the file, so with fp8 no longer denied for qwen-image, `auto` now
   picks fp8 and an allowlisted local INT8 checkpoint reads as an available fp8
   prequant. Planning then skips staging the dense transformer, the loader hits
   the same metadata.scheme check it runs at load time, refuses the file, and
   with no dense fallback the pick silently drops to GGUF.

   usable_prequant_source now requires the override to be baked for the scheme
   being resolved. Reading that is cheap despite the file size: mmap plus
   map_location="meta" maps the storages instead of reading them, so only the
   pickle structure is parsed (measured 1.18s on a 34 GB checkpoint), cached on
   (path, mtime, size) because the auto ladder asks once per candidate. An
   unreadable checkpoint counts as unknown, so planning budgets dense.

Three tests, all verified load-bearing against the unfixed code.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Pin the cached probe to the active cache root

The cached-prequant excuse added in f5ce05a called prequant_checkpoint_cached
without a cache_dir. Unpinned, cached_checkpoint_path searches only
huggingface_hub's import-time constant, so after Studio's cache folder changes
the retry proves the checkpoint cached in the LIVE root and this still called it
uncached and re-applied the space gate. That defeats the moved-cache retry the
excuse exists for, which is the same case the excuse was added to rescue.

Both other call sites already pin hub_cache_dir(); this one now does too, via
active_hf_hub_cache directly since importing diffusion here would be circular.

Test asserts the root reaching the probe, and fails when the argument is dropped.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Exempt a local pre-quant override from the cache-disk gate, and key the scheme memo on nanoseconds

Two follow-ons to the cached-prequant excuse.

prequant_checkpoint_cached only answers for hosted repos: _cached_in_root returns
None for any kind other than "repo", so a `path` source always reported "not
cached" and the space gate re-applied to a file the operator already has on disk.
On a low-disk host that dropped the local rung back to GGUF. A path override
downloads nothing, so it is cached by construction.

The local scheme memo keyed on int(st_mtime), which truncates to seconds. The
int8 and fp8 bakes of one model are the same size, so an atomic swap inside one
second left the key unchanged and every later probe in that process reported the
old scheme, which is the failure the scheme check exists to stop, inverted.
st_mtime_ns instead.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…nslothai#8121)

* Report the network error when the offline retry finds nothing cached

A dropped connection during a load triggers the forced-offline retry, which
can only succeed on what is already cached. When the cache is empty that
retry fails too, and Transformers reports it badly: under offline mode it
skips its "does not appear to have a file named" raise and falls through
with resolved_archive_file = None, so what reaches the user is

  AttributeError: 'NoneType' object has no attribute 'endswith'

from inside from_pretrained, with no mention of the network at all. Hit on
Kaggle loading unsloth/Qwen2.5-VL-7B-Instruct-bnb-4bit on a T4.

The online error is what surfaces now, with the offline attempt chained on
as its cause. Its type is preserved, so a caller retrying on network errors
still sees one. An out-of-memory retry is left alone: a second load of a
large VLM can exhaust memory where the first did not, and that is the
retry's own news rather than a symptom of the network.

* Shorten the comments on the offline retry

* Shorten the comments on the offline retry and its tests

* Stop the retry pinning the failed load, hiding real errors, or losing the cause

Four things the review found, all reproduced first.

Holding the online exception held its traceback, so the frames of the failed
load stayed reachable and the collect before the retry could not free the
half-built model. Keep the error, drop the traceback.

Selecting the retry's own error only for an OOM meant every other retry failure,
a corrupt checkpoint or a missing dependency, was replaced by the earlier network
error. Inverted: surface the online error only for offline mode's empty-cache
artifact, which is the one retry failure that says nothing. That also covers the
OOM spellings a type list cannot, since accelerate re-raises as a bare
RuntimeError and XPU has its own class.

raise ... from e overwrote the cause of an error classified as network-related
THROUGH its cause, leaving it unclassifiable. Only chain where there is no cause
to lose; the retry still arrives as __context__.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Free a wrapped online error's frames and keep its chained network cause

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Keep the failed cache retry visible without rewriting the online error's chain

Surface the online error from outside the retry's except handler, so its own
cause/context survive untouched and the cache miss is reported as a note rather
than as a chain link Python would either hide or overwrite. Also recognise the
tokenizer and processor cache-miss spellings, not just the weights one.

* Keep the surfaced error's origin and release the retry's frames

---------

Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
unslothai#7867)

* Keep an explicitly requested float32 model in float32 without bfloat16

A model loaded with dtype = torch.float32 was being wrapped in float16
autocast on V100/T4 even when the caller set fp16 = False and bf16 = False.
The mixed precision block in rl.py reads "neither flag set" as "caller did
not choose" and picks for them:

    use_bf16_amp = (not float16) and _bf16_supported()
    args.fp16    = not use_bf16_amp

so on a GPU without bf16 the answer is always float16. float16 has five
exponent bits against float32's eight, so a value the model was loaded wide
enough to hold overflows to inf and then NaN.

Spark_TTS_(0_5B) is the case that surfaced it: it loads with
dtype = torch.float32 ("Spark seems to only work on float32 for now"), sets
fp16 = False, bf16 = False, and on a T4 logs nan for every step, then dies
at inference inside torch.multinomial, which refuses a distribution
containing NaN. The sampler assert is two steps downstream of the cause.

Suppressing the autocast for every float32 model is too wide: full
finetuning upcasts trainable weights to float32 by itself, and float16
autocast over float32 master weights is the ordinary V100/T4 recipe
(issue unslothai#4082, tests/python/test_v100_fullft_precision.py). So
from_pretrained now records whether float32 was ASKED for in
UNSLOTH_USER_FLOAT32, as opposed to arrived at by upcasting, and only an
explicit request suppresses the autocast. It is set in both loaders, since
FastLanguageModel and FastBaseModel resolve dtype independently, and written
on every load so a previous run cannot leave a stale "1" behind.

Only the float16 fallback changes. bf16 has float32's exponent range, so a
bf16 GPU keeps autocasting and keeps the memory saving. An explicit
fp16 = True or bf16 = True is still obeyed, float16 and bfloat16 models are
untouched, and UNSLOTH_FORCE_FLOAT32 models still take their earlier branch.

tests/test_float32_no_fp16_autocast.py pulls the mixed precision block out
of rl.py by AST and executes it against fake args/model objects with the
bf16 capability check stubbed, so the no-bf16 path is covered without a
V100/T4. No GPU, no network, no trl import.

Also, separately: do not let one optional audio dependency kill the whole
test session. require_python_package calls sys.exit(1) when a package is
missing, and every caller is a test module invoking it at import time, so
under pytest that is not a skip of one module -- SystemExit propagates out
of collection and the run ends with

    INTERNALERROR> SystemExit: 1

with no report at all. A missing xcodec2 took out 1000+ unrelated tests. It
now skips the module under pytest; outside pytest the exit is unchanged,
since these helpers are also used by standalone scripts. test_whisper.py had
the same shape for a different reason: it downloads an audio fixture at
import and did `assert False` on failure. Wikimedia rate limits and this URL
really did answer 429 during a batch run, and an asset we could not fetch
says nothing about unsloth, so it skips too.

* Record the float32 request on the model, and let GRPO honour a disabled autocast

Two real gaps in the float32 gating, plus the provenance problem underneath both.

The gate never reached most users. llama, mistral, gemma, gemma2, qwen2 and
qwen3 LoRA/QLoRA loads go through FastLanguageModel to dispatch_model.from_pretrained,
which is neither of the two loaders that recorded the request, so user_float32
stayed false and the fp16 autocast this branch exists to avoid ran anyway. That
is most of the notebooks.

The value was also process-global and derived rather than asked for. A program
that loads two models before building a trainer described whichever loaded last,
and a dtype inferred from a 4bit config's bnb_4bit_compute_dtype was recorded as
an explicit model-wide request, which is especially wrong under full finetuning
where the loader then turns 4bit off again. Both entry points now read the
argument as the caller wrote it, before any normalisation, and the answer is
attached to the model. The outermost caller wins, since only it saw the raw
argument; the two delegating returns in FastLanguageModel re-stamp it for that
reason.

Then ACCELERATE_MIXED_PRECISION = 'no' was read as a two-way switch in the GRPO
replacements, so 'no' came out as bfloat16 and autocast was entered anyway. torch
does not ignore that on a T4 or V100, it raises "Current CUDA Device does not
support bfloat16", which is exactly the hardware this branch targets. Verified
against torch's own autocast __init__: the check is gated on `enabled`, so
disabling autocast is both the correct reading of 'no' and the minimal fix.
Full finetuning already set 'no', so this was reachable before this PR too.

Tests: 4384 passed against 4369 on the same tree with these changes stashed,
identical 1310 environment failures either way, and nothing failing on this
branch that is not also failing on its base.

* Keep forced float32 on fp16 autocast, size GRPO chunks by the flag, and run the tests off a GPU

Three follow-ups on the autocast change.

UNSLOTH_FORCE_FLOAT32 exports ACCELERATE_MIXED_PRECISION 'no' as well, and the
new gate read only that, so the injected _prepare_inputs header disabled
autocast for it while the dtype expression right beside it was still choosing
float16. That left Gemma3 and gpt-oss generation in full float32, and it
disagreed with the two other consumers, which set _autocast_enabled True for
exactly this case. The header honours the flag now.

The GRPO chunk autotuner derived dtype_bytes from _autocast_dtype alone, which
stays bfloat16 when autocast is off, so it sized hidden states and logits as
16-bit for a forward running in float32. That is half the real figure, on the
explicit-float32 and full-finetuning runs this branch is for.

The new tests drove torch.amp.autocast(device_type = "cuda") on a box that has
CUDA. On a CPU runner torch warns "CUDA is not available. Disabling" and hands
back a no-op, so the premise test would not have raised and every enabled case
would have read False, failing for reasons unrelated to the code. Measured, then
fixed by claiming the device rather than skipping, since a CPU job is where these
would most need to run. They pass with the GPUs visible and with
CUDA_VISIBLE_DEVICES empty.

Tests: 4386 passed, same 1310 environment failures as the branch base, nothing
failing here that is not also failing there.

* Size the GRPO chunk on the dtype the forward runs in

The autocast-off branch assumed float32, but pure bfloat16 full finetuning
also disables autocast (ACCELERATE_MIXED_PRECISION='no') while keeping bf16
weights and a bf16 forward. That path got dtype_bytes=32 where main gave 16,
cutting the chunk ~1.5x and doubling the forward-pass count on 10-22GB cards.
Read lm_head.dtype instead: float32 for an explicit float32 load, bfloat16
here. Retargets the test that pinned the old value.

* Apply ruff kwarg-spacing formatting

pre-commit.ci's ruff-format-with-kwargs hook reported "files were modified by
this hook" and could not push the result back, so the check stayed red.
Applied locally instead.

Three source-asserting tests had to be made robust rather than re-pinned,
since the reformatting is legitimate and will happen again:

- test_the_flag_is_recorded_beside_the_dtype counted the literal
  "self._autocast_enabled = (", which the formatter collapsed onto one line.
  Now pairs each _autocast_dtype initialiser with a nearby flag assignment by
  position, so it still catches a genuinely missing one.
- test_the_original_error_is_still_reported anchored on a whole f-string
  literal, which the formatter merged with the hint that follows it. Anchors
  on the message text alone now; either shape satisfies the intent.
- test_the_source_beats_the_version_fallback exposed a real fragility rather
  than a test problem: the detector matched the literal "kw_only=True", so any
  whitespace in transformers' own source would have read an install that needs
  nothing as one that needs patching. Made whitespace-tolerant.

* Latch the GRPO autocast decision on the trainer

* Add the license header to the new test files

* Stamp the forced float32 answer on the model

UNSLOTH_FORCE_FLOAT32 is process wide and from_pretrained clears it on every
load, so a model loaded after a Gemma3 or gpt-oss trainer was built left '0'
behind and GRPO's first generation dropped the float16 autocast that rl.py's
'no' was written expecting, running generation in full float32.

The loaders now stamp the answer on the model they loaded, next to the
existing float32 request marker, and the trainer reads it from there. Models
without the stamp fall back to the environment as before.

* Preserve a bf16 trainer when a forced-float32 model was loaded (unslothai#7867)

* Stamp the forced float32 answer on every loader return path (unslothai#7867)

* Stamp the float32 answers on the text-diffusion dispatch (unslothai#7867)

* Apply the repo ruff-format hook to a test touched by this PR

* Apply the repo ruff-format hook (ruff 0.6.9) to files this PR touches

* Fix the trainer reading the process-wide forced float32 flag for PR unslothai#7867

* Fix a missing optional dependency aborting the whole pytest session for PR unslothai#7867

require_package exited the process when a system package was absent. The TTS
test modules call it at import time, so under pytest the SystemExit escaped
collection and ended the run with INTERNALERROR / exit code 3 instead of
skipping one file. It now degrades to a module-level skip under pytest, the
same treatment require_python_package already had, and keeps the exit for the
standalone script callers.

test_whisper.py also imported the unsloth runtime unguarded, which is a
collection error on the Windows runner where triton is absent; guard it with a
module-level skip.

* Inherit an outer autocast by omitting dtype, not by a sentinel

* Read the forced float32 stamp inside native fast generation

* Stamp the full finetuning mode on the model the trainer reads

* Keep one missing-dependency helper after the merge with main

The merge left this branch's _skip_if_pytest alongside main's _missing_dependency, doing the same job, plus two near-duplicate test files. Fold both into main's helper and its test module, keeping this branch's extra coverage of require_package and of the call at module scope.

* Make the generation autocast tests independent of the host having CUDA

torch.autocast(device_type = 'cuda') disables itself when CUDA is absent, so reading _enabled off the constructed object measured the runner instead of the branch, and these could never pass on a CPU-only machine, a Mac or Windows. Record the arguments the code asks for instead. Also skip before importing rl_replacements, which needs unsloth_zoo.

* Apply the repo's ruff kwarg-spacing formatting

* Format these three files with the ruff the hook actually pins

The ruff-format-with-kwargs hook installs ruff==0.6.9 through
additional_dependencies, and 0.6.9 and 0.15 disagree on where the message
goes in a multi-line assert and on how a long lambda signature wraps. I
had run the script with the workspace ruff, so pre-commit.ci kept
reformatting these back and failing, with nothing to show in the diff.

AST is identical on all three.

* Drop the nullcontext import this PR no longer uses

Left over from the earlier shape of the autocast gating, which now omits dtype
instead of passing a sentinel context. Source lint's import-hoist check treats an
added-but-unused hoisted import as a blocker, and it is right: nothing in this
file references it.

* Tighten comments for the float32 dtype gating change

---------

Co-authored-by: danielhanchen <[email protected]>
…othai#8124)

* Do not let a broken TensorFlow install break the Unsloth import

Transformers 4.x imports TensorFlow and Flax merely because they are
installed: image_transforms.py does

  if is_tf_available(): import tensorflow

and that module is reached from processing_utils, which is on Unsloth's own
import path. So a broken optional backend breaks Unsloth, which uses
neither.

Hit on Colab running Qwen2.5_Coder_(1.5B)-Tool_Calling. The install cell
moves protobuf 5.29.6 down to 3.20.3, Colab's preinstalled TensorFlow then
raises

  ImportError: cannot import name 'runtime_version' from 'google.protobuf'

and that is what the user sees at the first `from unsloth import ...`, with
nothing in the traceback explaining why a torch library is importing
TensorFlow.

USE_TF and USE_FLAX are set to 0 with setdefault, so an explicit choice
still wins, and only when transformers has not already been imported, since
it reads them once at import and an already-loaded transformers has settled
the question. 5.x dropped both backends and ignores the variables.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Shorten the TF opt-out comments

* Tighten the TF opt-out comments

* Clear the cached TF/Flax availability when Transformers is already imported

The USE_TF/USE_FLAX opt-out only lands when Transformers has not been
imported yet. Once it has, the variables are spent, but the answer they
feed is not: Transformers decided _tf_available from find_spec plus the
installed version, without importing TensorFlow, so a broken backend is
still waiting to load in image_transforms on Unsloth's own import path.
Clear the cached flags in that case, unless the backend is already
imported or the user opted in with USE_TF / FORCE_TF_AVAILABLE, and
tolerate their absence on Transformers 5.x.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Keep an already imported backend when Transformers loads later

* Honor a backend opt-in Transformers already consumed

Transformers reads USE_TF, FORCE_TF_AVAILABLE and USE_FLAX once, at its own
import, and keeps the answer in module constants. The already-imported
branch consulted only the live os.environ, so a caller that set one of
those, let Transformers consume it, then put the environment back -- a
patch.dict around the import, a launcher that tidies up after itself --
looked like a caller who never opted in, and the flag was cleared despite
Transformers having honoured it.

Read what Transformers actually used, alongside the environment. Note the
spelling: the variable is USE_FLAX, the constant it lands in is USE_JAX,
so looking for a cached USE_FLAX would find nothing and keep the bug.

Only true values count. All three constants default to "AUTO" when unset,
and accepting AUTO would preserve every flag on every machine that never
set anything, turning the guard into a no-op that still looks like a fix.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Treat AUTO as unset when opting the backends out

setdefault keeps whatever is already in the environment, and "whatever is
already there" includes AUTO. Transformers reads AUTO as "enable if
installed", which is exactly the state this guard exists to prevent, so a
launcher or notebook that mirrors Transformers' own defaults into the
environment disabled the guard without anyone noticing.

Verified with a broken TensorFlow on the path: USE_TF=AUTO plus the old
setdefault leaves _tf_available True, and the import Unsloth was protecting
is reachable again.

Overwrite unless the value is a real opt-in, which also makes this branch
agree with the already-imported one below: same true-value set, same
FORCE_TF_AVAILABLE handling, same hands-off rule for a backend already in
sys.modules. Anything Transformers does not read as true already means off,
so writing "0" over it changes nothing else.

The two tests that pinned the old spelling now pin the behaviour instead.
Asserting "the source says setdefault" tracked how the guarantee happened to
be written rather than the guarantee, and setdefault was not even a correct
way to get it.

* Write the opt-out variables even when Transformers is already in sys.modules

Python publishes a module object before running its body, so a thread
part-way through `import transformers` makes `"transformers" in sys.modules`
true while `transformers.utils.import_utils` does not exist yet and has not
read the environment. The else branch then found no cached flag to clear, did
nothing, and Transformers went on to set `_tf_available = True`. Write the
variables in that branch as well: inert once Transformers has read them,
decisive inside the window.

Also drop USE_TORCH from the subprocess test environment. Transformers gates
`_tf_available` on `USE_TORCH not in ENV_VARS_TRUE_VALUES`, so a runner with
USE_TORCH=1 made the "BEFORE True" cases fail for an unrelated reason.

* Overwrite the cached backend constants while import_utils is mid-body

* Skip the cached flag probe on a runner without transformers

* Tighten the backend opt-out comments

* Trim the backend opt-out comments further

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Tighten comments in the TensorFlow opt-out guard

---------

Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…dow (unslothai#8253)

* Carry the sliding window into SDPA, and treat a zero window as no window

Three related holes, all of which let a Mistral-style model attend past its
configured sliding window without saying anything.

MistralAttention_fast_forward passed the window to the flash path through
window_size but never to run_attention, so with xFormers off and FlashAttention
absent nothing carried it. Training takes the `elif self.training: pass` branch,
so no 4D mask is synthesized either, and every sequence longer than
config.sliding_window attended its whole causal history.

run_attention had no way to apply a window when there was nothing to hang it on.
With no packing and no padding mask it fell through to SDPA's is_causal, which
is full causal and has no window at all. It now builds the band mask for that
case.

A non-positive window was passed through as a real width. That makes
window_size (0, 0) for flash, and an SDPA mask whose lower bound sits above its
causal upper bound, hiding every position from every other. Both sites now read
it as "no local attention", which is how the mask builders already read an
absent one.

llama.py also recomputed HAS_XFORMERS as `xformers is not None`, overriding the
dispatcher, which turns it off when the library imports but has no kernel that
runs here. Model code then stayed on the xFormers path the dispatcher had
already left, and Mistral answers xFormers by skipping the 4D mask, which is how
the first hole above is reached in practice.

* Build the dense window mask once per shape, not once per layer

Every layer of a Mistral-style model asks the SDPA fallback for the identical
q_len x kv_len mask. At 32K that tensor is 1 GiB, and the two comparisons plus
their conjunction keep two more alive while it is built, so rebuilding it per
layer is how this path OOMs a run that xFormers or flash would have carried --
on exactly the no-xFormers, no-FlashAttention configuration the mask exists for.

Cached per device and keyed on shape and window, the same single-entry shape
_SDPA_MASK_CACHE already uses for the packed path. Read-only by contract; the
one caller that combines a mask with another does so out of place.

* Free the outgoing window mask before allocating its replacement

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: Daniel Han <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
* fix(installer): prepare Apple Silicon dependencies

* fix(studio): route mlx-vlm processors to transformers 5
* Studio: align Images and settings layouts

* Studio: preserve mobile Images inset

* Studio: prevent narrow Images header overlap

* Studio: grid Images header controls

* Studio: preserve Images titlebar drag space

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: clip Images model selector

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…fusal (unslothai#8257)

Four tests are red on a clean checkout of main. unslothai#8165 made a declined EXPLICIT
precision refuse the load instead of falling back silently, and made the
text-encoder pass return a TEQuantOutcome the loader reads .mode off. Two later
squash merges carried branches cut before it: unslothai#8162 added the saved-recipe
precision contracts, and unslothai#8141 added a placement test whose stub returns a bare
None. Neither combination was ever run.

Fixed on the test side. quantize_text_encoders is annotated -> TEQuantOutcome
and every one of its seven returns constructs one, so the None at
diffusion.py:3113 only exists because a test monkeypatches the function; and the
route only calls assert_precision_available on the diffusers engine, which is
DiffusionBackend, which defines it. Neither AttributeError is reachable in a
real run, so there is no product guard to add.

- opt into UNSLOTH_DIFFUSION_ALLOW_PRECISION_FALLBACK where the contract is
  about what the recipe records once a fallback is allowed, as the routes,
  backend and video suites already do
- assert the decline reason unslothai#8165 records instead of the old wording naming what
  loaded instead. The substantive pair is untouched: off, from explicit
- give _EngagedBackend the assert_precision_available gate the route now calls,
  and return a TEQuantOutcome from the stubbed text-encoder pass
…ai#8241)

Picking a GGUF at Q8_0 showed "BF16" in the loaded models row. Nothing on
/images/status named the quant: dtype is the pipeline COMPUTE dtype and reads
bf16 for every CUDA load, so the row had nothing sharper to print. The chat
runtime has published gguf_variant all along.

The status payload gains gguf_quant, the quant of the GGUF that is actually
backing the transformer. It is null whenever the GGUF is not what ran: a
pipeline or single_file load, and a GGUF pick the dense fast path replaced with
a torchao build, which transformer_quant already describes.

The row then reads the build in the order it is decided: the dense scheme when
one engaged, else the GGUF quant, else the pipeline dtype. Video already did
this for the first and last of those. It also stops calling a row GGUF when the
fast path replaced the GGUF, since that names a file the pipeline never opened.
A backend without the field falls back to the dtype, so an older wheel keeps
the line it has always shown.
…ads (unslothai#8218)

* Studio: budget a pre-cast fp8 text encoder at its real size

The video memory plan sizes companions from the family's bf16 component table
and scales them only by the pipeline dtype, so a load that takes its text
encoder pre-cast from a hosted fp8 checkpoint is still budgeted at bf16. For
ltx-2 that encoder is Gemma3-12B at 24.4 GB against a measured 13.2 GB
artifact, so the plan over-states the resident requirement by about 11 GB.

Scale the text-encoder term by TE_PREQUANT_BUDGET_SCALE when te_prequant
resolves a hosted checkpoint for this pick. The VAE keeps its full size: it is
never quantised on this path.

* Studio: pin the text-encoder budget on the measured artifacts and the call sites

* Studio: log the text-encoder budget when it is scaled

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: return the video memory plan to bf16 when the pre-cast encoder does not inject

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Merge origin/main into tebudget

main's strict precision refusal now rejects an explicit text_encoder_quant the
CPU test stub cannot cast, which reaches the pre-cast budget tests even though
they are about the plan and not the cast. Allow the legacy silent fallback in
that helper, the same way the LTX-2.3 wiring test already does.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…g it (unslothai#8211)

* Desktop: keep probing the announced backend port instead of discarding it

The backend announces its port once, on a TAURI_PORT stdout line. That line
arrives while it is still importing torch, and validate_candidate_port probed
exactly once with a 2 s per-request budget. When the backend could not answer
in time the only announcement was dropped, and the window went on waiting for
a backend on the port the backend had already reported it could not bind,
until BACKEND_START_DEADLINE expired 300 s later.

Seen on a CPU-only Windows machine where 8888 was taken and the backend moved
to 8889:

  16:51:59 [backend] TAURI_PORT=8889
  16:52:01 [WARN] Ignoring unverified TAURI_PORT candidate 8889
  16:56:37 [error] The Unsloth backend did not start within 300 seconds

The backend was up the whole time. Its own log for that second records
/api/liveness taking 2156 ms against the 2000 ms LOCAL_HTTP_TIMEOUT. Healthy
runs on the same machine validated in 735 ms, 792 ms and 2295 ms, so this is a
race the fast path wins most of the time and loses on a cold start.

Retry until the backend answers or BACKEND_START_DEADLINE passes, rather than
giving the slowest moment of startup a single attempt. The loop stops early if
the generation changes or another path claims the port, so a restarted backend
does not leave an old probe running.

* Desktop: back off between port-verification probes

A probe is a liveness request plus a desktop-login request, each up to
LOCAL_HTTP_TIMEOUT, aimed at a backend that is by definition busy. Retrying at
a flat 2 s would have put roughly 90 requests into a 100 s torch import, adding
load to the slow start being waited on.

Double from 250 ms to a 5 s cap instead. The common race, where the backend is
a few hundred ms from ready, now resolves in about 2.2 s rather than 4 s, and
the long waits cost far less: about 18 probes rather than 26 across a 100 s
import, and 46 rather than 75 if the backend never answers at all.

* Desktop: share one start deadline between the watchdog and port validation

Port validation started its own 300 s clock when the TAURI_PORT line arrived,
which is well after the process starts: 23 s later in the report that prompted
this. So the retry loop could outlive the watchdog, and a validation that
succeeded in that gap emitted server-port after server-start-timeout had
already put the window in an error state. The frontend's server-port handler
sets the api base but does not clear backendError or startingRef, so that
combination leaves a healthy validated backend behind a permanent error screen.

Capture the deadline once at spawn and pass it to both. It is taken before
start_watchdog spawns its thread, so validation can only ever end at or before
the timeout it must not outlive.

* Desktop: check the start deadline before accepting a validated port

The deadline was only consulted after a failed probe, so a success could still
be emitted past it by two routes: the TAURI_PORT line itself arriving late, and
a probe that starts just under the deadline but finishes over it. The watchdog
does not kill a timed-out backend, so both are reachable on a slow start, and
either one puts server-port after server-start-timeout, which strands the
window in an error state it has no handler to leave.

Check before each probe and again before accepting one, and cap the sleep to
the time left. A port verified too late is now dropped with its own message
rather than reported as unverified, and an announcement that arrives after the
deadline says so instead of claiming zero attempts.

* Desktop: let only one of the start timeout and the port claim reach the window

Checking the clock and claiming the port were still two steps with a gap. A
probe could succeed just inside the deadline and then be descheduled, or wait
on the state mutex, long enough for the watchdog to observe port == None and
commit to server-start-timeout; validation would then assign the port and emit
server-port on top of it, which is the stranded error screen again.

Make the two outcomes mutually exclusive in the state they already share. The
watchdog sets start_timed_out while still holding the mutex it used to decide,
and port validation refuses to claim when that flag is set. Both generation
bumps clear it alongside the other per-start fields, so a restart starts clean.
…on (unslothai#8259)

tests/version_compat/test_trl_fake_train_cpu.py and
test_trl_padding_free_max_length.py replace torch.compile, make
torch.accelerator.is_available answer False, and rewrite every
device = "cuda" allocation to CPU, all at module import time and with no
teardown. pytest imports every selected file during collection, so a GPU
test running later in the same process gets CPU tensors out of
torch.randn(..., device = "cuda"): its CUDA autocast never applies and it
passes without testing anything.

Move the patches into module-scoped autouse fixtures driven by
pytest.MonkeyPatch, which undoes them at module teardown. They still land
before the module imports unsloth and generates a trainer, which is the
only reason they sat at import time.

Add tests/version_compat/test_import_leaves_torch_globals_alone.py: a
subprocess that imports both modules and checks torch.compile,
torch.Tensor.to/.cuda, torch.accelerator.is_available and a real
device = "cuda" allocation, plus a static check that no module in the
directory assigns to a torch attribute at import time.
@Imagineer99

Copy link
Copy Markdown
Owner Author

Closing disposable staging PR so unrelated PR workflows do not consume runner capacity; the dedicated branch-push Tauri A/B workflow remains active.

danielhanchen added a commit that referenced this pull request Nov 11, 2026
…nslothai#17459)

## Summary

Moves Studio's stable-diffusion.cpp prebuilt from
`master-982-0518b34-uba6ac30` to `master-982-0518b34-ueb0e729`, the
release built from fork master `eb0e729`. That is 36 fork commits on top
of the current pin. The tag keeps the `master-982` prefix because the
fork's release naming still counts from its last upstream release tag.

What the new build brings:

- Upstream resync to `master-1056` (unslothai/stable-diffusion.cpp#54):
packed INT4 convrot, MiniMax-H3 QKV chunking, RelayVSR, SDXL ControlNet
Union. Also Cosmos3-Nano-Sim-Transfer video-to-video (#53).
- x86 CPU: llamafile tinyBLAS GEMM for Q8_0 (#42), F16 / BF16 (#47) and
Q4_1 / Q5_0 / Q5_1 (#56) weights; an int8 tiled GEMM for Q8_0 / Q4_0 /
Q4_1 / Q5_0 / Q5_1 / IQ4_NL (#76); AVX512 kernels on Intel and a faster
direct convolution by default (#36, #70); Q4_K / Q2_K kept on the tiled
matmul on AMD (#57); Q5_0 / Q5_1 / Q4_1 through the Q8_0 GEMM at
diffusion batch sizes (#74); tiled flash attention and SIMD max fixes
(#66, #68, #62).
- aarch64 CPU: ik_llama.cpp GEMM kernels for K-quant and I-quant weights
(#48, #75), a NEON + i8mm variant for 128-bit SVE cores (#58), SVE flash
attention on the NEON path (#69), a 4x4 flash attention register tile
(#67).
- Metal: long graphs spread over more command buffers so the GPU
watchdog does not fire (#44), a coalesced im2col kernel (#45), flash
attention `auto` now means on without the timing probe (#46).
- Vulkan: RMS norm for short rows (#37), direct convolution chosen by an
output check instead of a timing race (#38), no host-buffer import on
AMD and MoltenVK (#60).
- HIP: bf16 WMMA operands for gfx11 / gfx12 (#59), FP32 accumulators in
the tile flash attention kernel (#61).
- CUDA: the Q8_1 block sum is computed from the quantized values, which
lowers matmul error for Q4_1 / Q5_1 / Q4_K / Q5_K / Q2_K weights (#63);
BF16 cuBLAS for large Q8_0 matmuls on A100, Hopper and datacenter
Blackwell (#39).
- Memory: the conditioning cache keeps entries across output sizes and
denoiser-only LoRA changes (#71); auto-fit charges unified-memory
devices against the RAM budget (#73, `SD_AUTOFIT_UMA=0` disables);
CPU-resident text-encoder weights are released when the next phase would
not fit (#72, `SD_TE_RELEASE=0` disables); `--mmap` repacks only what
the CPU repacks (#43); Qwen Image 2.1 prefix cache concatenated in F16
(#64).
- Packaging: bundles are smaller (#41; the Linux CPU bundle is 38.4 to
26.0 MiB, Linux CUDA 12 is 368.5 to 338.3 MiB, Linux Vulkan is 57.9 to
30.5 MiB), the Linux CPU bundles are run on emulated CPUs before
shipping (#49), and there is a new native Windows arm64 CPU bundle
(#55).

## Changes

- `studio/install_sd_cpp_prebuilt.py`: `DEFAULT_TAG` now names the new
release.
- Tests that pin the release name and its asset list now point at the
new tag. `test_sd_cpp_args.py` keeps the old pin in its list of builds
that support `--mmap`.
- The pinned asset lists gain `win-cpu-arm64`, with a test that a
Windows ARM64 host gets that bundle for `auto` / `cpu` while an x64 host
keeps `win-cpu-x64`, and that ARM64 with `cuda` or `vulkan` still gets
no match.

No Studio code changes. The existing selector already filters Windows
bundles by host architecture, so a Windows arm64 host, which today finds
no bundle in the pinned release and falls through to the upstream
fallback, now installs the native arm64 CPU build. An x64 Python running
under emulation on Windows arm64 reports `AMD64` and keeps the x64
bundle, as before. No option was removed from `sd-cli --help` or
`sd-server --help`; the new build only adds `--control-type`,
`--input-frames`, `--upscale-factor` and `--vsr-window-size`.

## Testing

- The sd.cpp, args, families, install, pin upgrade and download retry
tests pass (1406 passed). One test and one fixture error fail on main
and on this branch alike on this host, because its huggingface_hub is
older than the installed diffusers expects:
`test_create_causal_mask_patch_is_self_disabling_and_idempotent` and
`test_selection_installs_the_cuda_build`.
- Asset names: every bundle the selector can return was enumerated over
Linux x86_64 / aarch64, Windows AMD64 / ARM64 and macOS arm64 / x86_64,
with `auto`, `cpu`, `cuda` (no major, 12, 13), `vulkan` and `rocm`,
against the real asset list of the new release. Every returned name
exists in the release. The only change from the current pin is Windows
ARM64 `auto` / `cpu`, which goes from no match to `win-cpu-arm64`.
- SD1.5 (`v1-5-pruned-emaonly`), 512x512, 8 steps on CPU and 20 steps on
CUDA, euler, cfg 7, seed 42, both builds on the same machine. Each arm
repeated two or three times; every repeat was pixel-identical to the
first run of its arm. LPIPS is AlexNet.

Linux x86_64 CPU bundle, Xeon Platinum 8559C, 32 threads, wall time per
image:

| Weights | current pin | this branch | old vs new LPIPS | max pixel
diff |
| --- | --- | --- | --- | --- |
| f16 | 34.8 / 34.8 s | 16.4 / 17.2 s | 0.0001 | 13 |
| q8_0 | 31.3 / 32.4 s | 15.7 / 15.2 s | 0.007 | 118 |
| q4_K | 35.5 / 35.0 s | 18.7 / 19.0 s | 0.023 | 211 |

VAE decode alone went from 10 to 12 s down to 3.6 to 3.7 s. The
quantized CPU renders are not bit-identical to the current pin, but they
stay as close to the f16 render as before (q8_0 LPIPS to f16: 0.038 old,
0.046 new; q4_K: 0.163 old, 0.173 new).

Linux CUDA 12 bundle, Colab L4, wall time per image:

| Weights | current pin | this branch | old vs new LPIPS | max pixel
diff |
| --- | --- | --- | --- | --- |
| f16 | 4.70 / 4.70 / 4.71 s | 4.70 / 4.91 / 4.73 s | 0 | 0 |
| q8_0 | 7.42 / 4.92 / 4.90 s | 4.94 / 4.93 / 4.93 s | 0 | 0 |
| q4_1 | 18.13 / 17.97 / 17.94 s | 18.02 / 17.97 / 18.01 s | 0.025 | 198
|
| q4_K | 19.14 / 17.63 / 17.79 s | 17.74 / 17.63 / 17.61 s | 0.106 | 253
|

The current pin's first q8_0 run includes a cold start. f16 and q8_0 are
pixel-identical. q4_K moves, as the Q8_1 fix intends, and moves toward
the f16 render: LPIPS to f16 drops from 0.240 to 0.176 (q4_1: 0.327 to
0.322).

## Not covered

- macOS (Metal) and Windows were not run on hardware yet; the
cross-platform staging legs (Ubuntu, macOS 15, Windows) are still to
run.
- The new Windows arm64 bundle is covered only by the selector test and
the asset check. No Windows arm64 host ran it.
- No Vulkan, ROCm or HIP render with this build, no aarch64 Linux
render, and no Studio HTTP flow run (only `sd-cli` directly).
- No MiniMax-H3, MOSS-Image, Qwen-Image or FLUX.2 render with this
build; only SD1.5.
- CPU timings are from a shared host (both arms ran back to back with
the same thread count), and the CUDA timings come from one L4 VM, three
runs per arm. No T4 run.
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.