Skip to content

Studio FLUX.2 klein 9B-KV: run KV checkpoints on their own pipeline (cached reference K/V, 1.47-2.23x edits) - #18831

Merged
danielhanchen merged 8 commits into
mainfrom
studio-klein-ref-kv
Nov 22, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
studio-klein-ref-kv

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

Problem

black-forest-labs/FLUX.2-klein-9b-kv is BFL's klein 9B variant for reference-image edits. Its GGUF, FP8 and other single files already match the flux.2-klein family in Studio. All of them still load through Flux2KleinPipeline, and that is wrong for this checkpoint.

The KV checkpoint was trained with a different reference path:

  • Reference tokens attend only to themselves, not to the text or the noisy image.
  • Reference tokens are modulated at a fixed timestep 0, not at the step's timestep.

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.

Flux2KleinPipeline runs the stock bidirectional path instead, so these weights were being run as a model they are not. Picking Flux2KleinKVPipeline was not enough on its own either: Studio always passes guidance_scale, and Flux2KleinKVPipeline.__call__ takes no such argument, so every render would raise TypeError.

Stock klein 4B and 9B cannot take this as a runtime switch:

  • Their reference tokens attend to the noisy image and take the step's timestep, so their K/V change every step.
  • On a tiny random FLUX.2 transformer in fp64, the KV attention path differs from the stock path by a max abs of 1.0 to 2.6 on the same inputs.

Change

  • diffusion_families.py

    • New pipeline_class_variants field (folded id substring to pipeline class) and family_pipeline_class().
    • klein maps any id or file name spelling klein-9B-KV to Flux2KleinKVPipeline; everything else keeps Flux2KleinPipeline.
    • A KV GGUF or single file keeps the 9B as its base. Text encoder, VAE and scheduler are byte-identical to the 9B's (same LFS sha256). The transformer config is not byte-identical: it matches every architecture field and differs only in _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.
    • The KV repo is listed with the 9B in the large-base, inner-dim and size tables, and in the Qwen3-8B encoder equivalence group.
    • Flux2KleinKVPipeline has a floor of diffusers 0.38.0 (0.37.1 does not export it).
  • diffusion.py

    • Load and preflight resolve the per-checkpoint pipeline class.
    • A pipeline whose __call__ takes no guidance kwarg (and no **kwargs) reports guidance as unsupported and never receives it.
    • klein's distilled check also covers the KV pipeline, which does not register is_distilled.
  • diffusion_cuda_graph.py

    • A kv_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.
    • References are capped at 1 MP, as the pipeline does, with a x1.2 margin fitted to the measured slope. That is about 2.4 GiB per 1 MP reference in bf16, and 0 for every other pipeline.
    • The guard adds it to both the untiled and the tiled need, since tiling the decode cannot shrink a cache held through the denoise.
    • A measured placement's request extra also grows by it, so resident groups stream instead of the render running out of memory.
    • A refusal names the cache. The priced size is logged.
  • KV GGUFs (diffusion_families.py, diffusion.py)

    • The published KV GGUFs tag black-forest-labs/FLUX.2-klein-9b-kv as 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.
    • klein now trusts the KV repo.
    • A GGUF or single file whose base is the KV repo takes its text encoder, VAE, scheduler and transformer config from klein 9B, through the ungated mirror. The config matches every architecture field of the KV one. It needs no grant on the gated repo; the pipeline class still follows the file name.
  • 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's transformer/.

  • Early class check (diffusion.py): preflight checks the KV pipeline class on its own. On diffusers 0.37.x the family reads as buildable from Flux2KleinPipeline, 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): Flux2KleinInpaintPipeline always 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:

  • Pipeline routing for the KV repo and for GGUF, FP8 and quant-repo names; stock klein and every other family are unchanged.
  • KV files keep the ungated 9B base.
  • Size, inner-dim and encoder tables.
  • Guidance gating.
  • The KV cache estimate (bf16 / fp32 / quantized weights, batch, more than 1 MP, other pipelines).
  • The guard decision: the same request runs without the cache, is refused with the cache named, and runs again with room for it.
  • KV GGUF base resolution to the 9B mirror, and the trusted repo.
  • A KV file is a different transformer from the stock 9B base (or a local base dir), but not from the KV repo itself.
  • A faked diffusers 0.37.1 refuses a KV GGUF in preflight while the stock 9B GGUF still passes. Both of these tests fail on the previous code.
  • A faked diffusers 0.36.0 lets a KV GGUF through preflight when the router sends it to sd.cpp, and still refuses it for a diffusers load or an unreadable prediction.
  • On the native engine, a KV file's reference edit is refused with the sd.cpp#1341 message while its text to image still renders; a stock 9B GGUF keeps its own message. The preflight and native refusal tests fail on the previous head.
  • A KV checkpoint lists only text to image and reference, and its inpaint / upscale workflow pipe is refused before from_pipe runs; the stock 9B keeps both. These fail on the previous head.
  • A tiny-transformer exactness test, in fp64:
    • a cached step equals recomputing the reference tokens every step, bit for bit;
    • that function differs from the stock bidirectional one.

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

  • Base: klein 9B bf16 through Flux2KleinPipeline. Head: KV checkpoint through Flux2KleinKVPipeline.
  • KV weights: BFL's published FP8 file, dequantised to bf16.
  • Render: 1024x1024 output, 4 steps, 1024x1024 references, the same prompt embeddings and seed.
  • One A100-SXM4-40GB. Each arm ran in a fresh process with 3 timed repeats after one warm-up; median shown. Repeat spread was 20 ms or less.
Refs 9B wall (s) KV wall (s) Wall speedup 9B s/step KV step 0 / steps 1-3 (s) 9B peak (GiB) KV peak (GiB)
1 3.78 2.57 1.47x 0.863 0.833 / 0.468 19.5 21.2
2 6.00 3.34 1.79x 1.384 1.315 / 0.521 19.5 24.1
4 11.49 5.15 2.23x 2.694 2.551 / 0.628 20.5 30.1

Exactness and repeatability

  • KV with the cache vs the same weights recomputing the references every step: bit-identical images at 1 and 2 references (LPIPS 0, max pixel delta 0). The recompute arm ran out of memory at 4 references on 40 GB.
  • A second KV process matched the first bit for bit, and so did repeats within a process.

Memory

  • The cache holds about 2.4 GiB per 1 MP reference in bf16.
  • On a 24 GB L4, klein 9B bf16 ran 1/2/4 references at 3.47 / 5.66 / 11.04 s/step (peak 19.5 to 20.5 GiB). The KV checkpoint in bf16 ran out of memory at 1 reference there.

Image difference

  • KV vs klein 9B LPIPS is 0.42 to 0.47. They are different models: both give coherent edits of the same scene, with different subject detail.

Studio end to end

Studio's own load_pipeline + generate on one A100-SXM4-40GB, with each arm in a fresh process:

  • Workflow: reference edit at 1024x1024, 4 steps, seed 1234.
  • Files: QuantStack/FLUX.2-Klein-9B-KV-GGUF Q8_0 against unsloth/FLUX.2-klein-9B-GGUF Q8_0.
  • Warm wall is the second render of each size.
Arm Pipeline Base resolved 1 ref wall (s) 2 refs wall (s) Peak alloc 1 / 2 refs (GiB)
main, KV GGUF refused klein 4B - - -
this PR, KV GGUF Flux2KleinKVPipeline klein 9B (mirror) 2.72 3.81 24.6 / 27.6
this PR, stock 9B GGUF Flux2KleinPipeline klein 9B (mirror) 3.69 5.93 11.4 / 12.1
main, stock 9B GGUF Flux2KleinPipeline klein 9B (mirror) 3.69 5.94 11.4 / 12.1
  • On main, the KV GGUF load fails: "...is a FLUX.2-klein-9B / klein-base-9B checkpoint, but it is being loaded against 'black-forest-labs/FLUX.2-klein-4B'".
  • Stock path unchanged: the stock 9B edit images are md5-identical between main and this PR at 1 and 2 references, in both renders.
  • Speedup inside Studio: the KV edit is 1.36x faster with 1 reference and 1.56x with 2.
  • CUDA graphs: the KV steps ran eager (16 eager calls, 0 captures, no fallback); the stock arm captured 2 graphs.
  • Guard engaged: it logged pricing ~2458 MiB for 1 reference and ~4915 MiB for 2.
  • Peak memory caveat: the KV arm ran first and kept the 11.1 GiB text encoder resident, while the stock arms streamed it. Without the encoder, the KV peak sits about 2.1 / 4.4 GiB above stock, in line with the priced cache.

Not covered

  • The gated bf16 KV repo was not loaded through Studio (this account has no grant); the GGUF route was.
  • No 16 GB card was run, so a guard refusal or stream on real hardware was not exercised. The decision is covered by the CPU tests only.
  • Per-block CUDA graphs still run the cached steps eager, since the layer cache keeps its tensors as 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.
  • The INT8 attention route and the fused ConvRot attention are untested with the KV processors. They either pass the KV arguments through or are not applied.
  • Follow-up: on a deferred-tier load, a learned peak for the reference workflow already contains the cache, and the guard then adds it again to the request extra. The effect is that more of the denoiser streams than needed, not a refusal. Not exercised here.

Screenshots

Images page workflow list, klein 9B KV vs stock klein 9B, before and after

Images page workflow list with a FLUX.2 klein 9B KV GGUF loaded (top) and the stock klein 9B GGUF loaded (bottom), merge base f63869b on 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's DiffusionBackend.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's is_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 reports supports_guidance: false for the stock 9B and for the KV checkpoint on both commits. Here the PR only keeps the guidance kwarg out of the Flux2KleinKVPipeline call.

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).
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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-22T07:48:28.181093Z 6e5eea6 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.

@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: 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"),),

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

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

Comment on lines +5728 to +5731
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
)

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

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: 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]
@danielhanchen
danielhanchen marked this pull request as ready for review November 22, 2026 04:59
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: a5aa54afd3

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

…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]
@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: 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"),),

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

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.

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]
@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: 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

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

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

danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 22, 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. More of your lovely PRs please.

Reviewed commit: 6e5eea6e4c

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

Copy link
Copy Markdown
Member Author

(Python 3.13, diffusion) fails on this PR only:

tests/test_diffusion_flux2_klein_kv.py::test_kv_checkpoint_refuses_a_stock_workflow_pipe[inpaint]
tests/test_diffusion_flux2_klein_kv.py::test_kv_checkpoint_refuses_a_stock_workflow_pipe[upscale]
E   ModuleNotFoundError: No module named 'diffusers'

That shard runs without diffusers installed, and the new parametrised test reaches a diffusers import for the inpaint and upscale workflows. A pytest.importorskip("diffusers") at the top of the test (or of the helper that builds the stock pipe) keeps it running in environments that have diffusers and skipping in this one, the same way the neighbouring diffusers-dependent tests do.

@danielhanchen
danielhanchen merged commit acb504c into main Nov 22, 2026
@danielhanchen
danielhanchen deleted the studio-klein-ref-kv branch November 22, 2026 12:35
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