Skip to content

Studio: stop a GGUF pick from pulling the wrong companion bytes - #7870

Merged
danielhanchen merged 50 commits into
mainfrom
gatedfix
Aug 6, 2026
Merged

danielhanchen merged 50 commits into
mainfrom
gatedfix

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Two reports that look unrelated but are the same class of bug: I pick a GGUF, and Studio goes and fetches the wrong companion bytes for it. One ends in an opaque failure, the other in a silent multi-GB download the load then uses instead of the GGUF.

1. A gated companion base fails opaquely, 15 GiB in

Picking a FLUX / Krea / Ideogram GGUF resolves a companion base from the GGUF repo's cardData.base_model, and several of those bases are gated. The download starts confidently and then dies with:

Couldn't access this Hugging Face repo with the token used for this download.
Update the HF token and restart the download, or delete the partial download if
you no longer need it.

No repo name (the base is resolved from a card tag, so it was never named in the UI), no licence link, and it lands only after the manager has been pulling for a while.

The cause is that the Hub enforces gating on the byte endpoint only, not on metadata. Anonymously, right now:

black-forest-labs/FLUX.1-dev: gated='auto' private=False files=29 bytes=53.91 GiB
krea/Krea-2-Turbo:           gated='auto' private=False files=55 bytes=57.74 GiB
ideogram-ai/ideogram-4-fp8:  gated='auto' private=False files=30 bytes=25.66 GiB

model_info(..., files_metadata=True) answers in full, so download_plan builds an 18-file / 15.4 GiB plan it has every reason to believe in, and the first 401 arrives much later inside the download worker's snapshot_download. The same asymmetry hits the loader's own prefetch.

Ten repos across the image catalogue are affected: the FLUX.2-klein pair, FLUX.1-schnell / dev / Kontext-dev / Krea-dev, FLUX.2-dev, both Krea-2 bases and ideogram-4-fp8. All report gated == "auto" -- a truthy string, never True, so this is read for truthiness.

Fix. _assert_base_repo_accessible runs right after the base repo is resolved, on the plan path and on the load path. It reads gated and, only when it is set, fetches the one file the load fetches first anyway (model_index.json). A GatedRepoError becomes a ValueError naming the repo and its licence page; /images/download-plan already maps ValueError to a 400, and the load path stamps it onto load_progress, which the images page shows verbatim. Everything else fails open -- offline, a transient 5xx, or a base without a root manifest must never be the reason a load is refused.

Worth noting for anyone tracing the UI: the images page swallows a plan error and falls back to the direct load, so in practice the message arrives via the load toast. That is why the preflight is on both paths and not just the planner.

2. A GGUF pick downloads and uses a second full denoiser

From the report, having picked unsloth/Z-Image-GGUF:

Download complete: unsloth/Z-Image-GGUF [@diffusion]
Download complete: Tongyi-MAI/Z-Image-Turbo [@diffusion]
Z-Image-Turbo-FP8.pt: 100%| 6.29G/6.29G
diffusion.prequant: pinned 239 weights to the plain-torch fp8 kernel
diffusion.prequant: loaded fp8 checkpoint (repo) onto cuda
diffusion.loaded: repo=unsloth/Z-Image-GGUF base=Tongyi-MAI/Z-Image-Turbo device=cuda offload=none

The GGUF downloaded, then a 6.29 GB hosted fp8 prequant checkpoint downloaded on top of it and became the denoiser. The GGUF was never opened.

transformer_quant defaults to TQ_AUTO, and on kind == "gguf" the loader deliberately takes the dense-quant / prequant fast path, because dense + torchao beats per-matmul dequant on both speed and quality. usable_prequant_source validates local kind == "path" sources but does no reachability or cache check for kind == "repo" ones. While unsloth/Z-Image-Turbo-FP8 was private that call raised, hit the diffusion.transformer_quant_fallback handler, and the GGUF loaded. Publishing those repos this week turned the same code path into a successful second download. Nothing in the loader changed; the artifact became reachable.

Fix, keeping the optimisation where it is genuinely free. A hosted prequant engages on an auto quant for a GGUF pick only when its checkpoint is already in the local Hub cache. If it is not, the pick runs the GGUF it asked for and logs why:

diffusion.transformer_quant_declined: pre-quant checkpoint in unsloth/Z-Image-Turbo-FP8
is not cached (an auto quant never downloads a second transformer for a GGUF pick);
loading the GGUF

prequant_checkpoint_cached is a pure try_to_load_from_cache lookup -- a refs read and a stat, no network, never raises -- checking both the model-name and the legacy filename, and both the live cache setting and huggingface_hub's import-time default, since hf_hub_download falls back to the latter. It runs inside memory planning, so it has to be that cheap.

The decision lives in one helper that both load_pipeline and _dense_quant_prefetch_needed call, so the plan and the load agree on which denoiser the pick runs. Fixing only the loader would have left the plan free to widen to the base repo's transformer/ shards for a dense build that no longer happens. While tracing that, I also pass the resolved base into the plan's prefetch decision: the caller's raw base_repo is usually absent, and a variant base selects its own prequant repo and size entry, so the plan was asking a slightly different question than the loader.

Deliberately unchanged:

  • an explicit fp8 / int8 request still downloads the checkpoint -- asking for a scheme is asking for the artifact that serves it;
  • a baked-LoRA load, which needs the dense transformer by construction and cannot fall back to the GGUF;
  • kind != "gguf" loads, where the prequant is the entire point;
  • local transformer_prequant_path overrides, which never download.

Tests

studio/backend/tests/test_diffusion_gated_base.py (new) covers the preflight: gated metadata plus a 401 on the fetch raises a ValueError carrying the repo and its licence URL, an open base is never probed at all, unreadable metadata is named too, and every network error falls open. Plus the plan-level and load-level paths, and the route's 400.

test_diffusion_backend.py covers the second: an auto quant with an uncached hosted prequant declines and loads the GGUF, the same pick with the file cached engages, an explicit fp8 request still engages, a baked LoRA is untouched, the prefetch decision declines with the load and before any candidate sizing, and the plan stages neither the .pt nor the transformer/ shards. test_diffusion_prequant.py pins the cache lookup itself as local-only and non-raising.

studio/backend/tests/ and studio/backend/hub/tests/ both green (16536 passed / 172 passed); the 20 failures in the first are pre-existing on main on this host (13 live-server e2e in test_studio_api.py, 7 unrelated to diffusion, all reproduced with the branch stashed).

danielhanchen and others added 2 commits August 4, 2026 17:21
A gated companion base now fails at plan time with its licence URL instead of
dying mid-download, and an auto transformer quant no longer downloads a second
multi-GB denoiser for a checkpoint the user picked as a GGUF.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits August 4, 2026 18:49
…heck found

Two review catches, both reproduced against huggingface_hub 0.36.2.

The gating preflight used hf_hub_download, which is not an access check when the
file is already cached. file_download.py:1102-1118 catches the HEAD error, reads
refs/<revision>, and returns the pointer file if it exists, so a 401 never reaches
_raise_on_head_call_error. A manifest cached by an earlier authorized load meant a
removed or expired token passed the probe and 401'd again mid-prefetch. It is now a
get_hf_file_metadata HEAD on the same /resolve/ byte URL the shards use, which has
no cache fallback.

The prequant cache check searched the live Studio cache root as well as
huggingface_hub's import-time constant, but _resolve_checkpoint_path then called
hf_hub_download with neither, so a hit found under the live root was re-downloaded
into the default one. That is the second multi-GB download this change exists to
prevent. The resolver now reuses the exact matched path, and cache_dir is threaded
through both download calls for the case where there is no hit.
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 4, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: a687927fd5

ℹ️ About Codex in GitHub

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

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

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

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

chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits August 4, 2026 19:53
…oRA as no LoRA

Two review catches, both reproduced.

The preflight caught only GatedRepoError and RepositoryNotFoundError, so an expired
token fell through to the fail-open branch and the load continued to the same
opaque 401 the probe exists to replace. hf_raise_for_status does not classify it:
_http.py excludes 401 "Invalid credentials in Authorization header" from its
RepoNotFound branch by name, and a permission-scoped 403 has no branch at all, so
both surface as a plain HfHubHTTPError. A 401/403 is now an access verdict on both
halves of the probe, while a 5xx or a rate limit still fails open.

The uncached-prequant decline tested the lora list for truthiness, but LoraSpec and
five sibling checks all read weight 0 as disabled. A request carrying only disabled
adapters looked like a bake, skipped the decline, and fetched the dense companion
for a load that applies no adapter at all.

Not touched: the pre-existing `if loras` at the dense-fit re-check has the same
shape, but it predates this branch and is outside both items.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits August 4, 2026 20:52
…in the plan too

Both follow from the previous commit rather than predating it.

build_hf_headers sends any str verbatim, so an empty or whitespace hf_token becomes
a literal "Bearer " and the Hub answers 401 invalid-credentials. Until the last
commit that 401 fell into the fail-open branch and cost nothing; now that a 401 is
an access verdict, a blank token would turn an open base into a hard error. The
preflight now blanks to None first, matching what load_pipeline does later, where
None means use the cached login.

The load path started reading active LoRA weights but the plan path kept testing
the raw list, so a request carrying only disabled adapters had the plan size a
dense bake while the load ran the GGUF. The plan staged the base transformer/
shards for weights the load would never touch, which is the download this decline
exists to avoid. Both now agree.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…not a bake

The two entry points hand over different shapes: /images/load converts to
(id, weight) tuples, /images/download-plan passes the LoraSpec models straight
through. Unpacking a pydantic model yields its (field, value) pairs, so
`for (_lid, w) in loras` bound w to ("weight", 0.0) and a disabled adapter read as
active. The plan then sized a dense bake and staged the base transformer/ shards
for a load that runs the GGUF, which is the same divergence as the last commit
arriving by a different route.

Both call sites now go through one helper that reads .weight when it is there and
falls back to unpacking, so either shape gives the same answer. An unrecognised
shape or an unreadable weight counts as active: skipping a bake the user asked for
is worse than staging shards that turn out unused.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 4, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 4, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits August 4, 2026 23:51
…t pin a load

fallback_filename names the legacy transformer_<scheme>.pt for repos that never
published the canonical <Model>-<SCHEME>.pt, and it is primary-first by contract:
reached only once the primary turns out to be absent remotely. The cache probe
accepted either name, so once a legacy copy was on disk it short-circuited ahead of
the primary and the loader kept using a stale artifact even after the repo started
shipping the real one.

The probe now matches the primary alone. Whether the primary exists remotely cannot
be known without a network call, so a legacy-only cache reads as "would have to
download" and the GGUF runs instead, which is the same answer this decline gives
everywhere else. The fallback is still reached through EntryNotFoundError in the
resolver, so a repo that only ever shipped the legacy artifact still loads.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…the way down

The cache short-circuit returned any primary hit, including one in the very root
hf_hub_download was about to use. That call revalidates against the Hub and reuses
the same blob, so short-circuiting it pinned a stale checkpoint once a repo
republished a corrected file under the same name. It now fires only for a hit in
the OTHER cache root, which is the case hf_hub_download cannot see and would re-fetch
multiple GB for. The live root goes through the Hub as before.

The decline read active LoRA weights but handed the raw list onward, and
_load_dense_quant_pipeline's own gate read it as truthy, so a request carrying only
disabled adapters skipped the cached prequant and built the dense transformer for
adapters that apply nothing. That gate and the bake block below it now use the same
helper, so all five sites agree on what an active adapter is.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 839ede286d

ℹ️ About Codex in GitHub

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

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

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

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

Comment on lines +406 to +410
return hf_hub_download(
repo_id = source.location,
filename = name,
token = hf_token,
cache_dir = cache_dir,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep auto-selected prequant resolution cache-only

When a cached prequant checkpoint is republished under the same filename, the auto-GGUF gate treats the old cache entry as requiring no extra bytes, but this hf_hub_download revalidates it and downloads the new multi-GB blob. The load then uses that checkpoint instead of the selected GGUF, recreating the silent second-denoiser download this change is intended to prevent. Auto-derived quant loads should resolve the verified cached path without network updates; explicit quant requests can retain revalidation.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The gate/resolve asymmetry is real, but the conclusion inverts a tradeoff this PR already settled, so I am not taking it.

No worse than main. On merge base f11dc5a, _resolve_checkpoint_path calls hf_hub_download(repo_id, filename, token) with no revision and no cache_dir -- the same unconditional HEAD-and-refetch, in the same window. _uncached_prequant_repo does not exist there at all. So the republish window is pre-existing behaviour that this PR neither introduces nor widens.

Making auto resolution cache-only reverts an accepted fix from this same PR. 47645b6 removed the cache short-circuit precisely because it 'pinned a stale checkpoint once a repo republished a corrected file under the same name', and locked that in with test_a_live_root_hit_still_goes_through_the_hub_so_it_revalidates and test_a_republished_checkpoint_in_the_other_root_is_picked_up. Every prequant source is first-party (unsloth/FLUX.1-dev-FP8 and siblings), so a republish under the same filename is us shipping corrected weights, and _validate_checkpoint checks scheme, base and min_features, not scale values -- a pinned bad checkpoint would load silently wrong rather than fail. That trades a one-time bandwidth bug for a silent wrong-weights bug.

The stated harm also does not follow. The decline exists to stop a FIRST-EVER second-denoiser fetch. In the republish window the prequant is already cached, so every prior auto load already ran it rather than the GGUF; pinning the cache would not make the GGUF run, it would make the superseded prequant run. And a republish that does not change the checkpoint's bytes keeps its etag, so the blob is reused and nothing is downloaded -- only a genuine content change costs anything, once per machine, after which the gate is truthful again.

If the accounting is worth tightening later, the shape that honours both invariants is to keep the HEAD on auto and, when the etag names a blob not on disk, decline the prequant and load the GGUF with a log line -- rather than serving the stale one.

# never runs. An explicit scheme, a LoRA bake and every non-GGUF kind keep today's
# behaviour, where the prequant IS the point. An all-zero-weight list is not a
# bake, so plain truthiness would fetch the dense companion for no adapter at all.
baking_loras = _has_active_lora(loras)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Preserve zero-weight LoRAs in the baked topology

When a user loads a quantized GGUF with an adapter selected at weight 0 so it can be enabled in a later generation, this classifies the load as having no LoRA bake and never attaches that adapter. A subsequent generation using the same adapter at a nonzero weight then fails with the “built without LoRA adapters” reload error, even though the baked-LoRA path explicitly supports live weight changes and disabling via scale 0. Load-time topology should depend on the selected adapter set, not whether its initial weights are active.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Not taking this one: the proposed change does not fix the symptom, and the symptom is not reachable through the product.

The fix does not fix it. One frame below the line cited, the bake block resolves the set it attaches as [(i, w) for (i, w) in lora_specs if w != 0] (diffusion.py:2664). That filter came in with #6763 and this PR does not touch it. So making load-time topology follow the selected set rather than _has_active_lora only moves the failure: the bake block runs, resolves an empty set, and marks the pipe baked with _unsloth_loras = (). The later generate at 0.8 still refuses, just with 'Reload the model with the new adapter selection' instead of 'built without LoRA adapters'. Verified by monkeypatching the helper back to plain truthiness -- which is exactly the merge-base code -- and running the described flow: still raises.

It is not a regression either. On merge base f11dc5a the same load with a single weight-0 adapter fails in the same place; only the message differs.

And the premise does not occur: the images page strips weight-0 adapters before it builds the payload (.filter((l) => l.id && l.weight > 0), images-page.tsx:1731) and sends loras only when something survives, so 'selected at weight 0 so it can be enabled later' never reaches the backend. Zero-weight-means-disabled is the declared contract on the model itself.

The live-weight behaviour the item invokes is intact, and I checked it: bake at a nonzero weight, then move that adapter 0.8 -> 0 -> 0.8 across generations, and it works without a reload. What is not supported is baking a topology for adapters that apply nothing -- and making that work would force the multi-GB dense transformer build for an all-zero list, which is the exact defect 50ef397 / 9bfc385 / 47645b6 were written to remove.

The union merges per file, so two revisions of a base that repacked its shards
contribute both namings and roughly double the companion budget, which forces
offload on a base that fits resident. Take the revision each root actually
serves (refs/main, the one the per-file reuse probes for); a root that names
none still falls back to all of them, where over-counting beats reading zero.

Also pin the ref read to UTF-8 rather than the platform default.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 6, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits August 6, 2026 04:13
Each root is scoped to its own refs/main, so after a republish the two roots
can sit on different revisions. The same logical shard then carries a different
blob hash in each, the etag key never collides, and both copies were summed:
roughly double the bytes, reporting finalizing at about half the real progress.
Key on the path inside the snapshot instead, which also covers a no-symlink
cache storing the file in the snapshot itself.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2a60cd0e37

ℹ️ About Codex in GitHub

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

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

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

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

Comment on lines +1641 to +1643
for entry in blobs:
if entry.name.endswith(".incomplete"):
_add(entry.name, entry)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Ignore stale partials from inactive cache roots

After the Studio cache directory changes, the import-time root can retain an abandoned .incomplete blob from an interrupted download, while the current load downloads a different blob into the live root. This loop counts every partial from both roots without checking whether it belongs to either root's active revision, so load_progress can reach finalizing early and full-pipeline memory planning can select unnecessary offload based on bytes that this load will never consume.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Tried this and the existing tests disproved it, so no change.

I implemented exactly the suggested restriction, counting partials only from the root being written to. It broke test_load_progress_ignores_a_revision_the_moved_root_has_superseded, and that test is right: reuse_other_cache_root calls hf_hub_download with cache_dir=None for a file the live root misses, which writes into the import-time root. So a partial there is often this load's own progress, not an abandoned one.

There is also no check available to tell them apart. A partial is named for its own etag, so nothing on disk ties it to a revision, and the metadata that would is the HEAD this path could not make. Excluding the other root's partials would undercount a live download instead, which freezes the bar for the length of every multi-GB shard.

Comment on lines +1723 to +1725
live_rev = DiffusionBackend._live_snapshot_dir(repo_dir)
if live_rev is not None:
candidates.append(live_rev)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Avoid unioning companion shards across different revisions

When the live and import-time cache roots point at different revisions whose companion weights were repacked—for example, the old revision has two sharded text-encoder files and the new revision has one consolidated file—adding each root's refs/main snapshot and later merging by relative path counts both layouts. The loader requests the current layout and does not read the differently named old shards, so companion sizing can approach twice the actual resident footprint and force group/model offload for a pipeline that fits in memory.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The repacked-layout over-count is real, but narrowing it here is the wrong direction and is deliberate, not an oversight.

This is the memory plan, and its two failure modes are not symmetric. Over-counting picks offload for a base that would have fit resident, which is slower. Under-counting leaves an auto plan resident and OOMs on weights it never counted, which fails the load. The union spans revisions and keys on relative path precisely so a repack cannot hide half the companions, and the docstring on _union_over_cached_revs records that choice so a later pass does not quietly reverse it.

Note the progress path already does what you are asking, because there the asymmetry runs the other way: _cache_bytes is scoped to each root's refs/main and dedupes by snapshot path, so a repack cannot double the bar. Different helper, opposite safe direction, both intentional.

Comment on lines +550 to +552
if _is_auth_error(exc) and _already_downloaded():
return other_root_snapshot
raise ValueError(_repo_access_message(repo, gated = False)) from None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Allow complete cached bases after a repo 404

When a companion repo has been deleted or renamed but its required snapshot is fully cached, this unconditional 404 branch rejects the load before the cached files can be used. hf_hub_download resolves an existing pointer from refs/main before re-raising a failed metadata HEAD, so prior to this preflight from_pretrained could still assemble such a base entirely from disk; the same is true for cached native companion assets. Grant the cache escape for a demonstrably complete snapshot instead of making an upstream 404 invalidate usable on-disk models.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The mechanism is right, but refusing a 404 even when cached is the deliberate behaviour of this change, not a gap.

An access verdict, 401 or 403, is excused by a complete cached copy, and that escape is implemented and tested. A 404 is not, because a renamed or removed repo cannot be un-renamed by a stale copy: the id no longer resolves to what is on disk, and the size estimate swallows the 404 into a zero-byte plan. That reasoning is recorded at the branch and pinned by test_a_deleted_or_renamed_base_still_raises_even_when_cached.

Reversing it would invalidate that test, so if the product call should be the other way, allowing an offline load off a fully cached deleted base, it is worth doing as its own change with its own test rather than folded in here.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 6, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 6, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 6, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2a60cd0e37

ℹ️ About Codex in GitHub

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

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

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

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

Comment on lines 18986 to 18988
engine = await asyncio.to_thread(
select_and_activate_engine, fam, hf_token = request.hf_token, model_kind = kind
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preflight the fallback before activating its engine

When predict_engine selects native but the lazy sd.cpp install or runnability check subsequently fails, select_and_activate_engine falls back to diffusers and _activate may unload a resident native model here before the actual diffusers engine is preflighted. If that engine's companion repo is gated or unreadable, the later check at line 19021 rejects the request only after teardown; on CPU, that second check is skipped entirely. Resolve the actual fallback without activating it, or preflight every possible fallback before allowing _activate to switch engines.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Right on the CPU half, and fixed in 944a6fe.

predict_engine never installs, so a host where the sd-cli install then fails lands on the other engine. The GPU path already re-asked the engine it actually got; the CPU path skipped that re-ask entirely, so a mispredict there switched engines and started the load with the diffusers companions unread - the bare mid-download token error this preflight exists to replace. The re-ask now runs whenever a preflight was owed at all:

if (needs_gpu or preflighted is not None) and engine is not preflighted:
    await asyncio.to_thread(_preflight, engine)

Where no preflight was owed (CPU, no engine switch), CPU still pays nothing, which is the property test_cpu_load_skips_the_gated_preflight pins. New test test_a_cpu_mispredicted_engine_is_still_preflighted fails without the change.

On the teardown half - _activate unloading the resident engine before the fallback is preflighted - that is real and already tracked as a follow-up: the fix is to split select_and_activate_engine into a pure resolve plus an explicit activate, so the route can preflight the resolved engine before anything is torn down. That is a router refactor rather than a route fix, and it is deliberately out of scope here so this PR stays reviewable.

7952 landed the ungated unsloth mirrors, so the base a load reads is no longer
always the id the user picked. The preflight had to move onto that repo: probing
the upstream would refuse exactly the gated picks the mirror rescues, turning a
working load into a 400. Both backends and all three entry points (pre-eviction
preflight, download plan, load) now swap first and probe second, and the swap is
pure so all of them take the same decision.

Sizing keeps both sides too: the pipeline branch and the companion lookup take
the largest of the local dir, the staged snapshot and the cache of the repo the
bytes landed in, since under-counting leaves an auto plan resident and OOMing.

Tests: the refusal cases set UNSLOTH_DIFFUSION_NO_MIRROR so they pin the
preflight itself, and two new tests pin the rescue on both backends. Both fail
without this change.
@danielhanchen

Copy link
Copy Markdown
Member Author

Merged main in now that #7952 has landed. Eight conflict hunks, all in the two files both PRs rewrote, resolved by combining rather than picking a side.

The one real decision

#7952 sends a gated base to its ungated unsloth/* mirror. This PR's preflight refuses a base it cannot read. Run in the order the merge produced, the preflight probed the upstream id and raised before the swap was ever reached, so it would have refused exactly the picks the mirror rescues, turning a working load into a 400 - worse than the bare token error the preflight replaced.

So the probe now runs on the repo the pull actually reads, at all four entry points:

Entry point Was Now
DiffusionBackend.preflight_base_access upstream base prefer_ungated_mirror(base)
DiffusionBackend.download_plan upstream, before the file list fetch_base, decided from the staged file list
DiffusionBackend._run_load upstream, before the estimate fetch_base, the same one carried into load_pipeline
SdCppDiffusionBackend plan / load / preflight upstream specs post-swap specs

Moving two of those below the size estimate costs nothing: model_info answers anonymously for a gated repo, so nothing above them downloads a byte. And prefer_ungated_mirror is pure, so all four take the same decision as the fetch.

Sizing

_plan_memory and _companion_cache_bytes keep both sides: the largest of the local dir, the staged snapshot, and the cache of the repo the bytes landed in. Either one alone reads zero in a case the other covers, and under-counting is the direction that leaves an auto plan resident and OOMing.

Tests

  • The seven refusal cases set UNSLOTH_DIFFUSION_NO_MIRROR=1, so they pin the preflight itself rather than silently testing the swap.
  • Two new tests pin the rescue: test_a_gated_base_with_a_live_mirror_is_not_refused and test_the_native_load_lets_the_mirror_stand_in_for_a_gated_companion. Both fail with the probe on the upstream id (verified by reverting just that line), so they guard the regression rather than passing either way.
  • 1544 passed, 0 failed across test_diffusion_*, test_sd_cpp_*, test_video_families, test_video_backend. Formatted with scripts/run_ruff_format.py; pre-push gate PASS.

predict_engine is a prediction, not the selection: it never installs, so a host
where the sd-cli install then fails lands on the other engine. The GPU path
already re-asked the engine it got; the CPU path skipped that, so a mispredict
there switched engines and started the load with the diffusers companions
unread. Where no preflight was owed, CPU still pays nothing.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 944a6fe037

ℹ️ About Codex in GitHub

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

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

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

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

@danielhanchen
danielhanchen merged commit 82d3925 into main Aug 6, 2026
55 of 56 checks passed
@danielhanchen
danielhanchen deleted the gatedfix branch August 6, 2026 08:03
danielhanchen added a commit that referenced this pull request Aug 6, 2026
#7870 landed a plan-entry assertion naming Comfy-Org/z_image_turbo. This PR
repoints that table at unsloth/Z-Image-Turbo-ComfyUI, and no legacy copy is
cached in the test, so prefer_cached_legacy_source keeps the mirror.
danielhanchen added a commit that referenced this pull request Aug 6, 2026
* Tighten the gated-base preflight comments

Comment-only pass over the ten files #7870 touched, now that it has landed:
311 insertions, 437 deletions, net -126 lines of comment text. Multi-paragraph
docstrings squashed to single paragraphs, and eight copies of the same
three-line preamble in test_diffusion_gated_base.py collapsed to one line each.

Every non-obvious fact is kept, just shorter: huggingface_hub 1.x making
response a required keyword-only argument, hf_raise_for_status folding 401 into
RepositoryNotFoundError, expanduser raising RuntimeError rather than OSError,
blobs/ being append-only across republished revisions, and why the memory plan
and the progress ratio deliberately fail in opposite directions.

* Put back the facts the comment trim dropped

Restore the second failure mode on the dense-transformer hub id (a re-download
or a 401 into the GGUF fallback), the worker attribution in the repo-access
message, the blob-reuse and failed-HEAD guarantees behind the other-root
reuse, the needless re-download of every moved asset, and the reachability
notes for the unresolvable-home and renamed-repo branches.

* Keep the auth-failure branch in the hub-id test rationale
danielhanchen added a commit that referenced this pull request Aug 6, 2026
…ommunity repacks (#7995)

* Studio: fetch the sd.cpp companion assets from unsloth mirrors

The no-GPU path opens a single-file VAE and text encoder alongside the
transformer, and six of those files came from community repacks rather than
from the vendor: comfyanonymous/flux_text_encoders, three Comfy-Org repos and
QuantStack's Wan2.2 TI2V 5B quants. A rename, a reshuffle of split_files/ or a
takedown there turns every CPU FLUX, Qwen-Image, Z-Image or klein load into a
404 no client can work around, and two of the six publish no licence metadata
at all.

Each now has a byte-identical unsloth mirror, published under the terms the
upstream model sets for redistribution (LICENSE plus the prescribed NOTICE in
every one), so point the family tables at them. Relative paths are unchanged,
so this is an id swap.

One consequence needs handling. The cached-model listing tags a repo as a
pickable image model when it is trusted and its id resolves to a family; trust
means unsloth/*, which a community org never was. After the swap four
companion repos clear that gate and would each add an On Device row for a repo
with no denoiser in it. sd_cpp_companion_only_repo_ids() derives the
companion-only set from the tables and the listing skips it, minus any id that
is also a base: FLUX.1-schnell serves the FLUX.1 VAE and stays loadable.

Detection still resolves the old ids, so a QuantStack copy already in someone's
cache keeps working.

* Studio: keep the Apache-2.0 FLUX.2 VAE out of the non-commercial mirror

Comfy-Org/flux2-dev holds two files under two licences. The Mistral
conditioner travels under the FLUX Non-Commercial License, but Black Forest
Labs released the FLUX.2 autoencoder separately under Apache-2.0 and say so in
their own repository. Mirroring both into one repo would have labelled the
permissive file non-commercial, which matters because FLUX.2 klein 4B is itself
Apache-2.0 and this is the VAE it loads.

So the VAE gets its own mirror and both FLUX.2 families point at it. The
conditioner stays where it is, still non-commercial.

* Studio: tighten the comments on the sd.cpp mirror swap

* Flag companion mirrors on the row, since no task never dropped one

_cached_repo_task returning None does not omit the row: task null is exactly
what an unclassified chat repo carries, so a denoiser-less companion mirror
landed in the chat On Device list as a load that cannot succeed. Dropping the
row instead would hide tens of GB the user could then never find or delete, so
the row stays and carries a companion flag the chat picker filters on.

The set includes unsloth/Qwen2.5-VL-7B-Instruct-GGUF, which is a real chat model
sd.cpp only borrows as a text encoder. It is safe today only because this
listing never sees a GGUF-only repo; documented and pinned with a test.

* Fall back to a cached community repack instead of re-pulling the mirror

The HF cache is keyed by repo id, so an install that already holds the byte
identical repack has it filed under the OLD id. Repointing the tables alone
would leave the mirror namespace empty, re-download up to tens of GB on upgrade,
and fail an offline load over bytes already on disk. The mirror stays preferred
for a fresh install; the swap only fires when the repack already satisfies the
exact files this load wants, using the same probe the gated swap uses.

The delete-cached guard names the repack too, since which of the pair holds the
bytes is re-decided per load.

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

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

* Carry the companion flag on the hub inventory row too

The chat picker is backed by /api/hub/cached-models, not the legacy
/api/models one, so the flag set only on the legacy route arrived as undefined
where the filter reads it. Same trap single_file fell into, and the comment
recording that is three lines above where this now sits.

The classifier is imported from diffusion_families rather than routes.models: a
hub service reaching into a route is backwards, and that import is exactly what
made the first attempt return False under pytest.

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

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

* Mark a companion row non-chattable, not just flagged

The row flag only reaches the picker filter. Startup auto-load goes through
isChattableCachedRepo, which reads capabilities.can_chat and nothing else, so a
companion that reached the listing was still auto-loadable as a chat model.

Set in _cache_inventory_fields, which its own docstring calls the sole producer
of a row's capabilities, rather than patched on afterwards. A VAE / text-encoder
mirror holds no language model, so this is true regardless of weight format.

* Merge main; the native plan now stages the mirror, not the repack

#7870 landed a plan-entry assertion naming Comfy-Org/z_image_turbo. This PR
repoints that table at unsloth/Z-Image-Turbo-ComfyUI, and no legacy copy is
cached in the test, so prefer_cached_legacy_source keeps the mirror.

* Studio: keep the cached repack after a cache move, and drop taskless single-file repos from chat

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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.

1 participant