Repository navigation
[Diffusion] Port the Wan VAE decoder fast paths to the Qwen-Image VAE - #38020
Merged
Merged
Conversation
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.
Dayuxiaoshui
requested review from
AgainstEntropy,
BBuf,
HaiShaw,
mickqian,
ping1jing2 and
yichiche
as code owners
September 4, 2026 14:51
BBuf
approved these changes
Sep 5, 2026
This was referenced Sep 5, 2026
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.
Merged
5 tasks done
StevenChenSE
pushed a commit
to StevenChenSE/sglang
that referenced
this pull request
Sep 6, 2026
…sgl-project#38020) Co-authored-by: Xiaoyu Zhang <[email protected]>
This was referenced Sep 7, 2026
5 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 inmainreached it:cat_pad_channels_last_3d, PR [diffusion] Bit-exact data-movement elimination for the Wan causal VAE decoder (H200 LongLive2 704x1280x61f: decode 2.80->2.32 s lossless / 2.12->1.67 s quality=high, e2e -10.7%) #34125), andRMSNorm -> SiLUfusion (wan_vae_cuda_opt.py,wan_rmsnorm_silu).Profiling a 1024x1024 bf16 decode on H200 showed the same shape of waste the Wan work removed: 78
aten::copy_and 30fill_launches per decode from the per-convclone / cat / F.pad / relayoutbookkeeping, 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 (residualconv1/conv2, encoder/decoderconv_in/conv_out, upsample3dtime_conv) goes through a_run_cached_causal_convhelper with the same contract as the Wan one: the conv input (cache frames + hidden state + zero padding) is written directly inchannels_last_3dbycat_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_Totherwise), 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.forwarduses the fused cat+pad whenever its weights arechannels_last_3d(the loader already converts them for the Qwen-Image pipeline).QwenImageUpsampleskips thex.float() ... .type_as(x)round trip on AMP-capable platforms.nearest-exactis a pure gather, so bf16 in/out is bit-identical and three full-size copies at the largest resolutions disappear. Same predicateWanUpsamplealready uses.Quality-gated (
quality="extra-high"/"high", via the sharedVaeFastPathGate)wan_vae_cuda_opt.py:_install_norm_silu/_maybe_optimize_wan_family_vaeare parametrised by residual-block / RMSNorm class;maybe_optimize_qwen_image_vaereusesFusedWanRMSNormSiLUunchanged. Registered inplatforms/cuda.py::optimize_vae. Wan behaviour is unchanged.GatedChannelsLastUpsample:Resample.forwardreaches itsUpsample -> Conv2dthroughx.permute(0, 2, 1, 3, 4).reshape(b * t, c, h, w). On achannels_last_3dtensor withb * t == 1the merged batch dim keeps a degenerate stride;is_contiguous(channels_last)says NHWC but aten'ssuggest_memory_formatsays 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 viaas_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.identity + xunder the gate so the sum inherits thechannels_last_3dlayout. The add is commutative, but the layout changes the reduction order of the eagerF.normalizethat 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 newtest_qwen_vae_*cases: fused cat+pad vs. aten for 0/1/2 cache frames; three streamed chunks through one cache slot starting fromNoneand"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, withstate_dictkeys unchanged.existing-fast-paths.mdskill notes updated.Accuracy Tests
Hardware: 1x H200, torch 2.13.0+cu130, real
Qwen/Qwen-ImageVAE weights, bf16, 1024x1024 (latent[1, 16, 1, 128, 128]).Lossless path
torch.equalagainstmainoutput: True.sglang generate(8 steps, seed 1, 3 prompts,quality=lossless): all 3 PNGs md5-identical tomain(916dd0e8...,69b50c99...,9da49295...).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):
The whole difference comes from the pre-existing
wan_rmsnorm_silukernel (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):mainvs. this PR PSNR 34.71 dB / SSIM 0.976. Notequality=highalso 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.profilerkernel 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.main(lossless)Profile deltas (lossless):
aten::copy_78 -> 8 launches (8.76 -> 0.94 ms),fill_30 -> 0,Memcpy DtoD30 -> 0, replaced by 30_cat_pad_cl3d_kernellaunches (6.2 ms). Atquality=highall 29RMSNorm+SiLUsites hit the fused kernel (previously 25; the 4 up-block entry norms fell back on NCDHW input) and the cuDNNnchwToNhwcconversions around the resample conv2d disappear.End-to-end
DecodingStageon 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
ruff format,ruff check,isort: no new findings vs.main)test/registered/kernels/ops/diffusion/test_model_fast_paths.py: 58 passed, 1 skipped)Review and Merge Process
/tag-and-rerun-ci,/tag-run-ci-label,/rerun-failed-ciCI States
Latest PR Test (Base): ⏳ Run #33946630528
Latest PR Test (Extra): ❌ Run #33946630250
Latest PR Test (AMD ROCm 7.2): ⏳ Run #33946630396