Skip to content

Studio diffusion: fold the VAE nearest 2x upsample and 3x3 conv into one transposed conv - #18792

Merged
danielhanchen merged 4 commits into
mainfrom
studio-vae-upsample-fold
Nov 21, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
studio-vae-upsample-fold

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

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._upsample runs conv_transpose2d(x, W4, bias or None, stride 2, padding 1).
    • W4 is 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.
    • The deferred-bias contract is unchanged.
    • Maps up to 2^28 output elements (the measured 1024 px shapes) take one call. Larger maps run strip by strip with a one-row halo, so the workspace stays bounded and the output is copied once.
  • It is on by default on the measured cards: T4, A100, L4 and RTX PRO 6000.
  • UNSLOTH_VAE_UPSAMPLE_FOLD: 0 turns it off, 1 turns 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:

card (dtype) FLUX.1 VAE Z-Image VAE FLUX.2 VAE 2048 px (FLUX.1)
T4 (fp16) 525.3 -> 460.9 ms (1.14x) 595.1 -> 521.3 (1.14x) 612.1 -> 537.9 (1.14x) 2950 -> 2626 (1.12x)
L4 (bf16) 241.2 -> 217.1 (1.11x) 243.9 -> 219.4 (1.11x) 256.1 -> 233.1 (1.10x) 1246 -> 1171 (1.06x)
A100 (bf16) 62.3 -> 55.4 (1.12x) 62.7 -> 55.8 (1.12x) 63.0 -> 56.1 (1.12x) 304.3 -> 286.0 (1.06x)
RTX PRO 6000 (bf16) 41.4 -> 36.9 (1.12x) 40.6 -> 36.1 (1.13x) 40.9 -> 36.3 (1.13x) 210.0 -> 196.6 (1.07x)
  • Quality is at rounding level. Against the 2x path, LPIPS is about 7e-5 in bf16 and 1e-6 in fp16 on T4, with PSNR 55-59 dB (bf16) and 73-77 dB (fp16).
  • Against an fp32 decode, PSNR moves by 0.04 dB on T4 and 0.1 to 0.28 dB in bf16, from the bf16 rounding of the summed taps.
  • Peak memory: +18 MiB when one transposed conv covers the whole map; unchanged when it runs strip by strip.
  • At 1024 px the strip-by-strip variant is 1.08-1.10x faster than the 2x path. At 2048 px it is the path that runs anyway.

Tests

tests/test_diffusion_vae_upsample_fold.py (10, CPU, fp64):

  • The fold equals the 2x chain, over the whole map and strip by strip (first and last strip, 1-row maps), with and without bias.
  • The cached kernel follows in-place weight edits.
  • The gate covers the measured cards only, keeps ROCm off, and honours the switch.
  • Non-3x3 convs and dtype mismatches keep the 2x path.

The VAE suites (vae_strips / vae_fused users, 3337 tests) pass.

Not proven here

  • ROCm (MIOpen), MPS and Windows. They are off by default; an AMD probe is ready.
  • sm86, sm90 and sm100 were not measured, so they stay off.
  • Wan / Qwen video VAEs: their resample takes another path, diffusion_vae_fused.py:1607, and was not changed.
  • End-to-end renders: only decode timings were measured.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-21T19:26:52.172635Z d0dba40 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

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

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 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 👍 / 👎.

Comment on lines +648 to +649
if hit is not None and hit[0] is w and hit[1] == w._version:
return hit[2]

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 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 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Can't wait for the next one!

Reviewed commit: d0dba4087f

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

@danielhanchen
danielhanchen merged commit 3fb3b8d into main Nov 21, 2026
@danielhanchen
danielhanchen deleted the studio-vae-upsample-fold branch November 21, 2026 21:43
danielhanchen added a commit that referenced this pull request Nov 22, 2026
…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.
danielhanchen added a commit that referenced this pull request Nov 22, 2026
…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]`.
danielhanchen added a commit that referenced this pull request Nov 22, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant