Repository navigation
Studio FLUX.2 klein 9B-KV: run KV checkpoints on their own pipeline (cached reference K/V, 1.47-2.23x edits) - #18831
Conversation
black-forest-labs/FLUX.2-klein-9b-kv (and GGUF / FP8 / ComfyUI files of it) already matched the flux.2-klein family, but loaded through Flux2KleinPipeline, which runs the stock bidirectional reference path the checkpoint was not trained for. The KV checkpoint's reference tokens attend only to themselves and are modulated at timestep 0, so their K/V are the same on every step and Flux2KleinKVPipeline computes them once, on step 0. - diffusion_families: pipeline_class_variants + family_pipeline_class(); klein routes any id or file spelling klein-9B-KV to Flux2KleinKVPipeline; a KV GGUF / single file keeps the 9B base (identical config, encoder, VAE and scheduler; ungated mirror). The KV repo itself is a large small-DiT base with inner dim 4096; diffusers floor 0.38.0. - Text encoder: the KV repo's Qwen3-8B shards are the 9B's (LFS sha256), so it joins the 9B encoder equivalence group and its pre-cast files. - diffusion: load and preflight resolve the per-checkpoint class; a pipeline whose __call__ takes no guidance kwarg reports guidance off and never receives it (Flux2KleinKVPipeline raised TypeError on every render). - diffusion_cuda_graph: a kv_cache_mode="extract" call runs eager; its returned cache would fail the capture and poison later plain calls. Stock klein 4B / 9B are unchanged: caching their reference K/V is not exact (they attend to the noisy image and take the step's timestep).
|
@codex review |
Codex Review Summary: ✅ CompletedThis 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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 47bdc2fded
ℹ️ 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".
| # bidirectional path instead of the one it was trained for. A KV GGUF / single file keeps the 9B as its base on | ||
| # purpose: config, text encoder, VAE and scheduler are byte-identical, and the 9B's come from the ungated mirror | ||
| # while the KV repo is gated with no mirror; only the pipeline class follows the file. | ||
| pipeline_class_variants = (("klein9bkv", "Flux2KleinKVPipeline"),), |
There was a problem hiding this comment.
Prevent KV GGUFs from substituting the stock 9B transformer
When a KV GGUF is loaded with an explicit transformer quantization such as INT8 and the dense build fits, the loader can replace its weights with the stock 9B transformer while retaining the newly selected KV pipeline. KV files deliberately resolve to the stock 9B base, but this family has no checkpoint-variant distinction, so transformer_variant_differs_from_base() returns false and the guard in diffusion.py allows _load_dense_quant_pipeline() to read that base's transformer/ instead of the selected GGUF. This now runs stock weights through the incompatible cached-reference path and silently changes the selected model. Register the weight distinction and decline base-transformer substitution for KV files.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed: transformer_variant_differs_from_base() now treats a checkpoint whose pipeline class differs from its base's as a different transformer, so a klein 9B KV file never gets the stock 9B DiT. The dense / INT8 build is declined and the GGUF keeps its own weights; covered by test_a_kv_file_never_counts_as_the_stock_9b_transformer.
| if not family_buildable_here(fam, model_kind = kind, gguf_filename = gguf_filename): | ||
| assert_pipeline_class_available(fam.pipeline_class, fam.name) | ||
| assert_pipeline_class_available( | ||
| family_pipeline_class(fam, base_repo, repo_id, gguf_filename), fam.name | ||
| ) |
There was a problem hiding this comment.
Check variant availability before accepting the load request
On diffusers 0.37.x, which provides Flux2KleinPipeline but not Flux2KleinKVPipeline, family_buildable_here() returns true because it checks the family's default class. Consequently, this conditional skips the new variant-specific availability check entirely. A KV pipeline request passes preflight and only fails at the later _family_model_class() lookup, after the GPU handoff can evict the currently loaded model. Make the buildability check account for the resolved pipeline variant so unsupported KV requests are rejected before eviction.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed: validate_load_request now checks the checkpoint's own pipeline class before the GPU handoff, so on diffusers 0.37.x a KV pick is refused up front with the needs diffusers >= 0.38.0 message instead of failing after eviction; covered by test_preflight_refuses_a_kv_pick_on_a_diffusers_without_the_kv_pipeline.
Flux2KleinKVPipeline keeps every reference token's key and value for all 32 blocks from step 0 to the end of the denoise. On an A100-40 at 1024x1024 with 1024x1024 references that added 1.7 / 4.7 / 9.6 GiB of peak over klein 9B for 1 / 2 / 4 references, which neither the flat activation estimate nor a measured placement priced. - diffusion_memory.reference_kv_cache_mib: tokens x blocks x (K, V) x inner dim x activation dtype bytes x batch, references capped at 1 MP as the pipeline does, x1.2 to match the measured slope (about 2 KiB per reference pixel in bf16 before the margin). 0 for any other pipeline. - image_activation_verdict / raise_on / shortfall_message take persistent_mib, added to the untiled and the tiled need (tiling the decode cannot shrink a cache held through the denoise); the refusal names it. The Hires refine preflight passes 0. - generate prices it for every request with an input image, and adds it to the request extra of a measured placement so resident groups stream instead of the render running out of memory; it logs the priced size. - _pipe_takes_kwarg reads __call__ with getattr, so a status call on a placeholder pipe no longer raises.
… repo The published KV GGUFs tag black-forest-labs/FLUX.2-klein-9b-kv as their base. That repo was not in the trusted set, so the tag was dropped and the load fell to the family default (klein 4B), whose shapes do not match a 9B GGUF; a direct pipeline load of the KV repo was refused as untrusted. - klein's profile trusts black-forest-labs/flux.2-klein-9b-kv. - companion_base(): a GGUF / single file whose base is the KV repo reads its text encoder, VAE, scheduler and config from klein 9B (same LFS sha256 for every one of them), so it fetches from the ungated mirror and needs no grant on the gated KV repo; the file holds the denoiser and the pipeline class still follows the file name.
…peline - transformer_variant_differs_from_base: a checkpoint whose pipeline_class_variants class differs from its base's is a different transformer. KV GGUFs resolve to the stock 9B base for their companions, and with the old answer (False for this family) an explicit transformer quantisation could build the dense / INT8 model from the base's transformer/, i.e. the stock 9B DiT under the KV pipeline. The GGUF now keeps its own weights (dense build declined, as for other variants). - validate_load_request checks a variant pipeline class on its own, before the GPU handoff: on diffusers 0.37.x the family reads as buildable from Flux2KleinPipeline, so a KV pick skipped the check and failed late in _family_model_class() after the current model could have been evicted. It is now refused up front with the diffusers >= 0.38.0 message. [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. 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". |
…ht the KV pipeline only for diffusers loads sd.cpp has no reference K/V cache for FLUX.2 klein 9B KV (leejet/stable-diffusion.cpp#1341), so a reference or edit call on a KV file loaded natively now names that and points at the diffusers engine or the stock 9B; text to image there is the same math and keeps rendering. The diffusers >= 0.38.0 check for Flux2KleinKVPipeline now applies only when the GGUF will load on diffusers, so a Python 3.9 host (diffusers 0.36.0) that routes a KV GGUF to sd.cpp keeps loading it as before. [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c45b18c227
ℹ️ 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".
| # bidirectional path instead of the one it was trained for. A KV GGUF / single file keeps the 9B as its base on | ||
| # purpose: config, text encoder, VAE and scheduler are byte-identical, and the 9B's come from the ungated mirror | ||
| # while the KV repo is gated with no mirror; only the pipeline class follows the file. | ||
| pipeline_class_variants = (("klein9bkv", "Flux2KleinKVPipeline"),), |
There was a problem hiding this comment.
Disable stock inpainting for KV checkpoints
When a newly supported KV checkpoint is used with a mask, generate() still selects fam.inpaint_pipeline_class through _workflow_pipe(), which builds the stock Flux2KleinInpaintPipeline over the resident transformer. That pipeline concatenates output and reference latents and calls the transformer without kv_cache_mode or num_ref_tokens, so the references follow the stock bidirectional, per-step-modulated path rather than the KV checkpoint's trained reference path. The new routing therefore fixes reference edits but still silently runs the wrong model for the advertised inpainting workflow. Either provide a KV-compatible inpainting path or remove and reject that workflow for KV checkpoints.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed: Flux2KleinInpaintPipeline always passes the encoded source image to the transformer as condition tokens through the stock per-step path (no kv_cache_mode), and diffusers has no KV inpaint pipeline, so d3f3c50 refuses inpaint, outpaint, img2img and upscale for KV checkpoints with a message saying why, and drops them from the advertised workflows, leaving text to image and reference edits. The new tests fail on the previous head and pass on the fix.
…s advertised workflows Flux2KleinInpaintPipeline always feeds the encoded source image to the transformer as condition tokens through the stock bidirectional per-step path, with no kv_cache_mode, so built over the KV transformer it runs another model; and diffusers ships no KV inpaint pipeline. A checkpoint that needs its own pipeline class now refuses the workflows built from the family's stock workflow classes (inpaint, outpaint, img2img, upscale) with a message naming why, and status lists only the workflows its own pipeline runs (text to image and reference for the KV checkpoint). [skip ci]
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d3f3c50a26
ℹ️ 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".
| # No card tag: only a curated variant the name spells out. | ||
| base = named_variant_base(fam, repo_id, gguf_filename) or "" | ||
| # A KV-style checkpoint's card tags its gated repo; the file holds the denoiser, the rest is another base's bytes. | ||
| base = companion_base(base) or base |
There was a problem hiding this comment.
Preserve KV checkpoint identity when remapping its companion base
If a local GGUF or single file has a generic name and the caller supplies base_repo="black-forest-labs/FLUX.2-klein-9b-kv", this remapping discards the only identifier that distinguishes its weights from stock 9B. Preflight correctly selects Flux2KleinKVPipeline from the original base_repo, but the actual load calls family_pipeline_class(fam, base, repo_id, gguf_filename) with the remapped stock base and selects Flux2KleinPipeline instead. The transformer-variant guard likewise returns false, allowing dense quantization to substitute stock weights. Retain the original checkpoint identity separately from the companion download base and use it for pipeline selection and transformer-substitution checks.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 6e5eea6: the load keeps the caller's base_repo alongside the remapped companion base (checkpoint_base on the load state). Pipeline selection, the dense-substitution guard and the advertised workflows read it, and the native engine's reference refusal reads its own base_repo, so a generic local GGUF loaded with base_repo=black-forest-labs/FLUX.2-klein-9b-kv stays on Flux2KleinKVPipeline and never takes the stock 9B transformer. Tests cover all three.
|
@codex review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. 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". |
|
That shard runs without diffusers installed, and the new parametrised test reaches a diffusers import for the inpaint and upscale workflows. A |
…out a real diffusers [skip ci]
…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.
Problem
black-forest-labs/FLUX.2-klein-9b-kvis BFL's klein 9B variant for reference-image edits. Its GGUF, FP8 and other single files already match theflux.2-kleinfamily in Studio. All of them still load throughFlux2KleinPipeline, and that is wrong for this checkpoint.The KV checkpoint was trained with a different reference path:
Because of this, their keys and values are the same on every step.
Flux2KleinKVPipeline(diffusers 0.38.0 and later) computes them once on step 0, and steps 1 to 3 run on the output and text tokens only.Flux2KleinPipelineruns the stock bidirectional path instead, so these weights were being run as a model they are not. PickingFlux2KleinKVPipelinewas not enough on its own either: Studio always passesguidance_scale, andFlux2KleinKVPipeline.__call__takes no such argument, so every render would raiseTypeError.Stock klein 4B and 9B cannot take this as a runtime switch:
Change
diffusion_families.pypipeline_class_variantsfield (folded id substring to pipeline class) andfamily_pipeline_class().klein-9B-KVtoFlux2KleinKVPipeline; everything else keepsFlux2KleinPipeline._diffusers_version/_name_or_path. The 9B's files come from the ungated mirror. The KV repo is gated, under the same FLUX Non-Commercial licence as klein 9B, and has no mirror.Flux2KleinKVPipelinehas a floor of diffusers 0.38.0 (0.37.1 does not export it).diffusion.py__call__takes no guidance kwarg (and no**kwargs) reports guidance as unsupported and never receives it.is_distilled.diffusion_cuda_graph.pykv_cache_mode="extract"call now runs eager. It returns its cache beside the noise, so a capture of it would fail and leave every later plain call on that load eager.Activation guard (
diffusion_memory.py,diffusion.py)reference_kv_cache_mib()prices the reference cache: tokens x 32 blocks x (K, V) x inner dim x activation dtype bytes x batch.KV GGUFs (
diffusion_families.py,diffusion.py)black-forest-labs/FLUX.2-klein-9b-kvas their base. That repo was not trusted, so the tag was dropped and the load fell to klein 4B, then was refused on shape. A direct pipeline load of the KV repo was also refused as untrusted.Never the stock DiT for a KV file (
diffusion_families.py): a checkpoint whose pipeline class differs from its base's counts as a different transformer. The dense / INT8 build is declined for a KV GGUF, as it is for other variants, and the GGUF keeps its own weights rather than reading the 9B base'stransformer/.Early class check (
diffusion.py): preflight checks the KV pipeline class on its own. On diffusers 0.37.x the family reads as buildable fromFlux2KleinPipeline, so a KV pick now gets the diffusers >= 0.38.0 refusal before the current model is evicted. This applies only when the GGUF will load on diffusers: a host that sends it to the native sd.cpp engine (for example Python 3.9 on the diffusers 0.36.0 pin) keeps loading it as before.Native engine (
sd_cpp_backend.py): sd.cpp has no reference K/V cache for this checkpoint ([Feature] FLUX2 klein-9b-KV leejet/stable-diffusion.cpp#1341). A reference or edit call on a KV file loaded natively (CPU, MPS with sd.cpp, off-torch Vulkan, forced native) is refused with a message that names this and points at the diffusers engine on a CUDA, ROCm or XPU GPU, or the stock klein 9B. Text to image on a KV file is the same math there and keeps working.No stock workflow pipelines for a KV checkpoint (
diffusion.py):Flux2KleinInpaintPipelinealways feeds the encoded source image to the transformer as condition tokens through the stock bidirectional per-step path, and diffusers ships no KV inpaint pipeline. A checkpoint that needs its own pipeline class refuses inpaint, outpaint, img2img and upscale with a message naming why, and status lists only text to image and reference for it, so the Images page does not offer the others.No new picker entry. A loaded KV checkpoint shows the Text to image and Reference workflows only (screenshots at the end).
Tests
New file
tests/test_diffusion_flux2_klein_kv.py:from_piperuns; the stock 9B keeps both. These fail on the previous head.test_diffusion_cuda_graph.py: an extract call is refused without capture or poisoning.Family, fetch-id, freeze, cache, static-skip, block-graph, preflight, auto-policy and TE-default suites: 714 passed, 25 skipped. A further 1128 passed (4 skipped) on the pinned diffusers 0.42.1.
Benchmark
Setup
Flux2KleinPipeline. Head: KV checkpoint throughFlux2KleinKVPipeline.Exactness and repeatability
Memory
Image difference
Studio end to end
Studio's own
load_pipeline+generateon one A100-SXM4-40GB, with each arm in a fresh process:QuantStack/FLUX.2-Klein-9B-KV-GGUFQ8_0 againstunsloth/FLUX.2-klein-9B-GGUFQ8_0.pricing ~2458 MiBfor 1 reference and~4915 MiBfor 2.Not covered
k_ref/v_ref; this is left for a follow-up. On an L4, Studio armed no graphs for stock klein 9B GGUF text-to-image at the same 4096-token shape. Default vs graphs disabled measured 7.80 to 7.93 s against 7.71 to 7.89 s per image, so there is no measurable cost there. The A100 cost is not measured.Screenshots
Images page workflow list with a FLUX.2 klein 9B KV GGUF loaded (top) and the stock klein 9B GGUF loaded (bottom), merge base
f63869bon the left and this PR (d3f3c50) on the right. Each side's Studio is built from its own commit, and the page gets the load status from that commit'sDiffusionBackend.status()over a stand-in resident klein state (no weights, no GPU). The stand-in pipe uses the real diffusers__call__signature and klein 9B'sis_distilled. With the KV checkpoint loaded, Inpaint goes from enabled to greyed out, leaving Create (text to image) and Reference. With the stock 9B loaded, Inpaint is still enabled. Extend (outpaint) was never offered for klein, before or after. Guidance does not change: stock klein 9B is step-distilled (is_distilled: true), so status reportssupports_guidance: falsefor the stock 9B and for the KV checkpoint on both commits. Here the PR only keeps the guidance kwarg out of theFlux2KleinKVPipelinecall.