Skip to content

[Diffusion] Port the Wan VAE decoder fast paths to the Qwen-Image VAE - #38020

Merged
BBuf merged 2 commits into
sgl-project:mainfrom
Dayuxiaoshui:qwen-image-vae-fast-path
Sep 5, 2026
Merged

BBuf merged 2 commits into
sgl-project:mainfrom
Dayuxiaoshui:qwen-image-vae-fast-path

Conversation

@Dayuxiaoshui

@Dayuxiaoshui Dayuxiaoshui commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

The Qwen-Image VAE (autoencoder_kl_qwenimage.py) is the Wan 2.1 VAE under other class names, but none of the Wan VAE decoder fast paths that already live in main reached it:

Profiling a 1024x1024 bf16 decode on H200 showed the same shape of waste the Wan work removed: 78 aten::copy_ and 30 fill_ launches per decode from the per-conv clone / cat / F.pad / relayout bookkeeping, plus a fully eager norm chain. On the way we found a layout issue that silently sends the 2D upsample and conv2d of every up block down their NCHW paths.

This PR generalises the Wan installer into a Wan-family installer and wires the Qwen-Image VAE into it. It does not add a new kernel.

Modifications

Lossless (bit-exact vs. the eager chain, mounted unconditionally)

  • autoencoder_kl_qwenimage.py: every causal-conv feature-cache slot (residual conv1/conv2, encoder/decoder conv_in/conv_out, upsample3d time_conv) goes through a _run_cached_causal_conv helper with the same contract as the Wan one: the conv input (cache frames + hidden state + zero padding) is written directly in channels_last_3d by cat_pad_channels_last_3d, and the same pass emits the compact next-chunk cache. The compact cache is sized exactly like the reference bookkeeping (min(CACHE_T, T) frames for the first chunk of a clip, CACHE_T otherwise), so single-frame image decodes do not pin a second full-size frame per conv site (without this, peak memory rose from 3.89 GB to 6.11 GB).
  • QwenImageCausalConv3d.forward uses the fused cat+pad whenever its weights are channels_last_3d (the loader already converts them for the Qwen-Image pipeline).
  • QwenImageUpsample skips the x.float() ... .type_as(x) round trip on AMP-capable platforms. nearest-exact is a pure gather, so bf16 in/out is bit-identical and three full-size copies at the largest resolutions disappear. Same predicate WanUpsample already uses.

Quality-gated (quality="extra-high" / "high", via the shared VaeFastPathGate)

  • wan_vae_cuda_opt.py: _install_norm_silu / _maybe_optimize_wan_family_vae are parametrised by residual-block / RMSNorm class; maybe_optimize_qwen_image_vae reuses FusedWanRMSNormSiLU unchanged. Registered in platforms/cuda.py::optimize_vae. Wan behaviour is unchanged.
  • GatedChannelsLastUpsample: Resample.forward reaches its Upsample -> Conv2d through x.permute(0, 2, 1, 3, 4).reshape(b * t, c, h, w). On a channels_last_3d tensor with b * t == 1 the merged batch dim keeps a degenerate stride; is_contiguous(channels_last) says NHWC but aten's suggest_memory_format says NCHW, so the upsample and conv2d ran their NCHW kernels (with cuDNN converting to NHWC and back internally) and every up block started with an NCDHW tensor that the fused norm could not take (4 of 29 norm sites fell back). Under the gate the view is re-expressed with canonical NHWC strides via as_strided (same memory, no copy). The NHWC conv2d is not guaranteed to pick the same cuDNN algorithm as the NCHW one (measured: differs at 1 bf16 ulp on a few pixels), which is why this is gated rather than lossless.
  • Attention residual computed as identity + x under the gate so the sum inherits the channels_last_3d layout. The add is commutative, but the layout changes the reduction order of the eager F.normalize that follows under fp32 autocast; we measured this end-to-end as non-bit-exact on a Wan pipeline (fp32 VAE weights, bf16 autocast decode), so it is not offered on the lossless path.

Tests / docs

  • test_model_fast_paths.py: 6 new test_qwen_vae_* cases: fused cat+pad vs. aten for 0/1/2 cache frames; three streamed chunks through one cache slot starting from None and "Rep", comparing outputs and cache contents; upsample fp32-round-trip removal; gate dispatch; stride canonicalisation; tiny-decoder install with gate off required bit-exact and gate on bounded in relative error, with state_dict keys unchanged.
  • existing-fast-paths.md skill notes updated.

Accuracy Tests

Hardware: 1x H200, torch 2.13.0+cu130, real Qwen/Qwen-Image VAE weights, bf16, 1024x1024 (latent [1, 16, 1, 128, 128]).

Lossless path

  • Standalone decode of a fixed random latent: torch.equal against main output: True.
  • End-to-end sglang generate (8 steps, seed 1, 3 prompts, quality=lossless): all 3 PNGs md5-identical to main (916dd0e8..., 69b50c99..., 9da49295...).
  • Peak decode memory: 3.895 GB vs. 3.889 GB on main.

Quality path (quality=high)

Isolated on the VAE by encoding a real generated image and decoding the same latent both ways (random latents understate the difference: 59.4 dB):

comparison PSNR SSIM max abs diff (0-255)
high vs. lossless (this PR) 37.58 dB 0.98644 74
norm fusion only vs. lossless 37.60 dB 0.98641 78
NHWC layout only vs. lossless 89.57 dB 1.00000 2
lossless vs. original image 24.13 dB 0.77425 192
high vs. original image 24.13 dB 0.77411 187

The whole difference comes from the pre-existing wan_rmsnorm_silu kernel (fp32 statistics vs. five bf16 roundings in the eager chain); the layout change alone is at the 1-ulp level. Reconstruction error against the source image is identical for both paths.

End-to-end at quality=high (8 steps): main vs. this PR PSNR 34.71 dB / SSIM 0.976. Note quality=high also changes the Qwen-Image DiT path, so high-vs-lossless image diffs are not a VAE metric; main-high was confirmed deterministic across two runs (identical md5) before comparing.

Speed Tests and Profiling

Same setup. GPU time is torch.profiler kernel self time (device_type == CUDA), which is robust to host contention on this shared box; wall clock is the same-process interleaved CUDA-event median.

path GPU kernel time kernels wall median
main (lossless) 56.14 ms 439 57.06 ms
this PR, lossless 52.41 ms 369 52.96 ms
this PR, high 44.61 ms 185 46.02 ms

Profile deltas (lossless): aten::copy_ 78 -> 8 launches (8.76 -> 0.94 ms), fill_ 30 -> 0, Memcpy DtoD 30 -> 0, replaced by 30 _cat_pad_cl3d_kernel launches (6.2 ms). At quality=high all 29 RMSNorm+SiLU sites hit the fused kernel (previously 25; the 4 up-block entry norms fell back on NCDHW input) and the cuDNN nchwToNhwc conversions around the resample conv2d disappear.

End-to-end DecodingStage on warm requests was measured but is dominated by host-side jitter on this machine (2 samples per config, 70-180 ms for a ~50 ms GPU workload), so it is not used as evidence here.

Scope of the win: for a 50-step Qwen-Image request the VAE decode is ~57 ms against ~12 s of denoising, so this is invisible on standard T2I latency. It matters for few-step (Lightning) variants, batched/2K decode, and the Qwen-Image-Edit encoder path (which also takes the cat+pad helper; not benchmarked separately). The main value is structural: the Wan VAE fast paths are now a family-level mechanism, and the degenerate-stride layout issue found here also affects the Wan video VAE (follow-up PR).

Checklist

Review and Merge Process

  1. Ping Merge Oncalls to start the process. See the PR Merge Process.
  2. Get approvals from CODEOWNERS and other reviewers.
  3. Trigger CI tests with comments or contact authorized users to do so.
    • Common commands include /tag-and-rerun-ci, /tag-run-ci-label, /rerun-failed-ci
  4. After green CI and required approvals, ask Merge Oncalls or people with Write permission to merge the PR.

CI States

Latest PR Test (Base): ⏳ Run #33946630528
Latest PR Test (Extra): ❌ Run #33946630250
Latest PR Test (AMD ROCm 7.2): ⏳ Run #33946630396

The Qwen-Image VAE is the Wan 2.1 VAE under other class names, but none of
the Wan decoder fast paths reached it. This ports both families and fixes a
layout issue found on the way.

Lossless (bit-exact, mounted unconditionally):
- Route every causal-conv feature-cache slot (residual conv1/conv2,
  encoder/decoder conv_in/conv_out, upsample3d time_conv) through the
  cat_pad_channels_last_3d kernel: conv input plus compact next-chunk cache
  in one pass instead of clone/cat/F.pad/relayout per conv. Single-frame
  decodes keep the compact cache at the reference size (one frame) so peak
  memory stays flat.
- QwenImageCausalConv3d uses the fused cat+pad when its weights are
  channels_last_3d.
- The nearest-exact upsample skips its fp32 round trip on AMP-capable
  platforms (pure gather, values identical).

Quality-gated (extra-high / high, via the shared VaeFastPathGate):
- Reuse the Wan RMSNorm+SiLU fusion: the installer in wan_vae_cuda_opt is
  parametrised by residual-block / norm class and gains
  maybe_optimize_qwen_image_vae, registered in the CUDA platform.
- GatedChannelsLastUpsample: permute().reshape() on a channels_last_3d
  tensor with B*T == 1 leaves a degenerate batch stride that
  is_contiguous(channels_last) accepts but aten's suggest_memory_format
  does not, so the 2D upsample and conv2d silently ran their NCHW paths and
  handed every up block an NCDHW tensor the fused norm could not take.
  Re-express the view with canonical NHWC strides under the gate; the NHWC
  conv2d may pick a different cuDNN algorithm, hence gated.
- Attention residual computed as identity + x under the gate so the sum
  keeps channels_last_3d. Commutative, but the layout changes the
  reduction order of the eager norm that follows under fp32 autocast, so
  it is not offered on the lossless path.

Qwen-Image 1024x1024 bf16 decode on H200 (torch.profiler GPU kernel time):
main 56.1 ms / 439 kernels; lossless 52.4 ms / 369 (torch.equal vs main;
3-prompt end-to-end PNGs md5-identical); high 44.6 ms / 185. On a real
encoded latent the high path is PSNR 37.6 dB / SSIM 0.986 vs lossless, all
of which comes from the pre-existing wan_rmsnorm_silu kernel (layout part
alone: 89.6 dB). Peak memory unchanged.
@github-actions github-actions Bot added documentation Improvements or additions to documentation diffusion SGLang Diffusion labels Sep 4, 2026
@BBuf BBuf added run-ci CI: run the baseline test suite on this PR run-ci-extra CI: also run the extra suite (requires run-ci) labels Sep 5, 2026
@BBuf

BBuf commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator

@BBuf
BBuf merged commit 50c1bf0 into sgl-project:main Sep 5, 2026
155 of 199 checks passed
Dayuxiaoshui added a commit to Dayuxiaoshui/sglang that referenced this pull request Sep 6, 2026
…HWC nearest upsample

Follow-up to sgl-project#38020. The degenerate-stride layout issue found on the
Qwen-Image VAE also affects the Wan 2.1 video VAE, where the decoder is a
much larger share of short-step video pipelines, and it comes with a second
problem: once the decoder does run channels_last, aten's
upsample_nearest2d_nhwc kernel is several times slower than its NCHW
sibling on the same bytes.

Lossless (bit-exact, unconditional):
- New kernel layout/nearest_upsample_nhwc_triton.py: integer-factor nearest
  upsample of a dense channels_last [N, C, H, W] tensor as a pure gather.
  For integer factors nearest and nearest-exact both map output index i to
  input index i // f, so the result is bitwise identical to nn.Upsample in
  either mode for every dtype. Registered as diffusion.nearest_upsample_nhwc
  with a can_use_ predicate. 0.061 ms vs 0.458 ms (aten NHWC) and 0.190 ms
  (aten NCHW) for [1, 192, 240, 416] bf16 on H200.
- GatedChannelsLastUpsample runs it whenever the upsample input already has
  canonical NHWC strides (aten would run its NHWC kernel and return the
  same dense channels_last tensor), on the lossless path too.

Quality-gated (extra-high / high):
- resample_forward's upsample3d frame interleave (reshape / stack / reshape,
  which materialises NCDHW) writes the same values straight into a
  channels_last_3d buffer with one copy via _interleave_time_pairs.
- The Wan installer now wraps WanUpsample with GatedChannelsLastUpsample and
  hands the gate to WanResample and WanAttentionBlock (residual operand
  order), so all 29 RMSNorm+SiLU sites hit the fused kernel instead of 25.
  The attention operand order is commutative but changes the reduction order
  of the eager norm that follows under fp32 autocast, which is how Wan
  pipelines decode (fp32 VAE weights, bf16 autocast); measured end-to-end as
  non-bit-exact, hence gated.

Wan 2.1 VAE, 81 frames 480x832 on H200, torch.profiler GPU kernel time:
bf16 weights: main lossless 1342 ms / high 1178 ms -> 1324 / 1112 ms.
fp32 weights + bf16 autocast (the T2V pipeline setting): main 1633 / 1311 ms
-> 1593 / 1215 ms. Lossless mp4 from TurboWan2.1-T2V-1.3B md5-identical to
main; high vs main-high PSNR 36.3 dB mean / 35.0 dB min over 81 frames.
Peak memory unchanged (4.577 GB). Qwen-Image high: 44.6 -> 42.9 ms.
StevenChenSE pushed a commit to StevenChenSE/sglang that referenced this pull request Sep 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

diffusion SGLang Diffusion documentation Improvements or additions to documentation run-ci CI: run the baseline test suite on this PR run-ci-extra CI: also run the extra suite (requires run-ci)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants