Skip to content

Studio diffusion (Phase 2): memory planner, streamed offload, fp8 TE, speed layer, quality harness - #6675

Merged
oobabooga merged 20 commits into
image-generationfrom
diffusion-phase2-memory
Jun 30, 2026
Merged

oobabooga merged 20 commits into
image-generationfrom
diffusion-phase2-memory

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Phase 2 of porting the richer diffusion stack onto the image-generation backend, building on #6670 (Phase 1: device policy, fp16 guard, lock split, validate-before-evict). This adds the memory, speed, and accuracy machinery as small, independently tested, GPU-verified slices.

Everything here is opt-in: the defaults reproduce the prior behavior byte-for-byte, so this is a no-op on a roomy GPU and only changes anything when a knob is set. Stacked on #6670; once that lands I will rebase onto main and retarget the base.

What it does

  • Measured-budget memory planner (diffusion_memory.py). Snapshots free device memory and estimates the model's resident footprint, then picks a placement policy and VAE tiling/slicing, reporting the policy actually engaged so status never overstates it. memory_mode: auto (measured), fast (resident), balanced (stream the transformer, near-resident speed, moderate VRAM cut), low_vram (offload every component, lowest VRAM). The legacy cpu_offload flag still works.
  • Streamed block-level offload + functional VAE tiling. balanced drives diffusers apply_group_offloading (block_level, use_stream) to flow the transformer through the GPU a few blocks at a time while the text encoder / VAE stay resident; VAE tiling now targets pipe.vae (pipelines like Z-Image expose it there, not on the pipeline). Sequential offload, which is broken for GGUF transformers on diffusers 0.38, falls back to whole-module offload.
  • Opt-in fp8 text-encoder casting (diffusion_precision.py). text_encoder_fp8 casts the dense companion text encoder to fp8 (e4m3) storage with bf16 compute, norms and embeddings kept full precision. It is a memory-vs-quality tradeoff, not free, and is off by default.
  • Opt-in speed layer (diffusion_speed.py). speed_mode: default (channels_last VAE + regional torch.compile of the repeated denoiser block where eligible) and max (also TF32 + fused QKV). Regional compile is gated off for the GGUF transformer and for families flagged not compile-friendly (a new supports_torch_compile, off for Z-Image), so it activates automatically only once a non-GGUF bf16 transformer is loaded.
  • Image quality-vs-quant harness (scripts/diffusion_quality.py). The accuracy analogue of the KLD workflow: render a fixed prompt/seed grid with a reference quant, then with each candidate quant, and report mean PSNR + SSIM (pure numpy) and optional CLIP scores, plus size, latency, and VRAM, then recommend the smallest quant within a quality budget. --selftest validates the metrics on CPU.

Measured results (Z-Image-Turbo Q4_K_M, single B200)

All memory tiers are lossless except where noted (PSNR inf vs the resident image):

config offload gen peak VRAM median
auto (default) none 15951 MB 2.07 s
balanced group (streamed) 10840 MB (-32%) 2.99 s
balanced + fp8 TE group + fp8 6791 MB (-57%) ~3 s (fp8 shifts fine detail, ~20 dB PSNR)
low_vram model (offload all) 8318 MB (-48%) 7.99 s

The auto to auto regression compare passes at PSNR inf with 0% VRAM/latency delta, confirming the default path is unchanged. The quality harness degrades monotonically with quant size (Q8 to Q4 to Q2: PSNR 21.7 to 15.5, SSIM 0.82 to 0.61) while CLIP-text stays flat (~0.34), i.e. quantization erodes fine detail far more than prompt adherence.

Tests

CPU only, with torch and diffusers stubbed, run from studio/backend:

python -m pytest tests/test_diffusion_device.py tests/test_diffusion_memory.py \
  tests/test_diffusion_speed.py tests/test_diffusion_precision.py \
  tests/test_diffusion_backend.py tests/test_diffusion_routes.py tests/test_gpu_arbiter.py

127 tests pass (was 73), covering the planner matrix, the offload/VAE applier (including the group and sequential fallbacks), the speed gating, fp8 gating + casting, and the route wiring for the new knobs. python scripts/diffusion_quality.py --selftest validates the quality metrics with no GPU.

Out of scope (later phases)

GGUF-native text-encoder quantization (the fp8 path above covers the text-encoder memory axis for now), the safetensors diffusion path, a native stable-diffusion.cpp engine for CPU/Mac, and image-to-image / editing / LoRA / upscale / video.

danielhanchen and others added 8 commits June 25, 2026 11:14
…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.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a comprehensive memory-budget planning and optimization framework for the diffusion backend, including CPU offloading policies, VAE tiling/slicing, FP8 text encoder casting, and opt-in speed optimizations. It also adds a quality-vs-quantization evaluation harness (scripts/diffusion_quality.py) along with extensive unit tests. Feedback on the quality harness includes fixing a bug in _mean where math.inf is incorrectly filtered out (resulting in missing "inf" values for identical image comparisons), replacing a risky and/or ternary operator pattern with standard Python ternary syntax, and addressing invalid JSON serialization of math.inf.

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.

Comment on lines +258 to +260
) -> dict[str, Any]:
psnrs, ssims, clip_txt, clip_sim = [], [], [], []
for key, img in grid["images"].items():

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

In _mean, the list comprehension filters out non-finite values using math.isfinite(x). Since math.inf is not finite, any math.inf values (which occur in psnrs when comparing identical images, such as the reference quant against itself) are excluded. If the list only contains math.inf values, finite will be empty, and _mean will return None instead of math.inf. This causes the reference quant's PSNR to be printed as "-" instead of "inf" in the final table. Update _mean to explicitly handle and return math.inf if it is present in the input list.

    def _mean(xs: list[float]) -> Optional[float]:
        if any(x == math.inf for x in xs):
            return math.inf
        finite = [x for x in xs if math.isfinite(x)]
        return round(sum(finite) / len(finite), 4) if finite else None

def _sweep(args: argparse.Namespace) -> int:
from core.inference.diffusion import get_diffusion_backend

out_dir = Path(args.out_dir).resolve()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Using and/or as a ternary operator is a risky anti-pattern in Python. If the left-hand side of the or (in this case, ref_grid) evaluates to a falsy value (e.g., if it is empty or None), Python will fall back to executing the right-hand side (_render_grid), leading to redundant execution. Use the standard Python ternary operator instead.

Suggested change
out_dir = Path(args.out_dir).resolve()
grid = ref_grid if gguf == args.reference_quant else _render_grid(backend, args, gguf, out_dir)

Comment on lines +306 to +315
"quant": gguf,
"file_size_mib": grid["file_size_mib"],
"is_reference": gguf == args.reference_quant,
"median_latency_s": grid["median_latency_s"],
"peak_vram_mib": (grid["peak_vram_bytes"] or 0) // (1024 * 1024) or None,
**metrics,
}
)
print(f" {metrics}", flush = True)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

Serializing math.inf directly with json.dumps produces Infinity in the output, which is invalid according to the standard JSON specification (RFC 8259). This can cause parsing failures in other languages or strict JSON parsers (such as JavaScript's JSON.parse). It is safer to convert math.inf to a string representation (like "inf") or None (which serializes to null) before dumping to JSON.

def _write_outputs(args: argparse.Namespace, out_dir: Path, rows: list[dict]) -> None:
    sanitized_rows = [
        {k: ("inf" if v == math.inf else v) for k, v in r.items()}
        for r in rows
    ]
    (out_dir / "quality.json").write_text(json.dumps({
        "config": {
            "model": args.model, "reference_quant": args.reference_quant,
            "prompts": args.prompts, "seeds": args.seeds, "steps": args.steps,
            "width": args.width, "height": args.height, "guidance": args.guidance,
            "memory_mode": args.memory_mode, "clip": args.clip,
        },
        "rows": sanitized_rows,
    }, indent = 2))

@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: 817e14ad19

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +135 to +136
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True

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 Reset TF32 when leaving max speed

On CUDA after one load with speed_mode="max", these assignments stay process-global; a later load with speed_mode omitted/off returns early in apply_speed_optims and never restores them, so the supposedly bit-identical default path (and other torch users in the process) can keep running with TF32 matmuls. Please save/restore the previous flags or explicitly disable/reset them for non-max loads.

Useful? React with 👍 / 👎.

Comment on lines +399 to +400
if explicit_offload and policy == OFFLOAD_NONE and can_offload and not device_memory.is_unified:
policy = OFFLOAD_MODEL

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 Honor fast memory mode over legacy offload

When a caller sends memory_mode="fast" but also has the legacy cpu_offload=true flag set, this override still converts the resident OFFLOAD_NONE plan into model offload. The request model documents memory_mode as overriding cpu_offload, so an explicit fast load on a roomy GPU runs offloaded/slower instead of resident; only apply the legacy override when no memory_mode was provided.

Useful? React with 👍 / 👎.

Comment on lines +258 to +260
def _mean(xs: list[float]) -> Optional[float]:
finite = [x for x in xs if math.isfinite(x)]
return round(sum(finite) / len(finite), 4) if finite else None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep infinite PSNR in quality averages

When the quality harness compares the reference quant against itself, or any candidate that exactly matches the reference images, psnr() returns math.inf for every image; filtering to finite values makes the list empty and records mean_psnr as None. That hides the expected infinite reference score in the JSON/CSV/table and makes exact matches indistinguishable from missing comparisons, so preserve inf when all scores are infinite.

Useful? React with 👍 / 👎.

from diffusers.hooks import apply_group_offloading

onload = torch.device(device)
use_stream = onload.type == "cuda" # overlap H2D copies with compute on CUDA

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 Warm up or disable streaming with tiled VAE

For CUDA balanced/auto-offloaded loads, the planner enables VAE tiling whenever the policy is not none, and this line then enables group-offload streams. Diffusers documents this combination (use_stream=True with VAE tiling) as needing a dummy forward before inference to avoid device-mismatch errors; since the backend goes straight to generate(), the first generation in balanced mode can fail instead of falling back. Either run the warm-up after applying the plan or don't use streams when tiling is active.

Useful? React with 👍 / 👎.

# are being offloaded (the device is already tight) or the backend has no spare
# device pool (MPS/CPU). On a roomy discrete GPU it stays off so output is
# bit-identical to a plain resident run.
tile = policy != OFFLOAD_NONE or device_memory.backend in ("mps", "cpu")

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 Keep default CPU/MPS output untiled

With the default memory_mode="auto" on CPU or MPS, this enables VAE tiling/slicing even though no offload is engaged. Tiled VAE decode can change pixel values/tone compared with the prior full-image decode path, so Apple Silicon/CPU users no longer get the advertised byte-identical default behavior; only enable tiling for explicit low-memory modes or actual offload pressure.

Useful? React with 👍 / 👎.

encoder,
storage_dtype = torch.float8_e4m3fn,
compute_dtype = target.dtype,
skip_modules_pattern = DEFAULT_SKIP_MODULES_PATTERN,

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 Skip token embeddings during fp8 casting

When text_encoder_fp8=True, DEFAULT_SKIP_MODULES_PATTERN does not match common text-encoder token tables such as embed_tokens or shared, and diffusers layerwise casting applies to nn.Embedding modules. Those prompt-token embeddings are therefore stored in fp8 despite the feature being documented as keeping embeddings full precision, which can unnecessarily degrade prompt conditioning; add embedding names/classes to the skip set.

Useful? React with 👍 / 👎.

danielhanchen and others added 2 commits June 25, 2026 14:42
…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.

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

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

)
# The companion components (VAE + text encoders) load near their on-disk
# size; sum whatever the prefetch already placed in the base-repo cache.
companion = self._cache_bytes(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 Estimate companions from the selected base snapshot

When the HF cache already contains another revision/variant of the same base repo, _cache_bytes(base) totals every blob under models--.../blobs, including files that this pipeline will not load. That inflates companion_mib, so the default auto planner can choose group/model offload and enable VAE tiling even though the current VAE/text encoders fit resident, making a default load slower or non-identical purely because of unrelated cache contents. Estimate the selected snapshot/files or the loaded modules instead of the whole repo cache.

Useful? React with 👍 / 👎.

if name == "transformer":
continue
if isinstance(comp, torch.nn.Module):
comp.to(onload)

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 Clear group hooks before model-offload fallback

If moving one of the non-transformer components fails here after apply_group_offloading has already attached hooks to the transformer (for example an OOM while trying balanced mode on a tight GPU), _apply_group_offload returns False with those group hooks still installed. The caller then tries enable_model_cpu_offload(), but diffusers rejects model offload while group offload is active, so the intended fallback turns into a load failure instead of recovering; remove the group hooks before returning False or move companions before installing group offload.

Useful? React with 👍 / 👎.

model_dense_mib = None
if transformer_dense is not None:
model_dense_mib = transformer_dense + (companion_mib or 0)
runtime_headroom = estimate_image_runtime_mib(width = None, height = None, family = 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 Size the memory plan for allowed image requests

Here the load-time plan always reserves runtime headroom for the default 1024x1024, batch-1 render because width, height, and batch size are not provided. The API accepts much larger requests (for example 2048x2048 or multi-image batches), so a model can be marked resident with VAE tiling off at load time and then OOM on a larger generation that would have needed offload/tiling. Plan against the maximum/selected generation size or re-plan the memory savers per generation.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a comprehensive memory-budget policy, opt-in speed optimizations, and low-precision text-encoder quantization (FP8/NVFP4) to the local diffusion backend, along with a quality-vs-quantization evaluation harness (diffusion_quality.py) and extensive unit tests. The review feedback highlights three key improvement opportunities: correcting the mean calculation in the quality harness to properly handle infinite PSNR values for identical reference images, adding local path validation in the file size helper to prevent confusing Hugging Face Hub errors, and implementing a local directory size fallback in the memory planner when companion cache bytes return zero to ensure the balanced offload mode works correctly with local models.

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.

Comment on lines +270 to +272
def _mean(xs: list[float]) -> Optional[float]:
finite = [x for x in xs if math.isfinite(x)]
return round(sum(finite) / len(finite), 4) if finite else None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

When comparing identical images (such as the reference quant against itself), the PSNR is math.inf. Since math.isfinite(math.inf) is False, the entire list of PSNR values is filtered out, resulting in an empty list and returning None. This causes the reference row in the quality table to display - for PSNR instead of inf.

    def _mean(xs: list[float]) -> Optional[float]:
        if not xs:
            return None
        if any(math.isinf(x) for x in xs):
            return math.inf
        finite = [x for x in xs if math.isfinite(x)]
        return round(sum(finite) / len(finite), 4) if finite else None

Comment on lines +188 to +197
def _hf_file_size_mib(repo: str, filename: str) -> Optional[int]:
try:
from huggingface_hub import HfApi
info = HfApi().model_info(repo, files_metadata = True, token = os.environ.get("HF_TOKEN"))
for s in info.siblings:
if s.rfilename == filename and s.size:
return int(s.size // (1024 * 1024))
except Exception:
return None
return None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

If repo is a local path (e.g., in offline deployments or local directories), we should check if the path exists locally first and raise a clear FileNotFoundError if the file is missing, rather than falling back to Hugging Face Hub functions which would treat the local path as a repository ID and raise confusing validation or repository not found errors.

Suggested change
def _hf_file_size_mib(repo: str, filename: str) -> Optional[int]:
try:
from huggingface_hub import HfApi
info = HfApi().model_info(repo, files_metadata = True, token = os.environ.get("HF_TOKEN"))
for s in info.siblings:
if s.rfilename == filename and s.size:
return int(s.size // (1024 * 1024))
except Exception:
return None
return None
def _hf_file_size_mib(repo: str, filename: str) -> Optional[int]:
local_path = Path(repo).expanduser()
is_local = local_path.is_absolute() or repo.startswith(".") or repo.startswith("~")
if is_local:
if not local_path.exists():
raise FileNotFoundError(f"Local path '{repo}' does not exist.")
file_path = local_path / filename if local_path.is_dir() else local_path
if not file_path.exists():
raise FileNotFoundError(f"File '{filename}' not found in local path '{repo}'.")
return int(file_path.stat().st_size // (1024 * 1024))
try:
from huggingface_hub import HfApi
info = HfApi().model_info(repo, files_metadata = True, token = os.environ.get("HF_TOKEN"))
for s in info.siblings:
if s.rfilename == filename and s.size:
return int(s.size // (1024 * 1024))
except Exception:
return None
return None
References
  1. When loading files from a local directory path, check if the path is a local directory first and raise a clear FileNotFoundError if the file is missing, rather than falling back to Hugging Face Hub download functions (like hf_hub_download) which would treat the local path as a repository ID and raise confusing validation or repository not found errors.

Comment on lines +547 to +548
companion = self._cache_bytes(base)
companion_mib = int(companion // (1024 * 1024)) if companion else None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The _cache_bytes static method only checks the Hugging Face hub cache directory. If the model or companion components are loaded from a local path (e.g., in offline deployments or local directories), _cache_bytes returns 0. This causes the memory planner to assume the companion size is unknown (None), which prevents the auto memory mode from ever selecting OFFLOAD_GROUP (balanced offload) even if the local companion fits in VRAM, forcing it to fall back to OFFLOAD_MODEL (slow, whole-module offload). We should add a fallback to check the local directory size if _cache_bytes returns 0. To avoid redundant file traversals, we can check is_file() or is_dir() directly without a separate exists() check.

        companion = self._cache_bytes(base)
        if not companion:
            try:
                local_path = Path(base).expanduser()
                if local_path.is_file():
                    companion = local_path.stat().st_size
                elif local_path.is_dir():
                    companion = sum(f.stat().st_size for f in local_path.rglob("*") if f.is_file())
            except Exception:
                pass
        companion_mib = int(companion // (1024 * 1024)) if companion else None
References
  1. To improve efficiency, avoid redundant file traversals. If a function calculating a property (e.g., size) returns a zero/null value when no files are found, use its result to check for existence instead of calling a separate existence-checking function.

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

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +133 to +134
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True

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 Restore TF32 state after max speed mode

When a user loads once with speed_mode="max", these assignments change PyTorch's process-wide CUDA/CUDNN flags and nothing in unload() or a later speed_mode="off" load restores the previous values. If TF32 was disabled for bit-identical default renders or chat inference, all subsequent CUDA matmuls in this process may run with TF32, so the opt-in speed mode leaks into later runs and can change outputs outside the requested load.

Useful? React with 👍 / 👎.

Comment on lines +547 to +548
companion = self._cache_bytes(base)
companion_mib = int(companion // (1024 * 1024)) if companion else None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Avoid counting whole HF cache as companion weights

In environments where the base repo cache already contains files that this GGUF path does not load (especially base transformer shards, which _base_file_downloaded explicitly excludes), _cache_bytes(base) still sums the entire Hugging Face repo cache and treats it as VAE/text-encoder companion memory. That inflates model_dense_mib/group_floor and can make the default auto mode enable offload/tiling on a roomy GPU solely because unrelated cached blobs exist, changing the default path and performance.

Useful? React with 👍 / 👎.

Comment on lines +270 to +272
def _mean(xs: list[float]) -> Optional[float]:
finite = [x for x in xs if math.isfinite(x)]
return round(sum(finite) / len(finite), 4) if finite else None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve infinite PSNR for exact matches

When every rendered image is identical to the reference (the included reference row, or a lossless candidate), psnrs contains only math.inf, and filtering to finite values turns the mean into None. The quality JSON/CSV then records a perfect match as missing PSNR and the table prints -, which loses the accuracy signal this harness is meant to report for no-op or lossless comparisons.

Useful? React with 👍 / 👎.

Comment on lines +396 to +398
if explicit_offload and policy == OFFLOAD_NONE and can_offload and not device_memory.is_unified:
policy = OFFLOAD_MODEL
reasons.append("explicit cpu_offload overrides resident placement")

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 Honor legacy cpu_offload over auto/group

When cpu_offload=True is used without an explicit memory_mode, this guard only forces whole-module offload if auto planning chose none; on a tight GPU where auto selects group, the legacy request is ignored and the transformer is streamed while text encoder/VAE remain resident. That changes the old cpu_offload behavior from enable_model_cpu_offload() to a higher-VRAM group plan, which can still OOM for users who enabled the flag specifically to offload every component.

Useful? React with 👍 / 👎.

def _hf_file_size_mib(repo: str, filename: str) -> Optional[int]:
try:
from huggingface_hub import HfApi
info = HfApi().model_info(repo, files_metadata = True, token = os.environ.get("HF_TOKEN"))

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 Stat local quant files for size-based recommendations

The parser advertises --model as a repo id or local path, but this size helper only queries Hugging Face metadata. With a local model directory, the API call is caught and every file_size_mib becomes None; _recommend() then filters out all candidates because it requires a size, so local sweeps can never produce the intended smallest-quant recommendation even though the GGUF files are on disk.

Useful? React with 👍 / 👎.

return int(storage_mib * 2.8)
if "Q5" in q:
return int(storage_mib * 3.3)
if "Q4" in q or "IQ4" in q or "UD" in q:

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 Parse UD low-bit quants before the generic UD fallback

For Unsloth Dynamic filenames such as *-UD-IQ2_XXS.gguf or *-UD-Q3_K_XL.gguf, infer_gguf_quant_label() returns a label containing UD, and this branch classifies it as a 4-bit-ish model before the Q3/Q2 checks can run. That can halve the estimated resident transformer size for low-bit UD quants, causing auto/fast planning to keep too much resident or choose group offload when the model actually needs stronger offload, leading to avoidable OOMs.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces advanced memory management, low-precision text encoder quantization (FP8/NVFP4), and opt-in speed optimizations (such as regional compilation and TF32) to the diffusion backend, along with a new image quality-vs-quantization evaluation harness (diffusion_quality.py) and extensive unit tests. The review feedback highlights critical multi-GPU compatibility issues, specifically pointing out that exact string comparisons for the "cuda" device will fail when device indices are present (e.g., "cuda:0"), and that torch.cuda.get_device_properties is hardcoded to device 0. Additionally, a bug was identified in the quality harness where identical image comparisons (returning infinite PSNR) are incorrectly filtered out of the mean calculation, displaying as - instead of inf.

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.

Comment on lines +56 to +57
if getattr(target, "device", None) != "cuda":
return False

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

The check getattr(target, "device", None) != "cuda" will fail on multi-GPU systems where the device is specified with an index (e.g., "cuda:0" or "cuda:1"). This will incorrectly disable text-encoder quantization on those systems.

We should check if the device string starts with "cuda" instead of doing an exact equality check.

    device = getattr(target, "device", None)
    if not isinstance(device, str) or not device.startswith("cuda"):
        return False

Comment on lines +96 to +97
if getattr(target, "device", None) == "cuda":
applied["tf32"] = _enable_tf32(logger)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

The check getattr(target, "device", None) == "cuda" will fail on multi-GPU systems where the device is specified with an index (e.g., "cuda:0" or "cuda:1"). This will prevent TF32 from being enabled on those systems.

We should check if the device string starts with "cuda" instead of doing an exact equality check.

Suggested change
if getattr(target, "device", None) == "cuda":
applied["tf32"] = _enable_tf32(logger)
device = getattr(target, "device", None)
if isinstance(device, str) and device.startswith("cuda"):
applied["tf32"] = _enable_tf32(logger)

Comment on lines +270 to +272
def _mean(xs: list[float]) -> Optional[float]:
finite = [x for x in xs if math.isfinite(x)]
return round(sum(finite) / len(finite), 4) if finite else None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

In the _mean function, math.isfinite(x) is used to filter out non-finite values. However, if a candidate quant is identical to the reference, the PSNR calculation returns math.inf. Since math.inf is not finite, it gets filtered out. If all comparisons are identical (e.g., when comparing the reference quant against itself), finite becomes empty, and _mean returns None. This causes the quality table to print - instead of inf for the reference quant.

To fix this, we should explicitly check for math.inf in the input list and return math.inf if it is present.

def _mean(xs: list[float]) -> Optional[float]:
    if any(x == math.inf for x in xs):
        return math.inf
    finite = [x for x in xs if math.isfinite(x)]
    return round(sum(finite) / len(finite), 4) if finite else None

free, total = torch.cuda.mem_get_info()
kind = "discrete_vram"
try:
props = torch.cuda.get_device_properties(0)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

torch.cuda.get_device_properties(0) is hardcoded to query the properties of device 0. On multi-GPU systems where the active device is not device 0 (e.g., when running on cuda:1), this will query the wrong GPU's properties.

We should query the properties of the currently active CUDA device instead.

            device_idx = torch.cuda.current_device()
            props = torch.cuda.get_device_properties(device_idx)

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

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +133 to +134
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True

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 Restore TF32 after max speed loads

When a CUDA load uses speed_mode="max", these process-global PyTorch flags are set permanently, but neither unload() nor a later load with speed_mode="off" resets them. After one max-speed diffusion load, subsequent diffusion or chat matmuls in the same server process can keep using TF32 even though the current model reports the default/off speed mode, breaking the per-load opt-in and bit-identical default path.

Useful? React with 👍 / 👎.

Comment on lines +271 to +272
finite = [x for x in xs if math.isfinite(x)]
return round(sum(finite) / len(finite), 4) if finite else None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve infinite PSNR in sweep averages

For identical renders, psnr() returns math.inf, but this averaging helper drops all non-finite values and returns None when every comparison is identical. That makes the reference row and any lossless quant/offload comparison report mean_psnr: null instead of inf, corrupting the quality table/JSON for the exact regression case this harness is meant to verify.

Useful? React with 👍 / 👎.

Comment on lines +396 to +397
if explicit_offload and policy == OFFLOAD_NONE and can_offload and not device_memory.is_unified:
policy = OFFLOAD_MODEL

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 Honor legacy cpu_offload before auto group offload

When a caller sets legacy cpu_offload=True without an explicit memory_mode on a tight card where the companion components fit, auto planning chooses OFFLOAD_GROUP above and this guard does not fire because it only overrides OFFLOAD_NONE. That changes the existing cpu_offload=True behavior from whole-module offload to keeping the text encoder/VAE resident with streamed transformer offload, so users who requested CPU offload can still OOM on the resident companions or hit group-offload-specific incompatibilities.

Useful? React with 👍 / 👎.

"status": status,
"median_latency_s": round(latencies[len(latencies) // 2], 4) if latencies else None,
"peak_vram_bytes": _cuda("max_memory_allocated"),
"file_size_mib": _hf_file_size_mib(args.model, gguf),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P3 Badge Size local GGUFs for recommendations

When --model is a local path, which the parser and backend both allow, this Hugging Face-only size lookup returns None for every quant. _recommend() then filters out all candidates with file_size_mib is None, so local sweeps always say no candidate met the quality budget even when PSNR/SSIM pass; use the local GGUF's stat size before falling back to the Hub lookup.

Useful? React with 👍 / 👎.

)
# The companion components (VAE + text encoders) load near their on-disk
# size; sum whatever the prefetch already placed in the base-repo cache.
companion = self._cache_bytes(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 Count only loaded companion files in the memory plan

When the base repo cache already contains files this GGUF pipeline does not load, especially dense transformer/ shards from a previous diffusers run, this raw cache sum treats them as resident companion memory. Auto planning can then choose model offload/tiling even though only the VAE/text encoders are actually loaded, making the default path unexpectedly slower on machines where the model itself would fit.

Useful? React with 👍 / 👎.

- diffusion_memory: query torch.cuda.current_device() for the integrated/unified probe
  instead of hardcoding device 0 (wrong GPU / misclassification on multi-GPU).
- diffusion_memory: legacy cpu_offload=True (no explicit memory_mode) again forces
  whole-module offload over an auto group-offload choice on a tight card, so the flag
  keeps its historical meaning; an explicit memory_mode still wins.
- diffusion: companion-memory estimate counts only the base-repo files the GGUF pipeline
  loads (VAE + text encoders), excluding leftover dense transformer/ shards in the cache
  that would inflate it and push the auto plan toward needless offload/tiling.
- diffusion_quality: _mean preserves +inf so the reference / lossless PSNR prints inf
  not '-'; _hf_file_size_mib stats a local model path so local sweeps get recommendations.
- tests for the cpu_offload override + explicit-mode precedence.

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

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +589 to +593
companion = self._cache_bytes_loaded(base)
companion_mib = int(companion // (1024 * 1024)) if companion else None
model_dense_mib = None
if transformer_dense is not None:
model_dense_mib = transformer_dense + (companion_mib or 0)

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 Account for TE quantization in memory estimates

When a CUDA load uses text_encoder_quant="fp8" or "nvfp4", the encoders have already been cast before this plan is built, but these lines still size the companions from the dense cached base-repo files and add that to model_dense_mib/group_floor. On cards where the quantized encoders would fit but the dense estimate does not, auto/fast mode can choose model offload and VAE tiling unnecessarily, so the opt-in memory reduction does not produce the intended resident/group plan.

Useful? React with 👍 / 👎.

Comment on lines +128 to +130
self.device = "cuda" if torch.cuda.is_available() else "cpu"
self.model = CLIPModel.from_pretrained(model_id).to(self.device).eval()
self.proc = CLIPProcessor.from_pretrained(model_id)

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 Keep CLIP scoring off the measured GPU

With --clip, _Clip is constructed before the sweep and this selects CUDA whenever it is available, so the CLIP model remains in VRAM while each diffusion model loads. That reduces the free-memory snapshot used by the planner and makes reset_peak_memory_stats() start from CLIP's allocation, so peak_vram_bytes and even the chosen offload policy can change only because CLIP scoring was requested.

Useful? React with 👍 / 👎.

Comment on lines +286 to +287
if xs and any(x == math.inf for x in xs):
return math.inf

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 Don't let one exact image make mean PSNR infinite

When a sweep has multiple prompts/seeds and a candidate matches one reference image exactly but differs on the others, this any() returns math.inf for the whole mean. That candidate then trivially satisfies the PSNR threshold and can be recommended despite finite or low PSNR on the remaining images; preserve inf only when all comparisons are infinite.

Useful? React with 👍 / 👎.


def _write_outputs(args: argparse.Namespace, out_dir: Path, rows: list[dict]) -> None:
(out_dir / "quality.json").write_text(
json.dumps(

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 Emit valid JSON for infinite PSNR

The reference row always carries mean_psnr = math.inf; json.dumps writes that as bare Infinity by default, which is not valid JSON and is rejected by strict consumers such as JSON.parse. A normal sweep therefore creates a quality.json file that many tools cannot read unless infinities are sanitized or encoded explicitly.

Useful? React with 👍 / 👎.

Comment on lines +589 to +590
companion = self._cache_bytes_loaded(base)
companion_mib = int(companion // (1024 * 1024)) if companion else None

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Size local base-repo companions

When base_repo points at a local diffusers directory, this helper only looks for a Hugging Face cache entry and returns zero, so companion_mib becomes None and the planner ignores the local VAE/text-encoder weights. For local bases with multi-GB text encoders, auto/fast mode can incorrectly keep the pipeline resident and leave VAE tiling off, causing loads or the first generation to OOM even though the same remote base would have been offloaded.

Useful? React with 👍 / 👎.

Comment on lines +63 to +64
if mode == TE_QUANT_FP8:
return hasattr(torch, "float8_e4m3fn")

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 Gate fp8 casting by compute capability

On ROCm or NVIDIA GPUs below the documented fp8-capable range, PyTorch can still expose torch.float8_e4m3fn, so this check accepts text_encoder_quant="fp8" and attempts layerwise fp8 casting instead of treating it as unsupported. In those environments the load can leave the text encoder in an unsupported/partially cast state or fail later during generation; also check the actual CUDA vendor/capability before enabling this path.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

/gemini review

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

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

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +133 to +134
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True

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 Restore TF32 after max speed mode

When a CUDA load uses speed_mode="max", these assignments flip PyTorch's process-wide TF32 flags and nothing resets them on unload or on a later speed_mode="off"/"default" load (those paths return without touching the flags). In a long-lived Studio process this makes subsequent diffusion runs, and potentially the chat backend after GPU handoff, continue using TF32 even though the status reports no TF32 optimization and the default path is documented as bit-identical.

Useful? React with 👍 / 👎.

Comment on lines +583 to +585
transformer_dense = estimate_gguf_dense_mib(
file_size_mib(gguf_path), infer_gguf_quant_label(gguf_filename)
)

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 Scale GGUF estimates for fp32 loads

When the target dtype has been promoted to float32 (for example Z-Image on pre-Ampere CUDA, or CPU/MPS fallback), this still uses the bf16/fp16 expansion assumptions inside estimate_gguf_dense_mib. In those environments the auto planner can undercount the GGUF transformer's resident footprint by roughly 2x and choose offload_policy="none", causing an OOM instead of selecting CPU offload.

Useful? React with 👍 / 👎.

Comment on lines +590 to +593
companion_mib = int(companion // (1024 * 1024)) if companion else None
model_dense_mib = None
if transformer_dense is not None:
model_dense_mib = transformer_dense + (companion_mib or 0)

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 Treat missing companion size as unknown

If _cache_bytes_loaded(base) returns zero because the base repo was not present in the expected HF snapshot layout (for example after a failed metadata/prefetch path or a local/custom base), this adds 0 for the VAE/text encoders and lets auto planning decide that the model fits resident based only on the GGUF transformer. Those companion modules can be several GB, so the plan can report no offload and then OOM during placement; missing companion size should make the total estimate unknown or otherwise conservative.

Useful? React with 👍 / 👎.


def _write_outputs(args: argparse.Namespace, out_dir: Path, rows: list[dict]) -> None:
(out_dir / "quality.json").write_text(
json.dumps(

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 Sanitize infinite PSNR before writing JSON

A normal sweep always includes the reference quant, and comparing that grid against itself makes mean_psnr equal to math.inf; json.dumps serializes that as Infinity, which is not valid JSON for strict parsers even though the file is advertised as quality.json. Convert infinities to a string/null or write with strict JSON-compatible values before persisting the rows.

Useful? React with 👍 / 👎.

# are being offloaded (the device is already tight) or the backend has no spare
# device pool (MPS/CPU). On a roomy discrete GPU it stays off so output is
# bit-identical to a plain resident run.
tile = policy != OFFLOAD_NONE or device_memory.backend in ("mps", "cpu")

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 Enable VAE tiling for unified CUDA memory

On integrated CUDA devices that report memory_kind == "unified_memory", the planner deliberately disables CPU offload because it cannot free a separate VRAM pool, but this condition leaves VAE tiling off because the backend is still "cuda". Those systems are exactly where the decode-time spike can exhaust the shared pool, so unified CUDA should get the same tiling/slicing treatment as MPS/CPU.

Useful? React with 👍 / 👎.

Comment on lines +531 to +532
plan = self._plan_memory(
target, gguf_path, gguf_filename, base, fam, memory_mode, cpu_offload

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 Account for text-encoder quant in placement planning

When text_encoder_quant successfully casts the companion encoders to fp8/nvfp4, placement is still planned from the dense cached companion size because _plan_memory does not receive the applied quant mode. In auto mode this can choose whole-module offload even though the now-smaller text encoders would fit resident or under group offload, so the new quant option may not deliver its intended VRAM/performance tradeoff.

Useful? React with 👍 / 👎.

@oobabooga

Copy link
Copy Markdown
Member
  • Merged the image-generation base into the branch, resolving conflicts in the diffusion backend, load route, request/status models, and tests. The resolution keeps the base's unload-waits-on-the-generate-lock behavior and re-points the device monkeypatch in the tests at the surviving resolve_diffusion_device_target.
  • Recalibrated the GGUF transformer's resident-size estimate to the packed on-disk file size. diffusers 0.38 keeps the GGUF weights packed (uint8) resident and dequantizes per layer transiently, so a Q4 file sits resident at roughly its file size, not roughly 4x. The old dequant-multiplier estimate over-counted and over-offloaded. Measured on a real box: a 2463 MiB Q4 GGUF sits resident at about 2482 MiB.
  • Allowed the GGUF transformer to torch.compile under the opt-in speed layer. It compiles fullgraph-clean with zero graph breaks and benchmarked 1.35-1.44x faster (FLUX.1-schnell Q2_K 1603 to 1186 ms, Qwen-Image-2512 Q2_K 1984 to 1375 ms), so the earlier "GGUF never compiles" skip was wrong and is removed.
  • Dropped the cpu_offload request flag. It never shipped on main, and memory_mode=low_vram already forces whole-module offload. The engaged-offload status field stays and now derives from the chosen policy.
  • VAE: always enable lossless slicing, gate only the lossy spatial tiling. Slicing is a no-op at batch size 1 and never alters output, so there is no reason to gate it. Tiling is the lossy one and stays behind the offload/unified-memory gate.
  • Hardened the offload, fp8, and TF32 paths. Group offload now places the resident components first, so a failure leaves no half-attached hooks for the model-offload fallback. The fp8 text-encoder keeps its embedding table at full precision. The process-global TF32 flags are snapshotted and restored so a max-speed load does not leave them flipped for the next tenant, including when a load flips them and then fails before committing (with a regression test).
  • Removed unused memory-plan serialization and dead runtime-estimate scaling, and corrected the overstated normalize and cache-bytes docstrings. Also dropped the now-stale cpu_offload arg from the bench script.

@oobabooga
oobabooga merged commit 6ae6fb1 into image-generation Jun 30, 2026
44 of 45 checks passed
@oobabooga
oobabooga deleted the diffusion-phase2-memory branch June 30, 2026 22:31

@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: 54cb454e3b

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

)
hf_token: Optional[str] = Field(None, description = "HuggingFace token for gated repos")
cpu_offload: bool = Field(False, description = "Enable model CPU offload to fit low-VRAM cards")
memory_mode: Optional[Literal["auto", "fast", "balanced", "low_vram"]] = Field(

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 legacy cpu_offload requests

Fresh evidence in this revision is that the load schema no longer declares cpu_offload at all. Existing clients that still POST cpu_offload: true to /images/load now have that extra field ignored by Pydantic, so the backend receives memory_mode=None and may choose resident/group placement instead of the previous whole-model CPU offload; on low-VRAM cards where users relied on the old flag to fit, this silently regresses to OOM. Please keep a compatibility field that maps cpu_offload: true to memory_mode="low_vram" (or reject it explicitly).

Useful? React with 👍 / 👎.

model_dense_mib = None
if transformer_resident is not None:
model_dense_mib = transformer_resident + (companion_mib or 0)
runtime_headroom = estimate_image_runtime_mib(family = 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 Use variant id for runtime headroom

For current distilled variants such as Z-Image-Turbo and FLUX.1-schnell, detect_family() normalizes them to architecture names like z-image or flux.1, so this call never lets estimate_image_runtime_mib() see the turbo/schnell substrings it explicitly checks. On borderline GPUs the default plan over-reserves about 15% runtime headroom and can unnecessarily choose offload/VAE tiling for models that would fit resident, making the default path slower and potentially non-identical; pass the repo/base/filename variant string (or an explicit distilled flag) into the estimate.

Useful? React with 👍 / 👎.

oobabooga added a commit that referenced this pull request Jul 1, 2026
…GGUF compile) (#6690)

* Studio diffusion: cross-platform device policy, fp16 guard, lock split, 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.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio diffusion (Phase 2A): measured-budget memory planner + offload/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.

* Studio diffusion (Phase 2D): streamed block-level offload + functional 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.

* Studio diffusion (Phase 5): image quality-vs-quant accuracy harness

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.

* Studio diffusion (Phase 3): opt-in speed layer (channels_last / compile / 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.

* Studio diffusion (Phase 2B): opt-in fp8 text-encoder layerwise casting

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.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio diffusion (Phase 2C): NVFP4 text-encoder quant (+ generalise fp8 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.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio diffusion (Phase 4): native stable-diffusion.cpp engine for CPU/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.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio diffusion (Phase 6): img2img / inpaint / edit / LoRA / upscale 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.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio diffusion (Phase 7): accuracy-preserving speed pass

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.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio diffusion (Phase 7): max tier uses max-autotune-no-cudagraphs + 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).

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio diffusion (Phase 7): robust backend-flag snapshot/restore and restore on failed speeded load

- snapshot_backend_flags reads each flag defensively (getattr + hasattr), so a build/platform
  missing one (no cuda.matmul on CPU/MPS) still captures the rest instead of skipping the
  whole snapshot. restore_backend_flags restores each flag independently so one failure can't
  leave the others leaked process-wide.
- load_pipeline restores the flags (and clears the GPU cache) when the build fails after
  apply_speed_optims mutated the process-wide flags but before _state captured them for unload
  to restore -- otherwise a failed default/max load left cudnn.benchmark/TF32 on and
  contaminated later off generations.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio diffusion (Phase 4): enforce the sd-cli timeout while reading output

Iterating proc.stdout directly blocks until the stream closes, so a sd-cli that hangs
without producing output (or without closing stdout) would never reach proc.wait and the
wall-clock timeout was silently bypassed. Drain stdout on a daemon thread and wait on the
PROCESS, so the main thread always enforces the timeout and kills a hung process (which
closes the pipe and ends the reader). Add a test that times out even when stdout blocks,
and make the no-binary test hermetic so a host-installed sd-cli can't leak in.

* Studio diffusion (Phase 7) review fixes: offload fallback + bench scripts

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

* Studio diffusion (Phase 4) review fixes: sd.cpp installer + engine hardening

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

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio diffusion (Phase 4) review round 2: collect sd-cli batch outputs

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.

* Studio diffusion (Phase 6) review round 2: img2img source dims + upscale 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.)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: oobabooga <[email protected]>
oobabooga added a commit that referenced this pull request Jul 1, 2026
…/fp4 on a dense source) (#6694)

* Studio diffusion: cross-platform device policy, fp16 guard, lock split, 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.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio diffusion (Phase 2A): measured-budget memory planner + offload/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.

* Studio diffusion (Phase 2D): streamed block-level offload + functional 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.

* Studio diffusion (Phase 5): image quality-vs-quant accuracy harness

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.

* Studio diffusion (Phase 3): opt-in speed layer (channels_last / compile / 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.

* Studio diffusion (Phase 2B): opt-in fp8 text-encoder layerwise casting

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.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio diffusion (Phase 2C): NVFP4 text-encoder quant (+ generalise fp8 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.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio diffusion (Phase 4): native stable-diffusion.cpp engine for CPU/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.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio diffusion (Phase 6): img2img / inpaint / edit / LoRA / upscale 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.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio diffusion (Phase 7): accuracy-preserving speed pass

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.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio diffusion (Phase 7): max tier uses max-autotune-no-cudagraphs + 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).

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio diffusion (Phase 8): opt-in fast transformer (torchao int8/fp8/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.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio diffusion (Phase 8): consumer-GPU tuning - lock fp8 fast accumulate, 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.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio diffusion (Phase 8): add fp8 fast-accum overflow verification 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.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio diffusion (Phase 8): detect consumer vs data-center GPU for fp8 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).

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio diffusion (Phase 8): add NVFP4 probe documenting it is not yet a win on torch 2.9

scripts/nvfp4_probe.py measures NVFP4 via torchao on the real Z-Image transformer.
Finding (B200, 1024px/8 steps): NVFP4 is a torchao feature and DOES run with
use_triton_kernel=False (the default triton path needs the missing MSLK library), but
only at bf16-compile rate (0.667s vs fp8 0.592s) -- it dequantises FP4->bf16 rather than
using the FP4 tensor cores. The real FP4 speedup needs MSLK or torch>=2.11 + torchao's
CUTLASS FP4 GEMM. The smoke probe (default triton=True) already keeps NVFP4 out of auto
on this env, so auto correctly stays on fp8; NVFP4 activates automatically once fast.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio diffusion (Phase 8): prefer fp8 over nvfp4 in Blackwell auto ladder

Validated NVFP4 on torch 2.11 + torchao CUTLASS FP4 in an isolated env. The FP4
tensor-core GEMM is genuinely active there (a 16384^3 GEMM hits ~3826 TFLOPS,
2.52x bf16 and 1.37x fp8), but it only beats fp8 on very large GEMMs. At the
diffusion transformer's shapes (hidden ~3072, MLP ~12288, M~4096) NVFP4 is both
slower (0.81x fp8 end to end on Z-Image 1024px) and less accurate (LPIPS 0.166
vs fp8's 0.044). Reorder the Blackwell auto ladder to fp8 before nvfp4 so auto is
correct even on a future MSLK-equipped box; nvfp4 stays an explicit opt-in. Add
scripts/nvfp4_t211_probe.py (extension diagnostics + GEMM micro + end-to-end).

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio diffusion (Phase 8): tolerate missing torch.float8_e4m3fn in the mxfp8 config

Accessing torch.float8_e4m3fn raises AttributeError on a torch build without it (not just
TypeError on older torchao), which would break the mxfp8 config helper instead of falling
back to the default. Catch both so the fallback is robust.

quant_probe.py: same AttributeError fallback; run LPIPS on CPU so the scorer never holds
CUDA memory during the per-row VRAM probe; output dir relative to the script.

* Studio diffusion (Phase 7): robust backend-flag snapshot/restore and restore on failed speeded load

- snapshot_backend_flags reads each flag defensively (getattr + hasattr), so a build/platform
  missing one (no cuda.matmul on CPU/MPS) still captures the rest instead of skipping the
  whole snapshot. restore_backend_flags restores each flag independently so one failure can't
  leave the others leaked process-wide.
- load_pipeline restores the flags (and clears the GPU cache) when the build fails after
  apply_speed_optims mutated the process-wide flags but before _state captured them for unload
  to restore -- otherwise a failed default/max load left cudnn.benchmark/TF32 on and
  contaminated later off generations.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio diffusion (Phase 4): enforce the sd-cli timeout while reading output

Iterating proc.stdout directly blocks until the stream closes, so a sd-cli that hangs
without producing output (or without closing stdout) would never reach proc.wait and the
wall-clock timeout was silently bypassed. Drain stdout on a daemon thread and wait on the
PROCESS, so the main thread always enforces the timeout and kills a hung process (which
closes the pipe and ends the reader). Add a test that times out even when stdout blocks,
and make the no-binary test hermetic so a host-installed sd-cli can't leak in.

* Studio diffusion (Phase 7) review fixes: offload fallback + bench scripts

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

* Studio diffusion (Phase 8) review fixes: quant compile + nvfp4 path

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

* Studio diffusion (Phase 4) review fixes: sd.cpp installer + engine hardening

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

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio diffusion (Phase 4) review round 2: collect sd-cli batch outputs

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.

* Studio diffusion (Phase 6) review round 2: img2img source dims + upscale 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.)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: oobabooga <[email protected]>