Sglang diffusion modelopt quant

From sgl-project/sglang · View interactive version

Sglang diffusion modelopt quant is an AI agent skill from the GitHub repository sgl-project/sglang. Use when quantizing a diffusion DiT with NVIDIA ModelOpt and making the resulting FP8 or NVFP4 checkpoint loadable, verifiable, and benchmarkable in SGLang Diffusion.

How to use this skill

Skill file

SGLang Diffusion ModelOpt Quant

Overview

Use this skill when the task is to take a diffusion transformer through the full ModelOpt workflow:

This skill owns the ModelOpt-to-SGLang bridge. It is not a generic kernel-tuning skill.

Core Rules

explicit. The current default is FlashInfer TensorRT-LLM

(flashinfer_trtllm); high-resolution Qwen Image can favor

SGLANG_DIFFUSION_FLASHINFER_FP4_GEMM_BACKEND=cutlass, while 1024x1024 can

remain BF16-faster. Benchmark the exact shape instead of assuming one backend

or quantized checkpoint wins.

Read First

Read these sources before changing code:

If you are working on a new model family, inspect the transformer's config and tensor naming before changing the generic converter.

What SGLang Supports Here

This repo now contains:

CODE0

CODE0

CODE0

Validated documentation and CI coverage currently center on these ModelOpt diffusion transformer override families:

Qwen Image Edit, Qwen Image Edit 2511

Treat a new family, a new precision, or a new checkpoint layout as unsupported until it has a documented matrix row and a matching validation story.

Current B200 CI also contains an Ideogram4 NVFP4 native load case

(ideogram4_nvfp4_t2i via Comfy-Org/Ideogram-4). Treat that as source

evidence for an existing NVFP4 path, but do not expand the ModelOpt support

matrix to Ideogram4 unless docs/docs/sglang-diffusion/quantization.mdx is updated with the

exact checkpoint, loader path, quality check, and benchmark scope.

Before writing CLI examples, re-read the active branch's docs/docs/sglang-diffusion/quantization.mdx: FLUX.2 NVFP4 is an official black-forest-labs/* repo rather than a lmsys/* converted repo, and its preferred flag depends on the current documented loader flow. Use --transformer-path for a component override directory with config.json; use --transformer-weights-path when the repo or path should be probed as raw weights.

B200 CI coverage can include loose BF16-vs-quantized quality checks. Inspect the active branch's run_suite.py before assuming they are part of the suite; mainline and feature branches may differ. Those checks are intended to catch blank, corrupted, or obviously divergent images, not exact image parity.

Mainline documentation now tracks thirteen published ModelOpt checkpoints.

Twelve live under lmsys/*; the FLUX.2 NVFP4 raw export remains

black-forest-labs/FLUX.2-dev-NVFP4. Do not use older BBuf/* examples unless

you are explicitly testing a historical branch.

MiniMax-H3 boundary

MiniMax-H3 is current-main evidence for the separate online FP8 path, not a

validated ModelOpt PTQ/export family. Its verified B200/B300 serving recipe

loads the unquantized root checkpoint with --quantization fp8 and preserves

the video/audio patch projections, timestep MLP, and final video/audio heads in

FP32. Do not add H3 to the ModelOpt support matrix or run the generic ModelOpt

converter until an exact H3 export, loader mapping, accuracy check, and

benchmark scope have been validated.

If the user asks for current H3 online quantization, route the command and

quality caveats through sglang-diffusion-performance and the MiniMax-H3

cookbook. Online FP8 is approximate and must be compared against eager

BF16/FP32 for both video and audio; combining it with Cache-DiT compounds two

approximations.

Related PR Watchlist

These related SGLang PRs are useful as ModelOpt diffusion support history.

Re-check the PR state and the active source tree before treating any item as

current behavior, and keep the docs/CI matrix as the support boundary.

Do not expand the validated matrix beyond the documented rows solely because a

related PR exists. Add a row only after the exact checkpoint, loader path,

accuracy check, and benchmark scope are validated on the active branch.

Documentation Maintenance

FP8 Vs NVFP4

FP8 and NVFP4 are not wired into SGLang in exactly the same way.

FP8:

NVFP4:

Important caveat:

Generic Workflow

1. Verify The BF16 Baseline First

Before quantizing anything:

Do not start quantization work until the BF16 path is already healthy.

2. Quantize With Official ModelOpt

Use ModelOpt's official script. Generic template:

python quantize.py \
  --model <model-name> \
  --override-model-path <hf-repo-or-local-model> \
  --model-dtype <Half|BFloat16> \
  --format <fp8|fp4> \
  --batch-size 1 \
  --calib-size <calib-size> \
  --n-steps <calib-steps> \
  --quantize-mha \
  --prompts-file <prompt-file> \
  --quantized-torch-ckpt-save-path <out>/ckpt \
  --hf-ckpt-dir <out>/hf

For current ModelOpt diffusion examples, use --format fp4 for NVFP4 exports.

Do not assume the checked-out ModelOpt version accepts a literal nvfp4 format string unless you verified it locally.

For multi-transformer models:

3. Convert FP8 Exports For SGLang

FP8 requires an extra conversion step:

PYTHONPATH=python python3 -m sglang.multimodal_gen.tools.build_modelopt_fp8_transformer \
  --modelopt-hf-dir <out>/hf \
  --modelopt-backbone-ckpt <out>/ckpt/backbone.pt \
  --base-transformer-dir <base-model-transformer-dir> \
  --output-dir <out>/sglang_transformer \
  --overwrite

What the converter does:

For FLUX.1-dev, the validated fallback set currently keeps these modules in BF16:

Use --model-type flux1 to force that profile, or rely on --model-type auto when the export config identifies FluxTransformer2DModel.

HunyuanVideo uses HunyuanVideoTransformer3DModel, so the validated

HunyuanVideo FP8 fallback preset keeps these modules in BF16:

Use --model-type hunyuan-video to force that profile, or rely on

--model-type auto when the export config identifies

HunyuanVideoTransformer3DModel.

HunyuanVideo ModelOpt exports use diffusers module names that differ from

SGLang runtime names for fused QKV and fused QKV+MLP layers. Keep the

diffusers-to-runtime mapping in build_modelopt_fp8_transformer.py in sync

with runtime/models/dits/hunyuanvideo.py before trusting converted scale

tensors.

Qwen Image and Qwen Image Edit share QwenImageTransformer2DModel, so one

ModelOpt FP8 fallback preset covers both. The validated Qwen Image fallback set

keeps these modules in BF16:

Use --model-type qwen-image to force that profile, or rely on

--model-type auto when the export config identifies

QwenImageTransformer2DModel.

Qwen modulation weights can appear in safetensors as .img_mod.1.weight and

.txt_mod.1.weight. Canonicalize those module names to .img_mod and

.txt_mod before fallback matching.

For Qwen Image FP8, explicit BF16 fallback tensors must be written before

honoring ModelOpt ignored weights. Otherwise converter stats can report a

fallback while the output checkpoint still retains the source FP8 tensor, which

causes severe image-quality regressions.

For FLUX.1-dev NVFP4 model families that need a mixed BF16+NVFP4 checkpoint, build the merged transformer explicitly:

PYTHONPATH=python python3 -m sglang.multimodal_gen.tools.build_modelopt_nvfp4_transformer \
  --base-transformer-dir <base-model-transformer-dir> \
  --modelopt-hf-dir <out>/hf/transformer \
  --output-dir <out>/transformer-mixed \
  --pattern-preset flux1-nvfp4

The validated FLUX.1-dev mixed builder also needs to preserve:

4. Load The Quantized Checkpoint In SGLang

Single-transformer example:

sglang generate \
  --model-path <base-model> \
  --transformer-path <quantized-transformer> \
  --prompt "<prompt>" \
  --seed <seed> \
  --save-output

Multi-transformer example:

sglang generate \
  --model-path <base-model> \
  --transformer-path <quantized-transformer> \
  --transformer-2-path <another-transformer-or-bf16-override> \
  --prompt "<prompt>" \
  --seed <seed> \
  --save-output

Full ModelOpt Diffusers repo example (current Qwen Image NVFP4 path):

sglang generate \
  --model-path lmsys/qwen-image-2512-modelopt-nvfp4-sglang \
  --prompt "<prompt>" \
  --seed <seed> \
  --save-output

Guideline:

as the Qwen Image NVFP4 family; this is different from a transformer-only

override

5. Validate Accuracy

Use two levels of validation.

Reduced deterministic validation:

Tool:

PYTHONPATH=python python3 -m sglang.multimodal_gen.tools.compare_diffusion_trajectory_similarity \
  --model-path <base-model> \
  --model-id <optional-native-model-id> \
  --prompt "<prompt>" \
  --width <w> \
  --height <h> \
  --num-inference-steps <steps> \
  --guidance-scale <cfg> \
  --seed <seed> \
  --candidate-transformer-path <quantized-transformer> \
  --output-json <report.json>

Use --model-id FLUX.1-dev when --model-path points to a local directory but the runtime still needs the native FLUX.1 model registration.

Full-output validation:

6. Benchmark Correctly

Benchmark only when these match between BF16 and quantized:

Only the quantized checkpoint path should differ.

Interpretation rule:

7. Add Model-Specific Fallbacks Only When Needed

If the generic FP8 path fails on a new model family:

Do not turn one validated model quirk into a generic rule unless another family also needs it.

FP8 Offload Constraint

Current diffusion ModelOpt FP8 support requires:

Reason:

Runtime behavior:

Claim Discipline

When documenting results:

Current Code Areas

| File | Role |

| --- | --- |

| runtime/layers/quantization/__init__.py | registers diffusion quant methods |

| runtime/layers/quantization/modelopt_fp8.py | static per-tensor ModelOpt FP8 path used by flat quant_method=modelopt exports |

| runtime/layers/quantization/modelopt_quant.py | ModelOpt FP8 and NVFP4 runtime loading |

| runtime/utils/quantization_utils.py | resolves flat ModelOpt configs and reconstructs NVFP4 config from metadata |

| runtime/loader/transformer_load_utils.py | guards incompatible FP8 offload modes |

| runtime/models/dits/flux_2.py | packed-QKV handling for the packed FLUX.2 NVFP4 family |

| tools/build_modelopt_fp8_transformer.py | Build an SGLang-loadable FP8 transformer from a ModelOpt export |

| tools/build_modelopt_nvfp4_transformer.py | Build mixed BF16+NVFP4 transformer directories when a family needs preserved BF16 layers |

| tools/compare_diffusion_trajectory_similarity.py | reduced deterministic BF16-vs-quantized validation |

| docs/docs/sglang-diffusion/quantization.mdx | public ModelOpt support matrix and CLI examples |

| python/sglang/multimodal_gen/test/server/testcase_configs.py | reusable ModelOpt testcase constants, thresholds, and helpers |

| python/sglang/multimodal_gen/test/server/gpu_cases.py | concrete GPU and B200 ModelOpt CI case lists |

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.