Repository navigation
Reject an incompatible GGUF and base pair before the download, not after - #8158
Conversation
… 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.
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.
…ip 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.
|
Three follow-up fixes pushed in 159fa19, from reviewing this against installs that predate it. The whole-body deadline was a no-op on urllib3 < 2.3. The watchdog works by half-closing the The drain now runs on a worker the caller abandons, so the bound holds regardless of what is A remembered Hub failure outlived its cause. The negative memo was consulted before
Five tests, each verified against a mutation of the fix it covers. Full backend suite: 18653 One caveat now recorded in the comment rather than overclaimed: the parser is truncation-safe, and |
…alog 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.
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.
…ing 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.
… 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.
…as 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.
# Conflicts: # studio/backend/core/inference/diffusion.py # studio/frontend/src/features/images/images-page.tsx # studio/frontend/src/features/video/video-page.tsx
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.
|
Codex Review: Didn't find any major issues. Keep it up! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
One conflict, in test_sd_cpp_backend.py: both sides appended tests to the end of the file. Kept both, this branch's begin_load/worker probe pair and main's recipe-build assertion.
|
Ran the incompatible pick on a B200. Studio installed twice from clean trees, The pair is the klein-9B Q2_K GGUF (
{"entries":[{"repo_id":"unsloth/FLUX.2-klein-9B-GGUF",
"files":["flux-2-klein-9b-Q2_K.gguf"],"bytes":3980450080}],
"total_bytes":3980450080}
{"phase":"error","error":"'flux-2-klein-9b-Q2_K.gguf' is a FLUX.2-klein-9B / klein-base-9B
checkpoint, but it is being loaded against 'black-forest-labs/FLUX.2-klein-4B', which is
FLUX.2-klein-4B / klein-base-4B. Pass base_repo for the matching variant, or pick the GGUF
that matches the selected model."}
{"entries":[...],"total_bytes":3980450080,
"incompatible_reason":"'flux-2-klein-9b-Q2_K.gguf' is a FLUX.2-klein-9B / klein-base-9B
checkpoint, but it is being loaded against 'black-forest-labs/FLUX.2-klein-4B', ..."}and {"detail":"'flux-2-klein-9b-Q2_K.gguf' is a FLUX.2-klein-9B / klein-base-9B checkpoint, but
it is being loaded against 'black-forest-labs/FLUX.2-klein-4B', which is FLUX.2-klein-4B /
klein-base-4B. Pass base_repo for the matching variant, or pick the GGUF that matches the
selected model."}The 9B repo directory stayed at zero bytes for the whole minute the run watched it, Two things this does not cover. The refusal was driven through the API because the picker cannot express an arbitrary GGUF and base pairing, so the selection-time refusal in |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: da5cf7d387
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| if got is not None and got != want: | ||
| got = _revalidated_inner_dim(repo_id, gguf_filename, hf_token, got) |
There was a problem hiding this comment.
Revalidate cached matches before accepting the pairing
When the cached GGUF header matches the selected base, this skips the Hub-revision check entirely, so a stale cached 4B snapshot is treated as valid for a 4B base even if the repo/filename has since been republished as 9B; the plan/pre-eviction check then pass, staging refreshes the GGUF, and the loader only rejects after the large download/unload path (or native keeps the stale encoder choice). Fresh evidence beyond the prior stale-cache comment is that _revalidated_inner_dim is only called under got != want, so cached matches are never confirmed against the live revision even when networking is allowed.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Declining this one, and the gate on got != want is deliberate rather than an oversight.
The two directions are not symmetric, which is the whole premise of the module. A stale cached MISMATCH produces a false REFUSAL: a hard 400 on a pick that would have loaded, unrecoverable from the UI, and the docstring calls that strictly worse than the download it saves. That is why it is now confirmed against the live revision. A stale cached MATCH produces a MISSED refusal, which is the documented fail-open outcome shared by an unreadable header, a truncated prefix, an unmapped base, an offline host and a server that ignores Range. It is not a new hole: it lands on the loader's own backstop, and that backstop reads the file _resolve_gguf_path actually returns, which is hf_hub_download's refreshed copy, so the republished 9B is refused there by name with the same sentence.
The cost of closing it is the reason not to. Confirming a match means a Hub HEAD on the common path, at plan time, again on the pre-eviction path and again in the native asset resolver, on every correct pick, to catch a republication the backstop already catches. That round trip is exactly what reading the file we already hold exists to avoid, and it would be paid by every user who never republished anything.
The native encoder choice is the same trade one level down, and that resolver already accepts a coarser answer: with no header it falls back to the filename, which a renamed checkpoint makes silent. A wrong-size encoder there fails the sd.cpp load rather than producing a wrong image.
|
@codex review |
|
Codex Review: Didn't find any major issues. Keep them coming! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |

Summary
Two problems reported in an external QA pass, both about work done before it can be known to be useless.
Selecting an incompatible FLUX.2 4B GGUF against a 9B base was rejected with a clear family-mismatch error, but only after the full 19.17 GB base model had downloaded.
assert_flux2_gguf_matches_baseruns atdiffusion.py:1908, insideload_pipeline, after_prefetch_fileshas pulled both the GGUF and the base repo, and after_unload_locked()has already torn down the working model. So a mismatch costs a large download and the model you had loaded.Separately, several preconfigured model entries could not be downloaded, returning 401 or 404.
What changed
studio/backend/core/inference/diffusion_compat.py: a metadata-only preflight. Range-reads the GGUF's first 256 KiB over HTTP, with an on-disk cache shortcut and a memoised(repo, file, has_token)probe.diffusion_families.py: extractedflux2_base_inner_dim,_flux2_inner_dim_from_tensorsandflux2_mismatch_reasonso all three checks share one message; newgguf_flux2_inner_dim_from_header;sd_cpp_text_encoders_forgains aninner_dimargument.diffusion.py: the preflight runs fromdownload_plan(reported),preflight_base_access(raises, pre-eviction) and_run_load(raises, before_prefetch_files).assert_flux2_gguf_matches_baseis untouched and remains the backstop.sd_cpp_backend.py: an_flux2_inner_dimprobe threaded through_asset_specs, closing the sibling hole wheresd_cpp_text_encoders_forpicked the 9B encoder by filename string match.models/inference.py:DiffusionDownloadPlanResponse.incompatible_reason.incompatible_reasoninside thetryand acting on it outside so a throw cannot fall through to the load.model-catalog.ts:canonicalId: "unsloth/LTX-2.3"returned 404; corrected to"Lightricks/LTX-2.3".model-catalog.check.tsgains an opt-in--networkmode plusnpm run catalog:check:network, and a daily scheduled workflow. It never runs onpull_request, so Hub flakiness cannot block a normal PR.Verification
Verified live against the Hub: a 4B GGUF against a 9B base now blocks in 0.3s from about 11 KB of header, matching pairs allow, the
unsloth/FLUX.2-klein-9Bmirror blocks too becausecanonical_basemaps it back, and an unmapped base costs zero requests.The
--networksweep confirms every declared repoId, filename and gated flag currently agrees with the Hub. I injected each of the four failure classes into a scratch copy and all four were caught with exit 1.test_diffusion_compat_preflight.pyalone: 33 passed. Frontend typecheck clean, 900/900 tests, both catalog checks pass,test_model_picker_contracts.py162 passed.A bug I found in my own first version
It was not fail-open.
GGUFReaderreads a tensor's name and its dims as separate_getcalls, so a prefix cutting between them left the name matching while the shape came back zero-filled, givinginner_dim 0and a false refusal of a valid pick. Reproduced live: a genuine klein-9B GGUF against its correct base, with a 206 body 28 bytes short, refused the load. Sweeping the last 120 bytes gave{None: 92, 0: 16, 4096: 12}.Fixed by making
_getraise past the prefix instead of fabricating, overriding_build_tensorsso no tensor-data views are built, rejecting a non-positive dim, and adding adata_offsetsanity check. Sweeping every prefix offset of a valid header now yieldsNoneonly.The
_build_tensorsoverride matters on its own: the old path allocated the whole declared checkpoint as zeros, about 20 GiB VSZ measured, which commits pagefile on Windows and would have turned the preflight into a silent no-op on the platform this was reported from. It is now 5 MiB and 35 ms.Known gaps
quantbut notsetStepsorsetGuidance, and threeloadOrStagecall sites discard the boolean. Pre-existing, but this change makes it fire at selection time rather than only on a load failure, so the sliders can describe a model that was never loaded. Fixing it means reshapingquantRevert, which the poll-based rollback also consumes.incompatible_reasonis only populated byDiffusionBackend.download_plan. The sd.cpp and video planners share the envelope but have no diffusers base to pair against, so on a GPU-less host routing to native sd.cpp the selection-time refusal does not fire; theinner_dimencoder plumbing is that path's fix instead.unsloth/Z-Image,ideogram-ai/ideogram-4andhunyuanvideo-community/HunyuanVideo-1.5are also non-repo canonicalIds. Unlike LTX-2.3 they have no real same-name artifact to key on, so the network check emits an advisory warning rather than failing.