Repository navigation
Studio FLUX.2-class VAEs: decode the whole map instead of colour-shifting tiles off the NVIDIA default path - #17966
Conversation
…pNorm stats Tiles cut from a large FLUX.2-class latent (FLUX.2, FLUX.3 Klein, Ideogram-4, MOSS-Image) take their own GroupNorm stats and shift colour: a 2048 px decode in diffusers' stock tiles is 25.6 dB from the untiled decode (46 dB from the photo). On NVIDIA with the fused VAE the strip decode already avoids it; speed mode off, ROCm, MPS, CPU, a failed fused install or low free memory still tiled. diffusion_vae_strips.full_map_decode runs the strip decode there too: the three Triton primitives fall back to torch ops, and the tiled path takes it whenever its peak fits the free memory (else the tiles, as before). UNSLOTH_FLUX_VAE_FULL_MAP=0 keeps the tiles. Other VAEs and untiled decodes are unchanged. The image-family coverage test now resolves every family (fixture fallback for modular / Studio-built pipelines that it skipped), and the seam guard workflow runs it and the new tests.
A card without room for the whole-map decode keeps the stock tiles (per-tile colour shift possible); one warning per VAE names the peak and the free memory, and one info line marks the whole-map decode. A test pins the fallback: free memory a hair under the peak decodes bit-identically to the kill-switch path.
…here no fused SDPA takes it On gfx1151 the whole-map decode peaked at 37.7 GB (the math SDPA over all 65536 latents at 2048 px) against a 3.7 GB estimate. It now runs under Studio's chunked VAE attention mode (exact, engages only on calls no fused kernel takes: ROCm, MPS), and the estimate counts that mode's score tile.
|
@codex review |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex Review: Didn't find any major issues. Delightful! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…ake-run floor red on main) (#17967) ## Summary `GRPO fake-run (CPU spoof, TRL floor)` is red on main (seen on the staging run of #17966): every test in `tests/version_compat/test_sft_assistant_only_loss_vision_routing.py`, added to that lane by #17942, fails on the floor pins (TRL 0.18.2, transformers 4.52.4, torch 2.6.0): ``` AttributeError: 'SFTConfig' object has no attribute 'assistant_only_loss' AttributeError: 'Qwen2VLProcessor' object has no attribute 'pad_token' ValueError: The checkpoint you are trying to load has model type `qwen3_vl` but Transformers does not recognize this architecture. AssertionError: assert [[151644, 894...]] == [[-100, -100, ...]] ``` TRL added `SFTConfig.assistant_only_loss` in 0.20. On TRL 0.18.2 the flag does not exist (`dataclasses.fields(trl.SFTConfig)` has only `completion_only_loss`), so a user cannot ask for assistant-only loss and #17942's routing has nothing to act on. The test still builds configs with the flag and expects masked labels, so every case fails on that lane. #17942's code is fine; the test assumed a TRL with the flag. Separately, Qwen3-VL does not exist in transformers 4.52, so that parameter cannot load there. ## Change Test only, `tests/version_compat/test_sft_assistant_only_loss_vision_routing.py`: - Skip the module, with the reason, when the installed TRL's `SFTConfig` has no `assistant_only_loss` field. - `_load` skips a model whose architecture the installed transformers does not know (it already skipped Hub fetch failures), instead of failing the parameter. ## Testing | lane | before | after | |---|---|---| | floor: TRL 0.18.2, transformers 4.52.4, torch 2.6.0 | 8 failed | 1 skipped (module, reason printed) | | TRL 1.15, transformers 5.17 | 8 passed | 8 passed |
…ameter name (#17972) ## Summary `tests/test_cp_ulysses_media_towers_gloo.py::test_gemma4_with_towers_matches_one_process` (from #17930) has failed in four of the last gloo shard runs on unrelated PRs (staging runs of #17957, #17960, #17831 and #17966), always as: ``` E AssertionError: model.language_model.layers.0.self_attn.q_proj.weight ``` and it passes locally every time (5 of 5 standalone, and 53 of 53 with all five `test_cp_*gloo*.py` files in one process, so it is not state left by an earlier test in the worker). The assertion passes `msg = name`, which replaces torch's whole mismatch report with the parameter name, so the CI logs do not say how many elements are off or by how much. Without that there is no way to tell a float32 reduction-order difference on the CI runners' CPUs (a tolerance question) from a real context parallel gradient bug. ## Change Test only. The gradient `assert_close` calls in `test_cp_ulysses_media_towers_gloo.py` and `test_cp_ulysses_generic_gloo.py` pass `msg` as a callable that prefixes the parameter name to torch's report instead of replacing it: ``` model.language_model.layers.0.self_attn.q_proj.weight: Tensor-likes are not close! Mismatched elements: ... Greatest absolute difference: ... (up to ... allowed) Greatest relative difference: ... (up to ... allowed) ``` Tolerances are unchanged. The next CI failure will carry the numbers needed to decide whether the tolerance or the code is wrong. ## Testing - Both files (2-rank gloo, CPU): 24 passed. - The message form checked directly against `torch.testing.assert_close` (output above).
…fusion red on main) (#17974) ## Summary `(Python 3.13, diffusion)` is red on main (seen on the staging runs of #17966 and #17971): ``` studio/backend/tests/test_diffusion_flux3_fp32_calibrated.py::test_only_the_load_plan_reads_the_scaled_table E assert 2 == 1 ``` The test pinned that the scaled (float32) activation row, `_calibrated_activation(..., fp32_scaled = True)`, is read in exactly one place in `DiffusionBackend`: the load plan. #17949 (FLUX.3 Klein on T4) added a second read in the generation guard: ```python guard_measured = placement_measured_activation(state.pipe) if guard_measured is None and getattr(state, "calibrated_placement", False): guard_measured = _calibrated_activation(fam, guard_target, fp32_scaled = True) ``` That read re-uses the same row the calibrated placement was sized from, so the guard and the plan agree. It is intended, and it keeps what the test protects (an uncalibrated or post-load reader never sees the scaled row). The string count was just too blunt. ## Change Test only, `test_only_the_load_plan_reads_the_scaled_table`, now walks the AST instead of counting a substring: - exactly two `fp32_scaled=True` reads in `DiffusionBackend`; - one is the load plan's `calibrated_activation=` argument (still pinned verbatim); - the other must sit under an `if` whose test checks `calibrated_placement`. ## Testing - `test_diffusion_flux3_fp32_calibrated.py`: 10 passed. On main the test fails as above. - Sabotage: dropping the `calibrated_placement` condition from the guard fails it; adding a third scaled read fails it.
…, when the strip kernels fail full_map_decode chose the Triton steps from _kernels_ok alone, so on a card or Triton build where the strip kernels raise, every tiled request paid a failed partial decode and then got the colour-shifting tiles. It now skips kernels the strip decode already marked failed, and on a non-OOM kernel failure marks them and reruns the whole map in torch ops. [skip ci]
…a peak figure [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
…3.3 (#18591) Triton 3.2 and 3.3 (the Triton of torch 2.6 and 2.7, and the newest torch on CUDA 11.8 wheels, all inside Studio's `torch>=2.4,<2.12` install range) resolve the names a `@triton.jit` kernel reads in the kernel's module globals only. Newer Triton also reads the function's closure. Most Studio kernels are built inside a lazy factory (`_kernels()`, `_kernel()`, ...) that imports `triton.language as tl` locally and often defines JIT helpers and constants next to the kernel, so on Triton 3.2 / 3.3 they fail to lower with `NameError('tl is not defined')` (or the same for a helper). Three factories (`diffusion_vae_fused`, `diffusion_int8_fused`, `video_minimax_h3_vae`) already worked around this with `globals().update(triton = triton, tl = tl)`; the other fourteen did not. Depending on the call site the result is a crash at the first launch, a silent fallback to a slower path (the frozen FP8 transpose), or a kernel probe that fails and keeps the stock path. Found in a recheck of #17966 (`_rows_residual` in the VAE strip decode, confirmed with an offline Triton 3.3.0 compile for sm75 and sm80: fails on main, compiles with the name in module globals, still compiles on 3.8.0). ## Change - New `core/inference/triton_closure_globals.py`: `publish(result)` finds every JIT kernel reachable from a factory's result (namespaces, containers, plain launcher closures, and the JIT helpers a kernel calls) and copies each kernel's closure names into its module globals with `setdefault`, so an existing module global is never overwritten. `publishes_closure_globals` is the decorator form. - The decorator sits under the existing `lru_cache` on the factories in `diffusion_convrot_quant`, `diffusion_flux2_rope`, `diffusion_flux3_qk_rope`, `diffusion_int8_fused`, `diffusion_int8_gemm`, `diffusion_int8_gemv`, `diffusion_moss_fused`, `diffusion_native_w8a8_rdna`, `diffusion_qwenimage21_eager`, `diffusion_rocm_fused`, `video_minimax_h3_qknorm`, `video_minimax_h3_rowmod` and `video_wan_fused`; `diffusion_frozen_fp8` publishes its transpose kernel when it builds it. `diffusion_vae_strips` binds `tl` like the fused VAE module (first commit). - No kernel source changes. On current Triton the published names are the same objects the closure already holds. ## Tests - New `tests/test_triton_closure_globals.py` (CPU, nothing compiles): for each of the 17 factories, every reachable JIT kernel must find every closure name in its module globals. 16 fail on main (for example `_f3_qk_norm_rope:tl`, `_qk_norm_rope_kernel:_rsqrt`, `i8mm_dq:_rbf16`, `transpose:tl`); `diffusion_vae_fused` passes on both. A second test checks that a kernel reached only through a plain launcher, and the JIT helper it calls, are published, and that an existing module global is left alone. - `tests/test_diffusion_vae_strips.py::test_kernel_names_resolve_from_module_globals`: fails on main, passes here. Base vs head over the changed test files: 16 fixed, 56 unchanged, 0 failing on this branch. ## Not proven here - No real launch on torch 2.6 / 2.7: only the offline Triton 3.3 compile of the VAE strip kernel and the module-globals check above. A T4 run on torch 2.7.1 is the follow-up. - Triton 3.4 to 3.6 were not checked for which release started reading closures.
…18999) ## Summary Follow-up to #18839 and #18863. On the sd.cpp (GGUF) route the offload policies (`model` / `sequential`) always pass `--vae-tiling`, and both the CPU VAE tile (#18839, from spare host RAM) and the GPU VAE tile (#18863, from free VRAM) stop at 1024 px. Any image larger than the tile is decoded in pieces, and each tile normalises its GroupNorm layers on its own statistics. There are no seams, but on FLUX.2 klein the tone and contrast follow the tile grid: 31.3 dB PSNR against the untiled decode at 1536 x 1536 and 25.9 dB at 2048 x 2048 (block-diff std 5.7 and 10.9 grey levels). This is the same per-tile statistics problem #17966 fixed on the diffusers path. The tiled decode is also slower than the whole one at every size we measured. This PR decodes the image in one tile whenever the RAM / VRAM budget holds a whole decode of the family's largest output. A tile at least as large as the image is a single tile: the same pixels as an untiled decode (bit-identical in every run below). ## Why a launch-time tile sd-server fixes `--vae-tile-size` at launch, while the image size comes with each request. The pinned build's `/sdcpp/v1/img_gen` body does accept `vae_tiling_params`, so a per-request tile is possible. That would need new plumbing on both the server path and the one-shot sd-cli path, plus a budget kept on the loaded state. Restarting the server per size costs a full model reload. A tile covering the family's largest output gives every request up to that size an untiled decode, and only the tile size changes. A smaller image still decodes in one tile sized to the image (sd.cpp clamps the tile to the latent), so its buffer is the same as before. ## What changes - `sd_cpp_args.WHOLE_VAE_DECODE_MIB`: the measured VAE compute buffer (ggml, MiB) of one whole 2048 px / 1536 px decode, per VAE: FLUX.2 (klein, dev) 17040 / 6336, FLUX.1 (Z-Image, FLUX.1, Kontext, Chroma) 17028 / 6336, Qwen-Image 2.1 15552 / 8748. The CPU decode allocates the same buffers (17028 and 15556 MiB measured at 2048 px on the CPU backend). The FLUX VAEs grow faster than the image area past 1536 px (2816 MiB per 1024 x 1024 of area up to 1536 px, 4260 at 2048 px), so nothing is extrapolated beyond 2048 px. - `gpu_vae_tile_size` / `cpu_vae_tile_size` take the family's `(tile, MiB)` pairs (`whole_vae_tiles(family)`) and try them before the existing ladder: the card gets the 2048 / 1536 px tile when the measured buffer + 15% fits beside the VAE weights (counted twice, as before). The card retries a failed allocation with halved tiles. The CPU VAE needs the measured buffer + 30% in spare host RAM, because the CPU path has no retry. - `sd_cpp_backend._offload_vae_flags`, `_cpu_vae_tile_size` and `_cpu_backend_offload` (the restart onto the CPU backend) pass the loaded family through. - Unmeasured families (Qwen-Image / Edit / Layered with the Wan-style VAE, SDXL, FLUX.3, Krea 2, MiniMax-H3 and its own tiler / overlap path) get exactly the old ladder. Below the 1536 px price every family gets exactly the old tile, so tight hosts and cards are unchanged. `UNSLOTH_SD_CPP_VAE_TILE` / `UNSLOTH_SD_CPP_VAE_GPU` still win. Video (`video.py`) does not use these functions and is unchanged. ## Results Same seed (42), prompt, steps and flags per (family, size), so every arm decodes the same latent. Each arm's flags come from that tree's own `sd_cpp_args` (`offload_flags`, the tile choosers, `gpu_te_fits`, `device_backend_flags`), fed the VM's real readings the way `sd_cpp_backend` reads them. Pinned prebuilt `master-982-0518b34-u27b9ddc`. PSNR is against an untiled decode from the same run. GPU VAE, Colab L4 (idle free 22564 MiB, so the limit after the 1536 MiB card reserve is 21028). Base picks 1024 px, head picks 2048 px for all three families: | family | size | base tiles | base PSNR dB | base decode s | head tiles | head PSNR | head decode s | head card peak MiB | |---|---|---|---|---|---|---|---|---| | FLUX.2 klein 4B | 1024 | 1 | identical | 1.17 | 1 | identical | 1.17 | 6270 | | FLUX.2 klein 4B | 1536 | 2x2 | 31.32 | 3.54 | 1 | identical | 2.32 | 7840 | | FLUX.2 klein 4B | 2048 | 3x3 | 25.93 | 7.66 | 1 | identical | 4.29 | 19442 | | Qwen-Image 2.1 | 1024 | 1 | identical | 2.69 | 1 | identical | 2.47 | 5206 | | Qwen-Image 2.1 | 1536 | 2x2 | 59.52 | 7.56 | 1 | identical | 4.74 | 10786 | | Qwen-Image 2.1 | 2048 | 3x3 | 58.50 | 16.11 | 1 | identical | 7.93 | 18600 | | Z-Image Turbo | 1024 | 1 | identical | 1.14 | 1 | identical | 1.15 | 7706 | | Z-Image Turbo | 1536 | 2x2 | 44.45 | 3.61 | 1 | identical | 2.32 | 7848 | | Z-Image Turbo | 2048 | 3x3 | 42.45 | 7.64 | 1 | identical | 4.23 | 19438 | A/A: two untiled klein 2048 decodes are bit-identical (4.17 / 4.19 s), and repeated head decodes are bit-identical at 4.29 / 4.30 s (klein), 7.93 / 7.93 s (Qwen) and 4.23 / 4.23 s (Z-Image). The largest whole decode peaks at 19442 MiB on the card. That is below the 21772 MiB of free VRAM the head needs before it picks the 2048 px tile (17040 x 1.15 + 2 x 320 VAE + 1536 reserve), and below the 22564 MiB the idle card has. CPU VAE (`--vae-on-cpu`, CPU build, 2 denoising steps; the 2048 px rows ran 1 step, head arm only, to record the whole-decode buffer and RSS). No Colab CPU High-RAM VM was free during this run, so the CPU arms ran with the CPU build on GPU VMs (the card unused): | family | size | host | base tiles | base PSNR dB | base decode s | head tiles | head PSNR | head decode s | head peak RSS MiB (weights) | |---|---|---|---|---|---|---|---|---|---| | FLUX.2 klein 4B | 1024 x 1024 | L4 host, 12 vCPU, 53 GB | 1 | identical | 52.1 | 1 | identical | 50.8 | 12063 (10481) | | FLUX.2 klein 4B | 1536 x 864 | L4 host, 12 vCPU, 53 GB | 2x1 | 32.75 | 83.5 | 1 | identical | 67.4 / 68.0 (A/A) | 12843 (10481) | | FLUX.2 klein 4B | 2048 x 2048, 1 step | L4 host, 12 vCPU, 53 GB | | | | 1 | | 328.8 | 26557 (10481) | | Z-Image Turbo | 1536 x 864 | G4 host, 48 vCPU, 185 GB | 2x1 | 47.25 | 17.0 | 1 | identical | 13.9 | 15257 (11668) | | Z-Image Turbo | 2048 x 2048, 1 step | G4 host, 48 vCPU, 185 GB | | | | 1 | | 81.2 | 28979 (11668) | | Qwen-Image 2.1 | 1536 x 864 | G4 host, 48 vCPU, 185 GB | 2x1 | 61.52 | 26.0 | 1 | identical | 19.5 | 14757 (9559) | | Qwen-Image 2.1 | 2048 x 2048, 1 step | G4 host, 48 vCPU, 185 GB | | | | 1 | | 63.6 | 25667 (9559) | The base picks 1024 px on both hosts. The head picks 2048 px because spare host RAM (36098 MiB on the L4 host) covers the priced whole decode (22152 MiB for klein, 17040 x 1.3). At 1536 x 864 the head is bit-identical to the untiled decode where the base is 32.8 dB (klein), 47.3 dB (Z-Image) and 61.5 dB (Qwen-Image 2.1), and its decode is 16 to 25% faster. The CPU backend allocates the same whole-decode buffer as CUDA (17040 / 17028 / 15556 MiB at 2048 px). Peak RSS above the weights at 2048 px is 16.1 GB (klein), 17.3 GB (Z-Image) and 16.1 GB (Qwen-Image 2.1), within the 22.2 / 22.1 / 20.2 GB the head prices. ## Tests - New `tests/test_sd_cpp_whole_vae_tile.py` (42 cases): the measured families and their prices, the GPU and CPU tile against the budget (an idle L4 gets 2048 for all three families), unchanged choices below the 1536 px price and for unmeasured families (MiniMax-H3 included), env switches, the restart onto the CPU backend, and a real `_run_load` where Z-Image gets the 2048 px CPU tile and SDXL keeps 1024. On main the file fails to import, and the behaviour cases fail: `_run_load` gives Z-Image `--vae-tile-size 1024`, and `_offload_vae_flags` has no family. - The 43 existing `tests/*sd_cpp*` files: 2009 passed, 5 skipped and the same 2 failed on both main and head (`test_sd_cpp_moss_image.py::test_diffusers_takes_a_moss_safetensors_single_file`, `test_sd_cpp_torch_vae.py::test_decode_matches_the_diffusers_pipeline_decode`, both outside this change). ## Not covered - Prices were measured on CUDA (L4) and on the x86 CPU backend. A Vulkan card (an off-torch AMD / Intel card on the offload path) was not run. Its decode still has sd.cpp's halving retry if the allocation fails. - The VAE encode of reference / edit images reuses the same tile and was not measured separately at 2048 px on the CPU path. - Windows and macOS were not run. The tile choice is OS-neutral Python, and Windows commit headroom still caps the CPU spare as before.
Summary
FLUX.2-class VAEs (FLUX.2 Klein / Dev, FLUX.3 Klein and Klein Base, Ideogram-4, MOSS-Image) decoded in tiles at 2048 come out with a strong per-tile colour shift: whole regions over-saturated (colour spread 27.7 vs 19.6) with block offsets up to +14 levels, blended over 256 px, so no straight seam but visibly wrong colour. Tiled vs untiled at 2048 on the cat and astronaut test photos: 25.7 / 28.2 dB on main (untiled decodes sit at 46 dB against the photo). It is diffusers' own tiling: each tile cut from a large latent normalises with its own GroupNorm statistics.
On NVIDIA at the default speed setting Studio already avoids it with its whole-map strip decode. Every other path still tiled: speed mode off, AMD, Mac, CPU, a failed fused-kernel install, and low free memory at decode time.
Change
diffusion_vae_strips.py: the whole-map strip decode (GroupNorm statistics over the full image) now runs on every device, with torch fallbacks for its three Triton steps; on ROCm and MPS its mid-block attention goes through Studio's chunked attention (a math SDPA over the 65,536 tokens of a 2048 px map would hold an 8 GiB score matrix per bf16 copy). If the Triton strip kernels raise on a card, the decode reruns in torch ops instead of falling back to tiles.diffusion_vae_tiling.py: a would-be-tiled FLUX.2-class decode takes the whole-map decode when its estimated peak fits 75% of free memory, else the stock tiles exactly as before; which path ran, and why, is logged once per VAE.UNSLOTH_FLUX_VAE_FULL_MAP=0restores the old tiles.Results
Tests
tests/test_diffusion_vae_full_map.py(12 tests): a tiled FLUX.2 decode matches the untiled decode (fails on main, where the stock tiles shift it); the torch group statistics match GroupNorm; a peak one MiB over the budget keeps main's tiles bit-identical and warns once; no room, an untiled decode, other VAEs and the kill switch keep main's behaviour; the mid-block attention is chunked where no fused kernel takes it; a failing kernel path still decodes the whole map in torch ops.tests/test_diffusion_vae_tiling_general.py: the family coverage rule now resolves all 21 image families; it had silently skipped five (flux.3-klein, flux.3-klein-base, anima, moss-image, minimax-h3-image).Seam recheck across families (no change needed)
No straight-line tile seam was found in any other shipped family on either engine at 12, 16 and 24 GB: Qwen-Image-2.1 (diffusers, and sd.cpp Turbo with
--vae-tiling), Krea-2, MiniMax-H3-Image (diffusers and sd.cpp), Wan2.2-5B, LTX-2 and the MiniMax-H3 video tiler.Not covered
Screenshots
FLUX.3 Klein latents at 2048 x 2048, decoded on CPU in fp32 with the real FLUX.2-class VAE: the untiled decode (reference), main's tiled decode, and this PR's whole-map decode. PSNR is against the untiled decode of the same latent, measured on the 8-bit PNGs.
A 512 x 512 crop at full resolution from the top of the cat image: main's tiles shift the background colour, the whole-map decode matches the untiled one.