Repository navigation
Studio diffusion (Phase 8): opt-in fast transformer (torchao int8/fp8/fp4 on a dense source) - #6694
Conversation
…t, validate-before-evict Phase 1 of porting the richer diffusion stack onto the image-generation backend. - Add a compartmentalized device/dtype policy module (diffusion_device.py) resolving CUDA/ROCm/XPU/MPS/CPU with capability flags. Keeps the NVIDIA capability-based bf16 choice; ROCm and XPU are isolated; MPS uses bf16 or fp32, never a silent fp16 that renders a black image. - Add a per-family fp16_incompatible flag (Z-Image) and promote a resolved float16 to float32 for those families so they do not produce black images. - Split the backend locks: a generation holds only _generate_lock, so status, unload, and a new load are never blocked by a long denoise. Add per-generation cancellation via callback_on_step_end so an eviction or a superseding load preempts a running generation; a replacement load waits for it to stop before allocating, so two pipelines never sit in VRAM at once. - Validate a load request before the GPU handoff so an unloadable pick never evicts a working chat model, and reject missing local paths up front. - Add CPU-only tests for the device policy, dtype guard, lock split and cancellation, and validate-before-evict, plus a GPU benchmark/regression script (scripts/diffusion_bench.py) measuring latency, peak VRAM, and PSNR against a saved reference.
…/VAE policy Add a lean, backend-agnostic memory policy that picks a CPU-offload policy and VAE tiling/slicing from measured free device memory vs the model's estimated resident footprint, then applies it to the built pipeline. auto stays resident when the model fits (byte-identical to the prior resident path), and falls to whole-module offload when tight; fast/balanced/low_vram are explicit overrides. Sequential submodule offload is unreliable for GGUF transformers on diffusers 0.38, so it falls back to whole-module offload and status reports the policy actually engaged. Verified on Z-Image-Turbo Q4_K_M (B200): auto reproduces the resident image with no VRAM/latency regression (PSNR inf); balanced/low_vram cut generation peak VRAM 47.9% (15951 -> 8318 MB) with byte-identical output, at the expected latency cost. 73 prior + 35 new CPU tests pass.
…l VAE tiling Add a streamed 'group' offload tier (diffusers apply_group_offloading, block_level, use_stream) that keeps the transformer flowing through the GPU a few blocks at a time while the text encoder / VAE stay resident, and fix VAE tiling to drive the VAE submodule (pipelines like Z-Image expose enable_tiling on pipe.vae, not the pipeline). apply_memory_plan now returns the (policy, tiling) actually engaged so status never overstates either, and group falls back to whole-module offload when the transformer can't be streamed. Measured on Z-Image (B200), all lossless (PSNR inf vs resident): balanced/group cuts generation peak VRAM 32% (15951 -> 10840 MB) at near-resident speed (2.07 -> 2.99s); low_vram/model cuts it 48% (-> 8318 MB) but is slower (7.99s). Mode names now match that tradeoff: balanced = stream the transformer, low_vram = offload every component. auto picks group when the companions fit resident, else model. 112 CPU tests pass.
Add scripts/diffusion_quality.py, the accuracy analogue of the KLD workflow: hold prompt + seed fixed, render a grid with a reference quant (default BF16), then render each candidate quant and measure drift from the reference. Records mean PSNR + SSIM (pure-numpy, no skimage/scipy) and optional CLIP text-alignment + image-similarity (transformers, --clip), plus file size, latency, and peak VRAM, then prints a quality-vs-cost table and recommends the smallest quant within a quality budget. --selftest validates the metrics on synthetic images with no GPU or model. Verified on Z-Image (B200): the table degrades monotonically with quant size (Q8 -> Q4 -> Q2: PSNR 21.7 -> 15.5, SSIM 0.82 -> 0.61), while CLIP-text stays flat (~0.34) -- quantization erodes fine detail far more than prompt adherence.
…le / TF32) Add a speed_mode knob (off by default, so the render path stays bit-identical): default applies channels_last VAE + regional torch.compile of the denoiser's repeated block where eligible; max also enables TF32 matmul and fused QKV. Regional compile is gated off for the GGUF transformer (dequantises per-op) and for families flagged not compile-friendly (a new supports_torch_compile flag, False for Z-Image), so it activates automatically only once a non-GGUF bf16 transformer is loaded. Speed optims run before placement/offload, per the diffusers composition order. status now reports speed_mode + the optims actually engaged. Verified on Z-Image (B200): default -> ['channels_last'], max -> ['channels_last', 'tf32'], compile correctly skipped for GGUF; generation works in every mode. 121 CPU tests pass.
Add a text_encoder_fp8 knob that casts the companion text encoder(s) to fp8 (e4m3) storage via diffusers apply_layerwise_casting, upcasting per layer to the bf16 compute dtype while normalisations and embeddings stay full precision. Applied before placement, gated to CUDA + bf16, best-effort (a failure leaves the encoder dense). status reports which encoders were cast. Verified on Z-Image (B200, balanced/group mode where the encoder stays resident): generation peak VRAM dropped 37% (10840 -> 6791 MB, below the lowest-VRAM offload) at near-resident speed. It is a memory-vs-quality tradeoff, not free -- ~20 dB PSNR vs the bf16 encoder, a larger shift than one transformer quant step -- so it is off by default and documented as such, with the Phase 5 harness to size the cost. 127 CPU tests pass.
…p8 knob) Generalise the text-encoder precision knob from a fp8 bool to text_encoder_quant (fp8 | nvfp4). nvfp4 quantises the companion text encoder to 4-bit via torchao NVFP4 weight-only (two-level microscaling) on Blackwell's FP4 tensor cores; fp8 stays the broader-hardware path (cc>=8.9). Both are gated, best-effort, and run before placement; status reports the mode actually engaged. This is the lean realisation of GGUF-native text-encoder quant: 4-bit on the encoder without the 3045-line port. Verified on Z-Image (B200, balanced/group where the encoder stays resident), vs the bf16 encoder: nvfp4 cut generation peak VRAM 48% (10840 -> 5593 MB, the lowest TE option, below whole-model offload) at near-fp8 quality (16.4 vs 17.1 dB PSNR), and both quants ran faster than bf16. A memory-vs-quality tradeoff (off by default); size it per model with the Phase 5 quality harness. diffusion_bench gains --text-encoder-quant. 129 CPU tests pass.
…U/Mac Adds the CPU / Apple-Silicon tier of the two-engine strategy, mirroring the chat backend's llama.cpp shell-out. Diffusers stays the default on CUDA / ROCm / XPU; this covers the hardware diffusers serves poorly, consuming the same split GGUF assets Studio already curates. - sd_cpp_args.py: pure sd-cli command builder. Maps the family to its text-encoder flag (Z-Image Qwen3 to --llm, Qwen-Image to --qwen2vl, FLUX.1 CLIP-L + T5), and the diffusers memory policy (none/group/model/sequential) to sd.cpp's offload flags (--offload-to-cpu / --clip-on-cpu / --vae-on-cpu / --vae-tiling / --diffusion-fa), so one user knob drives both engines. - sd_cpp_engine.py: SdCppEngine over a located sd-cli. find_sd_cpp_binary() with the same precedence as the llama finder (env override, then the Studio install root, then in-tree, then PATH), an is_available/version probe, and a one-shot subprocess generate that streams progress and returns the PNG. runtime_env() prepends the binary's directory to the platform library path so a prebuilt's bundled libstable-diffusion.so resolves. select_diffusion_engine() is the pure routing decision (GPU backends to diffusers, CPU/MPS to native when present). - install_sd_cpp_prebuilt.py: resolve + download the per-host prebuilt (macOS-arm64/Metal, Linux x86_64 CPU, Vulkan/ROCm/Windows variants) into the Studio install root. resolve_release_asset() is a pure, unit-tested host-to-asset matrix. - scripts/sd_cpp_smoke.py: end-to-end native generation harness. Tests (CPU-only, subprocess/filesystem stubbed): 49 new across args, engine, routing, runtime env, and the installer resolver. Full diffusion suite 166 passing. Verified on a B200 box: built sd-cli (CUDA) and the prebuilt (CPU) both generate Z-Image-Turbo Q4_K end to end through SdCppEngine: balanced (group offload, 5.0s gen), low_vram (full CPU offload + VAE tiling, 13.4s), and the dynamically-linked CPU prebuilt (50.4s on CPU), all producing coherent images.
… on the native engine
Builds on Phase 4's native stable-diffusion.cpp engine, extending it from
text-to-image to the wider feature surface, since sd.cpp supports all of these
through the binary already. Pure command-builder additions plus one engine
method, so the txt2img path is unchanged.
- sd_cpp_args.py: SdCppGenParams gains image-conditioning fields. init_img +
strength make a run img2img, adding mask makes it inpaint, ref_images drives
FLUX-Kontext / Qwen-Image-Edit style editing (repeated --ref-image), and
lora_dir + the <lora:name:weight> prompt syntax select LoRAs. New
SdCppUpscaleParams + build_sd_cpp_upscale_command for the ESRGAN upscale run
mode (input image + esrgan model, no prompt / text encoders).
- sd_cpp_engine.py: the subprocess runner is factored into a shared _run() so
generate() (now carrying the conditioning flags) and a new upscale() reuse
the same streaming / error / output-check path.
- scripts/sd_cpp_smoke.py: --task {txt2img,img2img,upscale} with --init-img /
--strength / --upscale-model / --upscale-repeats.
Tests: 10 new across the img2img / inpaint / edit / LoRA flag construction, the
upscale builder and its validation, and the engine's img2img + upscale paths.
Full diffusion suite 176 passing.
Verified on a B200 box through SdCppEngine: img2img (Z-Image-Turbo Q4_K, the
init image conditioned at strength 0.6, 4.8s) and ESRGAN upscale
(512x512 -> 2048x2048 via RealESRGAN_x4plus_anime_6B, 2.7s), both producing
coherent images. Video and the diffusers-path feature wiring are deferred.
Re-review of the diffusion stack (#6675/#6679/#6680) surfaced one real accuracy bug and a dead-on-arrival speed path; this fixes both and adds the lossless / near-lossless wins, all measured on a B200. Correctness: - TF32 global-state leak (fix). speed_mode=max flipped torch.backends.*.allow_tf32 process-wide and never restored them, so a later `off` load silently inherited TF32 and was no longer bit-identical. Added snapshot_backend_flags / restore_backend_flags (TF32 + cudnn.benchmark), captured before the speed layer runs and restored on unload. Verified: load max -> unload -> load off is now byte-identical (PSNR inf) to a fresh off. - sd-cli timeout could hang forever. _run() blocked in `for line in stdout` and only checked the timeout after EOF, so a child stuck in model load / GPU init with no output ignored the timeout. Drained stdout on a reader thread with a wall-clock deadline. Added a silent-hang regression test. Speed (diffusers path), near-lossless, opt-in tiers: - Regional torch.compile now runs on the GGUF transformer. The is_gguf gate (and Z-Image's supports_torch_compile=False) were stale: compile_repeated_blocks compiles and runs ~2.2x faster on the GGUF Z-Image transformer on torch 2.9.1 / diffusers 0.38 (the per-op dequant stays eager, the rest of the block compiles). Measured: off 1.80s -> default 0.82s/gen (+54.7%), PSNR 37.7 dB vs eager -- far above the Q4 quant noise floor (~21 dB), so it does not move output quality. Gate relaxed; default tier delivers it. - cudnn.benchmark added to the default tier (autotunes the fixed-shape VAE convs). - torch.inference_mode() around the pipeline call (lossless, strictly faster than the no_grad diffusers uses internally). Memory path: - VAE tiling (not bit-identical >1MP) restricted to the model/sequential/CPU tiers; the balanced (group) tier keeps exact slicing only, so it is now bit-identical to the resident image (verified PSNR inf) and slightly faster. - Group offload adds non_blocking + record_stream on the CUDA stream path to overlap each block's H2D copy with compute (lossless; gated on the installed diffusers signature so older versions still work). Native (sd.cpp) path: - native_speed_flags: a first-class speed knob (default -> --diffusion-fa, a near-lossless CUDA win that was previously only added on offload tiers; max also -> --diffusion-conv-direct). conv-direct stays opt-in: measured +45% on CUDA, so it is never auto-on. Engine generate() merges it, de-duped against offload flags. Default profile: a GGUF model with no explicit speed_mode now resolves to the `default` profile (resolve_speed_mode), since compile's perturbation sits below the quantisation noise floor and so does not reduce quality versus the dense reference; out of the box a GGUF Z-Image generation drops from 1.80s to 0.81s. Dense models stay `off` / bit-identical, and an explicit speed_mode -- including "off" -- is always honored, so the byte-identical path remains one flag away and is the regression reference. Tooling: scripts/compile_probe.py (eager vs compiled GGUF probe), scripts/ perf_verify.py (the B200 verification above), and diffusion_bench.py gains --speed-mode so the speed tiers are benchmarkable. Tests: 183 passing (was 166); new coverage for the backend-flag snapshot/restore, GGUF compile eligibility, the balanced tiling/slicing split, native_speed_flags + the engine de-dup, and the sd-cli silent-hang timeout.
…+ engine/lever benchmarks The opt-in `max` speed tier now compiles the repeated block with mode=max-autotune-no-cudagraphs (dynamic=False) instead of the default mode: Triton autotuning for GEMM/conv-heavier models, gated to the tier where a longer cold compile is acceptable. CUDA-graph modes (reduce-overhead / max-autotune) are deliberately avoided -- both crash on the regionally-compiled block (its static output buffer is overwritten across denoise steps), measured. Adds two reproducible benchmarks used to validate the optimization research: - scripts/compare_engines.py: PyTorch (diffusers GGUF) vs native sd.cpp head-to-head. - scripts/leverage_probe.py: coordinate_descent_tuning + FirstBlockCache probes. Measured on B200 (Z-Image Q4_K_M, 1024px, 8 steps): default compile 0.80s/gen; coordinate_descent_tuning 0.79s (within noise, already covered by max-autotune); FirstBlockCache does not run on Z-Image (diffusers 0.38 block-detection / Dynamo).
…/fp4 on a dense source) Add an opt-in transformer_quant mode that loads the dense bf16 transformer and torchao-quantises it onto the low-precision tensor cores, instead of the GGUF transformer (which dequantises to bf16 per matmul and so runs at bf16 rate). On a B200 (Z-Image-Turbo, 1024px/8 steps): auto picks fp8 at 0.614s vs GGUF+compile's 0.823s (1.34x), int8 0.626s (1.32x), both at lower LPIPS than GGUF's own 4-bit floor. GGUF+compile stays the low-memory default and the fallback. The mode is gated on CUDA + bf16 + resident VRAM headroom (the dense load peaks ~21GB vs GGUF's 13GB); any unsupported arch/scheme, OOM, or quant failure falls back to GGUF with a logged reason. auto picks the best scheme per GPU via a real quantise+matmul smoke probe (Blackwell nvfp4/fp8/mxfp8, Ada/Hopper fp8, Ampere int8); a min-features filter skips the tiny projections that crash int8's torch._int_mm. New module mirrors diffusion_precision.py; quant runs before compile before placement. 184 -> tests pass; new test_diffusion_transformer_quant.py plus backend/route coverage. scripts/diffusion_bench.py gains --transformer-quant; scripts/quant_probe.py is the standalone torchao lever probe.
There was a problem hiding this comment.
Code Review
This pull request introduces an opt-in fast transformer path that loads the dense bf16 transformer and quantizes it using torchao dynamic quantization (supporting int8, fp8, nvfp4, and mxfp8) as a high-performance alternative to GGUF dequantization. It includes backend integration, API routing, CLI benchmarking scripts, and comprehensive unit tests. The feedback recommends improving robustness by catching potential AttributeError exceptions when torch.float8_e4m3fn is unavailable in both the backend and benchmark scripts, and replacing a hardcoded absolute path in the benchmark script with a relative path to ensure portability.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| return MXDynamicActivationMXWeightConfig() | ||
| raise ValueError(f"unknown transformer quant scheme '{scheme}'") | ||
|
|
||
|
|
||
| def make_filter_fn(min_features: int): | ||
| """A torchao ``quantize_`` filter keeping only the FLOP-heavy linears: nn.Linear |
There was a problem hiding this comment.
If torch.float8_e4m3fn is not available (e.g., on older PyTorch versions or non-CUDA environments), accessing it will raise an AttributeError. Since only TypeError is caught here, this could cause the configuration helper to fail. Catching both TypeError and AttributeError ensures robust fallback behavior.
| return MXDynamicActivationMXWeightConfig() | |
| raise ValueError(f"unknown transformer quant scheme '{scheme}'") | |
| def make_filter_fn(min_features: int): | |
| """A torchao ``quantize_`` filter keeping only the FLOP-heavy linears: nn.Linear | |
| try: | |
| return MXDynamicActivationMXWeightConfig( | |
| activation_dtype = torch.float8_e4m3fn, weight_dtype = torch.float8_e4m3fn | |
| ) | |
| except (TypeError, AttributeError): | |
| return MXDynamicActivationMXWeightConfig() |
| from torchao.prototype.mx_formats import NVFP4DynamicActivationNVFP4WeightConfig | ||
| return NVFP4DynamicActivationNVFP4WeightConfig() | ||
| if name == "mxfp8": | ||
| from torchao.prototype.mx_formats import MXDynamicActivationMXWeightConfig | ||
| try: | ||
| import torch | ||
| return MXDynamicActivationMXWeightConfig( |
There was a problem hiding this comment.
If torch.float8_e4m3fn is not available, accessing it will raise an AttributeError. Catching both TypeError and AttributeError ensures robust fallback behavior.
| from torchao.prototype.mx_formats import NVFP4DynamicActivationNVFP4WeightConfig | |
| return NVFP4DynamicActivationNVFP4WeightConfig() | |
| if name == "mxfp8": | |
| from torchao.prototype.mx_formats import MXDynamicActivationMXWeightConfig | |
| try: | |
| import torch | |
| return MXDynamicActivationMXWeightConfig( | |
| try: | |
| import torch | |
| return MXDynamicActivationMXWeightConfig( | |
| activation_dtype=torch.float8_e4m3fn, weight_dtype=torch.float8_e4m3fn | |
| ) | |
| except (TypeError, AttributeError): | |
| return MXDynamicActivationMXWeightConfig() |
| GGUF = "z-image-turbo-Q4_K_M.gguf" | ||
| BASE = "Tongyi-MAI/Z-Image-Turbo" | ||
| PROMPT = "A cinematic photograph of a red fox in a snowy forest at dawn, highly detailed" | ||
| OUT = Path("/mnt/disks/unslothai/ubuntu/workspace_81/outputs/quant_research/probe_images") |
There was a problem hiding this comment.
The output path is currently hardcoded to an absolute path specific to a particular workspace/machine. Using a relative path makes the script portable and runnable across different environments.
| OUT = Path("/mnt/disks/unslothai/ubuntu/workspace_81/outputs/quant_research/probe_images") | |
| OUT = Path("outputs/quant_research/probe_images") |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 983f2c14a0
ℹ️ 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".
| transformer = transformer_cls.from_pretrained( | ||
| base, subfolder = "transformer", torch_dtype = dtype, token = hf_token | ||
| ) |
There was a problem hiding this comment.
Prefetch dense transformer files before finalizing
When transformer_quant is requested and the base transformer's safetensors are not already cached, this from_pretrained(..., subfolder="transformer") call performs the multi-GB dense transformer download inside load_pipeline while _lock is held. _run_load still builds its prefetch/expected-byte list via _base_file_downloaded, which excludes transformer/ files because the GGUF path supplies them, so the new fast path skips the cancellable prefetch and the progress total omits those bytes; an unload/eviction will block until this uncancellable download finishes instead of preempting it.
Useful? React with 👍 / 👎.
| plan = self._plan_memory( | ||
| target, gguf_path, gguf_filename, base, fam, memory_mode, cpu_offload | ||
| ) |
There was a problem hiding this comment.
Plan memory after companion weights are cached
Computing the memory plan here now depends on _cache_bytes(base) before from_pretrained(base, ...) has populated the VAE/text-encoder files. If the best-effort size estimate/prefetch skipped those files (for example an HfApi metadata failure, a direct load_pipeline call, or an otherwise uncached base), _plan_memory sees the companion footprint as zero and can choose OFFLOAD_NONE; the later pipeline load then moves the full companions resident and can OOM instead of selecting group/model offload. Before this change the plan ran after from_pretrained, so the companion cache size reflected what was actually loaded.
Useful? React with 👍 / 👎.
| in_features = getattr(module, "in_features", None) | ||
| out_features = getattr(module, "out_features", None) | ||
| if in_features is None or out_features is None: | ||
| return False | ||
| return in_features >= min_features and out_features >= min_features |
There was a problem hiding this comment.
Skip AdaLN modulation linears for int8 quant
This feature-only filter still quantizes large conditioning/modulation linears, e.g. FLUX's AdaLayerNormZero.linear modules are Linear(dim, 6*dim) but run on the per-sample timestep embedding with M=batch (often 1). On Ampere auto selects int8, and torchao's int8 dynamic path uses torch._int_mm with the same M>16 constraint noted in this patch, so those non-FLOP-heavy linears can crash the first denoise despite passing the smoke probe, which only tests an M=32 linear.
Useful? React with 👍 / 👎.
…ulate, prefer fp8 over mxfp8, reject 2:4 sparsity Consumer Blackwell halves tensor-core throughput on FP32 accumulate (fp8 419 vs 838 TFLOPS with FP16 accumulate; bf16 209), so: - fp8 config locks use_fast_accum=True (Float8MMConfig). torchao already defaults it on; pinning it guards consumer cards against a default change. On B200 it is identical speed and slightly better quality (LPIPS 0.050 vs 0.091). - the Blackwell auto ladder prefers fp8 over mxfp8 (measured faster + more accurate). 2:4 semi-structured sparsity evaluated and rejected (scripts/sparse_accum_probe.py): 2:4 magnitude-prune + fp8 gives LPIPS 0.858 (broken image) with no fine-tune, the cuSPARSELt kernel errors on torch 2.9, and it does not compose with torch.compile (our main ~2x). Documented as a dead end, not shipped.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: bdb8eb9185
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| pipe = None | ||
| transformer_quant_engaged = None | ||
| if ( | ||
| normalize_transformer_quant(transformer_quant) is not None |
There was a problem hiding this comment.
Preflight the requested quant scheme before dense loading
When a valid but unsupported option is requested (for example transformer_quant="fp8" on an Ampere GPU), this guard passes because it only checks that the flag is non-null, so _load_dense_quant_pipeline downloads/builds and moves the full dense transformer to CUDA before quantize_transformer discovers the scheme is unsupported and falls back to GGUF. That makes an expected cheap fallback path incur a multi-GB transfer/VRAM allocation and can OOM before falling back; select/probe the concrete scheme before loading the dense source.
Useful? React with 👍 / 👎.
| import lpips | ||
|
|
||
| if _LPIPS["fn"] is None: | ||
| _LPIPS["fn"] = lpips.LPIPS(net = "alex", verbose = False).cuda().eval() |
There was a problem hiding this comment.
Keep LPIPS off GPU during VRAM probes
After the first non-reference row, this cached LPIPS module remains resident on CUDA for every subsequent config; each later run() resets peak memory while that allocation is still live, so the reported load/gen VRAM includes the scorer and the extra allocation can also reduce available memory or cause OOM. The same cache pattern is in sparse_accum_probe.py; move LPIPS to CPU, free it after scoring, or compute perceptual metrics after all CUDA VRAM measurements.
Useful? React with 👍 / 👎.
| transformer = transformer_cls.from_pretrained( | ||
| base, subfolder = "transformer", torch_dtype = dtype, token = hf_token | ||
| ) |
There was a problem hiding this comment.
Exclude dense transformer blobs from companion sizing
After any dense-quant load reaches this transformer/ download, those safetensors live in the base repo cache; later _plan_memory treats _cache_bytes(base) as only VAE/text-encoder companions and then adds the GGUF transformer's dense estimate separately. That double-counts the cached dense transformer on subsequent loads, so a GPU that fits can be planned into offload or have the dense path skipped because the companion footprint appears too large.
Useful? React with 👍 / 👎.
…probe scripts/fp8_overflow_check.py hooks every quantised linear during a real Z-Image generation and reports max-abs + non-finite counts for use_fast_accum True vs False. Confirms fast accumulation is an accumulation-precision knob, not an overflow one: across 276 linears, including Z-Image's ~1.0e6 activation peaks (which overflow FP16), 0 non-finite elements and identical max-abs for both modes.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 244124d740
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| memory_mode = memory_mode, | ||
| speed_mode = speed_mode, | ||
| text_encoder_quant = text_encoder_quant, | ||
| transformer_quant = transformer_quant, |
There was a problem hiding this comment.
Don't prefetch GGUF before trying dense quant
When transformer_quant is set for a remote model whose GGUF is not already cached, the worker still runs the existing _prefetch_files(..., gguf_filename, ...) path before load_pipeline can attempt the dense transformer branch. That makes a successful dense-quant load wait for and store the multi-GB GGUF that it never uses; use this forwarded flag to defer the GGUF download until the fallback path is actually needed.
Useful? React with 👍 / 👎.
| torch.cuda.empty_cache() | ||
| torch.cuda.reset_peak_memory_stats() | ||
| pipe = _load_dense() if source == "dense" else _load_gguf() | ||
| load_peak = torch.cuda.max_memory_allocated() / 1e9 |
There was a problem hiding this comment.
Measure load peak after quantization finishes
For quantized configs, load_peak is captured immediately after _load_dense() / _load_gguf() and before _apply_quant() or _compile() run, so the reported loadVRAM omits the torchao quantization and compilation phases that are part of making those configs usable. This can understate the peak needed to load int8/fp8/nvfp4/mxfp8 runs and skew the probe's VRAM comparison; update the peak after quantization/compile setup, before resetting stats for generation.
Useful? React with 👍 / 👎.
| pipe = None | ||
| transformer_quant_engaged = None | ||
| if ( | ||
| normalize_transformer_quant(transformer_quant) is not None |
There was a problem hiding this comment.
Validate transformer_quant before unloading
For direct load_pipeline / begin_load callers that pass an unsupported transformer_quant string, this normalization raises only after the old pipeline has already been unloaded under the lock. The HTTP route's Pydantic schema catches this case, but backend callers can still turn a typo into an eviction of the currently working diffusion model; normalize the new option before _unload_locked() or include it in the cheap load validation.
Useful? React with 👍 / 👎.
…8 accumulate, with user override Consumer/workstation GPUs (GDDR) halve fp8 FP32-accumulate throughput, so they want fast (FP16) accumulate; data-center HBM parts (B200/H100/A100/L40) are not nerfed and prefer the higher-precision FP32 accumulate. Add _is_consumer_gpu() (token-exact match on the device name per NVIDIA's GPU list, so workstation A4000 != data-center A40; GeForce/TITAN and unknown default to consumer) and gate the fp8 use_fast_accum on it. Measured: fast accumulate is ~2x on consumer Blackwell and ~8% on B200 (0.608 vs 0.665s), no overflow, quality below the quant noise floor. So the default leans to accuracy on data-center; a new request field transformer_quant_fast_accum (null=auto, true/false=force) lets the operator override per load (scripts/diffusion_bench.py --fp8-fast-accum auto|on|off). 187 diffusion tests pass (+ consumer detection, _resolve_fast_accum, and the override threading).
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: daad898d05
ℹ️ 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".
| transformer = transformer_cls.from_pretrained( | ||
| base, subfolder = "transformer", torch_dtype = dtype, token = hf_token | ||
| ) |
There was a problem hiding this comment.
Prefetch dense transformer shards before finalizing
When transformer_quant is requested and the dense transformer is not already cached, this from_pretrained(base, subfolder="transformer") becomes the first download of the transformer shards because the existing prefetch list still filters out transformer/ files. Those multi-GB downloads are therefore missing from expected_bytes and bypass the cancellable hf_hub_download_with_xet_fallback path, so the UI can sit in finalizing while an unload/eviction cannot interrupt the transfer. Please include the base transformer/ files in the estimate/prefetch when the dense path may be used.
Useful? React with 👍 / 👎.
|
|
||
| BASE = "Tongyi-MAI/Z-Image-Turbo" | ||
| PROMPT = "A cinematic photograph of a red fox in a snowy forest at dawn, highly detailed" | ||
| OUT = Path("/mnt/disks/unslothai/ubuntu/workspace_81/outputs/quant_research/nvfp4_images") |
There was a problem hiding this comment.
Make probe output paths portable
When these new probe scripts are run outside the author's /mnt/disks/unslothai/ubuntu/workspace_81 machine, OUT.mkdir(...) will either fail or write artifacts into an unexpected host-global path; the other diffusion probe already uses a repo-relative outputs/... directory. Please make the NVFP4/sparse probe outputs repo-relative or configurable with an --out-dir so the experiments can be reproduced in other checkouts.
Useful? React with 👍 / 👎.
| return Float8DynamicActivationFloat8WeightConfig() | ||
| if scheme == TQ_NVFP4: | ||
| from torchao.prototype.mx_formats import NVFP4DynamicActivationNVFP4WeightConfig | ||
| return NVFP4DynamicActivationNVFP4WeightConfig() |
There was a problem hiding this comment.
Disable Triton for NVFP4 backend quant
For explicit transformer_quant="nvfp4" on Blackwell systems where torchao's CUTLASS FP4 extension is available but MSLK is not installed, constructing this config without arguments uses torchao's default use_triton_kernel=True; the PyTorch AO docs state that option requires MSLK, so _smoke_probe rejects NVFP4 and the request falls back to GGUF instead of using the CUTLASS path the probes benchmark with use_triton_kernel=False. Please pass use_triton_kernel=False here or otherwise select the CUTLASS path for the backend.
Useful? React with 👍 / 👎.
| pipe_kwargs["token"] = hf_token | ||
| pipe = pipeline_cls.from_pretrained(base, **pipe_kwargs) | ||
| pipe.to(device) | ||
| scheme = quantize_transformer(pipe, target, mode = mode, fast_accum = fast_accum, logger = logger) |
There was a problem hiding this comment.
Fall back when quantized transformer is not compiled
When transformer_quant is used with speed_mode="off" (or if compile_repeated_blocks later fails/skips), this method still returns the quantized transformer as successfully engaged; apply_speed_optims can then leave compiled false and the loader commits a dynamic torchao-quantized model running eager. The module notes this path is ~30x slower eager, so the opt-in "fast" mode can become slower than the GGUF fallback. Please force/verify compile for transformer quantization, or reject/fallback when compilation does not engage.
Useful? React with 👍 / 👎.
…ipts - diffusion_memory: when group offload is unavailable and the plan falls back to whole-module offload, enable VAE tiling (the group plan left it off, but the fallback is the low-VRAM path where the decode spike can OOM). Covers both the group and sequential fallback branches. - perf_verify: include the balanced-vs-off PSNR in the pass/fail condition, so a balanced bit-identity regression actually fails the check instead of exiting 0. - compare_engines: --vae/--llm default to None (were author-absolute /mnt paths), and the load-progress poll has a 30 min deadline instead of looping forever on a hang. - test for the group->model fallback enabling VAE tiling.
- diffusion: a torchao-quantized transformer is committed only compiled. A dense model resolves to speed_mode=off, which would run the quant eager (~30x slower than the GGUF it replaced), so when transformer_quant engaged and speed resolved to off, promote to default (regional compile); warn loudly if compile still does not engage. - diffusion_transformer_quant: build the nvfp4 config with use_triton_kernel=False so the CUTLASS FP4 path is used (torchao defaults to the Triton kernel, which needs MSLK); otherwise the smoke probe fails on CUTLASS-only Blackwell and silently drops to GGUF. - nvfp4_probe: repo-relative output dir + --out-dir (was an author-absolute /mnt path). - test asserts the eager-quant -> default-compile promotion.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8bdd307889
ℹ️ 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".
| return Float8DynamicActivationFloat8WeightConfig() | ||
| if name == "nvfp4": | ||
| from torchao.prototype.mx_formats import NVFP4DynamicActivationNVFP4WeightConfig | ||
| return NVFP4DynamicActivationNVFP4WeightConfig() |
There was a problem hiding this comment.
Use the CUTLASS NVFP4 config in the probe
When scripts/quant_probe.py is run with its default config list on a Blackwell host that has torchao's CUTLASS FP4 extension but not MSLK, this default NVFP4DynamicActivationNVFP4WeightConfig() selects torchao's Triton NVFP4 path and the nvfp4_c row can fail even though the backend and nvfp4_probe.py deliberately use use_triton_kernel=False for the supported CUTLASS path. That makes the main comparison probe report NVFP4 as unavailable/slower for the exact environment this change is trying to evaluate; please pass use_triton_kernel=False here as well.
Useful? React with 👍 / 👎.
…rdening - install_sd_cpp_prebuilt: download the release archive with urlopen + an explicit timeout + copyfileobj (urlretrieve has no timeout and hangs on a stalled socket); extract through a per-member containment check (Zip-Slip guard); expanduser the --install-dir so a tilde path is not taken literally; and on Windows CUDA also fetch the separately-published cudart runtime DLL archive so sd-cli.exe can start. - sd_cpp_engine: find_sd_cpp_binary honors UNSLOTH_STUDIO_HOME / STUDIO_HOME like the installer, so a custom-root install is discovered without UNSLOTH_SD_CPP_PATH; start sd-cli with the parent-death child_popen_kwargs so it is not orphaned on a backend crash; reap the SIGKILLed child (proc.wait) so a cancel/timeout does not leave a zombie. - tests: Zip-Slip rejection, normal extraction, studio-home discovery.
|
@codex review |
|
/gemini review |
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8bdd307889
ℹ️ 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".
| transformer = transformer_cls.from_pretrained( | ||
| base, subfolder = "transformer", torch_dtype = dtype, token = hf_token |
There was a problem hiding this comment.
Prefetch dense transformer before taking the load lock
When transformer_quant is requested on a cold HF cache, this dense from_pretrained(..., subfolder="transformer") can still download the multi-GB transformer because the existing prefetch/size path only counts base files accepted by _base_file_downloaded, which excludes transformer/ files for the GGUF path. Since _load_dense_quant_pipeline is called while load_pipeline holds self._lock, that download is no longer cancelable by unload()/eviction and progress has already moved to finalizing; include the dense transformer shards in the prefetch/estimate for this mode or perform this load outside the lock.
Useful? React with 👍 / 👎.
| normalize_transformer_quant(transformer_quant) is not None | ||
| and dense_transformer_supported(target) | ||
| and plan.offload_policy == OFFLOAD_NONE |
There was a problem hiding this comment.
Preflight the requested quant scheme before dense load
For an allowed but unsupported request such as transformer_quant="fp8" on an Ampere card, this gate only checks CUDA/bf16/resident fit, so _load_dense_quant_pipeline downloads and loads the full dense transformer onto the GPU before quantize_transformer discovers the scheme is unsupported and falls back to GGUF. That makes a simple fallback path spend minutes and potentially OOM/evict the current model unnecessarily; run the scheme selection/smoke probe before loading the dense transformer and skip directly to GGUF when it returns None.
Useful? React with 👍 / 👎.
|
|
||
| BASE = "Tongyi-MAI/Z-Image-Turbo" | ||
| PROMPT = "A cinematic photograph of a red fox in a snowy forest at dawn, highly detailed" | ||
| OUT = Path("/mnt/disks/unslothai/ubuntu/workspace_81/outputs/quant_research/nvfp4_t211_images") |
There was a problem hiding this comment.
Avoid user-specific output paths
On any machine that does not have this developer-specific /mnt/disks/unslothai/... tree writable, the NVFP4 probe fails at OUT.mkdir(...) before running diagnostics/e2e, so the checked-in experiment cannot be reproduced by other users. Default this to a repo-relative outputs/... path as in nvfp4_probe.py, or add an --out-dir override before creating the directory.
Useful? React with 👍 / 👎.
|
|
||
| BASE = "Tongyi-MAI/Z-Image-Turbo" | ||
| PROMPT = "A cinematic photograph of a red fox in a snowy forest at dawn, highly detailed" | ||
| OUT = Path("/mnt/disks/unslothai/ubuntu/workspace_81/outputs/quant_research/sparse_images") |
There was a problem hiding this comment.
Avoid user-specific output paths
This probe writes to an absolute /mnt/disks/unslothai/... location, so running it outside that workstation fails during OUT.mkdir(...) instead of producing the sparse/accumulation results. Use a repo-relative default or expose an --out-dir argument so the experiment remains runnable in other environments.
Useful? React with 👍 / 👎.
Codex review: when batch_count > 1, stable-diffusion.cpp's save_results() writes the numbered files <stem>_<idx><suffix> (base_0.png, base_1.png, ...) instead of the literal --output path. SdCppEngine.generate checked only the literal path, so a batch generation would exit 0 and then raise 'no image' (or return a stale file). generate now returns the literal path when present and otherwise falls back to the numbered siblings; single-image behavior is unchanged. Test: a fake sd-cli that writes img_0.png/img_1.png (not img.png) is collected without error.
…ale repeats Codex review on the native engine arg builder: - build_sd_cpp_command emitted --width/--height unconditionally, so an img2img/inpaint/edit run that left dims unset forced a 1024x1024 resize/crop of the input. width/height are now Optional (None = unset): an image-conditioned run (init_img or ref_images) with unset dims omits the flags so sd.cpp derives the size from the input image (set_width_and_height_if_unset); a plain txt2img run with unset dims keeps the prior 1024x1024 default; explicit dims are always honored. width/height are read only by the builder, so the type change is local. - build_sd_cpp_upscale_command used a truthiness guard (params.repeats and ...) that silently swallowed repeats=0 into sd-cli's default of one pass, turning an explicit no-op into a real upscale. It now rejects repeats < 1 with ValueError and emits the flag for any explicit value != 1. Tests: img2img unset dims omit width/height (init_img and ref_images), explicit dims emitted, txt2img keeps 1024; upscale rejects repeats=0 and omits the flag at the default. (Two pre-existing binary-discovery tests fail only because a real sd-cli is installed in this dev environment; unrelated to this change.)
…-phase4-native # Conflicts: # scripts/diffusion_bench.py # scripts/diffusion_quality.py # studio/backend/core/inference/diffusion.py # studio/backend/core/inference/diffusion_device.py # studio/backend/core/inference/diffusion_families.py # studio/backend/core/inference/diffusion_memory.py # studio/backend/core/inference/diffusion_precision.py # studio/backend/core/inference/diffusion_speed.py # studio/backend/models/inference.py # studio/backend/routes/inference.py # studio/backend/tests/test_diffusion_backend.py # studio/backend/tests/test_diffusion_device.py # studio/backend/tests/test_diffusion_memory.py # studio/backend/tests/test_diffusion_precision.py # studio/backend/tests/test_diffusion_speed.py
# Conflicts: # studio/backend/core/inference/sd_cpp_engine.py # studio/backend/tests/test_sd_cpp_engine.py
# Conflicts: # studio/backend/core/inference/diffusion_memory.py # studio/backend/core/inference/diffusion_speed.py
# Conflicts: # studio/backend/core/inference/diffusion.py
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 394f7985df
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| target, | ||
| mode = text_encoder_quant, | ||
| logger = logger, | ||
| speed_applied = apply_speed_optims( |
There was a problem hiding this comment.
Restore backend flags when load aborts
When a load runs with speed_mode default/max, this call can flip process-global CUDA flags (for example cudnn.benchmark, and TF32 for max), but the commit removed the surrounding try/finally that restored them if a later step failed before _state was committed. If quantize_text_encoders or apply_memory_plan/pipe.to raises (OOM is the likely case), there is no _LoadState for unload() to restore from, so later off diffusion loads or chat inference can inherit the mutated flags and lose the bit-identical/default behavior.
Useful? React with 👍 / 👎.
…ffusion-phase6-features
…diffusion-phase7-perf
…usion-phase8-quant
# Conflicts: # scripts/diffusion_bench.py # studio/backend/core/inference/diffusion.py # studio/backend/tests/test_diffusion_backend.py
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f43910a4a4
ℹ️ 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".
| target, | ||
| mode = text_encoder_quant, | ||
| logger = logger, | ||
| speed_applied = apply_speed_optims( |
There was a problem hiding this comment.
Restore backend flags on failed loads
For loads using default/max speed mode, including transformer_quant loads promoted to default, apply_speed_optims() can mutate process-wide torch backend flags such as cudnn.benchmark/TF32. If a later step raises before _state is assigned, for example an OOM in apply_memory_plan(), there is no committed _LoadState for unload() to restore from, so those flags leak into later off loads or chat inference. The previous guard restored flags on non-committed exits; please wrap speed/quant/placement/commit in a try/finally again.
Useful? React with 👍 / 👎.
| transformer = transformer_cls.from_pretrained( | ||
| base, subfolder = "transformer", torch_dtype = dtype, token = hf_token | ||
| ) |
There was a problem hiding this comment.
Prefetch dense transformer weights before finalization
When transformer_quant is requested on a cold cache, this dense from_pretrained(base, subfolder="transformer") call downloads the base repo's transformer weights, but the prefetch path still excludes transformer/ files because the GGUF path supplies them. That leaves a multi-GB download running under the load lock during finalizing after the old pipeline has been evicted; unload()/cancellation cannot preempt it because they wait on the same lock. Please prefetch the dense transformer files when this path may be attempted, or move this download out of the locked finalization section.
Useful? React with 👍 / 👎.
| speed_mode = effective_speed, | ||
| logger = logger, | ||
| ) | ||
| if transformer_quant_engaged is not None and not speed_applied.get("compiled"): |
There was a problem hiding this comment.
Fall back when transformer quant cannot compile
When transformer_quant engages but regional compile is unavailable or fails, this only logs and still commits the dense torchao pipeline. The code immediately above notes that eager dynamic quant is about 30x slower and loses to the GGUF fallback, so users on an older diffusers/torch build or a transformer without compile_repeated_blocks() can opt into the “fast” path and get a severe latency regression while status still reports a quantized transformer. Please fall back to GGUF instead of assigning _state when compiled is false.
Useful? React with 👍 / 👎.
| pipe = None | ||
| transformer_quant_engaged = None | ||
| if ( | ||
| normalize_transformer_quant(transformer_quant) is not None |
There was a problem hiding this comment.
Preflight scheme support before dense loading
This condition treats any non-null transformer_quant as eligible, so an explicit unsupported scheme (for example fp8 on Ampere or nvfp4 off Blackwell) still enters the dense loader and only discovers the scheme is unsupported after downloading/allocating the dense transformer and moving the pipeline to CUDA. In those environments the advertised GGUF fallback can become a long finalization/OOM after the old model was evicted; please run the existing scheme-selection smoke check before _load_dense_quant_pipeline().
Useful? React with 👍 / 👎.
| return False | ||
| return in_features >= min_features and out_features >= min_features | ||
|
|
||
| return filter_fn |
There was a problem hiding this comment.
Exclude batch-only modulation linears from int8 quant
Filtering only by in_features/out_features does not actually guarantee the activation row count is >16: Flux/Qwen-style AdaLN or timestep modulation linears can have very large feature dimensions but are called on a batch-shaped tensor, so with the default batch size 1 they still hit the torch._int_mm M<=16 case noted above. Because transformer_quant=auto selects int8 on Ampere and this backend exposes the option to all diffusion families, those models can load successfully and then crash during generation; use the fqn to skip modulation/timestep/norm projections instead of relying on feature size alone.
Useful? React with 👍 / 👎.
Summary
An opt-in fast transformer mode for the Studio diffusion backend: load the dense bf16 transformer and torchao-quantise it onto the low-precision tensor cores, instead of the GGUF transformer. Stacked on the Phase 7 perf pass (#6690).
The motivation, measured on a B200 (Z-Image-Turbo, 1024px / 8 steps, LPIPS vs the dense bf16 reference): GGUF stores the transformer 4-bit but dequantises to bf16 on every matmul, so it runs at bf16 tensor-core rate and never touches the int8 / fp8 / fp4 cores. It is a memory win that costs speed. Loading the dense bf16 transformer and quantising it dynamically with torchao runs the matmul on the actual low-precision cores:
Every working scheme beats GGUF on both speed and quality (LPIPS lands below GGUF's own 4-bit floor of 0.083). The only cost is memory: the dense bf16 transformer must be loaded (~2x the 4-bit GGUF), so the mode is strictly opt-in and gated on resident VRAM headroom. GGUF + compile stays the low-memory default and the fallback.
What it does
New flag
transformer_quanton the load request (auto | int8 | fp8 | nvfp4 | mxfp8, default off). When set and the device qualifies (CUDA + bf16 + the dense weights fit resident), the loader:base_repo(from_pretrained(subfolder="transformer")) instead of the GGUF,autopicks the best scheme for the GPU via a real quantise+matmul smoke probe (Blackwell fp8 -> nvfp4 -> mxfp8 -> int8; Ada/Hopper fp8 -> int8; Ampere int8). An explicit scheme is honored only if supported, never silently swapped. Any failure (unsupported arch/scheme, OOM, partial quant, or the dense weights not fitting resident) falls back to the GGUF build with a logged reason — the default path cannot regress.A
min_features=512filter skips the tiny timestep/pooled/modulation projections: the int8 path usestorch._int_mm, which requires activation rows M>16, and those projections run at M=1 and crash it (measured: 239/276 Z-Image linears quantised, full speedup, no crash).Design
core/inference/diffusion_transformer_quant.pymirrorsdiffusion_precision.py(the text-encoder quant module): pure functions, torch/torchao imported lazily, best-effort, hermetic CPU tests. It owns scheme selection + the arch/capability/smoke probe + thequantize_call.diffusion.pyload_pipelinegains the source-branch (dense+quant or GGUF), the VRAM preflight (reusesplan_diffusion_memory/estimate_gguf_dense_mib), and the fallback.transformer_quantthreads throughbegin_load/_LoadState/status()exactly liketext_encoder_quant.text_encoder_quant: request + status models inmodels/inference.py, forwarded inroutes/inference.py.Blackwell nvfp4/mxfp8 are wired but
autodeliberately lands on fp8. NVFP4 is a torchao feature (torch core only provides thefloat4_e2m1fn_x2primitive, not a quantization workflow). It was validated both on this box's torch 2.9 (no FP4 kernel: torchao prints "Skipping import of cpp extensions ... upgrade to torch >= 2.11", so it dequantises FP4->bf16 and runs at bf16-compile rate) and in an isolated torch 2.11.0 + torchao CUTLASS env where the FP4 GEMM is genuinely live -- a 16384^3 GEMM hits ~3826 TFLOPS (2.52x bf16, 1.37x fp8). The catch is shape: the DiT's linears (hidden ~3072, MLP12288, M4096) sit below the crossover where FP4 compute beats fp8, so end-to-end on Z-Image 1024px NVFP4 is slower (0.81x fp8) and less accurate (LPIPS 0.166 vs fp8's 0.044) even with the fast kernel. So the Blackwellautoladder puts fp8 ahead of nvfp4 (nvfp4 stays an explicit opt-in); the NVFP4 triton path also still requires MSLK (repo unavailable), while the CUTLASS path is the real one. Seescripts/nvfp4_probe.py(torch 2.9) andscripts/nvfp4_t211_probe.py(torch 2.11 micro + e2e).Measured through the backend (single B200, Z-Image-Turbo, 1024x1024, 8 steps, seed 12345)
End to end through
DiffusionBackendviascripts/diffusion_bench.py. LPIPS vs the dense bf16 reference is fromscripts/quant_probe.py(the standalone lever probe).transformer_quantautoint8mxfp8autoselects fp8 on this B200 (nvfp4 smoke-fails on torch 2.9 -> the ladder prefers the measured-faster fp8 over mxfp8). The speed-for-memory trade is explicit: the dense bf16 load peaks ~21 GB vs GGUF's 13.4 GB; resident generation VRAM is close (16.5 vs 15.3 GB). Every engaged scheme is faster than GGUF and lands below its 0.083 LPIPS floor.Tests
CPU-only, hermetic (torch / torchao stubbed via
sys.modules):tests/test_diffusion_transformer_quant.py— normalisation, the arch-selection ladder (Ampere int8 / Ada-Hopper fp8 / Blackwell fp8->nvfp4->mxfp8 fallback / pre-Ampere none / explicit-unsupported none), the smoke-probe cache + tolerance, the feature filter, and the apply path (callsquantize_with a filter_fn, sets the marker, tolerates failure).tests/test_diffusion_backend.py— default load skips the dense path; the dense path engages and reports the scheme; a quant failure falls back to GGUF; the path is skipped when the plan would offload.tests/test_diffusion_routes.py— the flag threads through tobegin_loadand an invalid enum is a 422.scripts/diffusion_bench.pygains--transformer-quant(through-the-backend benchmark + regression guard);scripts/quant_probe.pyis the standalone torchao lever probe (latency + PSNR + LPIPS + VRAM vs the dense reference, with the--min-featfilter).