Skip to content

Studio diffusion: faster returning-user load for cached int8 FLUX.3 (one Hub call, persisted CUTLASS tile probe) - #18837

Merged
danielhanchen merged 4 commits into
mainfrom
studio-diffusion-warm-load
Nov 22, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
studio-diffusion-warm-load

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

This makes a returning user's load faster for FLUX.3 klein with cached int8 weights. That is the case where a launch reuses the Studio home and the local int8 cache from an earlier one. On a Colab L4 with klein base int8, a fully warm launch loads 2.4 to 6.7 s sooner (depending on the Hub round trip) and starts its first image 0.7 s sooner. Every image is bit-identical to main. The second launch's 10 s GEMM re-race at the real row count is a separate change and is not part of this PR.

I profiled the warm load first: a wall-clock stack sampler ran during the load and the first render of launches 1 to 3. The real costs turned out to be different from the earlier estimate:

warm load phase (launch 3, 26.7 s) s addressed here
Hub revalidation in the FLUX.3 loader, one request per file (processor, tokenizer, image / video processor, chat templates, configs, index, transformer) 8.5 yes
other Hub requests (prequant cache freshness, text encoder checkpoint, model_info) 2.5 no
first imports of diffusers / transformers / dynamo 5.9 no (needed anyway)
import unsloth for the zoo patch helpers 4.8 no, see below
upload, text encoder int8 read, plan, the rest 5.0 no
of which the dense transformer build before the cache read 0.75 (0.66 s Hub requests, 0.1 s build) by the first row

Before the first image, the prebuilt CUTLASS tile probe takes 1.3 to 1.5 s on every launch. On launch 2 only, a 10 s GEMM race also runs at 4224 rows; that is handled elsewhere.

Changes

  1. One Hub call instead of one per file (diffusion_hub_snapshot.py, FLUX.3 loader). A load that may download asks the Hub about every file it opens, about 25 requests. After a load has revalidated every file and the Hub confirms the commit, it writes a record. The record holds the repo, commit, components, library versions (transformers, diffusers, huggingface_hub, tokenizers), a hash of the loader code and the snapshot's file list, including .no_exist entries. A later load with the same record makes one model_info call. If main still names that commit, it reads every component with local_files_only=True, so it opens exactly the files the revalidating load opened. Anything else revalidates per file as before: a moved ref, new versions or code, a file added or removed, offline, unreachable, or a local directory. A component that fails the cache-only read is read online and the record is dropped. UNSLOTH_DIFFUSION_HUB_SNAPSHOT=0 turns it off.
  2. Persisted CUTLASS tile probe (diffusion_int8_cutlass.probed_tiles). The bit-exact probe verdict is stored through diffusion_probe_cache.Namespace. The key covers the card UUID, driver, torch / CUDA / Triton / torchao, the UNSLOTH_DIFFUSION_* env, the source of diffusion_int8_cutlass.py and diffusion_int8_gemm.py, and the loaded library's bytes. A missing, stale or malformed verdict re-probes. A failing tile is only stored when it fails twice in a row, so one transient error cannot drop a tile for good. UNSLOTH_DIFFUSION_PROBE_CACHE=0 turns it off.

Results

Colab L4, klein base int8, 1024x1024. Base is the merge base and head is this branch, on the same VM. Each arm runs launches 1 to N against its own home, one fresh process per launch. The weight files (Hub snapshot and the home's int8 cache) are read once right before every launch to control the page cache.

20 steps, two timed renders per launch. Launch 2 still re-races GEMM tiles in both arms (about 10 s, not changed here). Launches 3 and 4 show the fully warm state:

launch base load s head load s base first render s head first render s s/step base / head
1 58.69 59.79 81.45 80.57 0.961 / 0.952
2 22.29 19.65 37.99 37.10 0.943 / 0.944
3 22.13 19.84 29.79 29.00 0.948 / 0.953
4 21.90 19.53 29.36 28.63 0.949 / 0.949
  • Every image of every launch has the same md5 in both arms, and LPIPS is 0.0 for the pair that was scored.
  • Every image of every launch has the same md5 in both arms.
  • Engagement: a later run of the same Hub change logged the cached snapshot on launch 2 ("still the validated cached commit", one Hub call). On that VM's longer Hub round trip the load dropped 6.7 s (27.28 s to 20.61 s).
  • The load saving depends on the Hub round trip: 2.4 s here, 6.7 s on the other VM. The first-render saving (about 0.7 s) is the tile probe.
  • Steady s/step stays inside the A/A spread (base alone ranges 0.943 to 0.961). Peak VRAM and host RAM are unchanged.

Not changed

  • import unsloth (4.8 s) runs because the zoo patch helpers need it. Moving it to a background thread or skipping it could change which patches the text encoder sees, so it stays as is.
  • I did not build the transformer on the meta device. The dense build before the cache read costs 0.75 s, and 0.66 s of that is Hub requests, which change 1 already removes.

Tests

  • New CPU tests: test_diffusion_hub_snapshot.py (record / match / miss on a moved ref, other versions or code, a file added or gone, offline, the switch, loader routing and fallback), test_diffusion_int8_cutlass_probe_persist.py (stored verdict skips the probe; stale or malformed re-probes; a flapping failure is not stored; driver and library changes miss).
  • The FLUX.3 / int8 GEMM / CUTLASS / probe cache / prequant suites fail the same test IDs on base and head. Those failures were already there.

Not covered

  • klein 4B distilled. The run that held its arms lost its artifacts after the first base launch, and there was no budget left to repeat it. Change 2 does not depend on the family. Change 1 is wired only into the FLUX.3 loader.
  • One sample per cell: there are no repeated A/A runs for load time. The cold load differences between the two arms (+1.1 s and +3.1 s) are inside the variation that the cold quantize and cache write show across runs.
  • No GPU other than L4 was measured.

- Read an unchanged, already validated Hub snapshot from the cache with one
  Hub call instead of one revalidation per file (FLUX.3 loader).
- Persist the prebuilt CUTLASS tile probe verdict per card, driver, toolchain,
  library bytes and code.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-22T05:29:23.434855Z 6db5ce0 Manual request
ℹ️ 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.

@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: 6858657e21

ℹ️ 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 +495 to +496
if not any(_probe_tile(index, fam, t, pairs) for t in failed):
_store_tiles(index, fam, ok)

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 persisting an all-failed probe under temporary GPU pressure

If GPU memory pressure causes every tile probe to fail, immediately retrying the probes can encounter the same pressure and persist an empty ok list. _probe_tile converts allocation and CUDA exceptions into False, so these failures do not establish that the kernels are incompatible. Subsequent healthy launches accept that empty verdict without probing again, disabling CUTLASS acceleration indefinitely for the same fingerprint. Avoid persisting an all-failed result, as the existing quant-probe cache does, or distinguish resource failures from definitive correctness failures before storing them.

Useful? React with 👍 / 👎.

The warm-load record compared file names, so a dangling link still matched and the
load read cache-only; transformers (4.57.6 and 5.17) then loads the processor
without its chat template and raises nothing. Count only links that resolve, so a
partially deleted cache revalidates and fetches the file again.
A tile probe that ran out of memory on a full card, or after a sticky launch
error, failed both times and was stored, so the tile stayed off in every later
process on that card and driver. Persist only when the allocator's OOM count
did not move and the context still syncs.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 6db5ce031b

ℹ️ 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 added a commit that referenced this pull request Nov 22, 2026
…ding, not bitwise (#18840)

## Summary

`(Python 3.13, diffusion)` fails intermittently across unrelated PRs
(#18837, and the `studio-klein-ref-kv` branch):

```
tests/test_diffusion_vae_upsample_fold.py::test_strip_fold_matches_the_whole_map[5]
tests/test_diffusion_vae_upsample_fold.py::test_strip_fold_matches_the_whole_map[13]
E   assert False
E    +  where False = torch.equal(whole, strips)
```

The test, added by #18792, runs the folded transposed conv once over the
whole map and once strip by strip with the one-row halo, then asserts
the two are bitwise equal. The fold is correct (the same test passes
here, and its second assert still checks both against the unfused
nearest 2x + conv chain to 1e-6). Bitwise equality is just not something
the CPU conv backend promises: a strip-sized input can be blocked
differently from the whole map, so the taps are summed in another order.
Which kernel gets picked depends on the runner's CPU, which is why it
only fails on some runs and only for the multi-strip heights (5 and 13;
1 and 2 are a single strip).

## Fix

Compare `whole` and `strips` to `1e-10` instead of bitwise. The data is
fp64, so reordering costs about `1e-16`, while a seam or halo bug is off
by O(1).

## Testing

- `studio/backend/tests/test_diffusion_vae_upsample_fold.py`: 11 passed.
- Sabotage: dropping the halo row in `_fold_upsample` (`lo = a` instead
of `max(0, a - 1)`) still fails
`test_strip_fold_matches_the_whole_map[5]` and `[13]`.
@danielhanchen
danielhanchen merged commit 1353a63 into main Nov 22, 2026
@danielhanchen
danielhanchen deleted the studio-diffusion-warm-load branch November 22, 2026 09:41
danielhanchen added a commit that referenced this pull request Nov 23, 2026
…ache reads, OOM tile probe, ConvRot-only hosted int8 video (#18982)

## Summary

Four fixes found while re-checking recent Studio image and video load
changes, one commit each, plus one test-compat fix.

1. **klein 9B KV identity (follow-up to #18831).** `_resolve_base_repo`
swaps the KV base (`black-forest-labs/FLUX.2-klein-9b-kv`) for the stock
9B it borrows its text encoder, VAE and scheduler from. The queued load
then wrote that 9B back into `base_repo` before `load_pipeline` picked
the pipeline class, and a base taken from the model card never reached
it at all. A KV GGUF or single file with a generic name (no "KV" in the
repo or file name) ran through the stock `Flux2KleinPipeline`,
advertised inpaint / outpaint, and passed the guard that keeps the
base's dense transformer from replacing the KV DiT. `_resolve_base_repo`
now records the base the caller or the card named
(`_checkpoint_base_of`), the queued load passes it to `load_pipeline` as
`_checkpoint_base`, and the pipeline class, that guard, the dense
prefetch widening and the load state read it. Companion fetches still
use the stock 9B.
2. **FLUX.3 cache-only reads pin the validated commit (follow-up to
#18837).** `current_snapshot` returns the commit it validated, but the
loader only kept a bool. Every cache-only read then resolved `refs/main`
again. If another download moved that ref in between, the load read
files from a snapshot nobody had validated. The commit is now passed as
`revision` to every cache-only read (index, processor, text encoder,
transformer, VAE, stored-dtype probes). A read that falls back to the
Hub is unpinned, as before.
3. **CUTLASS tile probe and the async allocator (follow-up to #18837).**
A failure persists only when it repeats and `num_ooms` did not move.
Under `PYTORCH_CUDA_ALLOC_CONF=backend:cudaMallocAsync` that count stays
0, because the async allocator fills none of the native allocator's
stats (`CUDAMallocAsyncAllocator.cpp`, `getDeviceStats`). A probe on a
full card therefore persisted an empty tile list, and every later
process on that card skipped the CUTLASS int8 tiles. `_probe_tile` now
counts its own out-of-memory failures, and a probe that hit one does not
persist. Editing the module also invalidates the verdicts already
stored.
4. **Torchao-free hosted int8 commit takes only the ConvRot file
(follow-up to #18958).** With no usable torchao (the Windows ROCm stub),
the check that drops the dense LTX-2.5 DiT shards accepted any hosted
`.safetensors` name. The native read only accepts the ConvRot file. So
with `UNSLOTH_DIFFUSION_INT8_CONVROT=0` (which resolves the unrotated
`LTX-2.5-INT8.safetensors`), or with a listing that has no ConvRot file,
the load staged 25 GB and the reader then refused it. Now only the
`-ConvRot.safetensors` file counts. With ConvRot off, the ROCm hosted
int8 route (plan, price, commit) does not apply, so the load uses the
dense shards and runtime build as before. This matches the ConvRot gate
the image route already has.
5. **Tests.** The FLUX.3 warm-load fixture patched
`diffusers.Flux3Transformer2DModel.from_pretrained`, so its four loader
tests failed with `AttributeError` on a diffusers that meets the
declared floor (>= 0.39) but predates the FLUX.3 classes. A missing
class now gets a stand-in.

## Tests

New tests fail on the merge base and pass on this branch (base arm = the
merge base with the new test files copied in):

| file | new tests | base | head |
|---|---|---|---|
| `test_diffusion_flux2_klein_kv.py` | card-only and explicit KV
identity, queued load hands `load_pipeline` the KV identity,
`load_pipeline` wiring | 4 failed | pass |
| `test_diffusion_hub_snapshot.py` | cache-only reads pin the validated
commit, Hub fallback stays unpinned, real `hf_hub_download` cache read
after `refs/main` moves | 2 failed (4 more fail on the old fixture with
diffusers 0.40) | pass |
| `test_diffusion_int8_cutlass_probe_persist.py` | an OOM the allocator
stats never count is not persisted | 1 failed (persisted `ok: []`) |
pass |
| `test_video_hosted_int8_fit.py` | unrotated file never committed
without torchao, ConvRot file beside it still committed, ConvRot off
takes the hosted route off | 3 failed | pass |

Related suites (klein KV, FLUX.3 loader / storage / manual cast, hub
snapshot, CUTLASS, gated base, compat preflight, video hosted int8 /
native hosted / families, refactor guard): 1676 passed. The 8 failures
are the same 8 test IDs on the merge base: 5 MiniMax H3 download-plan
tests and 2 FLUX.3 retired-copy tests from a `huggingface_hub` without
`get_cached_repo_tree` / diffusers 0.40, and 1 causal-mask patch test.

## Not covered

- No GPU run. The async-allocator OOM path is shown by injecting
`OutOfMemoryError` with `num_ooms` fixed at 0, which is what the
upstream allocator source reports. It was not run on a real card with
`backend:cudaMallocAsync`.
- No Windows ROCm run of the ConvRot gate. The check is CPU-only, using
the existing torchao-stub fixture.
- The native sd.cpp engine takes its base from the request alone, so a
card-only KV identity does not reach its reference-edit refusal. That is
not changed here.
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