Skip to content

[diffusion] Fuse DiT FFN tanh-GELU into up-proj GEMM (cublasLt epilogue) behind quality=high (Qwen-Image 1024^2 denoise 12.36 -> 12.05 s on H200) - #33536

Merged
BBuf merged 2 commits into
sgl-project:mainfrom
BBuf:pr-gelu-epilogue-quality-high
Aug 4, 2026

Conversation

@BBuf

@BBuf BBuf commented Aug 4, 2026 •

Copy link
Copy Markdown
Collaborator

Branch: pr-gelu-epilogue-quality-high, single commit d6473eae5b on main (17d1908), standalone — no dependencies. 6 files, +397/−0.

Motivation

Diffusion DiT FeedForwards compute gelu(up_proj(x), approximate="tanh") as a standalone GEMM followed by a separate, bandwidth-bound GELU kernel over the [tokens, 4*dim] MLP intermediate. torch._addmm_activation(bias, x, w.t(), use_gelu=True) folds the bias-add and the GELU into the GEMM epilogue (cublasLt), removing the extra kernel launch and the intermediate HBM round-trip. cublasLt's GELU is the tanh-approximate GELU (max abs diff ~5e-6 vs F.gelu(approximate="tanh") in fp32), so for bf16 inference the fused path differs from the reference only at rounding-order level.

This fusion family shipped before: #28166 (FLUX) merged, then #28708 reverted it, deleting the shared fused_linear_act/ helper; the sibling PRs #28419 (Qwen-Image, denoise 1.061x on B200, SSIM 0.984), #28167 (generic FeedForward, GLM ~1.03x) and #28366 (shared MLP) were closed unmerged in the same sweep. The revert reason (#28708, quoted verbatim):

We are backing this out because follow-up checks on diffusion GELU epilogue fusion showed that the fused path can move generated images away from the original model behavior. For now we want the runtime to stay closer to the unfused/reference model semantics.

That reason is exactly the definition of the quality sampling param that has landed since (#33453 tier, already used by the FLUX.2 VAE fast path #33451 and the MiniMax-H3 cache-dit gating): "lossless" (default) = the exact reference path, bit-exact vs the CI golden outputs; "high" = opt into validated accelerated paths that are quality-guaranteed (PSNR > 25 dB bar) but not bit-exact. This PR re-lands the fusion inside that contract: the lossless default is byte-identical to main (verified below), and the fused path runs only for quality="high" requests.

Scope = the models we could actually measure end-to-end on this box: Qwen-Image (QwenImageGELU) and GLM-Image (GlmImageGELU). Two sites are deliberately left as follow-ups rather than shipped unvalidated:

  • FLUX.1 (flux.py FluxGELU — the original [Diffusion] FLUX: fuse FeedForward GELU into up-proj GEMM (cublasLt epilogue) #28166 site): we have no FLUX.1 weight access to revalidate, and FLUX.2-klein does not go through that site (its Flux2FeedForward is SwiGLU with the MLP-in GEMM merged into the QKV projection, so a GELU epilogue does not apply).
  • Wan2.1-T2V (shared layers/mlp.py MLP gelu_pytorch_tanh FFN, the [diffusion] Fuse tanh-GELU into shared MLP FFN up-proj GEMM epilogue #28366 site): Wan2.1-T2V-1.3B currently fails to load on main itself — the UMT5 text-encoder loader raises Following text encoder weights were not initialized from checkpoint: [... SelfAttention.qkv_proj ...] on the pristine 17d1908 tree (wan13b-main.log), so no lossless baseline, PSNR pair, or byte-exact check is obtainable. The wiring is a two-line follow-up once that pre-existing regression is fixed; the kernel-level evidence at the exact Wan shapes (1.17x microbench, fp32-equidistance) is already in this PR's tables.

Modifications

1. Kernel helper — new python/sglang/kernels/ops/diffusion/fused_linear_gelu.py (+182), restoring the #28708-deleted helper at its post-RFC-#29630 home (kernels side), plus the gating machinery:

  • fused_linear_gelu_tanh(x, weight, bias): the cublasLt-epilogue GEMM, registered via register_custom_op (opaque under torch.compile, like the other diffusion ops) and as diffusion.fused_linear_gelu_tanh (KernelBackend.TORCH) in the kernel registry.
  • can_fuse_linear_gelu_static / can_fuse_linear_gelu: the [Diffusion] FLUX: fuse FeedForward GELU into up-proj GEMM (cublasLt epilogue) #28166 guards (unquantized UnquantizedLinearMethod-or-plain linear, has-bias, no skip_bias_add, no multi-rank gather_output, half dtype, CUDA input). The weight-device check is runtime-only: under dit_cpu_offload the weights live on CPU at mount time.
  • mark_fused_gelu_site(module, linear_attr) + mount_fused_linear_gelu / unmount_fused_linear_gelu: the site protocol. Sites start unmounted (reference path, bit-exact). Mounting is all-or-nothing per transformer and fail-closed: if any marked site fails the static guards (with the reason logged), every site stays on the reference path.

2. Model sites (fused branch + mark_fused_gelu_site in __init__; the unmounted forward is the unmodified reference code path):

  • qwen_image.py QwenImageGELU (60 blocks x img+txt streams, dim 3072 -> 12288),
  • glm_image.py GlmImageGELU (30 blocks, dim 4096 -> 16384),

All other GELU sites (shared layers/mlp.py MLP/FeedForward users, FLUX, embedders) are untouched and stay on the reference path.

3. DenoisingStage gating — pipelines_core/stages/denoising.py (+36): _maybe_toggle_fused_gelu(batch) runs at the same batch-boundary hook as the cache-dit decision (_maybe_enable_cache_dit_and_torch_compile), mounting iff batch.sampling_params.quality == "high" (the MiniMax-H3 precedent: quality participates in the dynamic-batch signature, so a worker batch is uniform in quality and the process-wide transition is safe at the batch boundary). Models without marked sites are no-ops.

Speedup

All numbers H200, bf16, this branch, GPUs otherwise idle. Three levels:

Kernel microbenchmark (real up-proj shapes, us per call, median of 200 after 30 warmup; ref = F.linear + F.gelu(tanh), fused = torch._addmm_activation):

shape (tokens x in -> out) linear only GELU only ref (linear+GELU) fused speedup
Qwen-Image img 4096x3072->12288 460.2 73.1 517.9 477.1 1.09x
GLM-Image 4096x4096->16384 844.4 97.0 918.8 858.2 1.07x
Wan2.1-1.3B 32760x1536->8960 1419.4 348.5 1681.3 1435.6 1.17x
Wan2.1-14B 32760x5120->13824 — — 7385.2 7010.7 1.05x

The epilogue is nearly free (fused ~= linear-only + a few %), so the win is the eliminated GELU pass over the [tokens, 4*dim] intermediate.

Component denoise A/B (per-request [DenoisingStage] finished in X from the e2e runs below — same warmed process, 9 requests, drop first, 15% outlier filter, median of survivors):

model / workload lossless quality=high denoise speedup
Qwen-Image 1024^2 (50 steps) 12.356 s 12.049 s 1.026x
GLM-Image 1024^2 (30 steps) 6.491 s 6.365 s 1.020x

Cross-check: a --quality high run on the pre-fix branch state where the mount was rejected by the static guards showed denoise 12.332 s = lossless within noise, independently confirming the gate itself (attribute check per forward) adds no measurable overhead.

End-to-end latency (#33451 protocol: generate CLI, seed 42, --dit-layerwise-offload false --warmup --save-output; metric = client-side "Pixel data generated successfully in X seconds" wall-clock; one warmed process serving 9 sequential identical requests, first dropped, 15% outlier filter, median of >= 5 survivors):

model / resolution lossless --quality high Δ per request
Qwen-Image 1024^2 12.875 s 12.590 s -0.285 s (-2.2%)
GLM-Image 1024^2 40.30 s 39.60 s -0.70 s (within the AR-stage noise band)

(GLM-Image e2e is dominated by its AR vision-language stage (~33 s of the request), so the denoise win is diluted e2e; the component table above is the authoritative measurement.)

Lossless-path timing on this branch is unregressed vs main (same protocol, main = 17d1908): Qwen-Image 12.895 s / GLM-Image 42.18 (denoise 6.495) s medians vs branch-lossless 12.875 / 40.30 s.

Accuracy

  • Lossless default is bit-exact end-to-end: gate-off outputs of this branch are byte-identical (cmp) to origin/main outputs for the same seed/prompt — Qwen-Image byte-identical (cmp clean), GLM-Image byte-identical (cmp clean). Golden-output CI is unaffected.
  • fp32 ground-truth equidistance (real up-proj shapes, bf16 paths vs fp32 reference): Qwen-Image shape: baseline mean abs err 3.08e-05 / p99 1.32e-04 vs fused 2.68e-05 / 1.04e-04; GLM-Image 2.84e-05/1.24e-04 vs 2.46e-05/9.72e-05; Wan-1.3B 3.86e-05/1.60e-04 vs 3.38e-05/1.25e-04. The fused path is closer to the truth (the epilogue evaluates the GELU on the fp32 GEMM accumulator before the single bf16 round; the reference rounds to bf16 after the GEMM and again after the GELU) — the fused path is not statistically farther from the fp32 truth than the baseline bf16 path.
  • e2e quality (maintainer bar for quality="high": PSNR > 25 dB vs the lossless output, same seed, saved outputs):
model prompt PSNR (dB) SSIM bar PASS
Qwen-Image 1024^2 cyberpunk city (main) 37.08 0.98827 >25 yes
Qwen-Image 1024^2 mountain lake at sunrise 39.71 0.99298 >25 yes
Qwen-Image 1024^2 elderly fisherman portrait 39.45 0.98458 >25 yes
GLM-Image 1024^2 cyberpunk city (main) 51.75 0.99884 >25 yes
GLM-Image 1024^2 mountain lake at sunrise 53.99 0.99890 >25 yes
GLM-Image 1024^2 elderly fisherman portrait 55.35 0.99914 >25 yes
  • Unit tests: test/registered/kernels/ops/diffusion/test_fused_linear_gelu.py (7 cases: fused-vs-reference numeric bound bf16/fp16, fp32-truth equidistance, gate-off torch.equal bit-exactness + unmount restore, all-or-nothing mount, static-guard rejections, runtime-guard fallback). 7 passed on H200.

Sample images

Four lossless/high pairs saved on the box under /tmp/prG_imgs/ (to be attached here): qwen_cyberpunk_{lossless,high}.png, qwen_lake_{lossless,high}.png, glm_cyberpunk_{lossless,high}.png, glm_fisherman_{lossless,high}.png.

Checklist

  • Format your code according to the Format code with pre-commit.
  • Add unit tests.
  • Provide accuracy and speed benchmark results.
  • Follow the SGLang code style guidance.

Sample outputs (lossless vs --quality high)

lossless (default) --quality high
Qwen-Image, cyberpunk city 1024x1024
Qwen-Image, mountain lake 1024x1024
GLM-Image, cyberpunk city
GLM-Image, fisherman portrait

🤖 Generated with Claude Code


CI States

Latest PR Test (Base): ⏳ Run #30903491527
Latest PR Test (Extra): ❌ Run #30903492322

…ue) behind quality=high (Qwen-Image 1024^2 denoise 12.36 -> 12.05 s on H200)

Re-land the sgl-project#28166/sgl-project#28419/sgl-project#28167 GELU-epilogue fusion family inside the
quality sampling-param contract that sgl-project#28708 asked for: the lossless
default is byte-identical to main (cmp-verified for Qwen-Image and
GLM-Image), and torch._addmm_activation(use_gelu=True) replaces the
up-proj GEMM + separate tanh-GELU kernel only for quality=high batches.

- new kernels/ops/diffusion/fused_linear_gelu.py: custom op + static/
  runtime guards (unquantized, bias, no skip_bias_add, no multi-rank
  gather, half dtype) + mark/mount/unmount site protocol; mounting is
  all-or-nothing per transformer and fail-closed with reason logging.
- QwenImageGELU / GlmImageGELU marked as fusion sites (fused branch is
  a no-op until mounted).
- DenoisingStage mounts/unmounts at the batch boundary next to the
  cache-dit decision, keyed on batch.sampling_params.quality (which is
  in the dynamic-batch signature, so batches are quality-uniform).

H200 results (denoise stage, warmed 9-request median): Qwen-Image
1024^2 12.356 -> 12.049 s (1.026x), GLM-Image 1024^2 6.491 -> 6.365 s
(1.020x); e2e 12.875 -> 12.590 s / 40.3 -> 39.6 s. PSNR vs lossless
37.1-55.4 dB (bar >25), SSIM >= 0.984. fp32-truth: fused bf16 is
slightly closer to the fp32 reference than the baseline bf16 path.
FLUX.1 (no weight access) and Wan2.1 shared-MLP (model cannot load on
main: pre-existing UMT5 loader regression) are follow-ups.

Co-Authored-By: Claude Fable 5 <[email protected]>
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Caution

The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased.

@BBuf BBuf added the run-ci CI: run the baseline test suite on this PR label Aug 4, 2026
@github-actions github-actions Bot added diffusion SGLang Diffusion jit-kernel labels Aug 4, 2026
@BBuf

BBuf commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

@BBuf
BBuf merged commit 95d0e57 into sgl-project:main Aug 4, 2026
148 of 198 checks passed
saturn-acc pushed a commit to saturn-acc/sglang that referenced this pull request Aug 16, 2026
…ue) behind quality=high (Qwen-Image 1024^2 denoise 12.36 -> 12.05 s on H200) (sgl-project#33536)

Co-authored-by: Claude Fable 5 <[email protected]>
Atituiset pushed a commit to Atituiset/sglang that referenced this pull request Sep 10, 2026
…ue) behind quality=high (Qwen-Image 1024^2 denoise 12.36 -> 12.05 s on H200) (sgl-project#33536)

Co-authored-by: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

diffusion SGLang Diffusion jit-kernel run-ci CI: run the baseline test suite on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant