Repository navigation
Studio diffusion: fold the VAE nearest 2x upsample and 3x3 conv into one transposed conv - #18792
Conversation
…ride-2 transposed conv on A100 / RTX PRO 6000 (FLUX.1 1024 px decode -11%)
…red 1.05-1.14x per decode on every tier)
|
@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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 831ec51bde
ℹ️ 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".
| acc += wf[:, :, i, j] | ||
| wt[:, :, a, b] = acc.t() | ||
| wt = wt.to(w.dtype).contiguous(memory_format = torch.channels_last) | ||
| _FOLD_CACHE[id(conv)] = (w, w._version, wt) |
There was a problem hiding this comment.
Release folded kernels when their convolution is destroyed
After a VAE has decoded on an enabled GPU, this process-global dictionary retains strong references to both its original weights and its folded GPU kernels indefinitely. Repository-wide search finds no production cleanup of _FOLD_CACHE, and DiffusionBackend._unload_locked() drops the pipeline without clearing it. Consequently, unloading or switching models cannot reclaim these allocations, and repeated loads can accumulate additional retained kernels. Tie the cache lifetime to the convolution, for example with weak keys or module-owned cache entries.
Useful? React with 👍 / 👎.
| if hit is not None and hit[0] is w and hit[1] == w._version: | ||
| return hit[2] |
There was a problem hiding this comment.
Invalidate the folded cache when weight storage changes
When a previously decoded VAE is temporarily upcast for the non-finite fp32 retry, diffusion_vae_upcast.upcast_keeping_storage() replaces each parameter's .data without changing its identity or version counter. This cache therefore returns the old fp16/bf16 kernel for the now-fp32 convolution; _fold_ok() still passes because it checks the input against the current parameter dtype, and conv_transpose2d then raises a dtype mismatch. The strip wrapper permanently disables itself on this error, while the whole-map route falls back to tiles. Include dtype, device, and storage identity in cache validation so the existing retry can continue using the correct strip decode.
Useful? React with 👍 / 👎.
…e and dies with the conv [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Can't wait for the next one! 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". |
…DMD diffusers skip, risky loader lint) (#18824) ## Summary Four checks are red on `main` itself, so every open PR currently inherits them in the Backend CI shards and the risky loader lint. Each was reproduced on a clean `main` checkout before fixing. | Failing check | Introduced by | Which side was wrong | Fix | |---|---|---|---| | `tests/test_diffusion_rocm_tag_detect.py::test_no_diffusion_or_video_gate_reads_version_hip_directly` | #18793 (`diffusion_regional_compile.py`) and #18792 (`diffusion_vae_strips.py`) | Code. Both new gates read `torch.version.hip` directly, which the ROCm tag guard exists to forbid (a CUDA wheel with a stray `hip` attribute, or a ROCm wheel reporting it differently, takes the wrong branch). | Route both through the shared `is_rocm_torch(torch)` helper from `rocm_bf16`. Behaviour on CUDA and ROCm is unchanged. | | `tests/test_h3_quantised_offload.py::test_a_streamed_torchao_render_runs_under_no_grad_and_the_rest_keep_inference_mode` | #18780 added `draft_ctx` to the denoise `with` | Test. The invariant (the denoise loop enters `grad_ctx` together with its progress context) still holds; the test pinned one exact spelling of the `with` line. | Parse the `with` statements and assert `grad_ctx` and `progress_ctx()` are entered together, regardless of what other contexts join them. Verified it still fails when `grad_ctx` is dropped from the statement. | | `tests/test_video_dmd.py::test_dmd_scheduler_reseeds_per_render`, `::test_renoise_stream_is_independent_of_the_initial_latent_noise` | #18779 | Test. `make_dmd_scheduler` builds on a diffusers scheduler, but these two tests only skipped on missing torch, so they error with `No module named 'diffusers'` in the shard that runs without diffusers. | `pytest.importorskip("diffusers")`, matching the existing scheduler test in the same file. | | `scripts/lint_risky_loaders.py` (`diffusion_ddp.py:440 [dynamic-import] __import__`) | #18771 | Code. The rank bootstrap imported two fixed modules through `__import__` in a loop. | Import `utils.native_tls` and `utils.happy_eyeballs` by name, each in its own `try`, so a failure in one still does not stop the rank or skip the other. No baseline entry needed. | ## Testing - `tests/test_diffusion_rocm_tag_detect.py`, `tests/test_h3_quantised_offload.py`, `tests/test_video_dmd.py`, `tests/test_diffusion_ddp.py`, `tests/test_diffusion_training.py`, the native TLS and happy eyeballs suites, and the regional compile and VAE strip suites: all pass. - `tests/test_video_dmd.py` with diffusers blocked from import: 26 passed, 7 skipped (previously 2 errors). - `python scripts/lint_risky_loaders.py`: all call sites recorded. - Sabotage: restoring either original `torch.version.hip` read makes the ROCm tag guard fail; restoring the `__import__` loop makes the risky loader lint fail.
…ding, not bitwise (#18840) ## Summary `(Python 3.13, diffusion)` fails intermittently across unrelated PRs (#18837, and the `studio-klein-ref-kv` branch): ``` tests/test_diffusion_vae_upsample_fold.py::test_strip_fold_matches_the_whole_map[5] tests/test_diffusion_vae_upsample_fold.py::test_strip_fold_matches_the_whole_map[13] E assert False E + where False = torch.equal(whole, strips) ``` The test, added by #18792, runs the folded transposed conv once over the whole map and once strip by strip with the one-row halo, then asserts the two are bitwise equal. The fold is correct (the same test passes here, and its second assert still checks both against the unfused nearest 2x + conv chain to 1e-6). Bitwise equality is just not something the CPU conv backend promises: a strip-sized input can be blocked differently from the whole map, so the taps are summed in another order. Which kernel gets picked depends on the runner's CPU, which is why it only fails on some runs and only for the multi-strip heights (5 and 13; 1 and 2 are a single strip). ## Fix Compare `whole` and `strips` to `1e-10` instead of bitwise. The data is fp64, so reordering costs about `1e-16`, while a seam or halo bug is off by O(1). ## Testing - `studio/backend/tests/test_diffusion_vae_upsample_fold.py`: 11 passed. - Sabotage: dropping the halo row in `_fold_upsample` (`lo = a` instead of `max(0, a - 1)`) still fails `test_strip_fold_matches_the_whole_map[5]` and `[13]`.
Follow-up to #18792. The VAE upsample fold, one stride-2 transposed conv in place of nearest 2x plus conv3x3, turns on by default only on the measured CUDA cards. On ROCm it stayed off because MIOpen's transposed conv had not been measured. This turns it on by default on gfx1151 (Radeon 8060S), the AMD arch it was measured on. ## Change `_fold_on` also arms on ROCm when the device's `gcnArchName` is in `_FOLD_ROCM_ARCHS` (gfx1151). Other ROCm archs, MPS and CPU keep the 2x path. `UNSLOTH_VAE_UPSAMPLE_FOLD=0` still turns it off, and `=1` still forces it anywhere. On ROCm the fold can only engage in `full_map_decode`, the whole-map strip decode the tile planner uses when the stock decode would not fit. The per-module strip install is refused on ROCm, so this change does not touch any other decode. ## Measured on gfx1151 FLUX.2 VAE whole-map decode, fold off vs on (12 fold calls per decode), fresh process per arm, order off-on-on-off, median of 3 after a warm-up: | OS | size | fold off s | fold on s | speedup | LPIPS fold vs off | peak GiB | |---|---|---|---|---|---|---| | Linux, torch 2.11.0+rocm7.13.0 | 1024 | 2.73 / 2.69 | 2.55 / 2.57 | 1.06x | 3.1e-5 | 1.55 -> 3.10 | | Linux | 2048 | 12.12 / 12.44 | 11.49 / 11.34 | 1.08x | 3.3e-5 | 3.67 -> 3.68 | | Windows, torch 2.11.0+rocm7.14.0 | 1024 | 2.86 / 2.87 | 2.73 / 2.69 | 1.06x | 3.1e-5 | 1.55 -> 3.10 | | Windows | 2048 | 12.67 / 12.80 | 11.83 / 11.81 | 1.08x | 3.2e-5 | 3.67 -> 3.68 | The fold is the same rounding-level change as on CUDA. On Linux the whole-map decode, with the fold on or off, stays 7-8e-5 LPIPS from the stock decode. ## Tests `test_diffusion_vae_upsample_fold.py::test_auto_arms_only_the_measured_cuda_cards` now covers ROCm. gfx1151, with or without feature suffixes, arms the fold. gfx942, gfx1100 and an empty arch name do not, and the kill switch still wins on gfx1151. It fails on main and passes here; the other 10 tests in the file are unchanged. ## Not proven here - Only gfx1151 was measured. Other RDNA and CDNA archs keep the 2x path until measured. - Only the FLUX.2 VAE was timed. FLUX.1, Z-Image and the other KL VAEs share the same three upsample conv shapes, as in #18792.
The strip decode used by AutoencoderKL-structured VAEs and the FLUX.2 VAE (FLUX.1, Kontext, Z-Image, HiDream, Lumina-2, Chroma, SDXL, FLUX.2) upsamples each decoder stage the same way. Triton writes the nearest-2x rows into a halo-padded strip, then cuDNN runs the 3x3 conv over the 4x-sized map.
A nearest-2x upsample followed by a 3x3 conv (padding 1) is exactly one 4x4, stride-2 transposed conv. Each of its taps is a sum of the original 3x3 taps. That needs 2.25x fewer MACs, and the 4x map is never written.
Change
diffusion_vae_strips._upsamplerunsconv_transpose2d(x, W4, bias or None, stride 2, padding 1).W4is built from the conv's taps summed in fp32 and rounded once to the conv dtype. It is cached per conv and rebuilt when the weight tensor or its version changes, for example after a fused LoRA.UNSLOTH_VAE_UPSAMPLE_FOLD:0turns it off,1turns it on for any device. ROCm (MIOpen), MPS and CPU stay on the 2x path unless forced.Results
Colab, 1024 px,
diffusion_vae_fused.install(strip decode), median of 5 interleaved rounds:Tests
tests/test_diffusion_vae_upsample_fold.py(10, CPU, fp64):The VAE suites (
vae_strips/vae_fusedusers, 3337 tests) pass.Not proven here
diffusion_vae_fused.py:1607, and was not changed.