Repository navigation
Studio diffusion: cache runtime-quantized denoisers as local pre-quant checkpoints - #13715
Conversation
A family with no hosted pre-quant read the dense bf16 transformer and quantized it on every load. The quantized state is now written once as an mmap-ready safetensors artifact in the hosted container and metadata, keyed by the source shards' headers and content identity plus scheme, filter, ConvRot spec, policy version and torch/torchao minor versions. The next load resolves it like a hosted checkpoint, so the dense transformer is never read again. - The writer streams one tensor at a time to the host. - Atomic: artifact then manifest, each through a temp file and rename. - LRU budget (UNSLOTH_DIFFUSION_PREQUANT_CACHE_MAX_GB, default 40), disk-short skip, kill switch UNSLOTH_DIFFUSION_PREQUANT_CACHE=0. - The Studio-owned cache root is trusted without the local prequant allowlist, symlinks resolved so nothing outside it is. - Image dense-quant path and single-denoiser video loads with an explicit scheme; nvfp4, native weight-only, LoRA bakes, non-bf16 and unflattenable int8 (torchao < 0.18) are skipped cleanly.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
…t accumulate mode The cache keys and labels fp8 artifacts with the auto accumulate mode, like the hosted fp8 builds, and lookup cannot see a forced mode. A build quantized with transformer_quant_fast_accum=false was stored under that auto label, so a later default load restored precise accumulation as if it were fast, and a later explicit-false load rejected the mislabelled file and re-quantized every time. Skip the save when the build's mode differs from the auto one.
…nother scheme is hosted for The cache fallback ran only when the family hosted no scheme at all, so HunyuanVideo-1.5 (hosted nvfp4) with an explicit int8 or fp8 never found the build an earlier load cached and re-read and re-quantized the dense denoiser on every load. Probe it whenever the requested scheme is not hosted. Auto still never consults the cache.
Only the GGUF-kind dense-quant route saved its build; a model_kind pipeline load quantizes its denoiser in its own loop and never called save_runtime_quant, so an unhosted pipeline load (FLUX.1-Kontext, Qwen-Image-Edit) read and quantized the dense transformer every time. Save once every denoiser engaged, for a single transformer denoiser without active LoRAs; the next pipeline load already resolves the cached build through the prequant source fallback.
…roots After a cache-folder change the loaders fetch with reuse_other_cache_root, so the dense shards may still sit under huggingface_hub's import-time root. The cache key lookup only asked the live root, so it could not rebuild the key there (or save at all) and such installs re-quantized on every load. Look in the live root, then the import-time root when it differs; an explicit cache_dir still means that root only.
… low disk The free-space check returned before eviction ever ran, and eviction only ran after a successful write, so a volume filled by old entries refused every new artifact for good. When the volume is short, evict least recently used entries until the shortfall is freed (the budget and the grace window still apply, and a disabled budget never evicts), then check again.
Eviction judged an entry by the last-used time from its initial scan, so an entry another Studio process resolved after that scan could still be renamed away before its loader opened it. Lookup now checks and touches an entry under a cross-process lock on the cache root, and eviction re-reads the last-used time under the same lock right before the rename: once lookup returns, the entry is inside the grace window and no process removes it.
Without fcntl the lookup and eviction sections ran unlocked, leaving the eviction race open on Windows. Fall back to msvcrt.locking on the lock file's first byte (the pattern diffusion_measured_peaks uses), unlocking before close.
…isk space The low-disk eviction ran before the artifact budget check, so a save the budget refuses anyway could first delete valid cached entries.
…ainst Two bases with byte-identical denoiser shards (renamed local copies) shared one key, yet the loader rejects an artifact whose recorded base_model_id names the other base, and the occupied key then blocked saving the right build. The key now carries the base identity normalized the way _same_base_model compares it.
An entry with same-size corruption, or one a torch/torchao patch can no longer read, still passes the manifest key and size check, so the save after the dense fallback skipped it as already cached and every later load repeated the failed attempt. load_prequantized_transformer now reports a rejected path source to the cache, and the next save of that key replaces it. A forced fp8 accumulate mismatch is the request's choice and leaves the entry alone.
…che entry The planner only ran hosted_fast_accum_conflict for hosted repo sources. A local cache entry bakes the auto accumulate the same way, so a forced different value could budget for it and drop the dense fallback before checkpoint validation rejected it. Cache entries now take the same guard; an operator's own file is still left to the loader.
The streaming writer copied and fsynced every tensor of a multi-GB artifact even after the load that produced it was cancelled or superseded, holding up unload or the next load. save_runtime_quant takes the load's cancellation check and calls it between tensors, so the temp file is removed promptly; the image, pipeline and video save sites pass theirs and re-check right after the save.
The manifest checks only the key and file size, and the artifact carried no fingerprint block, so _verify_packed_fingerprint passed same-size corruption and loaded altered weights. Record the canonical weight fingerprint the hosted builds carry, so such corruption falls back to the dense build.
The low-disk eviction keeps the key being saved, so a rejected artifact that filled most of the volume stayed in place and its replacement was skipped for lack of room. The rejected entry is now removed before free space is measured.
… and mtime A local shard replaced by different same-shaped weights with its size and mtime preserved kept its identity, so the cache served the old build. The stat identity and its memo now also carry inode and ctime, which a replacement changes. The base-identity test now shares one Hub blob between two bases, the case where identical sources still occur.
… every byte The canonical weight fingerprint covered only quantized .weight tensors, so same-size corruption of a bias, norm or root-level parameter still loaded, and computing it was a separate full-model pass that cancellation could not stop. The writer now hashes every byte it writes from the host copies it already makes (inside the cancellable loop), the manifest records the sha256, and load_prequantized_transformer refuses a cache entry whose file no longer matches it before reading any tensor. A file unchanged since its last check (size, mtime, inode, ctime) is not hashed again.
…ant cache hit A cache hit skips the from_pretrained request that would advance an unpinned ref, so after the repo's main moved Studio kept serving the old denoiser. On an online load, lookup now asks the Hub for each cached shard's current etag on main (memoized for 5 minutes, only when an entry exists) and misses when it differs or the file is gone. Offline and local-files-only loads, and loads where the Hub cannot answer, keep the local snapshot as before.
|
Codex Review: Didn't find any major issues. 🎉 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". |
…ounded flatten, auto never promoted by the cache
…storage [skip ci]
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bc4fc7a675
ℹ️ 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".
| try: | ||
| from huggingface_hub import try_to_load_from_cache | ||
| hit = try_to_load_from_cache(repo_or_dir, filename, cache_dir = cache_dir) |
There was a problem hiding this comment.
Resolve commit-pinned snapshots during cache lookup
For conventional video loads, _predownload_base stages the base at base_plan.revision and the save keys the artifact from _base_local_dir, but the next planner looks it up using the repo ID. Calling try_to_load_from_cache here without that revision only follows the default main ref; a fresh exact-commit snapshot need not have refs/main, so _key_for cannot rediscover its source shards. In that case the saved FP8/INT8 entry is permanently missed and every explicit reload rereads and requantizes the dense denoiser; carry the planned revision into lookup or search the cached snapshots for the staged commit.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in e42181f: when a repo has no refs/main (a commit-pinned download), the cache now also searches each cached snapshot commit, so a lookup by repo id finds the entry the staged load keyed. The online check against the Hub's current main still guards it.
| if _hub_source_stale( | ||
| source_shards(base_repo or getattr(fam, "base_repo", None), component), logger | ||
| ): |
There was a problem hiding this comment.
Propagate local-only mode into cache freshness checks
When a video request sets local_files_only=True and already has a local pre-quant entry, _video_planned_auto_denoiser_scheme runs in _run_load before the decorated load_pipeline establishes _LOCAL_FILES_ONLY. This unconditional freshness check therefore sees the context default and calls _remote_etag for each Hub shard, despite _run_load's no-network contract; an offline load can leak metadata requests and incur repeated five-second timeouts. Pass the request's local-only flag into lookup/_hub_source_stale rather than relying solely on the later context scope.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
_run_load is itself decorated with @scoped_local_files_only (video.py, right above _run_load), so _LOCAL_FILES_ONLY is already set from the request's local_files_only when _video_planned_auto_denoiser_scheme runs inside it, and _hub_source_stale returns before any Hub request on a local-only load. The other caller, download_plan, is the online plan route and has no local-only contract.
| if cached: | ||
| return PrequantSource(kind = "path", location = cached, filename = None) |
There was a problem hiding this comment.
Reject cache entries that fail the preliminary header probe
A same-size corruption in the safetensors header passes _entry and is returned here, but usable_prequant_source subsequently drops it when local_prequant_scheme cannot read or match the scheme. Because this happens before load_prequantized_transformer, note_rejected is never called; after the dense fallback requantizes, save_runtime_quant sees the old size-valid entry as already cached and refuses to replace it. The bad entry therefore causes every later load to repeat the dense quantization indefinitely, so a cache path that fails the scheme/header probe must be marked rejected or verified before being returned.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in a4045f67f2: lookup now reads the entry header, and an entry that no longer reads as the requested scheme is marked rejected and treated as a miss, so the dense fallback's save replaces it.
| _save_runtime_quant_to_cache( | ||
| fam, | ||
| views, | ||
| base = base, | ||
| source = _base_local_dir or base, |
There was a problem hiding this comment.
Fingerprint the repository that supplied video weights
When _base_local_dir is absent—always for local_files_only loads and also after a predownload fallback—the pipeline reads its dense weights from fetch_base, which may be the ungated mirror, but this save fingerprints base, the logical upstream. If both repositories have cached snapshots and the mirror was selected because it is more complete, source_shards(base) checks the upstream first; differing mirror/upstream revisions can therefore store mirror-derived quantized weights under the upstream source key, and a later upstream load can accept and run the wrong weights. Pass fetch_base here, as the image cache path already does.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 6399943: the video save now fingerprints _base_local_dir or fetch_base, the repo the dense weights were actually read from, matching the image path.
| from .diffusion_prequant_cache import path_in_cache, verify_entry | ||
| if path_in_cache(path) and not verify_entry(path, logger): |
There was a problem hiding this comment.
Make cache digest verification cancellable
On the first use of an entry, or whenever its stat marker changes, verify_entry hashes the entire multi-gigabyte artifact in 16 MiB chunks, but this call does not supply the load's cancellation check. Consequently an unload or replacement request cannot stop the worker until the full disk pass finishes, even though verify_entry exposes a cancel_check hook for exactly that purpose; thread the image/video load cancellation callback through this call and ensure its exception is propagated rather than converted into a corrupt-entry result.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The full hash is not a per-use cost: save_runtime_quant hashes while it writes and records the verified marker (_record_verified), so verify_entry skips hashing until the file's stat changes. When it does hash, the pass is the same size as the artifact read load_prequantized_transformer does next, which has no cancel hook either, and the callers check for cancellation right after the load. It can delay a cancel; it never runs a cancelled load.
…obe as rejected [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. 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". |
… in the CFG routers, and test fixes (#14420) ## Summary Follow-up fixes for the recently merged Studio diffusion work: two runtime fixes (the VAE OOM ladder under a multi-GPU component split, and bitwise comparison of expanded timesteps in the CFG routers) and five test fixes. Each change is its own commit. ### 1. VAE OOM step (a) frees only what sits on the VAE's card (#13802 with #13725) **What was broken.** Under a component split the VAE decodes on a secondary card while the denoiser stays resident on the primary. When that decode ran out of memory, `DecodeSession.free_others` reset the denoiser's CUDA graphs on the primary card and counted that as "released". The ladder then retried the same untiled decode on the secondary card, which ran out of memory again before it reached the tiled rung, and the denoiser lost its captured graphs for nothing. `_release_groups` had the same problem with resident offload groups on the primary card. A failed re-pin was also deferred against the VAE's card instead of the groups' own card. **Fix.** Graph handles are filtered to the VAE's card, using the card the graph was recorded on (or its module's card when nothing has been recorded yet). Resident-group modules are filtered by `_unsloth_resident_device`. This is the same filtering `_hook_torchao_resident` and `_move_components` already do with `_placement(comp, self.device)`. `release_resident_groups` takes an optional `device` filter. It is only passed when the pipeline has resident groups on more than one card, so single-card calls are unchanged. Anything whose card cannot be read is still freed, as before. **Tests** (`test_diffusion_vae_oom.py`, all fail on main): - `test_split_vae_oom_leaves_the_other_cards_graphs_alone`: a decode on cuda:1 with graphs on cuda:0 goes straight from the untiled decode to the tiled one, and no graph is reset. - `test_split_vae_oom_still_drops_graphs_on_its_own_card`: only the cuda:1 handle is reset. - `test_split_vae_oom_releases_only_groups_on_its_own_card`: groups on cuda:0 are left alone and nothing is deferred against them. With groups on both cards, the release is limited to cuda:1. - `test_release_resident_groups_device_filter`: the new filter releases only the matching card's groups, and with no filter every card's groups are released. ### 2. Expanded scalars compare bitwise in the CFG routers (#13725, #13787) **What was broken.** `_bitwise_equal` in `diffusion_multigpu.py` flattens both tensors, calls `contiguous()` and views them as `uint8`. WanPipeline passes `timestep = t.expand(batch)`. For a one-element tensor `contiguous()` is a no-op whatever the stride, so the stride-0 timestep reached `view(torch.uint8)`, which raised, and the comparison returned False for two equal timesteps. #13787 CFG batching uses it through `_record_template`, `_matches` and the branch merge. On Wan it missed three times in a row and turned itself off. CFG-parallel's prediction check uses the same helper. **Fix.** A small `_as_bytes` helper takes a dense copy only when the flattened tensor still has a non-unit stride. `_bitwise_equal` and `_unchanged_since_launch` both use it. Bitwise semantics are unchanged: equal NaN bits match, and -0.0 and 0.0 do not. The CFG batcher's three call sites all go through `_bitwise_equal`, so they are covered by the same fix. **Tests** (both fail on main): - `test_bitwise_equal_on_an_expanded_scalar` (`test_diffusion_multigpu.py`): `torch.tensor(941).expand(1)` against a clone and a fresh expand, plus NaN, signed zero and `_unchanged_since_launch`. - `test_wan_expanded_timesteps_serve_the_second_branch` (`test_diffusion_cfg_batch.py`): a Wan-style loop that passes `t.expand(batch)` to each branch. It matches the two-call reference with 4 hits, 0 misses, and batching stays on. On main it gets 0 hits. ### 3. Seeded denoiser cancel test pins the text encoder (#13715) **What was broken.** On a CUDA host, an unset `text_encoder_quant` also plans the hosted FP8 Wan text encoder. The load then fetched two artifacts and `test_the_seeded_denoiser_artifact_is_fetched_under_the_load_cancel_event` failed its exact single-fetch assertion. It passed only with the GPU hidden. **Fix.** The test passes `text_encoder_quant = "off"`, so it checks only what it is about: the denoiser fetch carries the load's cancel event. **Test.** Fails on main with a GPU visible and passes after. It passes both ways with the GPU hidden. ### 4. FLUX.2 FBCache test invalidates the child registry cache (#14401) **What was broken.** On diffusers 0.39 and 0.40, `enable_cache` does not drop the child-registry list that an earlier uncached render cached. `test_fbcache_on_flux2_skips_and_matches_the_full_pass` then failed with `ValueError: No context is set`. Production already calls `_invalidate_child_registry_cache` after `enable_cache` in `apply_step_cache`. Only the test helper skipped it. diffusers 0.41 invalidates the list itself. **Fix.** The test's `_render` helper calls `dc._invalidate_child_registry_cache(model)` after `enable_cache`. **Test.** With diffusers 0.39.0 the test failed before and the whole file passes after (7 passed). It also passes on the pinned diffusers. ### 5. Stream encode tests skip when diffusers cannot import the Wan VAE (#14405) **What was broken.** `pytest.importorskip("diffusers")` succeeds on the lazy top-level module. The next line, `from diffusers import AutoencoderKLWan`, can then raise `RuntimeError` (for example with a broken bitsandbytes), which aborted collection of the whole pytest run. **Fix.** Catch `ImportError` and `RuntimeError` on those imports and skip the module, as the other diffusion tests do. **Test.** In an environment with a broken bitsandbytes, collection errored before and the module is skipped after. In the Studio environment all 9 tests still run and pass. ### 6. Multi-GPU planner tests pin the host facts they read (#13725, #13793) **What was broken.** On a host with one GPU, 11 tests in `test_diffusion_multigpu.py` failed. `make_selection` drops ordinals at or above the real `torch.cuda.device_count()` and cards below the primary's capability, so `make_selection(0, [0, 1])` returned None on a one-card machine. An AMD Strix Halo CI runner (one integrated gfx1151) showed exactly these 11. `test_diffusion_fp8_unit_scale.py` gated on `get_device_capability() >= (8, 9)`, which passes on ROCm because ROCm reports the gfx version (gfx1151 gives (11, 5)), and torchao then refuses fp8 there. **Fix.** Tests only. The autouse fixture pins the card count and the capability check (tests that probe those filters still override them), and the fp8 GPU gate returns False on a HIP torch, matching Studio, which already declines torchao fp8 on ROCm. New test `test_two_discrete_rocm_cards_split_like_cuda`: with HIP set and two cards at capability (11, 0), the planner selects both and splits onto card 1, as on CUDA. **Tests.** Spoofed host (HIP + one integrated card, HIP + two discrete cards, one CUDA card without HIP): 11 failed before, 114 passed after on each. Normal CPU host: 133 passed, 1 skipped. ### 7. The ROCm APU pool discount applies only to HIP device snapshots (#14379) **What was broken.** `_rocm_linux_apu_os_room_outside_pool` (`diffusion_memory.py`) gave any unified-memory reading the smaller Linux ROCm APU reserve on a ROCm build, without checking the snapshot's device. On a ROCm host, a mocked Apple (`mps`) snapshot in `test_diffusion_unified_load_override.py` got that reserve, so two refusal tests failed. A real ROCm build never produces an `mps` reading, so the user impact is close to zero. **Fix.** The discount now requires a `cuda` device snapshot (`cuda` or `cuda:N`). `test_flux3_prompt_upsampler.py` also pins `torch.__version__` in the tests that stand in for a CUDA build (Studio reads `+rocm` there too) and pins the card count in its warm fixture, which read the real host. **Tests.** The new `mps` / `cpu` reserve test fails without the fix and passes with it. Prompt upsampler: 164 passed on a spoofed APU, two discrete ROCm cards, two CUDA cards and plain CPU. ## Tests Base is origin/main and head is this branch. Same host and same Studio venv (diffusers 0.41 dev, torch 2.13). Failing test IDs were compared, not counts. - CPU, GPU hidden: test_diffusion_vae_oom.py, test_diffusion_vae_oom_faults.py, test_diffusion_measured_placement.py, test_diffusion_offload_cuda_graph.py, test_diffusion_learned_peaks.py, test_diffusion_int8_gemm.py, test_video_stream_residency.py, test_diffusion_offload_prefetch.py, test_diffusion_small_host_prefetch.py, test_diffusion_fbcache_mixed_stream.py, test_video_stream_encode.py, test_diffusion_multigpu.py. Base: 3912 passed, 125 skipped, 0 failed. Head: 3916 passed (the 4 new tests), 125 skipped, 0 failed. No failing IDs on either side. - One GPU visible: test_video_prequant.py. Base: 1 failed (`test_the_seeded_denoiser_artifact_is_fetched_under_the_load_cancel_event`), 85 passed. Head: 86 passed. - CPU, GPU hidden: test_diffusion_cfg_batch.py, test_diffusion_multigpu.py, test_diffusion_multigpu_wiring.py, test_video_multigpu_wiring.py. Base: 128 passed. Head: 130 passed (the 2 new tests). No failures on either side. - test_diffusion_fbcache_mixed_stream.py on diffusers 0.39.0: 1 failed before, 7 passed after. Wan2.1-T2V-1.3B end to end on a Kaggle T4 capped at 7.25 GiB (streamed offload, fp32, 480x320, 17 frames, 6 steps, guidance 5, seed 1234). Base and head ran on the two T4s of one kernel, each on its own CPU slice: | Run | s/step | CFG batch | |---|---|---| | base, CFG batching off | 5.96 | not armed | | base, auto | 8.55 | 0 hits, 3 misses (timestep 941 vs 941), then off | | head, CFG batching off | 5.58 | not armed | | head, auto | 5.55 | 2 hits, 0 misses, then off: measured no gain (batched pair 5.42 s vs plain pair 5.39 s) | - The 43% slowdown on base is gone. On this streamed T4 placement a batched pair is no faster than two plain calls, so the batcher's own timing gate turns it off, as designed. - The batching-off latents are identical on base and head (`829b889b587d13f6`), so the plain path is unchanged. The two batched steps are not bit-exact, as documented for CFG batching. ## Not verified - CFG-parallel on two real cards: test_diffusion_multigpu_cuda.py needs two CUDA cards in one process and was skipped. - No real two-GPU decode that runs out of memory. The split case is covered by CPU tests that use real `torch.device("cuda", N)` indices with fake graph handles and resident modules. - diffusers 0.40.0 was not run. Its source lacks the same invalidation as 0.39.0.
…nreachable (unslothai#15039) ## Summary On a cache hit, the prequant cache freshness check added in unslothai#13715 sends a Hub HEAD request (5 s timeout) for every source shard, and a second one per shard when the Hub cache has no symlinks. A failed request was not remembered, so every later lookup asked again. With the network unreachable but not flagged offline (captive portal, a firewall that drops packets, slow DNS), a cached load paid about 5 s per shard per lookup before the cached entry was served. This change remembers, per Hub endpoint and per process, that a request failed at the transport level (connection refused or reset, connect or read timeout). For the existing 300 s TTL, later probes return "unanswerable" at once. That is the same result a failed HEAD already produced: the local snapshot stands, which is also what `huggingface_hub` does when its HEAD fails on a cached file. The first successful answer clears the verdict. ## Details - Only `httpx.ConnectError` / `httpx.TimeoutException`, the `requests` equivalents on older `huggingface_hub`, and plain socket errors count as unreachable. These are the same classes `huggingface_hub` treats as "connection down". Proxy errors and HTTP answers (gated, 404, 5xx, rate limit) are per repo and do not silence other checks. - The freshness check still runs whenever the Hub answers. Revision pinning, the moved-`main` check and the symlink-free commit check are unchanged. A network that comes back gets checked again once the TTL runs out. - The same files load: the change only skips requests whose result was already "unanswerable, keep the local snapshot". Measured on CPU, real `huggingface_hub` 1.33 HTTP stack. `HF_ENDPOINT` points at a local TCP server that accepts and never answers. `HF_HUB_OFFLINE` is unset. The cached snapshot is `hf-internal-testing/tiny-flux-transformer` (1 shard) and a 4-shard snapshot with the same layout: | Case | main: requests / wall | this PR: requests / wall | |---|---|---| | Blackholed, 1 shard, 3 lookups | 3 / 15.1 s (5.0 s each) | 1 / 5.0 s (then 0.00 s) | | Blackholed, 4 shards, per lookup | 4 / 20.0 s every lookup | 1 / 5.0 s first lookup, 0 / 0.00 s after | | Blackholed, 4 shards, 3 lookups (mocked transport test) | 12 requests | 1 request | | Healthy endpoint, 4 shards, 2 lookups | 4 / 0.04 s, then memoized | 4 / 0.04 s, then memoized | ## Tests - New `test_a_blackholed_hub_costs_one_probe_per_process_not_one_per_shard_per_lookup`: an `httpx.MockTransport` that times out every request is installed through `huggingface_hub.set_client_factory`, then 4 shards go through 3 lookups. It fails on main (`assert 12 == 1`) and passes here. - New `test_an_http_answer_is_not_taken_for_an_unreachable_hub` (a 503 does not set the verdict) and `test_the_hub_is_asked_again_once_the_unreachable_verdict_expires` (the TTL expires and the moved `main` is detected again). - `tests/test_diffusion_prequant_cache.py`, `tests/test_diffusion_pipeline_prequant.py` and `tests/test_video_prequant.py`: 282 passed, 1 skipped (CPU).
Summary
When a diffusion or video denoiser has no hosted pre-quantized checkpoint, Studio quantizes it to int8 / fp8 at every load. This PR saves that result once as a local pre-quant checkpoint (the same safetensors format as the hosted ones) and resolves it like a hosted source on the next load, so the dense transformer is not read or re-quantized again.
studio/backend/core/inference/diffusion_prequant_cache.py.maininstead of reading a link.autopicks. A cache entry never changes whatautopicks (an earlier explicit int8 load does not turn a laterautoload into int8).autoneither reads nor writes the cache).diffusion.prequant_cache: hit (...).UNSLOTH_DIFFUSION_PREQUANT_CACHE=0disables it;UNSLOTH_DIFFUSION_PREQUANT_CACHE_DIRandUNSLOTH_DIFFUSION_PREQUANT_CACHE_MAX_GBset the root and budget.transformer_quant=auto, the image pipeline-kind quantize route, nvfp4 / mxfp8, native weight-only quant, torchao below 0.18, and text encoders.Results
Explicit int8, base = main, fresh process per load:
Re-checked after the follow-up fixes on one B200, Wan2.1-T2V-1.3B, explicit int8:
dcd1e0f4) on main, on the saving load, on every cache hit and with the cache switched off.Large models gain a lot of load time; small ones gain nothing on load time.
Tests
studio/backend/tests/test_diffusion_prequant_cache.py: key contents, streaming writer vs the safetensors reader, payload digest on same-size corruption, LRU eviction, the kill switch, the per-key build lease, symlink-free freshness, the bounded flatten, and thatautois never promoted by the cache. The GPU tests (real torchao quantization, save / reload / bit-identical round trip) pass on a B200, 50 of 50.test_video_prequant.py,test_diffusion_pipeline_prequant.py: the explicit-scheme seed and resolver routes.Not covered: an unhosted image family on a real model (FLUX.1-Kontext is gated for our token), AMD, Mac and Windows hardware (the Windows lock is unit tested), and serial per-shard Hub HEAD requests on a cold freshness check.