Repository navigation
Studio sd.cpp: route all-Q8_0 image GGUFs to BF16 cuBLAS, keep k-quants on MMQ - #14983
Conversation
…and datacenter Blackwell Only Q8_0 diffusion GGUFs get GGML_CUDA_QUANT_CUBLAS_MIN_BATCH; k-quant and 4-bit GGUFs keep MMQ.
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7f14486a98
ℹ️ 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".
| if getattr(torch.version, "hip", None) or not torch.cuda.is_available(): | ||
| return [] | ||
| cards = [int(ordinal)] if ordinal is not None else list(range(torch.cuda.device_count())) | ||
| return [tuple(int(v) for v in torch.cuda.get_device_capability(i)) for i in cards] |
There was a problem hiding this comment.
Keep the CUDA capability probe bounded
When a CUDA driver call stalls, this helper performs is_available, device_count, and get_device_capability directly on the model-load thread, so the exception handler cannot prevent the load from hanging indefinitely. The existing torch_cuda_compute_capability immediately above deliberately runs the same class of calls in a daemon thread with TORCH_CC_TIMEOUT_S; the new multi-card probe needs equivalent timeout handling so an unavailable capability merely keeps MMQ.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in a953765. _torch_cuda_capabilities now runs the read in a daemon thread and joins with TORCH_CC_TIMEOUT_S, the same pattern as torch_cuda_compute_capability above it. A stalled is_available / device_count / get_device_capability returns an empty list, which quant_cublas_env treats as unknown, so the load keeps MMQ instead of hanging. test_the_capability_probe_is_bounded_when_the_driver_stalls blocks a fake torch.cuda.is_available and checks the probe returns [] within the timeout.
| device, offload = _placement(*_running()) | ||
| spawn_env = off_torch.child_env() if off_torch is not None else None | ||
| if device == "cuda" and off_torch is None: | ||
| spawn_env = {**(spawn_env or {}), **_sd_cpp_quant_cublas_env(gpu_ordinal, paths.get("diffusion_model"))} or None |
There was a problem hiding this comment.
Recompute the route after finalizing CUDA placement
When the initially resolved binary places the model on CPU but a deferred accelerator install or a server-to-one-shot fallback later changes device to CUDA, this block is skipped and spawn_env remains empty. The later placement recalculations at lines 3645, 3684, and 3780 do not revisit this decision, so that Q8_0 model keeps MMQ for both the resulting process and persisted child_env; calculate the environment again whenever final placement changes.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in a953765. The env is no longer decided right after the first _placement call. _sd_cpp_spawn_env is evaluated where the argv is handed to a binary: just before server.start (with the server's pinned flags) and again at commit (with committed_offload_flags), after the deferred install, the post-download re-resolve and the one-shot fallback have all had their chance to move device. The persisted child_env therefore matches the final placement. The GGUF tensor table is still read once per load (cached). test_the_cublas_route_follows_a_deferred_install_onto_cuda places a CUDA torch on the CPU bundle, lets the deferred upgrade land the CUDA build, and asserts both the started server and child_env get the Q8_0 threshold.
| if device == "cuda" and off_torch is None: | ||
| spawn_env = {**(spawn_env or {}), **_sd_cpp_quant_cublas_env(gpu_ordinal, paths.get("diffusion_model"))} or None |
There was a problem hiding this comment.
Fall back to all-card capabilities when the pin is unresolved
On a heterogeneous host with an explicit gpu_ordinal, this enables cuBLAS solely from the requested card even if the later --list-devices probe cannot resolve that ordinal. _offload_with_device_pin_impl then intentionally omits the backend pin and sd.cpp uses its default card; for example, selecting an sm80 card while an sm89 card is the default applies the sm80 threshold on hardware where this change intends to retain MMQ. Gate the setting on a successfully resolved pin, or conservatively evaluate every visible card when the pin cannot be guaranteed.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in a953765. The selected ordinal is only used when the argv actually carries its --backend pin (_offload_with_device_pin_impl added flags). When the pin cannot be resolved, sd.cpp picks its own default card, so the decision falls back to every visible card and quant_cublas_env only sets the variable if all of them map to the same threshold. Any sm89 / sm86 / sm87 card in the set keeps MMQ. test_an_unresolved_pin_judges_every_visible_card covers an sm89 card 0 plus an sm80 card 1 with gpu_ordinal=1: resolved pin gives 1024, unresolved pin gives no env.
…lacement and pin - Run the multi-card torch capability read in a daemon thread with TORCH_CC_TIMEOUT_S, like torch_cuda_compute_capability; a stalled driver keeps MMQ instead of hanging the load. - Compute the child env where the binary is handed its argv (server start and commit), so a deferred install or a one-shot fallback that moves placement onto CUDA is honoured. - Use the selected card only when the committed argv carries its --backend pin; otherwise every visible card must qualify, since sd.cpp then picks its own default. [skip ci]
|
@codex review |
…ess loads is Q8_0 (unslothai#15054) ## Summary Follow-up to unslothai#14983. Studio sets `GGML_CUDA_QUANT_CUBLAS_MIN_BATCH` for the sd.cpp child only when the model is all Q8_0, so large Q8_0 matmuls run as BF16 dequant + cuBLAS while k-quants stay on MMQ. The check read only the diffusion GGUF, but the variable is process-wide: - The pinned fork patch (`scripts/unsloth/ggml-patches/0001-ggml-cuda-h3-speed.patch`) reads it once per process and applies it to every quantized `src0` that has a BF16 converter. Q4_K, Q5_K and Q6_K all have one. - Nothing scopes it per tensor or per model. unslothai/stable-diffusion.cpp#39 adds a Q8_0-only default when the variable is unset, but a set value still applies to every quantized type. So a Q8_0 denoiser next to a k-quant text encoder (for example the default Qwen-Image-2.1 encoder) also moved the encoder's matmuls with 1024+ rows (4096 on sm120) off MMQ. That breaks the "k-quants stay on MMQ" rule and adds full-size BF16 dequant scratch for those weights. ## Change - `sd_cpp_args.model_files_quantized_weight_types(files)` unions the quantized tensor types of the diffusion model and every companion that sd.cpp loads: VAE, audio VAE, clip_l, clip_g, t5xxl, llm, llm_vision, qwen2vl. - Companions that are not GGUF (safetensors) load dense and add nothing. - An unreadable companion GGUF returns None, and unknown keeps MMQ, the same as an unreadable diffusion GGUF today. - The sd.cpp load path passes this union instead of the diffusion-only types. The existing `quant_cublas_env` gate is unchanged: the override is still set only when every quantized type is Q8_0, every card sd.cpp may pick agrees, and the user has not set the variable. ## Tests - `test_a_q8_0_diffusion_gguf_with_a_k_quant_companion_keeps_mmq` (backend load path) covers: - a Q8_0 diffusion GGUF with a Q4_K/Q6_K text encoder: no override - a Q8_0 TE with a Q5_K VAE: no override - an unreadable TE GGUF: no override - a Q8_0 TE with a dense GGUF VAE: override kept at 1024 - `test_gguf_quantized_weight_types_reads_the_tensor_table` now writes real Q8_0, Q4_K and F16 GGUFs and checks the union and the resulting env. On main, all five new cases fail: the k-quant TE cases get `{'GGML_CUDA_QUANT_CUBLAS_MIN_BATCH': '1024'}`, and the helper does not exist. With this change, `tests/test_sd_cpp_args.py` and `tests/test_sd_cpp_backend.py` pass (268 passed). ## Notes - This rule is conservative. A k-quant TE pinned to CPU with `--clip-on-cpu` never reaches ggml-cuda, but it still turns the route off. A narrower rule would need the final placement flags, which the fallback ladder can change after the env is chosen. - LoRA files (`--lora-model-dir`) and the upscaler are not inspected. Their behaviour is the same as before this change.
…F, not its companions (1.57x on A100) (unslothai#17098) ## Problem On CUDA, Studio sets `GGML_CUDA_QUANT_CUBLAS_MIN_BATCH` for the sd.cpp child when the model is Q8_0, so its large matmuls run as BF16 dequant + cuBLAS instead of int8 MMQ (unslothai#14983: faster on A100 / Hopper / datacenter Blackwell, and closer to the unquantized render). Since unslothai#15054 the check takes the union of the quantized types of the diffusion GGUF and every companion GGUF, so a Q8_0 DiT next to a k-quant encoder gets no env and the whole denoiser stays on MMQ. That pairing is common: the Qwen-Image families (text-to-image, edit, layered) load Qwen2.5-VL Q4_K_M as their encoder, `UNSLOTH_SD_CPP_TEXT_ENCODER_QUANT=q4_k_m` picks Qwen3-4B Q4_K_M, and a cache-only load falls back to an older cached Q4_K_M encoder. A100 40 GB, Studio's pinned prebuilt (`master-982-0518b34-uaba3a1c`, Linux CUDA 13 bundle), Z-Image Turbo Q8_0 DiT + Qwen3-4B Q4_K_M encoder, 1024 px, 8 steps, cfg 1, seed 42, Studio's native argv (`--diffusion-fa --diffusion-conv-direct`), one warm-up per arm then 3 interleaved reps. Each arm gets the env its own tree computes from the same GGUF files (`main`: none; this branch: `1024`): | | sampling s, median [min, max] | encoder s | VAE s | peak VRAM | |---|---|---|---|---| | `main` (MMQ) | 8.02 [8.01, 8.06] | 0.71-0.73 | 0.62 | 13148 MiB | | this branch (BF16 cuBLAS) | 5.10 [5.10, 5.30] | 0.71 | 0.62 | 13148 MiB | 1.57x faster sampling. Each arm renders the same pixels in every rep; the two arms differ, as expected when the denoiser changes matmul path. ## Why the companion rule can go unslothai#15054 added the union because the env is process-wide: with it set, an encoder's quantized matmuls with at least that many rows also take BF16 cuBLAS. In practice: - A text prompt is far below 1024 rows, so the encoder keeps MMQ. The encoder time above is unchanged (0.71 s both arms). On an earlier A100 run of the same Z-Image Q8_0 + Q4_K_M pair (fork master build), the env render was pixel-identical to the fork's Q8_0-only default from unslothai/stable-diffusion.cpp#39, which never moves a k-quant. So the encoder took the same path either way. - Where an encoder does reach the threshold (a large reference image through Qwen2.5-VL in an edit), those k-quant matmuls take BF16 cuBLAS. That was faster on these cards in unslothai#12527 (MiniMax-H3, k-quant DiT: 2.3x on A100 and B200) and closer to an F32 reference there. The cost is a BF16 copy of one weight at a time as scratch. ## Change - The load path now decides from `gguf_quantized_weight_types(files.diffusion_model)` instead of the union, and `model_files_quantized_weight_types` (its only caller) is removed. - Unchanged: - the per-GPU table: sm80 / sm90 / sm100 1024, sm120 4096, Ada / consumer Ampere / Orin / older MMQ; - every card sd.cpp may pick must agree; - a mixed, k-quant, 4-bit, unquantized or unreadable diffusion GGUF keeps MMQ; - a user-exported value always wins, `0` included. - Once the pin carries the fork's Q8_0-only default (unslothai/stable-diffusion.cpp#39, patch 0016), Studio can stop setting the env and leave a user value as the only override. The comment at `QUANT_CUBLAS_ENV` says so. ## Cells Each tree's own `sd_cpp_args` and load glue on real GGUFs (Z-Image Turbo Q8_0 / Q4_K_M DiT x Qwen3-4B Q4_K_M / Q8_0 / BF16 / safetensors encoder x sm75 / 80 / 86 / 89 / 90 / 100 / 120): 56 cells, 52 identical, 4 moved. The 4 moved cells are all Q8_0 DiT + Q4_K_M encoder on sm80 / sm90 / sm100 (none -> 1024) and sm120 (none -> 4096). L4 (sm89), consumer Ampere and T4 do not move. ## Tests `tests/test_sd_cpp_backend.py`: `test_a_q8_0_diffusion_gguf_with_a_k_quant_companion_keeps_mmq` becomes `test_a_q8_0_diffusion_gguf_takes_the_route_whatever_its_companions_hold`: a k-quant encoder, a Q8_0 encoder with a Q5_K VAE, an unreadable encoder, and a Qwen2.5-VL k-quant encoder with its projector all get `1024`, and only the diffusion GGUF is read. On `main` all 4 cases fail; the existing k-quant / mixed / unknown diffusion GGUF cases still keep MMQ. `tests/test_sd_cpp_args.py` checks the tensor-table reader and the route on real tiny GGUFs. `test_sd_cpp_args.py` + `test_sd_cpp_backend.py`: 291 passed. ## Not covered - MiniMax-H3 keeps its own setting (`h3_quant_cublas_env`, 1024 on every sm80+ card, every type). It was measured faster with the route on L4 too (unslothai#12527: 54.6 -> 44.3 s/step), so the image table is not applied to it. - Timed on A100 only. H100 / B200 / RTX PRO 6000 take the same env value they already got for an all-Q8_0 load (unslothai#14983), now also with a k-quant encoder. - The Qwen2.5-VL edit case (encoder rows above the threshold) was not timed here.
Problem
When an image GGUF runs on the stable-diffusion.cpp CUDA build (the native engine picked for the load or forced with
UNSLOTH_DIFFUSION_ENGINE=sd_cpp, and the families only sd.cpp can load, such as MOSS-Image GGUFs), every quantized DiT matmul runs on int8 MMQ, which also quantizes the activations to 8 bits. For a Q8_0 checkpoint that 8-bit activation step is the larger error. CUDA hosts otherwise use the diffusers path, which this PR does not touch. The pinned sd.cpp build already has the alternative (GGML_CUDA_QUANT_CUBLAS_MIN_BATCH: dequantize the weight to BF16, cuBLAS GEMM with FP32 accumulate), but Studio only turns it on for MiniMax-H3 video.Fix
A CUDA sd.cpp load of a Q8_0 diffusion GGUF now gets
GGML_CUDA_QUANT_CUBLAS_MIN_BATCHin its child env when every card it may run on is one where the route measured faster:10244096The env knob applies to every quantized type, so Studio reads the diffusion GGUF's tensor table (memory-mapped, no tensor data is read) and sets it only when every quantized tensor is Q8_0. K-quant and 4-bit GGUFs (Q4_K_M, Q5_K_M, Q6_K, Q4_0, ...), mixed files, safetensors and unreadable files keep MMQ. The capability comes from torch for the selected card (every visible card when unpinned; mixed cards that disagree get nothing). A user-exported value always wins, and nothing changes off CUDA. The same value reaches both the resident sd-server and the one-shot sd-cli (
child_env).The fork change
cuda-q8-bf16-cublasmakes the same Q8_0-only choice the build's default. Once the pin carries it, this env is redundant but harmless (same value, same types).Accuracy
Against an unquantized render of the same model (BF16 weights in the denoiser, same
sd-clibuild), B200, seeds 1-6 at 512 px plus seed 1 at 1024 px, LPIPS (AlexNet) mean over the 7 cells:Each arm renders identically run to run. Q4_K_M GGUFs stay on MMQ: routing them too was a coin flip against the same references (FLUX.2 klein 0.0736 -> 0.0738), because the 4-bit weights dominate both arms.
Speed
Clean VMs (Colab), published
master-982-0518b34-ud331c66bundle,sd-cli, Q8_0 DiT + Qwen3-4B Q8_0 encoder, seed 42, cfg 1, MMQ (env unset), MMQ again (A/A), andGGML_CUDA_QUANT_CUBLAS_MIN_BATCH=1024(the kernels this branch selects for Q8_0 by default). One VM per GPU, every arm on that VM, 4 rounds interleaved, first dropped, median sampling seconds [min, max]:On sm120 the default threshold is 4096 rows, so a 512 px image (1024 image tokens) stays on MMQ and only the 1024 px rows, where the route is even with MMQ, change path. Every arm rendered the same pixels in every round. L4 could not be allocated on Colab during this run; Ada keeps MMQ by rule, so this branch changes nothing there.
B200 (sm100, this host, exclusive card, resident
sd-server, Qwen3-4B BF16 encoder, 1024 px, this branch vs its base): Z-Image Turbo Q8_0 sampling 9.85 [7.85, 14.26] (MMQ), 8.16 [5.51, 9.79] (MMQ again), 5.03 [3.94, 8.61] (this branch), about 1.6x. The host's load average was 900-1200, so these spread 2-5x; the Colab table above is the clean measurement.Tests
tests/test_sd_cpp_args.py: the capability table, mixed-card disagreement, the user override, Q8_0-only gating (k-quant, mixed, 4-bit, unquantized and unknown files get nothing), and the tensor-table reader on real tiny GGUFs.tests/test_sd_cpp_backend.py: a CUDA server load of a Q8_0 GGUF gets the env (and records it inchild_envfor one-shot sd-cli), a k-quant / mixed / unknown GGUF does not and the check reads the diffusion model, not the encoder; Ada / unknown / CPU loads get nothing; a user value is left alone.pytest tests/test_sd_cpp_args.py tests/test_sd_cpp_backend.py tests/test_sd_cpp_engine.py tests/test_h3_native_server.py: 378 passed. On this host's GGUFs the reader returns{Q8_0}for the Z-Image Turbo and FLUX.2 klein Q8_0 files and{Q4_K, Q5_K, Q6_K}/{Q4_K, Q5_K}for their Q4_K_M files.Not covered
Q8_0 timing covers A100, H100, RTX PRO 6000 and B200; L4 could not be allocated (Ada keeps MMQ by rule). Consumer RTX 30 / 40 / 50 cards, Jetson, B300 and GB10 were not timed (the rule keeps MMQ on sm86 / sm87 / sm89). MiniMax-H3 keeps its own setting (
1024from sm80, every type). Windows CUDA uses the same env path but was not run.Related
Pairs with unslothai/stable-diffusion.cpp#39: the Studio side sets the env only for all-Q8_0 GGUFs on today's pin; once the pin carries the fork patch, that env is redundant but harmless.