Skip to content

Studio diffusion: cache runtime-quantized denoisers as local pre-quant checkpoints - #13715

Merged
danielhanchen merged 37 commits into
mainfrom
studio-diffusion-local-prequant-cache
Oct 20, 2026
Merged

danielhanchen merged 37 commits into
mainfrom
studio-diffusion-local-prequant-cache

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 14, 2026 •

Copy link
Copy Markdown
Member

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.

  • New studio/backend/core/inference/diffusion_prequant_cache.py.
  • Key: source shard headers plus file identity, scheme, a policy version, transformer class, the layer-selection filter settings, the ConvRot rotation settings, and torch / torchao versions. Never the family name alone.
  • Write safety:
    • Streamed one tensor at a time, artifact first and manifest last as the commit point, so an interrupted write is never served.
    • One builder per key: a per-key lease is held from the "already cached?" check through publication, and eviction skips a key whose lease is held.
    • The save is skipped when disk is short; size-capped LRU eviction (default 40 GB).
    • The flatten builds the header one parameter at a time and writes torchao's bytes straight from the live weights, with no whole-model copy on the GPU.
  • Freshness: a cached entry is checked against the source revision; without symlinks in the Hub cache (Windows, some filesystems) the check compares the snapshot's etag with main instead of reading a link.
  • Which loads use it:
    • Image: an explicit scheme, or the scheme auto picks. A cache entry never changes what auto picks (an earlier explicit int8 load does not turn a later auto load into int8).
    • Video: explicit schemes only (auto neither reads nor writes the cache).
  • Load: the next load resolves the cached artifact like a hosted prequant (mmap) and logs diffusion.prequant_cache: hit (...).
  • Env vars: UNSLOTH_DIFFUSION_PREQUANT_CACHE=0 disables it; UNSLOTH_DIFFUSION_PREQUANT_CACHE_DIR and UNSLOTH_DIFFUSION_PREQUANT_CACHE_MAX_GB set the root and budget.
  • Paths not covered fall back to the normal runtime quantization unchanged: the video MoE second expert, video 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:

Model Main, loads 2 / 3 This PR, loads 2 / 3 This PR, load 1 (pays the save) Host RAM after load (main -> PR)
HunyuanVideo-1.5 480p (Colab A100) 144 / 107 s 59 / 16.5 s 201 s vs 162 s 22.7 -> 17.7 GiB
Wan2.1-T2V-1.3B (Colab G4) 5.4 / 5.5 s 5.9 / 5.9 s 14.9 s vs 11.0 s 40.9 -> 33.1 GiB

Re-checked after the follow-up fixes on one B200, Wan2.1-T2V-1.3B, explicit int8:

  • The transformer's weights hash the same (dcd1e0f4) on main, on the saving load, on every cache hit and with the cache switched off.
  • The save of the 1.33 GiB artifact took 2.0 s.
  • Warm loads on main and from the cache are within noise of each other for this small model.

Large models gain a lot of load time; small ones gain nothing on load time.

Tests

  • New 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 that auto is never promoted by the cache. The GPU tests (real torchao quantization, save / reload / bit-identical round trip) pass on a B200, 50 of 50.
  • Each follow-up fix test fails on the earlier head and passes here.
  • test_video_prequant.py, test_diffusion_pipeline_prequant.py: the explicit-scheme seed and resolver routes.
  • Prequant / transformer-quant selection: the same single failing test ID on main and on this branch (pre-existing).

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.

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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-20T13:28:54.197850Z a5058d5 New commits
🔒 Security Review ⚠️ Failed 2026-10-14T12:17:27.300576Z cce9ca4 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-14T12:17:26.556288Z cce9ca4 PR opened
🔒 Security Review 🔄 Running since 2026-10-14T12:17:23.411962Z cce9ca4 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 5 commits October 14, 2026 12:31
…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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 3 commits October 14, 2026 13:27
… 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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 6 commits October 14, 2026 14:33
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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

… 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.
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: c6ac0cd682

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

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 20, 2026
@unslothai unslothai deleted a comment from NilayYadav Oct 20, 2026
@unslothai unslothai deleted a comment from NilayYadav Oct 20, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@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: 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".

Comment on lines +263 to +265
try:
from huggingface_hub import try_to_load_from_cache
hit = try_to_load_from_cache(repo_or_dir, filename, 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 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed 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.

Comment on lines +454 to +456
if _hub_source_stale(
source_shards(base_repo or getattr(fam, "base_repo", None), component), logger
):

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 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 👍 / 👎.

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.

_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.

Comment on lines +1084 to +1085
if cached:
return PrequantSource(kind = "path", location = cached, filename = 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 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed 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.

Comment thread studio/backend/core/inference/video.py Outdated
Comment on lines +8661 to +8665
_save_runtime_quant_to_cache(
fam,
views,
base = base,
source = _base_local_dir or base,

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 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed 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.

Comment on lines +2356 to +2357
from .diffusion_prequant_cache import path_in_cache, verify_entry
if path_in_cache(path) and not verify_entry(path, logger):

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 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 👍 / 👎.

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 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.

@danielhanchen danielhanchen self-assigned this Oct 20, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: 5d015b6bb5

ℹ️ 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 a6c1e06 into main Oct 20, 2026
@danielhanchen
danielhanchen deleted the studio-diffusion-local-prequant-cache branch October 20, 2026 17:16
danielhanchen added a commit that referenced this pull request Oct 21, 2026
… 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.
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Oct 24, 2026
…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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants