Skip to content

[diffusion] Fuse tanh-GELU into shared MLP FFN up-proj GEMM epilogue - #28366

Closed
BBuf wants to merge 1 commit into
sgl-project:mainfrom
BBuf:kda/mlp-fused-gelu
Closed

BBuf wants to merge 1 commit into
sgl-project:mainfrom
BBuf:kda/mlp-fused-gelu

Conversation

@BBuf

@BBuf BBuf commented Jun 16, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

The shared diffusion FFN MLP (python/sglang/multimodal_gen/runtime/layers/mlp.py) — used by Wan2.2 (T2V / TI2V / causal), HunyuanVideo, Hunyuan3D, Helios, JoyImage and MOVA — computed gelu_pytorch_tanh(fc_in(x)) as a standalone GEMM followed by a separate, bandwidth-bound GELU kernel over the [tokens, mlp_hidden] intermediate.

This routes the tanh-GELU FFN through the existing cublasLt GELU-epilogue helper linear_gelu_tanh (runtime/layers/fused_linear_act/gelu.py, already used by flux.py), folding the bias-add + tanh-GELU into the fc_in GEMM epilogue (torch._addmm_activation(..., use_gelu=True)). This removes the extra kernel launch and the HBM round-trip of the MLP intermediate.

  • Only the tanh-approx GELU path (act_type == "gelu_pytorch_tanh") is fused; every other activation keeps the exact reference path.
  • The helper's guards (unquantized, fp16/bf16, has-bias, CUDA, no multi-rank gather) keep correctness under TP / quantization; otherwise it falls back to fc_in(x) + F.gelu(approximate="tanh").
  • cublasLt's GELU matches tanh-approximate GELU within fp16/bf16 rounding, so the fused path is numerically equivalent for half-precision inference.

This is the same mechanism already shipped for FLUX; this PR extends it to the shared MLP FFN so every model that uses it benefits.

Benchmark

Wan2.2-TI2V-5B, 1280×720, 81 frames, 50 steps, B200, --enable-torch-compile --warmup, isolated HF cache. Denoise latency reported as steady-state per-step (steps 5–49; step 0 excluded as the one-time compile spike).

Command shape:

PYTHONPATH=python python3 \
  python/sglang/multimodal_gen/.claude/skills/sglang-diffusion-benchmark-profile/scripts/bench_diffusion_denoise.py \
  --model wan-ti2v --label <main|pr>
Metric Latest main PR Speedup
Denoise steady-state median (ms/step) 504.9 489.9 1.031×
Denoise steady-state min (ms/step) 494.6 482.7 1.025×

Per-run steady-state median (ms/step):

Run main PR
generate (save-output) 504.8 489.9
r1 505.0 489.8
r2 504.9 489.3

(steady-state per-step variance is < 0.3 ms within each side; the speedup is consistent run-to-run.)

Mechanism: the fused path removes the standalone triton_poi_fused_gelu kernel, which is 3.9% of denoise GPU time in the baseline torch.profiler trace; at Wan's FFN shape the MLP forward itself is 1.10–1.13× faster in isolation (compiled microbench).

Generated Video Check

Same prompt / input image / seed (42), main vs PR.

main vs PR vs 10x diff

Columns: main | PR | 10× absolute diff. Side-by-side video: https://github.com/BBuf/sglang/raw/kda/diffusion-gelu-artifacts/mlp-fused-gelu/wan_ti2v_side_by_side.mp4

Per-frame difference over all 81 frames:

Metric Value CI gate (publish_diffusion_gt.py)
mean_abs_diff (0–255) 2.71 (max 4.54) ≤ 45.0 ✓
RMS diff (0–255) 6.24 (max 10.47) —
luminance SSIM (CI formula) 0.984 (min 0.959) ≥ 0.20 ✓
windowed SSIM (skimage) 0.937 (min 0.890) —

The output is a perceptually-equivalent sample, not bit-identical: the bf16-level epilogue difference propagates through the 50-step denoise trajectory, so the residual differences concentrate on high-frequency edges (only visible at 10× amplification). Both diffusion-CI quality thresholds (SSIM ≥ 0.20, mean_abs_diff ≤ 45) pass by a wide margin.

Validation

  • MLP fused-vs-unfused parity at the Wan FFN shape (bf16): max relative diff 0.67% (rounding level).
  • Forward smoke test on the patched module: correct shapes, finite output.
  • Fallback verified: non-tanh-GELU activations and guard-failing layers (quantized / no-bias / multi-rank gather / non-CUDA) take the exact reference path.

Checklist

  • Format the code, ran pre-commit on changed files.
  • Verified numerical parity and end-to-end output quality on a real model run.
  • No new dependencies; reuses the existing fused_linear_act helper.
  • (reviewer) confirm desired on multi-GPU TP configs.

CI States

Latest PR Test (Base): ❌ Run #27602521664
Latest PR Test (Extra): ❌ Run #27602534758

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@github-actions github-actions Bot added the diffusion SGLang Diffusion label Jun 16, 2026
The shared diffusion FFN MLP (runtime/layers/mlp.py, used by Wan2.2,
HunyuanVideo, Hunyuan3D, Helios, JoyImage, MOVA, ...) computed
gelu_pytorch_tanh(fc_in(x)) as a standalone GEMM followed by a separate,
bandwidth-bound GELU kernel over the [tokens, mlp_hidden] intermediate.

Route it through the existing cublasLt GELU-epilogue helper linear_gelu_tanh
(already used by flux.py) so the bias-add + tanh-GELU fold into the fc_in GEMM
epilogue, removing the extra kernel launch and the intermediate HBM round-trip.
Only the tanh-approx GELU path is fused; other activations keep the exact
reference path, and the helper guards fall back when not applicable.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@BBuf
BBuf force-pushed the kda/mlp-fused-gelu branch from 16504c6 to 7b1217f Compare June 16, 2026 07:49
@BBuf BBuf added the run-ci CI: run the baseline test suite on this PR label Jun 16, 2026
@BBuf

BBuf commented Jun 16, 2026

Copy link
Copy Markdown
Collaborator Author

(This PR wires the shared MLP FFN; the failing cases here are the models that use it — wan2_*, mova_*. Same root cause as below; the rounding analysis used a representative FFN shape.)

CI consistency failure: root-cause analysis (it's a stale-GT / rounding issue, not a correctness bug)

The *_t2i / video consistency cases that fail here are not caused by an incorrect fusion. The fused linear_gelu_tanh (cublasLt _addmm_activation(use_gelu=True)) is numerically equivalent to — and in fact slightly more accurate than — the unfused proj(x) + F.gelu(approximate="tanh") path. Evidence below (all on B200, fp16/bf16):

1. The cublasLt epilogue is the tanh-approx GELU (not erf):

fp32:  fused-vs-F.gelu(tanh) max_abs = 5.5e-6   fused-vs-F.gelu(erf) = 4.7e-4

2. The fused path is closer to the fp32 ground truth than the unfused reference (Qwen FFN shape, bf16):

mean abs err vs fp32 truth
fused (cublasLt, single round) 6.26e-4
unfused reference (gemm→bf16→gelu→bf16) 9.34e-4
fused vs unfused reference 7.38e-4 ← this is what the consistency check sees

The unfused path rounds the GEMM result to bf16 before GELU (double rounding); the fused path keeps fp32 through bias+GELU and rounds once. So the fused output is the more precise one — but it differs from the stored GT, which was generated with the lower-precision unfused path.

3. Same-seed end-to-end is essentially identical on a normal prompt (Qwen/Qwen-Image, base, seed 0, main vs this PR):

mean_abs_diff = 1.48 (0-255)   luminance SSIM = 0.9968   windowed SSIM = 0.9819

The large CI delta (e.g. qwen_image_t2i: ssim 0.76, mean_abs 23.5) is the chaotic, prompt/seed-dependent amplification of that ~1-ULP per-element difference over the multi-step sampler — on some prompts it stays ~1.5, on others it lands on a visibly different (equally valid) sample. This is inherent to any op that changes bf16 accumulation on a chaotic sampler (it is not specific to cublasLt — a CUTLASS epilogue would be fp32-internal and single-round too, i.e. identical behavior).

Conclusion / proposed resolution: the fusion is correct and faster; the failure is that the consistency GT was baked with the lower-precision double-rounded path. The clean fix is to refresh the ground-truth for the affected cases against the fused output (the same path #28166 effectively took), or to gate the fusion off for cases where the GT cannot be refreshed. Happy to regenerate the GT (SGLANG_GEN_GT=1 via gen_diffusion_ci_outputs.py) for the affected cases if that's the preferred route.

@BBuf

BBuf commented Jun 19, 2026

Copy link
Copy Markdown
Collaborator Author

Closing this PR because the fused GELU path changes diffusion outputs too much; we want to stay closer to the original model behavior.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

diffusion SGLang Diffusion 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