From 23c2a026db0f5d5405f005e8c882492a26fdd851 Mon Sep 17 00:00:00 2001 From: "Zhang Yiyang (SII)" <30491374+CloudRipple@users.noreply.github.com> Date: Thu, 15 Oct 2026 19:23:56 +0800 Subject: [PATCH] [diffusion] model: support MOSS-Image (#44325) Co-authored-by: Mick Qian --- .../diffusion/OpenMOSS/MOSS-Image.mdx | 142 +++ docs/cookbook/diffusion/intro.mdx | 6 + docs/docs.json | 6 + .../snippets/configs/OpenMOSS/moss-image.jsx | 94 ++ docs/src/snippets/diffusion/model-catalog.jsx | 6 + python/sglang/kernels/ops/diffusion/README.md | 38 + .../sglang/kernels/ops/diffusion/__init__.py | 36 + .../activation/situ_softcap_mul_bitexact.py | 201 ++++ .../rmsnorm_cast_before_weight_bitexact.py | 346 ++++++ .../configs/models/dits/moss_image.py | 27 + .../configs/models/encoders/qwen3_5.py | 34 + .../configs/pipeline_configs/flux.py | 7 + .../configs/pipeline_configs/llada_image.py | 13 +- .../configs/pipeline_configs/moss_image.py | 98 ++ .../configs/sample/moss_image.py | 52 + .../runtime/models/dits/moss_image.py | 642 +++++++++++ .../runtime/models/encoders/qwen3_5.py | 392 +++++++ .../runtime/models/schedulers/moss_image.py | 88 ++ .../runtime/pipelines/moss_image.py | 64 + .../model_specific_stages/moss_image.py | 393 +++++++ .../test/unit/test_moss_image.py | 1027 +++++++++++++++++ .../test/unit/test_moss_image_parallel.py | 159 +++ .../test/unit/test_qwen3_5_encoder.py | 272 +++++ .../test/unit/test_text_encoding_cache.py | 106 +- .../kernels/ops/diffusion/test_activation.py | 124 +- .../ops/diffusion/test_model_fast_paths.py | 316 +++++ .../kernels/ops/diffusion/test_norm.py | 188 +++ 27 files changed, 4853 insertions(+), 24 deletions(-) create mode 100644 docs/cookbook/diffusion/OpenMOSS/MOSS-Image.mdx create mode 100644 docs/src/snippets/configs/OpenMOSS/moss-image.jsx create mode 100644 python/sglang/kernels/ops/diffusion/activation/situ_softcap_mul_bitexact.py create mode 100644 python/sglang/kernels/ops/diffusion/norm/rmsnorm_cast_before_weight_bitexact.py create mode 100644 python/sglang/multimodal_gen/configs/models/dits/moss_image.py create mode 100644 python/sglang/multimodal_gen/configs/models/encoders/qwen3_5.py create mode 100644 python/sglang/multimodal_gen/configs/pipeline_configs/moss_image.py create mode 100644 python/sglang/multimodal_gen/configs/sample/moss_image.py create mode 100644 python/sglang/multimodal_gen/runtime/models/dits/moss_image.py create mode 100644 python/sglang/multimodal_gen/runtime/models/encoders/qwen3_5.py create mode 100644 python/sglang/multimodal_gen/runtime/models/schedulers/moss_image.py create mode 100644 python/sglang/multimodal_gen/runtime/pipelines/moss_image.py create mode 100644 python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/moss_image.py create mode 100644 python/sglang/multimodal_gen/test/unit/test_moss_image.py create mode 100644 python/sglang/multimodal_gen/test/unit/test_moss_image_parallel.py create mode 100644 python/sglang/multimodal_gen/test/unit/test_qwen3_5_encoder.py diff --git a/docs/cookbook/diffusion/OpenMOSS/MOSS-Image.mdx b/docs/cookbook/diffusion/OpenMOSS/MOSS-Image.mdx new file mode 100644 index 0000000000..dab0760313 --- /dev/null +++ b/docs/cookbook/diffusion/OpenMOSS/MOSS-Image.mdx @@ -0,0 +1,142 @@ +--- +title: MOSS-Image +description: "Serve MOSS-Image with native Qwen3.5 conditioning, FLUX.2 decoding, and request-level guidance." +tag: NEW +--- + +import { DiffusionModelTags } from '/src/snippets/diffusion/model-tags.jsx'; +import { Deployment } from '/src/snippets/_deployment.jsx'; +import { config } from '/src/snippets/configs/OpenMOSS/moss-image.jsx'; + + + +## 1. Quick start + +Use a [SGLang Diffusion Docker environment](/docs/sglang-diffusion/installation). +Until your image includes this integration, install the model-support PR inside +the container: + +```bash Install model support +pip install 'sglang[diffusion] @ git+https://github.com/sgl-project/sglang.git@refs/pull/44325/head#subdirectory=python' +``` + +You need access to the selected Hugging Face checkpoint. The picker distinguishes +available implementation paths from hardware recipes that have not been measured. + + + +## 2. Model capabilities + +MOSS-Image is a text-to-image model using Qwen3.5 text conditioning and a FLUX.2 +image decoder. Its native pipeline accepts natural-language prompts and structured +layout descriptions through the same Images API. Structured prompts are passed +to the text encoder as text, not interpreted as a separate rendering language. + +Choose Base for reproducing the reference comparison. The SFT identifier resolves +to the same pipeline family, but its checkpoint has not been validated here. +Generation is supported; image editing is not implemented. Keep the scheduler, +guidance recipe, attention backend, and precision fixed when comparing outputs. + +## 3. Guidance and precision + +Defaults are 1024 x 1024, 50 steps, flow shift 5, CFG 3, and an empty negative +prompt. Width and height must be divisible by 16. DiT and text-encoder weights +use BF16; latents, CFG arithmetic, scheduler updates, and VAE decode use FP32. +Autocast is disabled by the pipeline configuration; no extra CLI flag is needed. + +The default two-pass recipe skips unconditional layer 22 inside the +`slg_start=0.01`, `slg_stop=1.0` window. It leaves the first step at full CFG. +Set `uncond_skip_layers=[]` for ordinary CFG. Three-pass SLG adds a skipped +conditional prediction and changes the sampling algorithm; it is not a lossless +speed optimization. + +```json Three-pass request overrides +{ + "guidance_scale": 5, + "uncond_skip_layers": [], + "slg_layers": [22], + "slg_scale": 3, + "slg_start": 0.01, + "slg_stop": 1.0 +} +``` + +For the official pipeline's start-at-zero behavior, explicitly set +`slg_start=0.0` and `uncond_skip_layers=[22]`, including when using three-pass +SLG. Guidance fields are request-scoped and do not require a server restart. + +`quality=exact` preserves the native rounding policy, but does not make different +attention backends identical. `quality=lossless` can additionally enable shared +VAE fast paths. Compare each configuration against its matched reference rather +than treating either quality name as a cross-backend guarantee. + +## 4. Deployment features + +Component and layerwise offload reuse the standard residency manager. Start with +Auto placement; use `--component-residency all=resident` only when weights and +request activations fit. Offload saves VRAM at the cost of host RAM and transfers. +The text encoder also supports layerwise offload through its native layer list. + +Sequence parallelism uses the shared shard/pad/gather helpers and USP attention; +the text refiner stays replicated. Ulysses degree must divide the 24 DiT heads. +Ring requires a backend exposing softmax LSE, such as FlashAttention. CFG +parallelism uses the shared branch dispatcher, including the optional third SLG +branch. Multi-GPU checkpoint recipes remain experimental until measured on the +selected hardware and workload. + +TP, Cache-DiT, quantization, LoRA, compilation, and breakable CUDA graphs do not +have validated recipes in this integration. Do not assume that a framework-wide +flag establishes model support. See [performance optimization](/docs/sglang-diffusion/performance-optimization) +for the shared feature contracts. + +## 5. Batching + +Dynamic batching uses the shared scheduler and is opt-in through the maximum +batch size. For example, on an H200: + +```bash +sglang serve --model-path OpenMOSS-Team/MOSS-Image-Base \ + --batching-max-size 4 --batching-delay-ms 20 +``` + +Compatible requests may have different prompts and seeds; resolution, step count, +negative prompt, and guidance settings must match. The maximum size limits total +outputs, not just HTTP requests. A request can also use `n` to generate multiple +images from one prompt. Higher batch sizes need more activation VRAM and can +increase individual-request latency; the default remains one output at a time. + +At `quality=lossless` (the default) or `high`, the DiT groups samples by their actual text length +and restores their original output order. Different lengths run in separate +groups without padding or switching attention backends. Empty negative prompts +can share one group even when positive prompts differ. The text refiner retains +per-sample GEMM shapes to reduce numerical drift. Batched DiT GEMM shapes can +change floating-point rounding, which denoising can amplify into visible changes; +cross-batch-size pixel identity is not guaranteed. `quality=exact` retains the +per-sample DiT path instead. Neither mode promises batch-invariant text encoding +or VAE decoding. Benchmark your prompts and batch sizes before deployment. + +On one H200, four concurrent requests with different prompts and seeds 42-45 measured +the following warmed HTTP throughput. Both paths use BF16 DiT/text encoder, +FP32 VAE, default attention backends, `quality=lossless`, resident components, +maximum batch size 4, and a 20 ms batching delay. Loading is excluded; PNG encoding, +transfer, and client decoding are included. Results average three measured waves +at 512 pixels and two at 1024, after one warmup wave per resolution. +The environment used PyTorch 2.14.1+cu130, Transformers 5.19.0, and eager execution. + +| Workload | Per-sample DiT | Grouped DiT | Throughput Change | +| --- | --- | --- | --- | +| 512 x 512, 8 steps | 2.51 images/s | 2.92 images/s | +16% | +| 1024 x 1024, 20 steps | 0.293 images/s | 0.296 images/s | Essentially unchanged | + +At 512 pixels, agreement with the per-sample DiT path ranged from 28.3 to 46.2 dB +PSNR and 0.939 to 0.996 SSIM. All four 1024-pixel outputs were pixel-identical. +These measure output agreement, not semantic quality or a guarantee for other +prompts. Visible differences remain possible; use `quality=exact` +to retain per-sample DiT execution. Fixed-batch repeated requests are checked +separately from cross-batch agreement. + +## 6. Run in ComfyUI + +import { ComfyUISupport } from '/src/snippets/diffusion/comfyui-support.jsx'; + + diff --git a/docs/cookbook/diffusion/intro.mdx b/docs/cookbook/diffusion/intro.mdx index 037efc3a29..1030a87869 100644 --- a/docs/cookbook/diffusion/intro.mdx +++ b/docs/cookbook/diffusion/intro.mdx @@ -128,6 +128,12 @@ Video models denoise a bounded latent video sequence for each request. Use these href="/cookbook/diffusion/MiniMax/MiniMax-H3" img="/cards/logos/minimax.png" /> + ({ tp_size: 1, ulysses_degree: Number(s.gpus_per_node), ring_degree: 1 }), + validateTopology: (s, t) => { + const errors = []; + if (![t.tp_size, t.ulysses_degree, t.ring_degree].every((n) => Number.isInteger(n) && n > 0)) errors.push("Parallel degrees must be positive integers."); + if (t.tp_size !== 1) errors.push("Tensor parallelism is not implemented for this model."); + if (Number(s.nodes) !== 1 || Number(s.gpus_per_node) !== t.tp_size * t.ulysses_degree * t.ring_degree) errors.push("GPU count must match TP times Ulysses times Ring on one node."); + if (24 % t.ulysses_degree) errors.push("Ulysses degree must divide the 24 attention heads."); + if (t.ring_degree > 1 && s.attention === "sdpa") errors.push("Ring requires an LSE-capable backend, not Torch SDPA."); + return errors; + }, + }, + resolveDeployment: (s) => { + const resource = config.commandBuilder.resource; + const topology = s.topology_mode === "manual" + ? { tp_size: Number(s.tp_size), ulysses_degree: Number(s.ulysses_degree), ring_degree: Number(s.ring_degree) } + : resource.autoTopology(s); + const errors = resource.validateTopology(s, topology); + const flags = ["--model-path {{MODEL_NAME}}"]; + if (Number(s.gpus_per_node) > 1) flags.push(`--num-gpus ${s.gpus_per_node}`, "--tp-size 1", `--ulysses-degree ${topology.ulysses_degree}`, `--ring-degree ${topology.ring_degree}`); + flags.push("--host {{HOST_IP}}", "--port {{PORT}}"); + return { + match: { hw: s.hw }, nnodes: 1, verified: false, flags, + builder: { + topology, errors, + topologySummary: `TP ${topology.tp_size}, Ulysses ${topology.ulysses_degree}, Ring ${topology.ring_degree}`, + warnings: ["This exact hardware and workload recipe is not end-to-end verified."], + verification: { serve: "unverified", request: "unverified" }, + }, + }; + }, + }, + modelNames: { default: "OpenMOSS-Team/MOSS-Image-Base" }, + placeholders: { + HOST_IP: { target: "command", label: "Bind host", default: "0.0.0.0" }, + PORT: { target: "command", label: "Bind port", default: "30000" }, + CURL_HOST: { target: "curl", label: "Server host", default: "localhost" }, + CURL_PORT: { target: "curl", label: "Server port", default: "30000" }, + }, + curl: (s) => { + const guidance = s.guidance === "ordinary" ? { uncond_skip_layers: [] } + : s.guidance === "three" ? { guidance_scale: 5, uncond_skip_layers: [], slg_layers: [22], slg_scale: 3 } : {}; + return `curl --fail-with-body http://{{CURL_HOST}}:{{CURL_PORT}}/v1/images/generations \\ + -H 'Content-Type: application/json' \\ + -d '${JSON.stringify({ model: "{{MODEL_NAME}}", prompt: "A quiet coastal town at sunrise, cinematic photography", size: "1024x1024", seed: 42, quality: s.quality, response_format: "b64_json", output_format: "png", ...guidance }, null, 2)}'`; + }, + cells: [], +}; diff --git a/docs/src/snippets/diffusion/model-catalog.jsx b/docs/src/snippets/diffusion/model-catalog.jsx index fd1d5a2c3c..55e3115a19 100644 --- a/docs/src/snippets/diffusion/model-catalog.jsx +++ b/docs/src/snippets/diffusion/model-catalog.jsx @@ -3,6 +3,12 @@ export const DiffusionModelCatalog = ({ category }) => { const MODEL_CATALOG = { image: [ + { + name: "MOSS-Image", + modelIds: ["OpenMOSS-Team/MOSS-Image-Base", "OpenMOSS-Team/MOSS-Image-SFT"], + cookbook: "/cookbook/diffusion/OpenMOSS/MOSS-Image", + note: "Base is the reference checkpoint; SFT checkpoint validation is pending.", + }, { name: "HunyuanImage-3.0", modelIds: ["tencent/HunyuanImage-3.0", "tencent/HunyuanImage-3.0-Instruct"], diff --git a/python/sglang/kernels/ops/diffusion/README.md b/python/sglang/kernels/ops/diffusion/README.md index 8eb3f7f0a5..c08abc12b1 100644 --- a/python/sglang/kernels/ops/diffusion/README.md +++ b/python/sglang/kernels/ops/diffusion/README.md @@ -125,6 +125,7 @@ Several norms look interchangeable and are not. Start here. | Entry point | Backend | Contract | Applies to | |---|---|---|---| +| `rmsnorm_cast_before_weight_modulate_bitexact` | Triton | ATen-ordered FP32 reduction and exact BF16 modulation | MOSS-Image BSC, width 3072 | | `fuse_scale_shift_kernel` | Triton | close | contiguous BLC; scalar/row/token modulation plus causal-video `[B, F, 1, C]`, using a static capped power-of-two tile to avoid request-time autotuning | | `fused_rmsnorm_scale_shift_bitexact` | Triton | bit-exact vs flashinfer CuTe RMSNorm + aten modulate | bf16, contiguous rows, `H == 64 * threads_per_row` | | `fused_scale_residual_rmsnorm_scale_shift_bitexact` | Triton | bit-exact, incl. the preceding residual-gate add | as above | @@ -139,6 +140,7 @@ Several norms look interchangeable and are not. Start here. | Entry point | Backend | Contract | Applies to | |---|---|---|---| +| `rmsnorm_cast_before_weight_bitexact` | Triton / aten | FP32 reduction, BF16 round before learned scale | MOSS-Image token and head RMSNorm | | `triton_group_norm_silu` / `apply_group_norm_silu` | Triton | close | NCHW-contiguous, any channels-per-group, always applies SiLU | | `group_norm_silu_4d` / `group_norm_silu_rows` | Triton | close | **channels_last only**; power-of-two `C <= 2048`; optional SiLU. This is what lets a VAE decoder run channels_last end-to-end with no `nchwToNhwc` | | `wan_rmsnorm_silu` | Triton | close | dense `channels_last_3d` 5D (`stride(C) == 1`), Wan VAE channel-first RMSNorm + SiLU; `[ROWS, C]` tiles (~3 TB/s at C = 96); optional `conv_bias` folds the preceding conv's bias with aten `add_` arithmetic | @@ -165,6 +167,12 @@ for coalesced residual reads and output writes. The contiguous layouts use JIT CUDA. Do not insert a `.contiguous()` to reach that path: it adds a full tensor copy at each residual site. +### Activations + +| Entry point | Backend | Contract | Applies to | +|---|---|---|---| +| `fused_situ_softcap_mul_bitexact` | Triton | bit-exact vs MOSSImage's nine-op BF16 SiTU chain | CUDA BF16 `[B, S, D]`, dense rows or strided halves of a packed FFN projection; first-use verification in the model wrapper | + ### RoPE / QK-norm | Entry point | Backend | Contract | @@ -174,6 +182,7 @@ tensor copy at each residual site. | `fused_qknorm_rope_out_of_place` | JIT CUDA | as above, bit-equal to the in-place kernel; reads strided q/k and writes contiguous copies, inputs untouched (VDN-H3 keeps the raw q/k for its linear branch) | | `try_fused_flux2_qkv_epilogue` | KDA (JIT CUDA) | bit-exact vs the selected BF16 chain | FLUX.2 QK RMSNorm + RoPE + joint QKV packing | | `try_fused_qwen_qkv_epilogue` | JIT CUDA | bit-exact vs the selected BF16 chain | Qwen-Image QK RMSNorm + RoPE + joint QKV writes; SM90+ | +| `rmsnorm_cast_before_weight_rope_bitexact` | Triton | ATen-ordered RMSNorm plus exact BF16 rotate-half RoPE, MOSS-Image width 128 | | `fused_rope_rotate_half_bitexact` | Triton | bit-exact (elementwise only) | | `fused_complex_rope` | Triton | preserves CUDA complex64 multiply rounding for contiguous BSHD inputs; Qwen-Image 2.1 verifies its first call against eager | | `rmsnorm_preserve_reduction` | Triton + aten | preserves the FP32 mean reduction and cast-before-weight rounding; fuses only pointwise work for FP16/BF16 inputs and materializes strided inputs as contiguous; Qwen-Image 2.1 verifies its first call | @@ -243,6 +252,35 @@ once they run channels_last end-to-end. 704p/121f *and* hands six strided slices downstream, whose `.contiguous()` calls copy each one again. +### BF16 activation and normalization contracts + +MOSS-Image's `fused_situ_softcap_mul_bitexact` uses exact BF16 lookup tables for inputs with +at least 65536 elements. The two factors are evaluated with the live aten CUDA +formula for every BF16 encoding, preserving each rounding boundary; the fused +kernel then looks up both factors and multiplies them. Tables use 256 KiB per +device and remain alive for captured graphs. Initialization finishes before +publication to other streams. Small inputs and captures without initialized +tables use the direct fused formula. This is an exact path, subject to the first-use bit-exact check. + +MOSS-Image uses `rmsnorm_cast_before_weight_bitexact` for contiguous CUDA BF16 token and +per-head tensors. Widths 3072 and 128 with at least 16 rows and fewer than +`2**29` elements use one kernel that reproduces ATen's vectorized FP32 mean +reduction order; other shapes retain ATen's mean with fused pointwise +operations around it (three kernels). +Both round the normalized value to BF16 **before** multiplying by the learned +weight. The model verifies each width/reduction regime on first sight and +falls back on unsupported layouts or a mismatch. Unverified regimes use the +native path during compilation or CUDA graph capture. + +MOSS-Image also uses `rmsnorm_cast_before_weight_modulate_bitexact` for width-3072 BSC +activations and `rmsnorm_cast_before_weight_rope_bitexact` for width-128 BSHD heads. +Both retain the same ordered reduction and BF16 round-before-gamma contract, +then preserve each modulation or rotate-half rounding boundary. Their guards +require contiguous CUDA BF16 tensors, at least 16 normalization rows, and +fewer than `2**29` elements. Modulation tensors may have a strided batch axis, +as produced by `unbind`, with contiguous channels. Model wrappers verify against the existing chain +before enabling either fusion and retain the separate operations on fallback. + ## What is not a kernel `sites/` rewrites `nn.Module` trees (mark / mount / unmount) and `ext/` builds diff --git a/python/sglang/kernels/ops/diffusion/__init__.py b/python/sglang/kernels/ops/diffusion/__init__.py index 3b625fd89b..30555525cf 100644 --- a/python/sglang/kernels/ops/diffusion/__init__.py +++ b/python/sglang/kernels/ops/diffusion/__init__.py @@ -77,6 +77,27 @@ _SPECS: tuple[tuple[str, KernelBackend, str, frozenset, str], ...] = ( _CUDA, "BF16 tanh GELU plus channel concatenation.", ), + ( + "diffusion.rmsnorm_cast_before_weight", + KernelBackend.TRITON, + "norm.rmsnorm_cast_before_weight_bitexact:rmsnorm_cast_before_weight_bitexact", + _CUDA, + "MOSSImage RMSNorm with ATen-ordered reduction and BF16 rounding before gamma.", + ), + ( + "diffusion.rmsnorm_cast_before_weight_modulate", + KernelBackend.TRITON, + "norm.rmsnorm_cast_before_weight_bitexact:rmsnorm_cast_before_weight_modulate_bitexact", + _CUDA, + "MOSSImage ATen-ordered RMSNorm with exact BF16 modulation.", + ), + ( + "diffusion.rmsnorm_cast_before_weight_rope", + KernelBackend.TRITON, + "norm.rmsnorm_cast_before_weight_bitexact:rmsnorm_cast_before_weight_rope_bitexact", + _CUDA, + "MOSSImage ATen-ordered head RMSNorm with exact rotate-half RoPE.", + ), ( "diffusion.apply_group_norm_silu", KernelBackend.TRITON, @@ -385,6 +406,13 @@ _SPECS: tuple[tuple[str, KernelBackend, str, frozenset, str], ...] = ( _CUDA, "Bit-exact silu(a) * b for split-projection SwiGLU.", ), + ( + "diffusion.situ_softcap_mul", + KernelBackend.TRITON, + "activation.situ_softcap_mul_bitexact:fused_situ_softcap_mul_bitexact", + _CUDA, + "Bit-exact bounded SiTU for MOSSImage FFN projections.", + ), ( "diffusion.bias_silu", KernelBackend.TRITON, @@ -696,6 +724,12 @@ _EXPORTS: dict[str, str] = { "try_fused_scale_residual_norm_scale_shift_fp8": "sglang.kernels.kda_kernels.norm_scale_shift_jit", "validate_scale_shift": "norm.scale_residual_norm_cutedsl", "try_fused_scale_residual_norm_scale_shift_nvfp4": "sglang.kernels.kda_kernels.norm_scale_shift_jit", + "can_use_rmsnorm_cast_before_weight": "norm.rmsnorm_cast_before_weight_bitexact", + "can_use_rmsnorm_cast_before_weight_modulate": "norm.rmsnorm_cast_before_weight_bitexact", + "can_use_rmsnorm_cast_before_weight_rope": "norm.rmsnorm_cast_before_weight_bitexact", + "rmsnorm_cast_before_weight_bitexact": "norm.rmsnorm_cast_before_weight_bitexact", + "rmsnorm_cast_before_weight_modulate_bitexact": "norm.rmsnorm_cast_before_weight_bitexact", + "rmsnorm_cast_before_weight_rope_bitexact": "norm.rmsnorm_cast_before_weight_bitexact", "can_use_wan_norm_silu_post": "norm.wan_norm_silu_post", "wan_norm_silu_post": "norm.wan_norm_silu_post", "can_use_wan_rmsnorm_silu": "norm.wan_rmsnorm_silu_triton", @@ -750,6 +784,8 @@ _EXPORTS: dict[str, str] = { "fused_bias_silu": "activation.sana_conv_post_triton", "fused_packed_silu_mul_bitexact": "activation.silu_mul_bitexact", "fused_silu_mul_bitexact": "activation.silu_mul_bitexact", + "can_use_fused_situ_softcap_mul": "activation.situ_softcap_mul_bitexact", + "fused_situ_softcap_mul_bitexact": "activation.situ_softcap_mul_bitexact", # Diffusion attention kernels "cam_scan_bidi_chunkwise": "attention.sana_wm_gdn_chunkwise_triton", "fused_bigdn_func": "attention.sana_wm_gdn_triton", diff --git a/python/sglang/kernels/ops/diffusion/activation/situ_softcap_mul_bitexact.py b/python/sglang/kernels/ops/diffusion/activation/situ_softcap_mul_bitexact.py new file mode 100644 index 0000000000..d5dc683cf9 --- /dev/null +++ b/python/sglang/kernels/ops/diffusion/activation/situ_softcap_mul_bitexact.py @@ -0,0 +1,201 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Fuse MOSSImage's bounded SiTU activation, preserving each BF16 rounding. + +The eager formula is ``4*tanh(gate/4)*sigmoid(gate) * 25*tanh(hidden/25)``. +Each of its nine elementwise operations rounds to BF16. The operands may be +separate projections or strided halves of one packed FFN projection. +Large inputs use exact per-device tables for the two independent factors; +small inputs and cold CUDA graph captures retain the direct fused formula. + +Verified on H200 for dense and packed rows with widths 128 and 8192, +including [1, 6620, 8192], [1, 4109, 8192], [1, 2524, 8192] and +[2, 65, 8192], plus every BF16 encoding of each operand. +""" + +from __future__ import annotations + +import threading + +import torch +import triton +import triton.language as tl +from triton.language.extra.cuda import libdevice + +from sglang.kernels.numerics import ( + mul_rn_f32, + round_bf16_to_fp32, +) +from sglang.kernels.ops.diffusion.common.platform import is_cuda +from sglang.srt.utils.custom_op import register_custom_op + +_SITU_TABLES: dict[torch.device, tuple[torch.Tensor, torch.Tensor]] = {} +_SITU_TABLES_LOCK = threading.Lock() + + +def _get_situ_tables(device): + tables = _SITU_TABLES.get(device) + if tables is not None: + return tables + if torch.compiler.is_compiling() or torch.cuda.is_current_stream_capturing(): + return None + with _SITU_TABLES_LOCK: + tables = _SITU_TABLES.get(device) + if tables is None: + # Enumerate bit patterns, not evenly spaced floating-point values. + # Generate with the live aten CUDA formula, including BF16 rounding. + values = ( + torch.arange(65536, device=device, dtype=torch.int32) + .to(torch.int16) + .view(torch.bfloat16) + ) + tables = ( + 25.0 * torch.tanh(values / 25.0), + (4.0 * torch.tanh(values / 4.0)) * torch.sigmoid(values), + ) + # Publish only complete tables so subsequent streams need no wait. + # Keep their 256 KiB of storage for the process lifetime: captured + # graphs may retain these addresses after the originating request. + torch.cuda.current_stream(device).synchronize() + _SITU_TABLES[device] = tables + return tables + + +@triton.jit +def _situ_lookup_kernel( + out_ptr, + hidden_ptr, + gate_ptr, + hidden_table, + gate_table, + numel, + hidden_row_stride, + gate_row_stride, + DIM: tl.constexpr, + BLOCK: tl.constexpr, +): + offsets = tl.program_id(0).to(tl.int64) * BLOCK + tl.arange(0, BLOCK) + mask = offsets < numel + rows, cols = offsets // DIM, offsets % DIM + hidden = tl.load(hidden_ptr + rows * hidden_row_stride + cols, mask, other=0).to( + tl.uint16, bitcast=True + ) + gate = tl.load(gate_ptr + rows * gate_row_stride + cols, mask, other=0).to( + tl.uint16, bitcast=True + ) + hidden_factor = tl.load(hidden_table + hidden.to(tl.int32)).to(tl.float32) + gate_factor = tl.load(gate_table + gate.to(tl.int32)).to(tl.float32) + tl.store(out_ptr + offsets, mul_rn_f32(gate_factor, hidden_factor), mask) + + +@triton.jit +def _tanh_bf16(value): + # tanh(x) rounds back to x in this range. Avoid libdevice's FTZ path so + # BF16 subnormals retain the same value as aten's tanh kernel. + return round_bf16_to_fp32( + tl.where(tl.abs(value) < 1.0e-4, value, libdevice.tanh(value)) + ) + + +@triton.jit +def _situ_kernel( + out_ptr, + hidden_ptr, + gate_ptr, + numel, + hidden_row_stride, + gate_row_stride, + DIM: tl.constexpr, + BLOCK: tl.constexpr, +): + offsets = tl.program_id(0).to(tl.int64) * BLOCK + tl.arange(0, BLOCK) + mask = offsets < numel + rows, cols = offsets // DIM, offsets % DIM + hidden = tl.load( + hidden_ptr + rows * hidden_row_stride + cols, mask=mask, other=0.0 + ).to(tl.float32) + gate = tl.load(gate_ptr + rows * gate_row_stride + cols, mask=mask, other=0.0).to( + tl.float32 + ) + + # Explicit non-FTZ multiplies also preserve subnormal intermediate values. + gate_quarter = round_bf16_to_fp32(mul_rn_f32(gate, 0.25)) + gate_tanh = _tanh_bf16(gate_quarter) + gate_scaled = round_bf16_to_fp32(mul_rn_f32(gate_tanh, 4.0)) + gate_sigmoid = round_bf16_to_fp32(tl.sigmoid(gate)) + gate_factor = round_bf16_to_fp32(mul_rn_f32(gate_scaled, gate_sigmoid)) + # This reciprocal and BF16 boundary match the eager scalar division. + hidden_scaled = round_bf16_to_fp32(mul_rn_f32(hidden, 1.0 / 25.0)) + hidden_factor = round_bf16_to_fp32(mul_rn_f32(25.0, _tanh_bf16(hidden_scaled))) + result = mul_rn_f32(gate_factor, hidden_factor) + # The integer BF16 rounding helper is for finite values; preserve NaNs. + result = tl.where((hidden == hidden) & (gate == gate), result, float("nan")) + tl.store(out_ptr + offsets, result, mask=mask) + + +def can_use_fused_situ_softcap_mul(*, device: torch.device, dtype: torch.dtype) -> bool: + return is_cuda() and device.type == "cuda" and dtype == torch.bfloat16 + + +def _valid_situ_inputs(hidden: torch.Tensor, gate: torch.Tensor) -> bool: + return ( + is_cuda() + and hidden.is_cuda + and gate.is_cuda + and hidden.device == gate.device + and hidden.dtype == gate.dtype == torch.bfloat16 + and hidden.shape == gate.shape + and hidden.ndim == 3 + and hidden.numel() > 0 + and hidden.stride(-1) == gate.stride(-1) == 1 + and hidden.stride(0) == hidden.shape[1] * hidden.stride(1) + and gate.stride(0) == gate.shape[1] * gate.stride(1) + and hidden.stride(1) >= hidden.shape[2] + and gate.stride(1) >= gate.shape[2] + ) + + +def _fake_situ(hidden: torch.Tensor, gate: torch.Tensor) -> torch.Tensor: + return torch.empty_like(hidden, memory_format=torch.contiguous_format) + + +@register_custom_op( + op_name="triton_fused_situ_softcap_mul_bitexact", + mutates_args=[], + fake_impl=_fake_situ, +) +def fused_situ_softcap_mul_bitexact( + hidden: torch.Tensor, gate: torch.Tensor +) -> torch.Tensor: + """Evaluate SiTU for BF16 ``[B, S, D]`` operands with packed or dense rows.""" + if not _valid_situ_inputs(hidden, gate): + raise ValueError("SiTU requires matching CUDA BF16 tensors with dense rows.") + out = torch.empty_like(hidden, memory_format=torch.contiguous_format) + with torch.cuda.device(hidden.device): + tables = _get_situ_tables(hidden.device) if hidden.numel() >= 65536 else None + if tables is not None: + _situ_lookup_kernel[(triton.cdiv(hidden.numel(), 1024),)]( + out, + hidden, + gate, + *tables, + hidden.numel(), + hidden.stride(1), + gate.stride(1), + DIM=hidden.shape[-1], + BLOCK=1024, + num_warps=4, + enable_fp_fusion=False, + ) + return out + _situ_kernel[(triton.cdiv(hidden.numel(), 1024),)]( + out, + hidden, + gate, + hidden.numel(), + hidden.stride(1), + gate.stride(1), + DIM=hidden.shape[-1], + BLOCK=1024, + enable_fp_fusion=False, + ) + return out diff --git a/python/sglang/kernels/ops/diffusion/norm/rmsnorm_cast_before_weight_bitexact.py b/python/sglang/kernels/ops/diffusion/norm/rmsnorm_cast_before_weight_bitexact.py new file mode 100644 index 0000000000..ca13738279 --- /dev/null +++ b/python/sglang/kernels/ops/diffusion/norm/rmsnorm_cast_before_weight_bitexact.py @@ -0,0 +1,346 @@ +# SPDX-License-Identifier: Apache-2.0 +"""MOSSImage RMSNorm: FP32 statistics, BF16 rounding before learned scale. + +For widths 128/3072 with at least 16 rows, reproduce ATen's vectorized FP32 +mean reduction in one kernel. CUDA Reduce.cuh uses 32 lanes, four accumulators +per lane, sequential fragment accumulation, then descending shuffle offsets. +Other shapes retain ATen's mean with fused pointwise operations around it. +Callers must verify against the live eager chain for each reduction regime. +""" + +import torch +import triton +import triton.language as tl + +from sglang.kernels.numerics import cuda_rsqrtf, mul_rn_f32 +from sglang.kernels.ops.diffusion.common.platform import is_cuda +from sglang.srt.utils.custom_op import register_custom_op + + +@triton.jit +def _fold_halves(values, ROWS: tl.constexpr, WIDTH: tl.constexpr): + # Match shfl_down: first half + second half, largest offset first. + lo, hi = tl.split(tl.permute(tl.reshape(values, (ROWS, 2, WIDTH)), (0, 2, 1))) + return lo + hi + + +@triton.jit +def _ordered_rstd( + X, + M: tl.constexpr, + DIM: tl.constexpr, + ROWS: tl.constexpr, +): + rows = tl.program_id(0).to(tl.int64) * ROWS + tl.arange(0, ROWS) + lanes = tl.arange(0, 32) + parts = tl.arange(0, 4) + acc = tl.full((ROWS, 32, 4), 0, tl.float32) + # ATen vectorizes the already-rounded FP32 squares, four per lane. + # Unroll to schedule loads ahead of the dependent accumulation chain. + for chunk in tl.static_range(DIM // 128): + cols = chunk * 128 + lanes[:, None] * 4 + parts[None, :] + x = tl.load( + X + rows[:, None, None] * DIM + cols[None, :, :], rows[:, None, None] < M, 0 + ).to(tl.float32) + acc = acc + mul_rn_f32(x, x) + even, odd = tl.split(tl.reshape(acc, (ROWS, 32, 2, 2))) + a, c = tl.split(even) + b, d = tl.split(odd) + total = ((a + b) + c) + d + total = _fold_halves(total, ROWS, 16) + total = _fold_halves(total, ROWS, 8) + total = _fold_halves(total, ROWS, 4) + total = _fold_halves(total, ROWS, 2) + total = _fold_halves(total, ROWS, 1) + mean = mul_rn_f32(tl.reshape(total, (ROWS,)), 1.0 / DIM) + return cuda_rsqrtf(mean + 1e-6) + + +@triton.jit +def _ordered_norm_kernel( + X, + Weight, + Out, + M: tl.constexpr, + DIM: tl.constexpr, + ROWS: tl.constexpr, + BLOCK: tl.constexpr, +): + rows = tl.program_id(0).to(tl.int64) * ROWS + tl.arange(0, ROWS) + rstd = _ordered_rstd(X, M, DIM, ROWS) + + cols = tl.arange(0, BLOCK) + mask = (rows[:, None] < M) & (cols[None, :] < DIM) + x = tl.load(X + rows[:, None] * DIM + cols[None, :], mask, 0).to(tl.float32) + weight = tl.load(Weight + cols, cols < DIM, 0).to(tl.float32) + normalized = mul_rn_f32(x, rstd[:, None]).to(tl.bfloat16).to(tl.float32) + tl.store( + Out + rows[:, None] * DIM + cols[None, :], + mul_rn_f32(normalized, weight[None, :]), + mask, + ) + + +@triton.jit +def _norm_modulate_kernel( + X, + Weight, + Scale, + Shift, + Out, + M: tl.constexpr, + SEQ: tl.constexpr, + SCALE_STRIDE: tl.constexpr, + SHIFT_STRIDE: tl.constexpr, +): + row = tl.program_id(0).to(tl.int64) + cols = tl.arange(0, 4096) + mask = cols < 3072 + rstd = _ordered_rstd(X, M, 3072, 1) + x = tl.load(X + row * 3072 + cols, mask, 0).to(tl.float32) + weight = tl.load(Weight + cols, mask, 0).to(tl.float32) + norm = mul_rn_f32(x, tl.sum(rstd, 0)).to(tl.bfloat16).to(tl.float32) + norm = mul_rn_f32(norm, weight).to(tl.bfloat16).to(tl.float32) + scale = tl.load(Scale + (row // SEQ) * SCALE_STRIDE + cols, mask, 0).to(tl.float32) + shift = tl.load(Shift + (row // SEQ) * SHIFT_STRIDE + cols, mask, 0).to(tl.float32) + factor = (1.0 + scale).to(tl.bfloat16).to(tl.float32) + scaled = mul_rn_f32(norm, factor).to(tl.bfloat16).to(tl.float32) + tl.store(Out + row * 3072 + cols, scaled + shift, mask) + + +@triton.jit +def _norm_rope_kernel(X, Weight, Cos, Sin, Out, M: tl.constexpr, HEADS: tl.constexpr): + rows = tl.program_id(0).to(tl.int64) * 16 + tl.arange(0, 16) + cols = tl.arange(0, 128) + mask = rows[:, None] < M + rstd = _ordered_rstd(X, M, 128, 16) + x = tl.load(X + rows[:, None] * 128 + cols[None, :], mask, 0).to(tl.float32) + weight = tl.load(Weight + cols).to(tl.float32) + norm = mul_rn_f32(x, rstd[:, None]).to(tl.bfloat16).to(tl.float32) + norm = mul_rn_f32(norm, weight[None, :]).to(tl.bfloat16).to(tl.float32) + lo, hi = tl.split(tl.permute(tl.reshape(norm, (16, 2, 64)), (0, 2, 1))) + half_cols = tl.arange(0, 64)[None, :] + rope_offsets = (rows // HEADS)[:, None] * 128 + half_cols + cos_lo = tl.load(Cos + rope_offsets, mask, 0).to(tl.float32) + cos_hi = tl.load(Cos + rope_offsets + 64, mask, 0).to(tl.float32) + sin_lo = tl.load(Sin + rope_offsets, mask, 0).to(tl.float32) + sin_hi = tl.load(Sin + rope_offsets + 64, mask, 0).to(tl.float32) + out_lo = mul_rn_f32(lo, cos_lo).to(tl.bfloat16).to(tl.float32) + mul_rn_f32( + -hi, sin_lo + ).to(tl.bfloat16).to(tl.float32) + out_hi = mul_rn_f32(hi, cos_hi).to(tl.bfloat16).to(tl.float32) + mul_rn_f32( + lo, sin_hi + ).to(tl.bfloat16).to(tl.float32) + tl.store(Out + rows[:, None] * 128 + half_cols, out_lo, mask) + tl.store(Out + rows[:, None] * 128 + half_cols + 64, out_hi, mask) + + +@triton.jit +def _square_kernel(X, Squared, N: tl.constexpr, BLOCK: tl.constexpr): + offsets = tl.program_id(0).to(tl.int64) * BLOCK + tl.arange(0, BLOCK) + x = tl.load(X + offsets, offsets < N, 0).to(tl.float32) + tl.store(Squared + offsets, mul_rn_f32(x, x), offsets < N) + + +@triton.jit +def _normalize_kernel( + X, Mean, Weight, Out, N: tl.constexpr, DIM: tl.constexpr, BLOCK: tl.constexpr +): + offsets = tl.program_id(0).to(tl.int64) * BLOCK + tl.arange(0, BLOCK) + mask = offsets < N + x = tl.load(X + offsets, mask, 0).to(tl.float32) + mean = tl.load(Mean + offsets // DIM, mask, 0) + weight = tl.load(Weight + offsets % DIM, mask, 0).to(tl.float32) + normalized = mul_rn_f32(x, cuda_rsqrtf(mean + 1e-6)) + # This rounding precedes gamma in MOSSImage, unlike conventional RMSNorm. + normalized = normalized.to(tl.bfloat16).to(tl.float32) + tl.store(Out + offsets, mul_rn_f32(normalized, weight), mask) + + +def can_use_rmsnorm_cast_before_weight( + *, + device: torch.device, + dtype: torch.dtype, + contiguous: bool = True, + eps: float = 1e-6, +) -> bool: + return ( + is_cuda() + and device.type == "cuda" + and dtype == torch.bfloat16 + and eps == 1e-6 + and contiguous + ) + + +def can_use_rmsnorm_cast_before_weight_modulate( + *, device: torch.device, dtype: torch.dtype, dim: int, rows: int +) -> bool: + return ( + can_use_rmsnorm_cast_before_weight(device=device, dtype=dtype) + and dim == 3072 + and rows >= 16 + and rows * dim < 2**29 + ) + + +def can_use_rmsnorm_cast_before_weight_rope( + *, device: torch.device, dtype: torch.dtype, dim: int, rows: int +) -> bool: + return ( + can_use_rmsnorm_cast_before_weight(device=device, dtype=dtype) + and dim == 128 + and rows >= 16 + and rows * dim < 2**29 + ) + + +def _valid_rmsnorm_cast_before_weight(x: torch.Tensor, weight: torch.Tensor) -> bool: + return ( + is_cuda() + and x.is_cuda + and weight.is_cuda + and x.device == weight.device + and x.dtype == weight.dtype == torch.bfloat16 + and x.ndim >= 2 + and weight.shape == (x.shape[-1],) + and x.is_contiguous() + and weight.is_contiguous() + and x.numel() > 0 + ) + + +def _fake_rmsnorm_cast_before_weight( + x: torch.Tensor, weight: torch.Tensor +) -> torch.Tensor: + return torch.empty_like(x) + + +def _valid_rmsnorm_cast_before_weight_modulate(x, weight, scale, shift): + return ( + _valid_rmsnorm_cast_before_weight(x, weight) + and x.ndim == 3 + and x.shape[-1] == 3072 + and 16 <= x.numel() // 3072 + and x.numel() < 2**29 + and scale.shape == shift.shape == (x.shape[0], 3072) + and scale.dtype == shift.dtype == x.dtype + and scale.device == shift.device == x.device + and scale.stride(-1) == shift.stride(-1) == 1 + ) + + +def _valid_rmsnorm_cast_before_weight_rope(x, weight, cos, sin): + return ( + _valid_rmsnorm_cast_before_weight(x, weight) + and x.ndim == 4 + and x.shape[-1] == 128 + and 16 <= x.numel() // 128 + and x.numel() < 2**29 + and cos.shape == sin.shape == (x.shape[0] * x.shape[1], 128) + and cos.dtype == sin.dtype == x.dtype + and cos.device == sin.device == x.device + and cos.is_contiguous() + and sin.is_contiguous() + ) + + +def _fake_rmsnorm_epilogue(x, weight, first, second): + return torch.empty_like(x) + + +@register_custom_op( + op_name="rmsnorm_cast_before_weight_modulate_bitexact", + mutates_args=[], + fake_impl=_fake_rmsnorm_epilogue, +) +def rmsnorm_cast_before_weight_modulate_bitexact( + x: torch.Tensor, weight: torch.Tensor, scale: torch.Tensor, shift: torch.Tensor +) -> torch.Tensor: + if not _valid_rmsnorm_cast_before_weight_modulate(x, weight, scale, shift): + raise ValueError("Unsupported MOSSImage RMSNorm + modulation inputs.") + with torch.cuda.device(x.device): + out = torch.empty_like(x) + rows = x.numel() // 3072 + _norm_modulate_kernel[(rows,)]( + x, + weight, + scale, + shift, + out, + rows, + x.shape[1], + scale.stride(0), + shift.stride(0), + num_warps=4, + enable_fp_fusion=False, + ) + return out + + +@register_custom_op( + op_name="rmsnorm_cast_before_weight_rope_bitexact", + mutates_args=[], + fake_impl=_fake_rmsnorm_epilogue, +) +def rmsnorm_cast_before_weight_rope_bitexact( + x: torch.Tensor, weight: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor +) -> torch.Tensor: + if not _valid_rmsnorm_cast_before_weight_rope(x, weight, cos, sin): + raise ValueError("Unsupported MOSSImage RMSNorm + RoPE inputs.") + with torch.cuda.device(x.device): + out = torch.empty_like(x) + rows = x.numel() // 128 + _norm_rope_kernel[(triton.cdiv(rows, 16),)]( + x, + weight, + cos, + sin, + out, + rows, + x.shape[2], + num_warps=4, + enable_fp_fusion=False, + ) + return out + + +@register_custom_op( + op_name="rmsnorm_cast_before_weight_bitexact", + mutates_args=[], + fake_impl=_fake_rmsnorm_cast_before_weight, +) +def rmsnorm_cast_before_weight_bitexact( + x: torch.Tensor, weight: torch.Tensor +) -> torch.Tensor: + """Match ``(x.float() * rsqrt(mean(x.float()**2) + 1e-6)).bf16() * w``.""" + if not _valid_rmsnorm_cast_before_weight(x, weight): + raise ValueError("RMSNorm requires contiguous CUDA BF16 inputs and weight.") + with torch.cuda.device(x.device): + out = torch.empty_like(x) + dim = x.shape[-1] + rows = x.numel() // dim + # At least 16 rows keeps ATen's reduction width at 32 lanes for + # these dimensions. Smaller row counts can select a different tree. + # Larger FP32 workspaces can make TensorIterator split the reduction. + if dim in (128, 3072) and rows >= 16 and x.numel() < 2**29: + _ordered_norm_kernel[(triton.cdiv(rows, 4),)]( + x, + weight, + out, + rows, + dim, + 4, + triton.next_power_of_2(dim), + num_warps=4, + enable_fp_fusion=False, + ) + return out + squared = torch.empty_like(x, dtype=torch.float32) + grid = (triton.cdiv(x.numel(), 1024),) + _square_kernel[grid](x, squared, x.numel(), 1024, enable_fp_fusion=False) + mean = squared.mean(-1, keepdim=True) + _normalize_kernel[grid]( + x, mean, weight, out, x.numel(), x.shape[-1], 1024, enable_fp_fusion=False + ) + return out diff --git a/python/sglang/multimodal_gen/configs/models/dits/moss_image.py b/python/sglang/multimodal_gen/configs/models/dits/moss_image.py new file mode 100644 index 0000000000..c096b00aa4 --- /dev/null +++ b/python/sglang/multimodal_gen/configs/models/dits/moss_image.py @@ -0,0 +1,27 @@ +# SPDX-License-Identifier: Apache-2.0 + +from dataclasses import dataclass, field + +from sglang.multimodal_gen.configs.models.dits.base import DiTArchConfig, DiTConfig + + +@dataclass +class MOSSImageArchConfig(DiTArchConfig): + dim: int = 3072 + ffn_dim: int = 8192 + num_heads: int = 24 + num_layers: int = 42 + text_dim: int = 4096 + freq_dim: int = 256 + latent_channels: int = 128 + rope_base: float = 10000.0 + + def __post_init__(self): + self.hidden_size = self.dim + self.num_attention_heads = self.num_heads + self.num_channels_latents = self.latent_channels + + +@dataclass +class MOSSImageDiTConfig(DiTConfig): + arch_config: MOSSImageArchConfig = field(default_factory=MOSSImageArchConfig) diff --git a/python/sglang/multimodal_gen/configs/models/encoders/qwen3_5.py b/python/sglang/multimodal_gen/configs/models/encoders/qwen3_5.py new file mode 100644 index 0000000000..4c4f94e50d --- /dev/null +++ b/python/sglang/multimodal_gen/configs/models/encoders/qwen3_5.py @@ -0,0 +1,34 @@ +# SPDX-License-Identifier: Apache-2.0 + +from dataclasses import dataclass, field + +from transformers import Qwen3_5TextConfig + +from sglang.multimodal_gen.configs.models.encoders.base import ( + TextEncoderArchConfig, + TextEncoderConfig, +) + + +@dataclass +class Qwen3_5EncoderArchConfig(TextEncoderArchConfig): + architectures: list[str] = field(default_factory=lambda: ["Qwen3_5Model"]) + text_config: Qwen3_5TextConfig | dict = field(default_factory=Qwen3_5TextConfig) + + +@dataclass +class Qwen3_5EncoderConfig(TextEncoderConfig): + arch_config: Qwen3_5EncoderArchConfig = field( + default_factory=Qwen3_5EncoderArchConfig + ) + + def post_diffusers_config_update(self): + text = self.arch_config.text_config + if isinstance(text, dict): + text = Qwen3_5TextConfig(**text) + self.arch_config.text_config = text + self.arch_config.hidden_size = text.hidden_size + self.arch_config.num_hidden_layers = text.num_hidden_layers + self.arch_config.num_attention_heads = text.num_attention_heads + self.arch_config.intermediate_size = text.intermediate_size + self.arch_config.vocab_size = text.vocab_size diff --git a/python/sglang/multimodal_gen/configs/pipeline_configs/flux.py b/python/sglang/multimodal_gen/configs/pipeline_configs/flux.py index 8d21318f8a..43dcc92fa5 100644 --- a/python/sglang/multimodal_gen/configs/pipeline_configs/flux.py +++ b/python/sglang/multimodal_gen/configs/pipeline_configs/flux.py @@ -351,6 +351,13 @@ def _patchify_latents(latents): return latents +def flux2_vae_bn_stats(vae, like: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: + mean = vae.bn.running_mean.view(1, -1, 1, 1).to(like) + variance = vae.bn.running_var.view(1, -1, 1, 1) + std = torch.sqrt(variance + vae.config.arch_config.batch_norm_eps).to(like) + return mean, std + + def _unpatchify_latents(latents): batch_size, num_channels_latents, height, width = latents.shape latents = latents.reshape( diff --git a/python/sglang/multimodal_gen/configs/pipeline_configs/llada_image.py b/python/sglang/multimodal_gen/configs/pipeline_configs/llada_image.py index 314748c43b..04af05d77c 100644 --- a/python/sglang/multimodal_gen/configs/pipeline_configs/llada_image.py +++ b/python/sglang/multimodal_gen/configs/pipeline_configs/llada_image.py @@ -3,7 +3,6 @@ from dataclasses import dataclass, field import numpy as np -import torch from sglang.multimodal_gen import envs from sglang.multimodal_gen.configs.models.dits.llada_image import ( @@ -15,14 +14,10 @@ from sglang.multimodal_gen.configs.pipeline_configs.base import ( ModelTaskType, SpatialImagePipelineConfig, ) -from sglang.multimodal_gen.configs.pipeline_configs.flux import _unpatchify_latents - - -def flux2_vae_bn_stats(vae, like: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: - mean = vae.bn.running_mean.view(1, -1, 1, 1).to(like) - variance = vae.bn.running_var.view(1, -1, 1, 1) - std = torch.sqrt(variance + vae.config.arch_config.batch_norm_eps).to(like) - return mean, std +from sglang.multimodal_gen.configs.pipeline_configs.flux import ( + _unpatchify_latents, + flux2_vae_bn_stats, +) @dataclass diff --git a/python/sglang/multimodal_gen/configs/pipeline_configs/moss_image.py b/python/sglang/multimodal_gen/configs/pipeline_configs/moss_image.py new file mode 100644 index 0000000000..c0f0bc5c1d --- /dev/null +++ b/python/sglang/multimodal_gen/configs/pipeline_configs/moss_image.py @@ -0,0 +1,98 @@ +# SPDX-License-Identifier: Apache-2.0 + +from dataclasses import dataclass, field + +from sglang.multimodal_gen.configs.models.dits.moss_image import MOSSImageDiTConfig +from sglang.multimodal_gen.configs.models.encoders.qwen3_5 import Qwen3_5EncoderConfig +from sglang.multimodal_gen.configs.models.vaes.flux import Flux2VAEConfig +from sglang.multimodal_gen.configs.pipeline_configs.base import ( + SpatialImagePipelineConfig, +) +from sglang.multimodal_gen.configs.pipeline_configs.flux import ( + _unpatchify_latents, + flux2_vae_bn_stats, +) +from sglang.multimodal_gen.configs.pipeline_configs.model_deployment_config import ( + ModelDeploymentConfig, +) +from sglang.multimodal_gen.configs.sample.moss_image import resolve_uncond_skip_layers +from sglang.multimodal_gen.configs.task_type import ModelTaskType +from sglang.multimodal_gen.runtime.distributed.cfg_policy import CFGPolicy + + +@dataclass +class MOSSImagePipelineConfig(SpatialImagePipelineConfig): + task_type: ModelTaskType = ModelTaskType.T2I + dit_config: MOSSImageDiTConfig = field(default_factory=MOSSImageDiTConfig) + vae_config: Flux2VAEConfig = field(default_factory=Flux2VAEConfig) + dit_precision: str = "bf16" + vae_precision: str = "fp32" + text_encoder_precisions: tuple[str, ...] = ("bf16",) + text_encoder_configs: tuple[Qwen3_5EncoderConfig, ...] = field( + default_factory=lambda: (Qwen3_5EncoderConfig(),) + ) + enable_autocast: bool = False + vae_tiling: bool = False + vae_sp: bool = False + flow_shift: float = 5.0 + should_use_guidance: bool = False + supports_auto_residency: bool = False + cfg_policy: CFGPolicy = field( + default_factory=lambda: CFGPolicy(parallel_uses_serial_arithmetic=True) + ) + + def get_model_deployment_config(self): + return ModelDeploymentConfig( + keep_resident_min_available_gb=40, + keep_resident_components=("dit", "text_encoder", "vae"), + auto_enable_cfg_parallel=False, + supports_cfg_parallel=True, + ) + + def validate_server_args(self, server_args): + if server_args.tp_size != 1: + raise ValueError("MOSSImage supports sequence and CFG parallelism, not TP.") + if server_args.enable_torch_compile: + raise ValueError("MOSSImage torch.compile support has not been validated.") + if not server_args.disable_autocast: + raise ValueError( + "MOSSImage requires disabled autocast to preserve reference precision." + ) + + def get_pos_prompt_embeds(self, batch): + return batch.prompt_embeds[0] + + def get_neg_prompt_embeds(self, batch): + return batch.negative_prompt_embeds[0] + + def prepare_neg_cond_kwargs(self, batch, device, rotary_emb, dtype): + return {"skip_layers": resolve_uncond_skip_layers(batch.sampling_params)} + + def post_denoising_loop(self, latents, batch): + return latents + + def get_decode_scale_and_shift(self, device, dtype, vae): + # BN normalization applies to packed channels, before 2x2 unpacking. + return 1.0, None + + def preprocess_decoding(self, latents, server_args=None, vae=None): + latents = latents.to(vae.bn.running_mean) + mean, std = flux2_vae_bn_stats(vae, latents) + return _unpatchify_latents(latents * std + mean) + + +def register(): + from sglang.multimodal_gen.configs.sample.moss_image import MOSSImageSamplingParams + from sglang.multimodal_gen.registry import register_configs + + register_configs( + sampling_param_cls=MOSSImageSamplingParams, + pipeline_config_cls=MOSSImagePipelineConfig, + hf_model_paths=[ + "OpenMOSS-Team/MOSS-Image-Base", + "OpenMOSS-Team/MOSS-Image-SFT", + ], + model_detectors=[ + lambda path: "mossimage" in path.lower().replace("-", "").replace("_", "") + ], + ) diff --git a/python/sglang/multimodal_gen/configs/sample/moss_image.py b/python/sglang/multimodal_gen/configs/sample/moss_image.py new file mode 100644 index 0000000000..14770f7a82 --- /dev/null +++ b/python/sglang/multimodal_gen/configs/sample/moss_image.py @@ -0,0 +1,52 @@ +# SPDX-License-Identifier: Apache-2.0 + +from dataclasses import dataclass, field +from typing import ClassVar + +from sglang.multimodal_gen.configs.sample.sampling_params import SamplingParams + + +def resolve_uncond_skip_layers(params: "MOSSImageSamplingParams") -> tuple[int, ...]: + layers = params.uncond_skip_layers + if layers is None: + # The recommended two-pass mode is the default. Selecting three-pass + # SLG keeps the unconditional branch complete unless explicitly overridden. + return () if params.slg_layers and params.slg_scale > 0 else (22,) + if not isinstance(layers, (list, tuple)): + raise ValueError("uncond_skip_layers must be a list of indices.") + return tuple(layers) + + +@dataclass +class MOSSImageSamplingParams(SamplingParams): + _default_height: ClassVar[int] = 1024 + _default_width: ClassVar[int] = 1024 + seed: int | list[int] = field(default=0, metadata={"batch_sig_exclude": True}) + num_frames: int = 1 + num_inference_steps: int = 50 + guidance_scale: float = 3.0 + negative_prompt: str = "" + # None selects the mode default; [] disables unconditional skipping. + uncond_skip_layers: list[int] | None = None + slg_layers: list[int] | None = field(default_factory=list) + slg_scale: float = 0.0 + slg_start: float = 0.01 + slg_stop: float = 1.0 + + def should_use_classifier_free_guidance(self) -> bool: + # The reference evaluates both branches even for guidance below one. + if self.negative_prompt is None: + self.negative_prompt = "" + return self.guidance_scale != 1.0 + + @classmethod + def image_request_extra_fields(cls) -> frozenset[str]: + return frozenset( + { + "uncond_skip_layers", + "slg_layers", + "slg_scale", + "slg_start", + "slg_stop", + } + ) diff --git a/python/sglang/multimodal_gen/runtime/models/dits/moss_image.py b/python/sglang/multimodal_gen/runtime/models/dits/moss_image.py new file mode 100644 index 0000000000..89de04ef20 --- /dev/null +++ b/python/sglang/multimodal_gen/runtime/models/dits/moss_image.py @@ -0,0 +1,642 @@ +# SPDX-License-Identifier: Apache-2.0 + +# Reference implementation license: +# BSD 3-Clause License +# +# (c) Meta Platforms, Inc. and affiliates. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice,this list +# of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above copyright notice, this +# list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# 3. Neither the name of the copyright holder nor the names of its contributors may +# be used to endorse or promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY +# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT +# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR +# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH +# DAMAGE. + +# Adapted from OpenMOSS-Team/MOSS-Image-Base, revision 355120bd6b44ff67b8df18f57e40b928fc886cd3. + +import msgspec +import torch +from torch import nn + +from sglang.kernels.ops.diffusion import ( + BitExactFusionGate, + can_use_fused_situ_softcap_mul, + can_use_rmsnorm_cast_before_weight, + can_use_rmsnorm_cast_before_weight_modulate, + can_use_rmsnorm_cast_before_weight_rope, + fused_rope_rotate_half_bitexact, + fused_situ_softcap_mul_bitexact, + modulate_scale_shift, + residual_gate_add, + rmsnorm_cast_before_weight_bitexact, + rmsnorm_cast_before_weight_modulate_bitexact, + rmsnorm_cast_before_weight_rope_bitexact, +) +from sglang.multimodal_gen.configs.models.dits.moss_image import MOSSImageDiTConfig +from sglang.multimodal_gen.configs.models.fsdp import is_layer +from sglang.multimodal_gen.runtime.distributed import ( + get_sp_world_size, + model_parallel_is_initialized, +) +from sglang.multimodal_gen.runtime.distributed.sp_shard_utils import ( + gather_seq, + shard_like, + shard_seq, + tail_attn_meta, +) +from sglang.multimodal_gen.runtime.layers.attention import USPAttention +from sglang.multimodal_gen.runtime.layers.attention.layer import LocalAttention +from sglang.multimodal_gen.runtime.managers.memory_managers.layerwise_offload import ( + LayerwiseOffloadableModuleMixin, +) +from sglang.multimodal_gen.runtime.models.dits.base import BaseDiT +from sglang.multimodal_gen.runtime.platforms import AttentionBackendEnum +from sglang.multimodal_gen.runtime.utils.logging_utils import init_logger + +logger = init_logger(__name__) +_SITU_FUSION = BitExactFusionGate("MOSSImage SiTU") +_ROPE_FUSION = BitExactFusionGate("MOSSImage RoPE") +_RMSNORM_FUSION = BitExactFusionGate("MOSSImage RMSNorm", per_signature=True) +_NORM_MOD_FUSION = BitExactFusionGate("MOSSImage RMSNorm + modulation") +_NORM_ROPE_FUSION = BitExactFusionGate("MOSSImage RMSNorm + RoPE") + + +def _fused_or_native(gate, eligible, fused, native, sig=None): + if eligible and not gate.disabled: + verified = gate.is_verified(sig) + if verified or not ( + torch.compiler.is_compiling() or torch.cuda.is_current_stream_capturing() + ): + try: + out = fused() + except ValueError: + raise + except Exception as exc: + gate.on_exception(exc, logger=logger) + else: + return ( + out + if verified + else gate.accept_or_fallback(out, native(), sig=sig, logger=logger) + ) + return native() + + +def validate_skip_layers(skip_layers, num_layers): + try: + skip_layers = tuple(skip_layers) + except TypeError as exc: + raise ValueError("skip_layers must be a sequence of layer indices") from exc + if any( + isinstance(index, bool) + or not isinstance(index, int) + or not 0 <= index < num_layers + for index in skip_layers + ): + raise ValueError( + f"skip_layers must contain integer indices in [0, {num_layers})." + ) + return skip_layers + + +class _ConditioningGroup(msgspec.Struct, frozen=True): + indices: torch.Tensor | None + text: torch.Tensor + rope: tuple[torch.Tensor, torch.Tensor] + + +class MOSSImageConditioning(msgspec.Struct, frozen=True): + """Refined text and RoPE owned by one request and one CFG branch.""" + + spatial_shape: tuple[int, int] + groups: tuple[_ConditioningGroup, ...] + + @property + def batch_size(self): + return sum(group.text.shape[0] for group in self.groups) + + +class _RMSNorm(nn.Module): + """Normalize in fp32, then round before applying the learned scale.""" + + def __init__(self, dim): + super().__init__() + self.weight = nn.Parameter(torch.ones(dim)) + + def forward(self, x): + return _fused_or_native( + _RMSNORM_FUSION, + can_use_rmsnorm_cast_before_weight( + device=x.device, dtype=x.dtype, contiguous=x.is_contiguous() + ), + lambda: rmsnorm_cast_before_weight_bitexact(x, self.weight), + lambda: self.forward_native(x), + sig=(x.device.index, x.dtype, x.shape[-1], x.numel() // x.shape[-1] >= 16), + ) + + def forward_native(self, x): + y = x.float() * torch.rsqrt(x.float().square().mean(-1, keepdim=True) + 1e-6) + return y.to(x.dtype) * self.weight + + +def _situ_native(hidden, gate): + return (4.0 * torch.tanh(gate / 4.0) * torch.sigmoid(gate)) * ( + 25.0 * torch.tanh(hidden / 25.0) + ) + + +def _situ(hidden, gate): + return _fused_or_native( + _SITU_FUSION, + can_use_fused_situ_softcap_mul(device=hidden.device, dtype=hidden.dtype), + lambda: fused_situ_softcap_mul_bitexact(hidden, gate), + lambda: _situ_native(hidden, gate), + ) + + +def _prepare_rope(rope): + # Every layer and both Q/K projections share these expanded coefficients. + sin, cos = rope.chunk(2, -1) + return torch.cat((sin, sin), -1), torch.cat((cos, cos), -1) + + +def _rotate_native(x, rope): + sin, cos = (part.unsqueeze(-2) for part in rope) + a, b = x.chunk(2, -1) + return x * cos + torch.cat((-b, a), -1) * sin + + +def _rotate(x, rope): + sin, cos = (part.flatten(0, 1) for part in rope) + return _fused_or_native( + _ROPE_FUSION, + x.is_cuda and x.dtype is torch.bfloat16, + lambda: fused_rope_rotate_half_bitexact(x, cos, sin), + lambda: _rotate_native(x, rope), + ) + + +def _attention(q, k, v, rope, heads, attention, attn_mask_meta=None): + shape = (*q.shape[:2], heads, q.shape[-1] // heads) + q, k = q.reshape(shape), k.reshape(shape) + if rope is not None: + q = _rotate(q, rope) + k = _rotate(k, rope) + v = v.reshape(shape) + kwargs = {"attn_mask_meta": attn_mask_meta} if attn_mask_meta is not None else {} + return attention(q.to(v.dtype), k.to(v.dtype), v, **kwargs).flatten(2) + + +def _norm_modulate(norm, x, scale, shift): + return _fused_or_native( + _NORM_MOD_FUSION, + can_use_rmsnorm_cast_before_weight_modulate( + device=x.device, + dtype=x.dtype, + dim=x.shape[-1], + rows=x.numel() // x.shape[-1], + ), + lambda: rmsnorm_cast_before_weight_modulate_bitexact( + x, norm.weight, scale, shift + ), + lambda: modulate_scale_shift(norm(x), scale, shift), + ) + + +def _norm_rope(norm, x, rope, heads): + x = x.unflatten(-1, (heads, -1)) + sin, cos = (part.flatten(0, 1) for part in rope) + return _fused_or_native( + _NORM_ROPE_FUSION, + can_use_rmsnorm_cast_before_weight_rope( + device=x.device, + dtype=x.dtype, + dim=x.shape[-1], + rows=x.numel() // x.shape[-1], + ), + lambda: rmsnorm_cast_before_weight_rope_bitexact(x, norm.weight, cos, sin), + lambda: _rotate(norm(x), rope), + ).flatten(2) + + +class _TextBlock(nn.Module): + def __init__(self, dim, ffn_dim, heads): + super().__init__() + self.heads = heads + self.attention = LocalAttention( + num_heads=heads, + head_size=dim // heads, + supported_attention_backends={ + AttentionBackendEnum.FA, + AttentionBackendEnum.TORCH_SDPA, + }, + default_attention_backend=AttentionBackendEnum.FA, + compute_dtype=torch.bfloat16, + ) + self.norm1, self.norm2 = _RMSNorm(dim), _RMSNorm(dim) + self.q_norm, self.k_norm = _RMSNorm(dim // heads), _RMSNorm(dim // heads) + self.qkv = nn.Linear(dim, 3 * dim) + self.proj = nn.Linear(dim, dim) + self.ffn_gate, self.ffn_up = nn.Linear(dim, ffn_dim), nn.Linear(dim, ffn_dim) + self.ffn_down = nn.Linear(ffn_dim, dim) + + def forward(self, x, rope): + q, k, v = self.qkv(self.norm1(x)).chunk(3, -1) + q = self.q_norm(q.unflatten(-1, (self.heads, -1))).flatten(2) + k = self.k_norm(k.unflatten(-1, (self.heads, -1))).flatten(2) + x = x + self.proj(_attention(q, k, v, rope, self.heads, self.attention)) + y = self.norm2(x) + return x + self.ffn_down(_situ(self.ffn_up(y), self.ffn_gate(y))) + + +class _TextProjection(nn.Module): + def __init__(self, text_dim, dim, ffn_dim, heads): + super().__init__() + self.proj = nn.Linear(text_dim, dim) + self.blocks = nn.ModuleList([_TextBlock(dim, ffn_dim, heads) for _ in range(2)]) + + def forward(self, x, rope): + x = self.proj(x.to(self.proj.weight.dtype)) + for block in self.blocks: + x = block(x, rope) + return x + + +class _Block(nn.Module): + def __init__(self, dim, ffn_dim, heads): + super().__init__() + self.heads = heads + attention_cls = ( + USPAttention + if model_parallel_is_initialized() and get_sp_world_size() > 1 + else LocalAttention + ) + self.attention = attention_cls( + num_heads=heads, + head_size=dim // heads, + supported_attention_backends={ + AttentionBackendEnum.FA, + AttentionBackendEnum.TORCH_SDPA, + }, + default_attention_backend=AttentionBackendEnum.FA, + compute_dtype=torch.bfloat16, + ) + self.norm1, self.norm2 = _RMSNorm(dim), _RMSNorm(dim) + self.q_norm, self.k_norm = _RMSNorm(dim // heads), _RMSNorm(dim // heads) + self.proj = nn.ModuleDict( + {name: nn.Linear(dim, dim, bias=False) for name in ("q", "k", "v", "o")} + ) + self.proj["ffn_up_gate"] = nn.Linear(dim, 2 * ffn_dim, bias=False) + self.proj["ffn_down"] = nn.Linear(ffn_dim, dim, bias=False) + + def forward(self, x, rope, modulation, attn_mask_meta=None): + shift_a, scale_a, gate_a, shift_f, scale_f, gate_f = modulation.unbind(1) + y = _norm_modulate(self.norm1, x, scale_a, shift_a) + dtype = self.proj["q"].weight.dtype + y = y.to(dtype) + q = _norm_rope(self.q_norm, self.proj["q"](y), rope, self.heads) + k = _norm_rope(self.k_norm, self.proj["k"](y), rope, self.heads) + x = residual_gate_add( + x, + self.proj["o"]( + _attention( + q, + k, + self.proj["v"](y), + None, + self.heads, + self.attention, + attn_mask_meta, + ) + ), + gate_a[:, None], + ) + y = _norm_modulate(self.norm2, x, scale_f, shift_f) + hidden, gate = self.proj["ffn_up_gate"](y.to(dtype)).chunk(2, -1) + return residual_gate_add( + x, self.proj["ffn_down"](_situ(hidden, gate)), gate_f[:, None] + ) + + +class _RoPE(nn.Module): + def __init__(self, head_dim, base): + super().__init__() + self.num_bands = head_dim // 8 + self.base = base + self.register_buffer("bands", self._default_bands(torch.device("cpu"))) + + def _default_bands(self, device): + # Match training's CPU fp32 construction, including under meta init. + exponent = ( + torch.arange(self.num_bands, device="cpu", dtype=torch.float32) + / self.num_bands + ) + return (1 / (self.base**exponent)).to(device) + + def _apply(self, fn, recurse=True): + super()._apply(fn, recurse=recurse) + # .float() cannot recover frequencies already rounded by .to(bf16). + self.reset_bands() + return self + + def reset_bands(self): + bands = self._default_bands(self.bands.device) + # The shared assign=True loader can materialize buffers as Parameters. + self._parameters.pop("bands", None) + self.register_buffer("bands", bands) + + def _load_from_state_dict(self, *args, **kwargs): + super()._load_from_state_dict(*args, **kwargs) + # Frequencies are derived constants; retain the key for checkpoint compatibility. + self.reset_bands() + + def forward(self, height, width, text_length, device): + # Diffusers/Accelerate can install tensors directly, bypassing load hooks. + if self.bands.dtype != torch.float32: + self.reset_bands() + # Coordinates: (r, f, h, w); sequence order is image followed by text. + h, w = torch.meshgrid( + torch.arange(height, device=device), + torch.arange(width, device=device), + indexing="ij", + ) + image = ( + torch.stack( + (torch.zeros_like(h), torch.full_like(h, text_length), h, w), -1 + ) + .flatten(0, 1) + .float() + ) + image[:, 2] -= (height - 1) / 2 + image[:, 3] -= (width - 1) / 2 + text = torch.zeros(text_length, 4, device=device, dtype=torch.float32) + text[:, 1] = torch.arange(text_length, device=device) + phase = torch.cat((image, text), 0).unsqueeze(-1) * self.bands + return torch.cat((phase.sin(), phase.cos()), -2).flatten(-2).unsqueeze(0) + + +class MOSSImageTransformer(BaseDiT, LayerwiseOffloadableModuleMixin): + """MOSSImage DiT with checkpoint-compatible names and SGLang attention. + + Each sample is evaluated at its true text length, including text refinement; + padded tokens cannot influence either text or joint attention. + """ + + _fsdp_shard_conditions = [is_layer] + _fsdp_forward_methods = ("prepare_conditioning",) + _compile_conditions = [] + param_names_mapping = {} + reverse_param_names_mapping = {} + _supported_attention_backends = { + AttentionBackendEnum.FA, + AttentionBackendEnum.TORCH_SDPA, + } + + def __init__( + self, config: MOSSImageDiTConfig, hf_config=None, quant_config=None, **kwargs + ): + super().__init__(config, hf_config or {}, **kwargs) + if quant_config is not None: + raise NotImplementedError("MOSSImage DiT quantization is not implemented") + arch = self.config + dim, ffn_dim, num_heads = arch.dim, arch.ffn_dim, arch.num_heads + num_layers, text_dim = arch.num_layers, arch.text_dim + freq_dim, latent_channels, rope_base = ( + arch.freq_dim, + arch.latent_channels, + arch.rope_base, + ) + self.layer_names = ["layers"] + self.hidden_size = dim + self._sequence_parallel = ( + model_parallel_is_initialized() and get_sp_world_size() > 1 + ) + self.num_attention_heads = num_heads + self.num_channels_latents = latent_channels + if dim % num_heads or (dim // num_heads) % 8 or freq_dim % 2: + raise ValueError( + "Require dim divisible by heads, head_dim divisible by 8, and even freq_dim." + ) + self.video_embedder = nn.Linear(latent_channels, dim) + self.text_embedder = _TextProjection(text_dim, dim, ffn_dim, num_heads) + self.rope = _RoPE(dim // num_heads, rope_base) + self.time_embedding = nn.Sequential( + nn.Linear(freq_dim, dim), nn.SiLU(), nn.Linear(dim, dim) + ) + self.shared_block_modulation = nn.Linear(dim, 6 * dim) + self.layers = nn.ModuleList( + [_Block(dim, ffn_dim, num_heads) for _ in range(num_layers)] + ) + self.final_norm_video = _RMSNorm(dim) + self.final_linear_video = nn.Linear(dim, latent_channels, bias=False) + self.video_head_modulation = nn.Linear(dim, 2 * dim) + + def _unpad_text(self, encoder_hidden_states, encoder_attention_mask): + if ( + encoder_hidden_states.ndim != 3 + or encoder_hidden_states.shape[-1] != self.config.text_dim + ): + raise ValueError("encoder_hidden_states must be [B, S, text_dim].") + mask = encoder_attention_mask + if mask is None: + contexts = tuple(encoder_hidden_states.split(1)) + else: + if mask.shape != encoder_hidden_states.shape[:2] or not torch.all( + (mask == 0) | (mask == 1) + ): + raise ValueError("encoder_attention_mask must be a binary [B, S] mask.") + contexts = tuple( + encoder_hidden_states[index : index + 1, mask[index].bool()] + for index in range(encoder_hidden_states.shape[0]) + ) + if any(context.shape[1] == 0 for context in contexts): + raise ValueError("Each sample needs at least one valid text token.") + return contexts + + def _prepare_sample_conditioning(self, context, height, width, dtype): + rope = _prepare_rope( + self.rope(height, width, context.shape[1], context.device).to(dtype) + ) + rope = tuple( + part.expand(context.shape[0], -1, -1).contiguous() for part in rope + ) + # Small text GEMMs are particularly sensitive to changing batch shape. + texts = [ + self.text_embedder( + context[index : index + 1], + tuple(part[index : index + 1, height * width :] for part in rope), + ) + for index in range(context.shape[0]) + ] + text = texts[0] if len(texts) == 1 else torch.cat(texts) + return text, rope + + def prepare_conditioning( + self, + encoder_hidden_states, + encoder_attention_mask, + height, + width, + dtype, + *, + batch_samples=False, + ): + # Neither the text refinement blocks nor RoPE depend on the timestep. + contexts = self._unpad_text(encoder_hidden_states, encoder_attention_mask) + by_length = {} + for index, context in enumerate(contexts): + key = context.shape[1] if batch_samples else index + by_length.setdefault(key, []).append(index) + groups = [] + for indices in by_length.values(): + context = torch.cat([contexts[index] for index in indices]) + text, rope = self._prepare_sample_conditioning( + context, height, width, dtype + ) + groups.append( + _ConditioningGroup( + indices=( + torch.as_tensor(indices, device=context.device) + if len(by_length) > 1 + else None + ), + text=text, + rope=rope, + ) + ) + return MOSSImageConditioning( + spatial_shape=(height, width), + groups=tuple(groups), + ) + + def forward( + self, + hidden_states, + timestep, + encoder_hidden_states, + encoder_attention_mask=None, + prepared_conditioning: MOSSImageConditioning | None = None, + skip_layers=(), + ): + skip_layers = validate_skip_layers(skip_layers, self.config.num_layers) + if ( + hidden_states.ndim != 4 + or hidden_states.shape[1] != self.config.latent_channels + ): + raise ValueError("hidden_states must be [B, latent_channels, H, W].") + batch, _, height, width = hidden_states.shape + if encoder_hidden_states.ndim != 3 or encoder_hidden_states.shape[0] != batch: + raise ValueError("encoder_hidden_states must be [B, S, text_dim].") + if prepared_conditioning is not None and ( + prepared_conditioning.spatial_shape != (height, width) + or prepared_conditioning.batch_size != batch + ): + raise ValueError( + "Prepared conditioning must match the latent batch and size." + ) + times = torch.as_tensor( + timestep, device=hidden_states.device, dtype=torch.float32 + ).reshape(-1) + times = times.expand(batch) + # Training computes the sinusoid in float64 and feeds float32 into its MLP. + half = self.config.freq_dim // 2 + freq = 10000 ** ( + -torch.arange(half, device=times.device, dtype=torch.float64) / half + ) + phase = times.double()[:, None] * freq + embedding = torch.cat((phase.cos(), phase.sin()), -1).float() + time = self.time_embedding( + embedding.to(self.time_embedding[0].weight.dtype) + ).float() + mod = self.shared_block_modulation( + time.to(self.shared_block_modulation.weight.dtype) + ).view(batch, 6, -1) + head = self.video_head_modulation( + time.to(self.video_head_modulation.weight.dtype) + ).view(batch, 2, -1) + if prepared_conditioning is None: + device_type = hidden_states.device.type + dtype = ( + torch.get_autocast_dtype(device_type) + if torch.is_autocast_enabled(device_type) + else self.video_embedder.weight.dtype + ) + prepared_conditioning = self.prepare_conditioning( + encoder_hidden_states, + encoder_attention_mask, + height, + width, + dtype, + ) + outputs = ( + torch.empty_like(hidden_states, dtype=torch.float32) + if len(prepared_conditioning.groups) > 1 + else None + ) + for group in prepared_conditioning.groups: + indices = group.indices + if indices is None: + group_video, group_mod, group_head = hidden_states, mod, head + else: + group_video, group_mod, group_head = ( + tensor.index_select(0, indices) + for tensor in (hidden_states, mod, head) + ) + group_video = self.video_embedder( + group_video.flatten(2) + .transpose(1, 2) + .to(self.video_embedder.weight.dtype) + .contiguous() + ) + x = torch.cat((group_video, group.text), 1) + rope = group.rope + layer_kwargs = {} + if self._sequence_parallel: + x, shard = shard_seq(x) + rope = tuple(shard_like(part, shard) for part in rope) + layer_kwargs["attn_mask_meta"] = tail_attn_meta( + shard, x.shape[0], x.device + ) + for layer_index, layer in enumerate(self.layers): + if layer_index not in skip_layers: + x = layer(x, rope, group_mod, **layer_kwargs) + if self._sequence_parallel: + x = gather_seq(x, shard.orig_len) + x = self.final_norm_video( + x[:, : height * width].to(self.final_norm_video.weight.dtype) + ) + x = x * (1 + group_head[:, 1, None]) + group_head[:, 0, None] + x = self.final_linear_video(x.to(self.final_linear_video.weight.dtype)) + sample = ( + x.transpose(1, 2) + .reshape(x.shape[0], -1, height, width) + .to(dtype=torch.float32, memory_format=torch.contiguous_format) + ) + if indices is None: + return sample + outputs.index_copy_(0, indices, sample) + return outputs + + def post_load_weights(self): + self.rope.reset_bands() + + +EntryClass = MOSSImageTransformer diff --git a/python/sglang/multimodal_gen/runtime/models/encoders/qwen3_5.py b/python/sglang/multimodal_gen/runtime/models/encoders/qwen3_5.py new file mode 100644 index 0000000000..f65c1d8e4b --- /dev/null +++ b/python/sglang/multimodal_gen/runtime/models/encoders/qwen3_5.py @@ -0,0 +1,392 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2025 The Qwen Team and The HuggingFace Inc. team. All rights reserved. +# Adapted from the Transformers Qwen3.5 text model (Apache-2.0). + +from collections.abc import Iterable + +import torch +import torch.nn.functional as F +from torch import nn + +from sglang.multimodal_gen.configs.models.encoders.base import BaseEncoderOutput +from sglang.multimodal_gen.configs.models.encoders.qwen3_5 import Qwen3_5EncoderConfig +from sglang.multimodal_gen.runtime.layers.attention import LocalAttention +from sglang.multimodal_gen.runtime.layers.linear import ReplicatedLinear +from sglang.multimodal_gen.runtime.loader.weight_utils import load_stacked_weight +from sglang.multimodal_gen.runtime.models.encoders.base import TextEncoder +from sglang.multimodal_gen.runtime.models.encoders.qwen3vl import Qwen3VLTextMLP +from sglang.multimodal_gen.runtime.models.encoders.qwen_vl_rope import ( + apply_qwen_vl_text_rope, +) +from sglang.multimodal_gen.runtime.platforms import AttentionBackendEnum +from sglang.srt.layers.layernorm import GemmaRMSNorm, RMSNorm +from sglang.srt.layers.rotary_embedding import get_rope + + +def _chunk_gated_delta_rule( + query, key, value, g, beta, chunk_size=64, use_qk_l2norm=False +): + """FP32 chunked prefill using the current Qwen3.5 triangular solve.""" + initial_dtype = query.dtype + query, key, value, beta, g = [ + x.transpose(1, 2).to(torch.float32, memory_format=torch.contiguous_format) + for x in (query, key, value, beta, g) + ] + batch, heads, length, key_dim = key.shape + value_dim = value.shape[-1] + if use_qk_l2norm: + query = query * torch.rsqrt(query.square().sum(-1, keepdim=True) + 1e-6) + key = key * torch.rsqrt(key.square().sum(-1, keepdim=True) + 1e-6) + query = query * (key_dim**-0.5) + padding = (chunk_size - length % chunk_size) % chunk_size + query, key, value = [F.pad(x, (0, 0, 0, padding)) for x in (query, key, value)] + beta, g = [F.pad(x, (0, padding)) for x in (beta, g)] + num_chunks = (length + padding) // chunk_size + v_beta = value * beta.unsqueeze(-1) + k_beta = key * beta.unsqueeze(-1) + query, key, k_beta, v_beta = [ + x.reshape(batch, heads, num_chunks, chunk_size, x.shape[-1]) + for x in (query, key, k_beta, v_beta) + ] + g = g.reshape(batch, heads, num_chunks, chunk_size).cumsum(dim=3) + upper = torch.ones( + chunk_size, chunk_size, dtype=torch.bool, device=query.device + ).triu(1) + decay = (g.unsqueeze(4) - g.unsqueeze(3)).masked_fill(upper, float("-inf")).exp() + system = (k_beta @ key.transpose(-1, -2)) * decay + intra = (query @ key.transpose(-1, -2)) * decay + decayed_k_beta = k_beta * g.exp().unsqueeze(-1) + values = torch.linalg.solve_triangular( + system, v_beta, upper=False, unitriangular=True + ) + k_cumdecay = torch.linalg.solve_triangular( + system, decayed_k_beta, upper=False, unitriangular=True + ) + state = torch.zeros( + batch, heads, key_dim, value_dim, dtype=values.dtype, device=values.device + ) + output = torch.zeros_like(values) + query = query * g.exp().unsqueeze(-1) + key = key * (g[..., -1:] - g).exp().unsqueeze(-1) + chunk_decay = g[..., -1].exp()[..., None, None] + for i in range(num_chunks): + v_new = values[:, :, i] - k_cumdecay[:, :, i] @ state + inter = query[:, :, i] @ state + output[:, :, i] = inter + intra[:, :, i] @ v_new + state = state * chunk_decay[:, :, i] + key[:, :, i].transpose(-1, -2) @ v_new + output = output.reshape(batch, heads, -1, value_dim)[:, :, :length] + return output.transpose(1, 2).to( + initial_dtype, memory_format=torch.contiguous_format + ) + + +class Qwen3_5Linear(ReplicatedLinear): + def forward(self, x): + return super().forward(x)[0] + + +class Qwen3_5RMSNorm(GemmaRMSNorm): + """Preserve the reference's FP32 reduction and offset-weight rounding.""" + + def forward(self, x): + return self.forward_native(x) + + +class Qwen3_5RMSNormGated(RMSNorm): + def __init__(self, hidden_size, eps): + super().__init__( + hidden_size, eps=eps, cast_x_before_out_mul=True, force_native=True + ) + + def forward(self, x, gate): + # Keep the reference's BF16 rounding before applying the FP32 gate. + return (super().forward(x) * F.silu(gate.float())).to(x.dtype) + + +class Qwen3_5GatedDeltaNet(nn.Module): + def __init__(self, config): + super().__init__() + self.num_k_heads = config.linear_num_key_heads + self.num_v_heads = config.linear_num_value_heads + self.head_k_dim = config.linear_key_head_dim + self.head_v_dim = config.linear_value_head_dim + self.key_dim = self.num_k_heads * self.head_k_dim + self.value_dim = self.num_v_heads * self.head_v_dim + conv_dim = 2 * self.key_dim + self.value_dim + self.conv1d = nn.Conv1d( + conv_dim, + conv_dim, + config.linear_conv_kernel_dim, + groups=conv_dim, + padding=config.linear_conv_kernel_dim - 1, + bias=False, + ) + self.in_proj_qkv = Qwen3_5Linear(config.hidden_size, conv_dim, bias=False) + self.in_proj_z = Qwen3_5Linear(config.hidden_size, self.value_dim, bias=False) + self.in_proj_b = Qwen3_5Linear(config.hidden_size, self.num_v_heads, bias=False) + self.in_proj_a = Qwen3_5Linear(config.hidden_size, self.num_v_heads, bias=False) + self.dt_bias = nn.Parameter(torch.empty(self.num_v_heads)) + self.A_log = nn.Parameter(torch.empty(self.num_v_heads)) + self.norm = Qwen3_5RMSNormGated(self.head_v_dim, eps=config.rms_norm_eps) + self.out_proj = Qwen3_5Linear(self.value_dim, config.hidden_size, bias=False) + + def forward(self, hidden_states, padding_mask): + if padding_mask is not None: + hidden_states = hidden_states * padding_mask[:, :, None].to(hidden_states) + batch, length, _ = hidden_states.shape + qkv = self.in_proj_qkv(hidden_states).transpose(1, 2) + qkv = F.silu(self.conv1d(qkv)[:, :, :length]).transpose(1, 2) + q, k, v = qkv.split([self.key_dim, self.key_dim, self.value_dim], dim=-1) + q = q.reshape(batch, length, self.num_k_heads, self.head_k_dim) + k = k.reshape(batch, length, self.num_k_heads, self.head_k_dim) + v = v.reshape(batch, length, self.num_v_heads, self.head_v_dim) + repeats = self.num_v_heads // self.num_k_heads + if repeats != 1: + q = q.repeat_interleave(repeats, dim=2) + k = k.repeat_interleave(repeats, dim=2) + beta = self.in_proj_b(hidden_states).sigmoid() + g = -self.A_log.float().exp() * F.softplus( + self.in_proj_a(hidden_states).float() + self.dt_bias + ) + output = _chunk_gated_delta_rule(q, k, v, g, beta, use_qk_l2norm=True) + z = self.in_proj_z(hidden_states).reshape(-1, self.head_v_dim) + output = self.norm(output.reshape(-1, self.head_v_dim), z) + return self.out_proj(output.reshape(batch, length, self.value_dim)) + + +class Qwen3_5Attention(nn.Module): + def __init__(self, config): + super().__init__() + self.head_dim = config.head_dim + self.num_heads = config.num_attention_heads + self.num_kv_heads = config.num_key_value_heads + self.q_proj = Qwen3_5Linear( + config.hidden_size, + self.num_heads * self.head_dim * 2, + bias=config.attention_bias, + ) + self.k_proj = Qwen3_5Linear( + config.hidden_size, + self.num_kv_heads * self.head_dim, + bias=config.attention_bias, + ) + self.v_proj = Qwen3_5Linear( + config.hidden_size, + self.num_kv_heads * self.head_dim, + bias=config.attention_bias, + ) + self.o_proj = Qwen3_5Linear( + self.num_heads * self.head_dim, + config.hidden_size, + bias=config.attention_bias, + ) + self.q_norm = Qwen3_5RMSNorm(self.head_dim, eps=config.rms_norm_eps) + self.k_norm = Qwen3_5RMSNorm(self.head_dim, eps=config.rms_norm_eps) + self.attn = LocalAttention( + self.num_heads, + self.head_dim, + num_kv_heads=self.num_kv_heads, + causal=True, + supported_attention_backends=Qwen3_5Model._supported_attention_backends, + default_attention_backend=AttentionBackendEnum.TORCH_SDPA, + ) + + def forward(self, hidden_states, position_ids, rotary_emb, attention_mask): + batch, length, _ = hidden_states.shape + q, gate = ( + self.q_proj(hidden_states) + .view(batch, length, self.num_heads, 2 * self.head_dim) + .chunk(2, dim=-1) + ) + k = self.k_proj(hidden_states).view( + batch, length, self.num_kv_heads, self.head_dim + ) + v = self.v_proj(hidden_states).view( + batch, length, self.num_kv_heads, self.head_dim + ) + q, k = apply_qwen_vl_text_rope( + rotary_emb, + position_ids, + self.q_norm(q).transpose(1, 2), + self.k_norm(k).transpose(1, 2), + ) + output = self.attn( + q.transpose(1, 2), k.transpose(1, 2), v, attn_mask=attention_mask + ) + output = ( + output.reshape(batch, length, -1) + * gate.reshape(batch, length, -1).sigmoid() + ) + return self.o_proj(output) + + +class Qwen3_5DecoderLayer(nn.Module): + def __init__(self, config, layer_idx): + super().__init__() + self.layer_type = config.layer_types[layer_idx] + if self.layer_type == "linear_attention": + self.linear_attn = Qwen3_5GatedDeltaNet(config) + elif self.layer_type == "full_attention": + self.self_attn = Qwen3_5Attention(config) + else: + raise ValueError(f"Unsupported Qwen3.5 layer type: {self.layer_type}") + self.mlp = Qwen3VLTextMLP(config) + self.input_layernorm = Qwen3_5RMSNorm( + config.hidden_size, eps=config.rms_norm_eps + ) + self.post_attention_layernorm = Qwen3_5RMSNorm( + config.hidden_size, eps=config.rms_norm_eps + ) + + def forward( + self, hidden_states, position_ids, rotary_emb, attention_mask, padding_mask + ): + residual = hidden_states + hidden_states = self.input_layernorm(hidden_states) + if self.layer_type == "linear_attention": + hidden_states = self.linear_attn(hidden_states, padding_mask) + else: + hidden_states = self.self_attn( + hidden_states, position_ids, rotary_emb, attention_mask + ) + hidden_states = residual + hidden_states + return hidden_states + self.mlp(self.post_attention_layernorm(hidden_states)) + + +class Qwen3_5TextModel(nn.Module): + def __init__(self, config): + super().__init__() + if config.hidden_act != "silu": + raise ValueError("Qwen3.5 text encoding requires SiLU activation") + self.embed_tokens = nn.Embedding( + config.vocab_size, config.hidden_size, config.pad_token_id + ) + self.layers = nn.ModuleList( + [Qwen3_5DecoderLayer(config, i) for i in range(config.num_hidden_layers)] + ) + self.norm = Qwen3_5RMSNorm(config.hidden_size, eps=config.rms_norm_eps) + rope = dict(config.rope_parameters) + rope.setdefault("mrope_interleaved", True) + self.rotary_emb = get_rope( + head_size=config.head_dim, + rotary_dim=int(config.head_dim * rope.get("partial_rotary_factor", 1.0)), + max_position=config.max_position_embeddings, + base=rope["rope_theta"], + is_neox_style=True, + rope_scaling=rope, + ) + + +class Qwen3_5Model(TextEncoder): + """Qwen3.5 text-only prefill for diffusion conditioning.""" + + layer_names = ["language_model.layers"] + host_resident_table_names = ["language_model.embed_tokens"] + + _supported_attention_backends = { + AttentionBackendEnum.FA, + AttentionBackendEnum.TORCH_SDPA, + } + + def __init__(self, config: Qwen3_5EncoderConfig): + super().__init__(config) + if config.quant_config is not None: + raise NotImplementedError( + "Qwen3.5 diffusion encoder quantization is not supported" + ) + self.language_model = Qwen3_5TextModel(config.arch_config.text_config) + + @staticmethod + def should_materialize_checkpoint_weight(name: str) -> bool: + return not name.startswith("visual.") + + def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: + params = dict(self.named_parameters()) + loaded = set() + for name, weight in weights: + if not self.should_materialize_checkpoint_weight(name): + continue + if name not in params: + raise KeyError(name) + loaded.add(load_stacked_weight(name, weight, params, ())) + return loaded + + @torch.no_grad() + def forward( + self, + input_ids=None, + position_ids=None, + attention_mask=None, + inputs_embeds=None, + output_hidden_states=None, + use_cache=False, + return_dict=None, + past_key_values=None, + **kwargs, + ): + if output_hidden_states is None: + output_hidden_states = self.config.output_hidden_states + if return_dict is None: + return_dict = self.config.use_return_dict + if use_cache or past_key_values is not None: + raise ValueError( + "Qwen3.5 diffusion encoding does not use an autoregressive cache" + ) + if (input_ids is None) == (inputs_embeds is None): + raise ValueError("Specify exactly one of input_ids or inputs_embeds") + if any( + kwargs.get(name) is not None + for name in ( + "pixel_values", + "pixel_values_videos", + "image_grid_thw", + "video_grid_thw", + ) + ): + raise ValueError("Qwen3.5 diffusion encoder accepts text inputs only") + model = self.language_model + hidden_states = ( + model.embed_tokens(input_ids) if inputs_embeds is None else inputs_embeds + ) + batch, length, _ = hidden_states.shape + if position_ids is None: + position_ids = torch.arange(length, device=hidden_states.device)[ + None + ].expand(batch, -1) + if position_ids.ndim == 2: + position_ids = position_ids[None].expand(3, -1, -1) + elif position_ids.shape[0] == 4: + position_ids = position_ids[1:] + padding_mask = attention_mask + if padding_mask is not None and bool(torch.all(padding_mask == 1)): + padding_mask = None + causal_mask = None + if padding_mask is not None: + causal_mask = torch.ones( + length, length, dtype=torch.bool, device=hidden_states.device + ).tril() + causal_mask = ( + causal_mask[None, None] & padding_mask[:, None, None, :].bool() + ) + all_hidden = () if output_hidden_states else None + for layer in model.layers: + if output_hidden_states: + all_hidden += (hidden_states,) + hidden_states = layer( + hidden_states, position_ids, model.rotary_emb, causal_mask, padding_mask + ) + hidden_states = model.norm(hidden_states) + if output_hidden_states: + all_hidden += (hidden_states,) + if not return_dict: + return ( + (hidden_states, all_hidden) + if output_hidden_states + else (hidden_states,) + ) + return BaseEncoderOutput( + last_hidden_state=hidden_states, hidden_states=all_hidden + ) + + +EntryClass = Qwen3_5Model diff --git a/python/sglang/multimodal_gen/runtime/models/schedulers/moss_image.py b/python/sglang/multimodal_gen/runtime/models/schedulers/moss_image.py new file mode 100644 index 0000000000..0d4e3feeee --- /dev/null +++ b/python/sglang/multimodal_gen/runtime/models/schedulers/moss_image.py @@ -0,0 +1,88 @@ +# SPDX-License-Identifier: Apache-2.0 + +# Reference implementation license: +# BSD 3-Clause License +# +# (c) Meta Platforms, Inc. and affiliates. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice,this list +# of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above copyright notice, this +# list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# 3. Neither the name of the copyright holder nor the names of its contributors may +# be used to endorse or promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY +# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT +# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR +# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH +# DAMAGE. + +import math + +import torch +from diffusers import FlowMatchEulerDiscreteScheduler +from diffusers.configuration_utils import register_to_config + + +class MOSSImageScheduler(FlowMatchEulerDiscreteScheduler): + """Euler integration using the training project's V2, nearest-grid schedule.""" + + @register_to_config + def __init__(self, num_train_timesteps=1000, shift=5.0, training_shift=1.0): + super().__init__(num_train_timesteps=num_train_timesteps, shift=1.0) + self.register_to_config(shift=shift, training_shift=training_shift) + + def set_timesteps(self, num_inference_steps=50, device=None): + if ( + not isinstance(num_inference_steps, int) + or num_inference_steps < 1 + or not math.isfinite(self.config.shift) + or self.config.shift <= 0 + or not math.isfinite(self.config.training_shift) + or self.config.training_shift <= 0 + ): + raise ValueError("Steps and shifts must be positive.") + total = self.config.num_train_timesteps + + def grid(count, shift): + lower = shift / (total + shift - 1) + values = torch.linspace(1, lower, count) + return shift * values / (1 + (shift - 1) * values) + + sigmas = grid(num_inference_steps, self.config.shift) + training = grid(total, self.config.training_shift).flip(0) + upper = torch.searchsorted(training, sigmas).clamp(max=total - 1) + lower = (upper - 1).clamp(min=0) + nearest = torch.where( + (sigmas - training[lower]).abs() <= (training[upper] - sigmas).abs(), + lower, + upper, + ) + sigmas = torch.unique_consecutive(training[nearest]) + # Our sigmas have already been shifted and snapped. Avoid a second shift. + self._shift = 1.0 + super().set_timesteps(device=device, sigmas=sigmas.tolist()) + + def set_shift(self, shift): + if not math.isfinite(shift) or shift <= 0: + raise ValueError("shift must be positive") + self.register_to_config(shift=shift) + + def scale_model_input(self, sample, timestep=None): + return sample + + +EntryClass = MOSSImageScheduler diff --git a/python/sglang/multimodal_gen/runtime/pipelines/moss_image.py b/python/sglang/multimodal_gen/runtime/pipelines/moss_image.py new file mode 100644 index 0000000000..8e85ab7678 --- /dev/null +++ b/python/sglang/multimodal_gen/runtime/pipelines/moss_image.py @@ -0,0 +1,64 @@ +# SPDX-License-Identifier: Apache-2.0 + +from sglang.multimodal_gen.configs.pipeline_configs.moss_image import ( + MOSSImagePipelineConfig, +) +from sglang.multimodal_gen.configs.sample.moss_image import MOSSImageSamplingParams +from sglang.multimodal_gen.runtime.disaggregation.roles import RoleType +from sglang.multimodal_gen.runtime.pipelines_core.composed_pipeline_base import ( + ComposedPipelineBase, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.input_validation import ( + InputValidationStage, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.moss_image import ( + MOSSImageBeforeDenoisingStage, + MOSSImageDenoisingStage, +) + + +class MOSSImagePipeline(ComposedPipelineBase): + pipeline_name = "MOSSImagePipeline" + pipeline_config_cls = MOSSImagePipelineConfig + sampling_params_cls = MOSSImageSamplingParams + _required_config_modules = [ + "text_encoder", + "tokenizer", + "vae", + "transformer", + "scheduler", + ] + + def _load_config(self): + config = super()._load_config() + # Route the export's custom classes through the standard SGLang loaders. + for name, architecture in ( + ("transformer", "MOSSImageTransformer"), + ("scheduler", "MOSSImageScheduler"), + ): + if config.get(name) == ["pipeline_moss_image", architecture]: + config[name] = ["diffusers", architecture] + return config + + def create_pipeline_stages(self, server_args): + self.add_stage(InputValidationStage()) + self.add_stage( + MOSSImageBeforeDenoisingStage( + text_encoder=self.get_module("text_encoder"), + tokenizer=self.get_module("tokenizer"), + scheduler=self.get_module("scheduler"), + ) + ) + self.add_stage_factory( + RoleType.DENOISER, + lambda: MOSSImageDenoisingStage( + transformer=self.get_module("transformer"), + scheduler=self.get_module("scheduler"), + pipeline=self, + ), + "denoising_stage", + ) + self.add_standard_decoding_stage() + + +EntryClass = MOSSImagePipeline diff --git a/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/moss_image.py b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/moss_image.py new file mode 100644 index 0000000000..f65ca90021 --- /dev/null +++ b/python/sglang/multimodal_gen/runtime/pipelines_core/stages/model_specific_stages/moss_image.py @@ -0,0 +1,393 @@ +# SPDX-License-Identifier: Apache-2.0 + +# Reference implementation license: +# BSD 3-Clause License +# +# (c) Meta Platforms, Inc. and affiliates. +# +# Redistribution and use in source and binary forms, with or without modification, +# are permitted provided that the following conditions are met: +# +# 1. Redistributions of source code must retain the above copyright notice,this list +# of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above copyright notice, this +# list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# 3. Neither the name of the copyright holder nor the names of its contributors may +# be used to endorse or promote products derived from this software without specific +# prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY +# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT +# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR +# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH +# DAMAGE. + +import math +from dataclasses import replace + +import torch +from diffusers.utils.torch_utils import randn_tensor + +from sglang.multimodal_gen.configs.sample.moss_image import ( + MOSSImageSamplingParams, + resolve_uncond_skip_layers, +) +from sglang.multimodal_gen.configs.sample.sampling_params import quality_allows +from sglang.multimodal_gen.runtime.cache.conditioning import ( + cached_encoder_call, + prefer_conditioning_cache, +) +from sglang.multimodal_gen.runtime.distributed import get_local_torch_device +from sglang.multimodal_gen.runtime.distributed.cfg_parallel_utils import ( + run_cfg_parallel, +) +from sglang.multimodal_gen.runtime.distributed.cfg_policy import CFGPolicy +from sglang.multimodal_gen.runtime.managers.forward_context import set_forward_context +from sglang.multimodal_gen.runtime.managers.memory_managers.component_manager import ( + ComponentUse, +) +from sglang.multimodal_gen.runtime.models.dits.moss_image import validate_skip_layers +from sglang.multimodal_gen.runtime.pipelines_core.diffusion_scheduler_utils import ( + get_or_create_request_scheduler, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.base import PipelineStage +from sglang.multimodal_gen.runtime.pipelines_core.stages.denoising import DenoisingStage + + +class MOSSImageDenoisingStage(DenoisingStage): + @staticmethod + def _has_extra_slg(params: MOSSImageSamplingParams) -> bool: + return bool(params.slg_layers) and params.slg_scale > 0.0 + + @classmethod + def _has_dynamic_guidance(cls, params: MOSSImageSamplingParams) -> bool: + return cls._has_extra_slg(params) or ( + bool(resolve_uncond_skip_layers(params)) + and (params.slg_start != 0.0 or params.slg_stop != 1.0) + ) + + @staticmethod + def _with_uncond_skip_layers( + cfg_policy: CFGPolicy, skip_layers: tuple[int, ...] + ) -> CFGPolicy: + if all( + branch.is_conditional + or tuple(branch.kwargs.get("skip_layers", ())) == skip_layers + for branch in cfg_policy.branches + ): + return cfg_policy + # Preserve the request-wide branches when changing one step's topology. + return replace( + cfg_policy, + branches=[ + branch + if branch.is_conditional + else replace( + branch, kwargs={**branch.kwargs, "skip_layers": skip_layers} + ) + for branch in cfg_policy.branches + ], + ) + + def _predict_noise_with_cfg( + self, + current_model, + latent_model_input, + timestep, + batch, + timestep_index, + attn_metadata, + target_dtype, + current_guidance_scale, + cfg_policy, + cfg_gate_state, + server_args, + guidance, + latents, + ): + params = batch.sampling_params + active = ( + params.slg_start <= timestep_index / len(batch.timesteps) < params.slg_stop + ) + uncond_layers = resolve_uncond_skip_layers(params) if active else () + cfg_policy = self._with_uncond_skip_layers(cfg_policy, uncond_layers) + # A cached CFG delta represents the old branch topology. Keep the + # reference's actual forwards when guidance changes within a request. + if self._has_dynamic_guidance(params): + cfg_gate_state = None + if not (active and self._has_extra_slg(params)): + return super()._predict_noise_with_cfg( + current_model=current_model, + latent_model_input=latent_model_input, + timestep=timestep, + batch=batch, + timestep_index=timestep_index, + attn_metadata=attn_metadata, + target_dtype=target_dtype, + current_guidance_scale=current_guidance_scale, + cfg_policy=cfg_policy, + cfg_gate_state=cfg_gate_state, + server_args=server_args, + guidance=guidance, + latents=latents, + ) + + config = server_args.pipeline_config + + def predict(branch): + branch.configure_batch(batch) + with set_forward_context( + current_timestep=timestep_index, + attn_metadata=attn_metadata, + forward_batch=batch, + ): + prediction = self._predict_noise( + current_model=current_model, + latent_model_input=latent_model_input, + timestep=timestep, + target_dtype=target_dtype, + guidance=guidance, + **branch.kwargs, + ) + return config.slice_noise_pred(prediction, latents).float() + + slg_branch = replace( + cfg_policy.branches[0], + kwargs={ + **cfg_policy.branches[0].kwargs, + "skip_layers": tuple(params.slg_layers), + }, + ) + expanded_policy = replace( + cfg_policy, branches=[*cfg_policy.branches, slg_branch] + ) + predictions = ( + run_cfg_parallel(expanded_policy, predict) + if server_args.enable_cfg_parallel + else [predict(branch) for branch in expanded_policy.branches] + ) + noise_pred = cfg_policy.combine( + predictions[:-1], + batch, + config.get_classifier_free_guidance_scale(batch, current_guidance_scale), + config, + cfg_parallel=server_args.enable_cfg_parallel, + ) + skipped = predictions[-1] + if not batch.do_classifier_free_guidance: + # Reference CFG=1 SLG uses the skipped prediction as its base. + noise_pred = skipped + return noise_pred + params.slg_scale * (predictions[0] - skipped) + + def _before_denoising_loop(self, ctx, batch, server_args): + super()._before_denoising_loop(ctx, batch, server_args) + self._manage_dit_use_site(self.transformer, "transformer", batch) + height, width = ctx.latents.shape[-2:] + with set_forward_context(0, None): + for branch in ctx.cfg_policy.branches: + kwargs = branch.kwargs + kwargs["prepared_conditioning"] = self.transformer.prepare_conditioning( + kwargs["encoder_hidden_states"], + kwargs.get("encoder_attention_mask"), + height, + width, + ctx.target_dtype, + batch_samples=quality_allows( + batch.sampling_params.quality, "lossless" + ), + ) + + +class MOSSImageBeforeDenoisingStage(PipelineStage): + def __init__(self, text_encoder, tokenizer, scheduler): + super().__init__() + self.text_encoder = text_encoder + self.tokenizer = tokenizer + self.scheduler = scheduler + + def component_uses(self, server_args, stage_name=None): + return [ + ComponentUse( + self._component_stage_name(stage_name), + "text_encoder", + memory_intensive=True, + start_at_stage_entry=False, + ) + ] + + @torch.no_grad() + def _encode_prompt(self, prompts, device, max_sequence_length=4096): + rows = [] + for prompt in prompts: + formatted = self.tokenizer.apply_chat_template( + [{"role": "user", "content": prompt}], + tokenize=False, + add_generation_prompt=True, + enable_thinking=True, + ) + inputs = self.tokenizer( + formatted, + return_tensors="pt", + truncation=True, + max_length=max_sequence_length, + ) + + def encode_row(): + self.begin_declared_component_use( + component_name="text_encoder", module=self.text_encoder + ) + with set_forward_context(0, None): + output = self.text_encoder( + **inputs.to(device), use_cache=False, return_dict=True + ) + return output.last_hidden_state[0] + + rows.append( + cached_encoder_call( + self.text_encoder, + (dict(inputs),), + {"device": str(device)}, + encode_row, + namespace=self, + nested=False, + share_in_group=True, + ) + ) + self.finish_unused_declared_component( + component_name="text_encoder", module=self.text_encoder + ) + length = max(row.shape[0] for row in rows) + embeds = rows[0].new_zeros(len(rows), length, rows[0].shape[-1]) + mask = torch.zeros(len(rows), length, dtype=torch.bool, device=device) + for index, row in enumerate(rows): + embeds[index, : row.shape[0]] = row + mask[index, : row.shape[0]] = True + return embeds, mask + + @staticmethod + def _validate_request(batch, server_args): + params = batch.sampling_params + try: + valid_scale = math.isfinite(params.slg_scale) and params.slg_scale >= 0 + except (TypeError, ValueError): + valid_scale = False + if not valid_scale: + raise ValueError("MOSSImage slg_scale must be finite and nonnegative.") + validate_skip_layers( + resolve_uncond_skip_layers(params), + server_args.pipeline_config.dit_config.arch_config.num_layers, + ) + validate_skip_layers( + params.slg_layers if params.slg_layers is not None else (), + server_args.pipeline_config.dit_config.arch_config.num_layers, + ) + try: + valid_window = 0 <= params.slg_start <= params.slg_stop <= 1 + except (TypeError, ValueError): + valid_window = False + if not valid_window: + raise ValueError("MOSSImage requires 0 <= slg_start <= slg_stop <= 1.") + if ( + not isinstance(batch.height, int) + or not isinstance(batch.width, int) + or batch.height <= 0 + or batch.width <= 0 + or batch.height % 16 + or batch.width % 16 + ): + raise ValueError( + "MOSSImage height and width must be positive multiples of 16." + ) + if not math.isfinite(batch.guidance_scale) or batch.guidance_scale < 0: + raise ValueError("MOSSImage guidance_scale must be finite and nonnegative.") + prompts = [batch.prompt] if isinstance(batch.prompt, str) else batch.prompt + if not prompts or not all(isinstance(p, str) for p in prompts): + raise ValueError( + "MOSSImage requires a prompt string or nonempty list of strings." + ) + count = batch.num_outputs_per_prompt + if count < 1: + raise ValueError("num_outputs_per_prompt must be positive.") + max_length = batch.max_sequence_length + if max_length is None: + max_length = batch.sampling_params.max_sequence_length + max_length = 4096 if max_length is None else max_length + if not 1 <= max_length <= 4096: + raise ValueError( + "MOSSImage max_sequence_length must be between 1 and 4096." + ) + if batch.flow_shift is not None and ( + not math.isfinite(batch.flow_shift) or batch.flow_shift <= 0 + ): + raise ValueError("MOSSImage flow_shift must be finite and positive.") + return prompts, max_length + + def _prepare_prompt_embeddings(self, batch, prompts, device, max_length): + count = batch.num_outputs_per_prompt + embeds, mask = self._encode_prompt(prompts, device, max_length) + batch.prompt_embeds = [embeds.repeat_interleave(count, 0)] + batch.prompt_attention_mask = mask.repeat_interleave(count, 0) + if batch.do_classifier_free_guidance: + negative = ( + batch.negative_prompt if batch.negative_prompt is not None else "" + ) + negative = ( + [negative] * len(prompts) if isinstance(negative, str) else negative + ) + if len(negative) != len(prompts): + raise ValueError("negative_prompt must match the prompt batch size.") + with prefer_conditioning_cache(): + embeds, mask = self._encode_prompt(negative, device, max_length) + batch.negative_prompt_embeds = [embeds.repeat_interleave(count, 0)] + batch.negative_attention_mask = mask.repeat_interleave(count, 0) + + @staticmethod + def _prepare_latents(batch, *, batch_size, latent_channels, device): + shape = ( + batch_size, + latent_channels, + batch.height // 16, + batch.width // 16, + ) + if batch.latents is None: + batch.latents = randn_tensor( + shape, generator=batch.generator, device=device, dtype=torch.float32 + ) + elif tuple(batch.latents.shape) != shape: + raise ValueError(f"MOSSImage latents must have shape {shape}.") + else: + batch.latents = batch.latents.to(device=device, dtype=torch.float32) + batch.raw_latent_shape = shape + + def _prepare_timesteps(self, batch, device): + scheduler = get_or_create_request_scheduler( + batch, self.scheduler, isolate=batch.flow_shift is not None + ) + if batch.flow_shift is not None: + scheduler.set_shift(batch.flow_shift) + scheduler.set_timesteps(batch.num_inference_steps, device=device) + batch.timesteps = scheduler.timesteps + batch.num_inference_steps = len(batch.timesteps) + batch.sigmas = scheduler.sigmas.tolist() + + @torch.no_grad() + def forward(self, batch, server_args): + prompts, max_length = self._validate_request(batch, server_args) + device = get_local_torch_device() + self._prepare_prompt_embeddings(batch, prompts, device, max_length) + self._prepare_latents( + batch, + batch_size=len(prompts) * batch.num_outputs_per_prompt, + latent_channels=server_args.pipeline_config.dit_config.arch_config.latent_channels, + device=device, + ) + self._prepare_timesteps(batch, device) + return batch diff --git a/python/sglang/multimodal_gen/test/unit/test_moss_image.py b/python/sglang/multimodal_gen/test/unit/test_moss_image.py new file mode 100644 index 0000000000..68f7b4b354 --- /dev/null +++ b/python/sglang/multimodal_gen/test/unit/test_moss_image.py @@ -0,0 +1,1027 @@ +# SPDX-License-Identifier: Apache-2.0 + +import json +from types import SimpleNamespace + +import pytest +import torch + +from sglang.multimodal_gen.configs.models.dits.moss_image import ( + MOSSImageArchConfig, + MOSSImageDiTConfig, +) +from sglang.multimodal_gen.configs.pipeline_configs.moss_image import ( + MOSSImagePipelineConfig, +) +from sglang.multimodal_gen.configs.sample.moss_image import MOSSImageSamplingParams +from sglang.multimodal_gen.runtime.distributed.cfg_policy import CFGPolicy +from sglang.multimodal_gen.runtime.managers.forward_context import set_forward_context +from sglang.multimodal_gen.runtime.models.dits.moss_image import ( + MOSSImageTransformer, + _RoPE, +) +from sglang.multimodal_gen.runtime.models.schedulers.moss_image import ( + MOSSImageScheduler, +) +from sglang.multimodal_gen.runtime.pipelines_core.schedule_batch import Req +from sglang.multimodal_gen.runtime.pipelines_core.stages.decoding import ( + scale_and_shift_latents, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.input_validation import ( + InputValidationStage, +) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.moss_image import ( + MOSSImageBeforeDenoisingStage, + MOSSImageDenoisingStage, +) + + +@pytest.fixture(autouse=True) +def cpu_attention_backend(monkeypatch): + from sglang.multimodal_gen.runtime.server_args import get_global_server_args + + monkeypatch.setattr(get_global_server_args(), "attention_backend", "torch_sdpa") + + +def test_v2_schedule_and_shift_override(): + scheduler = MOSSImageScheduler(shift=1) + scheduler.set_shift(5) + scheduler.set_timesteps(5) + # Golden V2 nearest-training-grid values from the standalone reference. + torch.testing.assert_close( + scheduler.timesteps, + torch.tensor([1000.0, 938.0, 835.0, 630.0, 24.0]), + rtol=0, + atol=0, + ) + torch.testing.assert_close( + scheduler.sigmas, + torch.tensor([1.0, 0.938, 0.835, 0.630, 0.024, 0.0]), + rtol=0, + atol=0, + ) + sample = torch.ones(1, 8, 2, 2) + scheduler.step(torch.ones_like(sample), scheduler.timesteps[0], sample) + scheduler.set_timesteps(5) + assert scheduler.step_index is None + with pytest.raises(ValueError): + scheduler.set_shift(0) + + +@pytest.mark.parametrize("invalid", [None, 22, [True], [-1], [42], [1.5], ["22"]]) +def test_formal_skip_layer_validation(invalid): + from sglang.multimodal_gen.runtime.models.dits.moss_image import ( + validate_skip_layers, + ) + + with pytest.raises(ValueError, match="skip_layers"): + validate_skip_layers(invalid, 42) + + +def test_unsupported_quantization_is_not_silently_ignored(): + with pytest.raises(NotImplementedError, match="quantization"): + MOSSImageTransformer(MOSSImageDiTConfig(), quant_config=object()) + + +def test_formal_guidance_is_unconditional_only_and_request_scoped(): + from sglang.multimodal_gen.configs.sample.moss_image import MOSSImageSamplingParams + + config = MOSSImagePipelineConfig() + default = MOSSImageSamplingParams() + disabled = MOSSImageSamplingParams(uncond_skip_layers=[]) + for params, expected in ((default, (22,)), (disabled, ()), (default, (22,))): + batch = SimpleNamespace(sampling_params=params) + positive = config.prepare_pos_cond_kwargs(batch, "cpu", None, torch.bfloat16) + negative = config.prepare_neg_cond_kwargs(batch, "cpu", None, torch.bfloat16) + assert "skip_layers" not in positive + assert negative["skip_layers"] == expected + + +@pytest.mark.parametrize( + "extra", + [ + {"uncond_skip_layers": [0, 41]}, + {"uncond_skip_layers": []}, + {"uncond_skip_layers": [22], "slg_start": 0.01, "slg_stop": 1.0}, + { + "uncond_skip_layers": [], + "slg_layers": [22], + "slg_scale": 3.0, + "slg_start": 0.01, + "slg_stop": 1.0, + }, + ], +) +@pytest.mark.parametrize("nested", [False, True]) +def test_image_api_preserves_model_owned_guidance_fields(extra, nested): + from sglang.multimodal_gen.configs.sample.moss_image import MOSSImageSamplingParams + from sglang.multimodal_gen.configs.sample.sampling_params import SamplingParams + from sglang.multimodal_gen.runtime.entrypoints.openai.protocol import ( + ImageGenerationsRequest, + ) + from sglang.multimodal_gen.runtime.entrypoints.openai.utils import ( + request_model_kwargs, + ) + + request = ImageGenerationsRequest( + prompt="example", **({"extra_params": extra} if nested else extra) + ) + kwargs = request_model_kwargs(request, MOSSImageSamplingParams, "image") + assert kwargs == extra + params = MOSSImageSamplingParams(**kwargs) + for name, value in extra.items(): + assert getattr(params, name) == value + assert request_model_kwargs(request, SamplingParams, "image") == {} + + +def test_dit_skips_requested_layer_and_restores_full_forward(): + config = MOSSImageDiTConfig( + arch_config=MOSSImageArchConfig( + dim=64, + ffn_dim=128, + num_heads=2, + num_layers=2, + text_dim=32, + freq_dim=16, + latent_channels=8, + ) + ) + torch.manual_seed(0) + model = MOSSImageTransformer(config).eval() + calls = [] + hooks = [ + layer.register_forward_pre_hook(lambda module, args, i=i: calls.append(i)) + for i, layer in enumerate(model.layers) + ] + latent = torch.randn(1, 8, 2, 3) + text = torch.randn(1, 3, 32) + with torch.no_grad(), set_forward_context(0, None): + expected = model(latent, torch.tensor(500.0), text) + skipped = model(latent, torch.tensor(500.0), text, skip_layers=[1]) + restored = model(latent, torch.tensor(500.0), text) + for hook in hooks: + hook.remove() + assert calls == [0, 1, 0, 0, 1] + assert torch.equal(expected, restored) + assert not torch.equal(expected, skipped) + + +@pytest.mark.parametrize("name", ["Base", "SFT"]) +def test_model_identifiers_resolve_native_configs(name, monkeypatch, tmp_path): + """Resolve registered model IDs and local snapshots through native configs.""" + from sglang.multimodal_gen import registry + + config = {"_class_name": "MOSSImagePipeline", "_diffusers_version": "0.38.0"} + monkeypatch.setattr(registry, "maybe_download_model_index", lambda _: config) + for path in ( + f"OpenMOSS-Team/MOSS-Image-{name}", + str(tmp_path / f"MOSS-Image-{name}"), + ): + info = registry.get_model_info(path, backend="sglang") + assert info.pipeline_cls.__name__ == "MOSSImagePipeline" + assert info.pipeline_config_cls is MOSSImagePipelineConfig + + +def test_rope_keeps_fp32_derived_buffer_after_assign_loading(): + rope = _RoPE(128, 10000) + bands = rope.bands.clone() + rope.to(torch.bfloat16) + assert rope.bands.dtype == torch.float32 + assert torch.equal(rope.bands, bands) + rope.load_state_dict( + {"bands": torch.nn.Parameter(bands.bfloat16(), requires_grad=False)}, + assign=True, + ) + assert "bands" in dict(rope.named_buffers()) + assert "bands" not in dict(rope.named_parameters()) + assert torch.equal(rope.bands, bands) + + +def test_joint_attention_ignores_padded_text_tokens(): + torch.manual_seed(0) + config = MOSSImageDiTConfig( + arch_config=MOSSImageArchConfig( + dim=64, + ffn_dim=128, + num_heads=2, + num_layers=2, + text_dim=32, + freq_dim=16, + latent_channels=8, + ) + ) + model = MOSSImageTransformer(config).eval() + latents = torch.randn(1, 8, 2, 3) + text = torch.randn(1, 3, 32) + padded = torch.cat([text, torch.randn(1, 5, 32) * 1000], 1) + with torch.no_grad(), set_forward_context(0, None): + unpadded = model(latents, torch.tensor([630.0]), text) + masked = model( + latents, + torch.tensor([630.0]), + padded, + torch.tensor([[1, 1, 1, 0, 0, 0, 0, 0]], dtype=torch.bool), + ) + assert unpadded.abs().max() > 0 + assert torch.equal(unpadded, masked) + with pytest.raises(ValueError, match="at least one valid text token"): + model( + latents, + torch.tensor([630.0]), + text, + torch.zeros(1, 3, dtype=torch.bool), + ) + + +def test_vae_bn_denormalization_precedes_channel_major_unpacking(): + config = MOSSImagePipelineConfig() + latents = torch.arange(48, dtype=torch.bfloat16).reshape(1, 8, 2, 3) + mean = torch.arange(8, dtype=torch.float32) + var = torch.full((8,), 4.0) + vae = SimpleNamespace( + bn=SimpleNamespace(running_mean=mean, running_var=var), + config=SimpleNamespace(arch_config=SimpleNamespace(batch_norm_eps=0.0)), + ) + scaled = scale_and_shift_latents( + latents, SimpleNamespace(pipeline_config=config), vae + ) + actual = config.preprocess_decoding(scaled, vae=vae) + assert actual.dtype == torch.float32 + expected = torch.empty(1, 2, 4, 6) + for c in range(2): + for h in range(2): + for w in range(3): + for i in range(2): + for j in range(2): + k = 4 * c + 2 * i + j + expected[0, c, 2 * h + i, 2 * w + j] = ( + 2 * latents[0, k, h, w] + mean[k] + ) + assert torch.equal(actual, expected) + + +def test_encoder_respects_active_sdpa_policy(): + from torch.nn.attention import SDPBackend, sdpa_kernel + from transformers import BatchEncoding + + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.moss_image import ( + MOSSImageBeforeDenoisingStage, + ) + + class Tokenizer: + def apply_chat_template(self, messages, **kwargs): + assert kwargs["enable_thinking"] and kwargs["add_generation_prompt"] + return messages[0]["content"] + + def __call__(self, prompt, **kwargs): + assert kwargs["max_length"] == 4096 + return BatchEncoding({"input_ids": torch.ones(1, 2, dtype=torch.long)}) + + class Encoder: + def __call__(self, **kwargs): + assert not torch.backends.cuda.cudnn_sdp_enabled() + assert torch._C._get_sdp_priority_order() == expected_priority + return SimpleNamespace(last_hidden_state=torch.ones(1, 2, 4)) + + stage = MOSSImageBeforeDenoisingStage(Encoder(), Tokenizer(), None) + with sdpa_kernel( + [SDPBackend.FLASH_ATTENTION, SDPBackend.EFFICIENT_ATTENTION, SDPBackend.MATH], + set_priority=True, + ): + expected_priority = torch._C._get_sdp_priority_order() + for _ in range(2): + stage._encode_prompt(["a prompt"], torch.device("cpu")) + assert not torch.backends.cuda.cudnn_sdp_enabled() + assert torch._C._get_sdp_priority_order() == expected_priority + + +@pytest.mark.parametrize( + "library", ["pipeline_moss_image", "diffusers", "another_pipeline"] +) +def test_pipeline_uses_generic_component_loaders(tmp_path, monkeypatch, library): + from sglang.multimodal_gen.runtime.loader.component_loaders.component_loader import ( + ComponentLoader, + ) + from sglang.multimodal_gen.runtime.loader.component_loaders.scheduler_loader import ( + SchedulerLoader, + ) + from sglang.multimodal_gen.runtime.loader.component_loaders.text_encoder_loader import ( + TextEncoderLoader, + ) + from sglang.multimodal_gen.runtime.loader.component_loaders.transformer_loader import ( + TransformerLoader, + ) + from sglang.multimodal_gen.runtime.loader.component_loaders.vae_loader import ( + VAELoader, + ) + from sglang.multimodal_gen.runtime.pipelines.moss_image import MOSSImagePipeline + from sglang.multimodal_gen.runtime.pipelines_core import composed_pipeline_base + + model_index = { + "_class_name": "MOSSImagePipeline", + "_diffusers_version": "0.38.0", + "transformer": [library, "MOSSImageTransformer"], + "scheduler": [library, "MOSSImageScheduler"], + "text_encoder": ["transformers", "Qwen3_5Model"], + "vae": ["diffusers", "AutoencoderKLFlux2"], + } + for name in ("transformer", "scheduler", "text_encoder", "vae"): + (tmp_path / name).mkdir() + source = json.dumps(model_index) + index_path = tmp_path / "model_index.json" + index_path.write_text(source) + monkeypatch.setattr( + composed_pipeline_base, "maybe_download_model", lambda path, **kwargs: path + ) + pipeline = object.__new__(MOSSImagePipeline) + pipeline.model_path = str(tmp_path) + pipeline.server_args = SimpleNamespace(model_subfolder=None, revision=None) + config = pipeline._load_config() + expected_library = "diffusers" if library == "pipeline_moss_image" else library + assert not MOSSImagePipeline.component_loaders + for name, loader in ( + ("transformer", TransformerLoader), + ("scheduler", SchedulerLoader), + ): + assert config[name] == [expected_library, model_index[name][1]] + if expected_library == "diffusers": + assert ( + type(ComponentLoader.for_component_type(name, *config[name])) is loader + ) + else: + with pytest.raises(AssertionError, match="must be loaded from diffusers"): + ComponentLoader.for_component_type(name, *config[name]) + with pytest.raises(AssertionError, match="must be loaded from diffusers"): + ComponentLoader.for_component_type(name, "pipeline_moss_image") + + assert config["text_encoder"] == model_index["text_encoder"] + assert config["vae"] == model_index["vae"] + assert index_path.read_text() == source + assert ( + composed_pipeline_base.ComposedPipelineBase._load_config(pipeline) + == model_index + ) + assert ( + type(ComponentLoader.for_component_type("text_encoder", "transformers")) + is TextEncoderLoader + ) + assert type(ComponentLoader.for_component_type("vae", "diffusers")) is VAELoader + with pytest.raises(AssertionError, match="text_encoder must be loaded"): + ComponentLoader.for_component_type("text_encoder", "pipeline_moss_image") + + +def test_request_shift_and_text_limit_do_not_leak(monkeypatch): + from sglang.multimodal_gen.configs.sample.moss_image import MOSSImageSamplingParams + from sglang.multimodal_gen.runtime.pipelines_core.schedule_batch import Req + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages import ( + moss_image, + ) + + monkeypatch.setattr( + moss_image, "get_local_torch_device", lambda: torch.device("cpu") + ) + template = MOSSImageScheduler(shift=5) + stage = moss_image.MOSSImageBeforeDenoisingStage(None, None, template) + limits = [] + + def encode(prompts, device, max_sequence_length): + limits.append(max_sequence_length) + return torch.zeros(1, 2, 4), torch.ones(1, 2, dtype=torch.bool) + + monkeypatch.setattr(stage, "_encode_prompt", encode) + args = SimpleNamespace( + pipeline_config=MOSSImagePipelineConfig(), enable_cfg_parallel=False + ) + for shift in (3.0, None): + params = MOSSImageSamplingParams( + prompt="test", + height=16, + width=16, + num_inference_steps=5, + guidance_scale=1.0, + flow_shift=shift, + max_sequence_length=128, + seed=0, + ) + batch = Req(sampling_params=params) + batch.sampling_params.generator_device = "cpu" + InputValidationStage().forward(batch, args) + batch = stage.forward(batch, args) + assert batch.scheduler.config.shift == (3.0 if shift is not None else 5.0) + assert template.config.shift == 5.0 + assert limits == [128, 128] + + +@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16]) +def test_prepared_rope_matches_original_rotation(dtype): + from sglang.multimodal_gen.runtime.models.dits.moss_image import ( + _prepare_rope, + _rotate, + ) + + torch.manual_seed(0) + x = torch.randn(1, 15, 2, 32).to(dtype) + packed = _RoPE(32, 10000)(3, 4, 3, torch.device("cpu")).to(dtype) + sin, cos = packed.chunk(2, -1) + a, b = x.chunk(2, -1) + expected = torch.cat( + ( + a * cos.unsqueeze(-2) - b * sin.unsqueeze(-2), + b * cos.unsqueeze(-2) + a * sin.unsqueeze(-2), + ), + -1, + ) + assert torch.equal(_rotate(x, _prepare_rope(packed)), expected) + + +@pytest.fixture +def small_model(): + config = MOSSImageDiTConfig( + arch_config=MOSSImageArchConfig( + dim=64, + ffn_dim=128, + num_heads=2, + num_layers=2, + text_dim=32, + freq_dim=16, + latent_channels=8, + ) + ) + return MOSSImageTransformer(config).eval() + + +@pytest.mark.parametrize("dtype", [torch.float32, torch.bfloat16]) +def test_prepared_conditioning_matches_steps_and_requests( + small_model, dtype, monkeypatch +): + model = small_model.to(dtype) + torch.manual_seed(0) + + def unexpected(*args, **kwargs): + pytest.fail("A denoising step repeated static conditioning work") + + # Different requests, spatial shapes and non-prefix masks must stay independent. + for height, width in [(2, 3), (3, 2), (2, 3)]: + text = torch.randn(2, 5, 32).to(dtype) + mask = torch.tensor([[1, 0, 1, 0, 0], [0, 1, 1, 1, 1]]) + with torch.no_grad(), set_forward_context(0, None): + prepared = model.prepare_conditioning(text, mask, height, width, dtype) + saved = [ + tensor.clone() + for group in prepared.groups + for tensor in (group.text, *group.rope) + ] + for timestep in (938.0, 24.0): + latents = torch.randn(2, 8, height, width) + expected = model(latents, timestep, text, mask) + with monkeypatch.context() as patch: + patch.setattr(model, "_unpad_text", unexpected) + patch.setattr(model, "_prepare_sample_conditioning", unexpected) + actual = model(latents, timestep, text, mask, prepared) + assert torch.equal(actual, expected) + current = [ + tensor + for group in prepared.groups + for tensor in (group.text, *group.rope) + ] + assert all(torch.equal(a, b) for a, b in zip(saved, current)) + + +@pytest.mark.parametrize("skip", [(), (1,)]) +@pytest.mark.parametrize("batch_samples", [False, True]) +def test_batch_groups_true_lengths_and_restores_sample_order( + small_model, skip, batch_samples +): + torch.manual_seed(42) + x, text = torch.randn(4, 8, 2, 3), torch.randn(4, 5, 32) + mask = torch.tensor( + [[1, 0, 1, 0, 0], [1, 1, 1, 1, 0], [0, 1, 0, 1, 0], [1, 1, 1, 0, 0]] + ) + times = torch.tensor([1000.0, 630.0, 24.0, 835.0]) + with torch.no_grad(), set_forward_context(0, None): + expected = torch.cat( + [ + small_model( + x[i : i + 1], + times[i], + text[i : i + 1], + mask[i : i + 1], + skip_layers=skip, + ) + for i in range(4) + ] + ) + calls = [] + hook = small_model.layers[0].register_forward_pre_hook( + lambda _, args: calls.append(args[0].shape[0]) + ) + try: + prepared = small_model.prepare_conditioning( + text, mask, 2, 3, torch.float32, batch_samples=batch_samples + ) + actual = small_model( + x, times, text, mask, prepared_conditioning=prepared, skip_layers=skip + ) + finally: + hook.remove() + assert calls == ([2, 1, 1] if batch_samples else [1, 1, 1, 1]) + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-5) + + +@pytest.mark.parametrize( + "mask", [torch.zeros(1, 3), torch.tensor([[1.0, 0.5, 0.0]]), torch.ones(1, 2)] +) +def test_prepare_conditioning_rejects_invalid_masks(small_model, mask): + with torch.no_grad(), set_forward_context(0, None), pytest.raises(ValueError): + small_model.prepare_conditioning( + torch.randn(1, 3, 32), mask, 2, 3, torch.float32 + ) + + +@pytest.mark.parametrize("shape", [(1, 8, 3, 2), (2, 8, 2, 3)]) +def test_prepared_conditioning_requires_matching_latents(small_model, shape): + text = torch.randn(1, 3, 32) + with torch.no_grad(), set_forward_context(0, None): + prepared = small_model.prepare_conditioning(text, None, 2, 3, torch.float32) + with pytest.raises(ValueError, match="latent batch and size"): + small_model( + torch.randn(shape), + 630.0, + text.expand(shape[0], -1, -1), + prepared_conditioning=prepared, + ) + + +@pytest.mark.parametrize("use_cfg", [False, True]) +def test_denoising_stage_prepares_actual_cfg_branches( + small_model, use_cfg, monkeypatch +): + from sglang.multimodal_gen.runtime.distributed.cfg_policy import CFGPolicy + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.moss_image import ( + MOSSImageDenoisingStage, + ) + + batch = SimpleNamespace( + do_classifier_free_guidance=use_cfg, + sampling_params=SimpleNamespace(cfg_gate_step=1.0, quality="exact"), + ) + latents = torch.randn(1, 8, 2, 3) + pos = {"encoder_hidden_states": torch.randn(1, 3, 32)} + neg = {"encoder_hidden_states": torch.randn(1, 2, 32)} + ctx = SimpleNamespace( + cfg_policy=CFGPolicy().build(batch, {}, pos, neg), + pos_cond_kwargs=pos, + neg_cond_kwargs=neg, + latents=latents, + target_dtype=torch.float32, + scheduler=MOSSImageScheduler(), + timesteps=torch.tensor([938.0, 24.0]), + extra={}, + ) + stage = object.__new__(MOSSImageDenoisingStage) + stage.transformer = small_model + uses = [] + monkeypatch.setattr(stage, "_manage_dit_use_site", lambda *args: uses.append(args)) + with torch.no_grad(), set_forward_context(0, None): + stage._before_denoising_loop( + ctx, batch, SimpleNamespace(enable_cfg_parallel=False) + ) + assert uses == [(small_model, "transformer", batch)] + assert len(ctx.cfg_policy.branches) == (2 if use_cfg else 1) + for branch in ctx.cfg_policy.branches: + assert "prepared_conditioning" in branch.kwargs + expected = small_model( + latents, 938.0, branch.kwargs["encoder_hidden_states"] + ) + actual = small_model(latents, 938.0, **branch.kwargs) + assert torch.equal(actual, expected) + + +@pytest.fixture +def text_stage(): + from transformers import BatchEncoding + + from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.moss_image import ( + MOSSImageBeforeDenoisingStage, + ) + + class Tokenizer: + prefix = "" + token_offset = 0 + + def apply_chat_template(self, messages, **kwargs): + return self.prefix + messages[0]["content"] + + def __call__(self, prompt, **kwargs): + ids = [ord(char) % 13 + 1 + self.token_offset for char in prompt] + [2] + ids = torch.tensor([ids[: kwargs["max_length"]]], dtype=torch.long) + return BatchEncoding( + {"input_ids": ids, "attention_mask": torch.ones_like(ids)} + ) + + class Encoder(torch.nn.Module): + def __init__(self): + super().__init__() + self.scale = torch.nn.Parameter(torch.arange(1, 5, dtype=torch.float32)) + self.calls = 0 + + def forward(self, input_ids, **kwargs): + self.calls += 1 + return SimpleNamespace( + last_hidden_state=input_ids.to(self.scale.dtype).unsqueeze(-1) + * self.scale + ) + + return MOSSImageBeforeDenoisingStage( + Encoder().eval(), Tokenizer(), MOSSImageScheduler() + ) + + +def test_conditioning_cache_preserves_padding_and_request_ownership( + text_stage, +): + from sglang.multimodal_gen.runtime.cache.conditioning import ConditioningCache + + stage = text_stage + prompts = ["short", "short", "a longer negative"] + device = torch.device("cpu") + expected, expected_mask = stage._encode_prompt(prompts, device) + stage.text_encoder.calls = 0 + cache = ConditioningCache(max_bytes=1024 * 1024) + with cache.scope(): + first, mask = stage._encode_prompt(prompts, device) + first.add_(1000) + actual, _ = stage._encode_prompt(prompts, device) + assert stage.text_encoder.calls == 2 + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + assert torch.equal(mask, expected_mask) + + +@pytest.mark.parametrize("change", ["template", "vocabulary", "truncation"]) +def test_conditioning_cache_keys_actual_tokens(text_stage, change): + from sglang.multimodal_gen.runtime.cache.conditioning import ConditioningCache + + stage = text_stage + device = torch.device("cpu") + cache = ConditioningCache(max_bytes=1024 * 1024) + with cache.scope(): + stage._encode_prompt(["negative"], device) + limit = 4096 + if change == "template": + stage.tokenizer.prefix = "prefix: " + elif change == "vocabulary": + stage.tokenizer.token_offset = 1 + else: + limit = 3 + actual, mask = stage._encode_prompt(["negative"], device, limit) + assert stage.text_encoder.calls == 2 + expected, expected_mask = stage._encode_prompt(["negative"], device, limit) + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + assert torch.equal(mask, expected_mask) + + +def test_pipeline_residency_declares_only_components_used_by_each_stage( + small_model, monkeypatch +): + from sglang.multimodal_gen.runtime.pipelines.moss_image import MOSSImagePipeline + from sglang.multimodal_gen.runtime.pipelines_core.stages.decoding import ( + DecodingStage, + ) + from sglang.multimodal_gen.runtime.server_args import get_global_server_args + + args = get_global_server_args() + monkeypatch.setattr(args, "pipeline_config", MOSSImagePipelineConfig()) + monkeypatch.setattr(args, "component_precisions", {}, raising=False) + pipe = object.__new__(MOSSImagePipeline) + pipe.modules = { + "transformer": small_model, + "text_encoder": torch.nn.Identity(), + "tokenizer": object(), + "scheduler": MOSSImageScheduler(), + "vae": torch.nn.Identity(), + } + stages = [] + monkeypatch.setattr(pipe, "add_stage", stages.append) + monkeypatch.setattr( + pipe, "add_stage_factory", lambda role, factory, name: stages.append(factory()) + ) + monkeypatch.setattr( + pipe, + "add_standard_decoding_stage", + lambda: stages.append(DecodingStage(vae=pipe.modules["vae"], pipeline=pipe)), + ) + pipe.create_pipeline_stages(args) + # Offload/auto-residency must see encoding -> DiT -> VAE. MOSSImage never + # uses the VAE in denoising, unlike the shared stage's TI2V callers. + assert [ + [use.component_name for use in stage.component_uses(args)] for stage in stages + ] == [[], ["text_encoder"], ["transformer"], ["vae"]] + assert stages[1].component_uses(args)[0].memory_intensive + assert stages[2].vae is None + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA") +@pytest.mark.parametrize("resident_layers", [0, 1]) +@pytest.mark.parametrize("skip_layers", [(), (0,), (1,), (0, 1)]) +def test_layerwise_offload_preserves_requests_and_streams( + small_model, resident_layers, skip_layers +): + torch.manual_seed(0) + model = small_model.to(device="cuda", dtype=torch.bfloat16) + text = torch.randn(1, 5, 32, device="cuda", dtype=torch.bfloat16) + timestep = torch.tensor([630.0], device="cuda") + latents = [ + torch.randn(1, 8, h, w, device="cuda", dtype=torch.bfloat16) + for h, w in [(2, 3), (3, 2), (2, 3)] + ] + with torch.inference_mode(), set_forward_context(0, None): + expected = [model(x, timestep, text, skip_layers=skip_layers) for x in latents] + model.configure_layerwise_offload( + SimpleNamespace( + performance_mode="manual", + pin_cpu_memory=True, + layerwise_tuning_for=lambda *args, **kwargs: ( + 1, + resident_layers, + "strided", + "forward", + ), + ) + ) + assert len(model.layerwise_offload_managers) == 1 + manager = model.layerwise_offload_managers[0] + assert manager.enabled and manager.num_layers == 2 + streams = [torch.cuda.Stream(), torch.cuda.Stream()] + torch.cuda.synchronize() + try: + for index, (x, reference) in enumerate(zip(latents, expected)): + with ( + torch.cuda.stream(streams[index % 2]), + torch.inference_mode(), + set_forward_context(0, None), + ): + model.prepare_for_next_req() + prepared = model.prepare_conditioning( + text, None, *x.shape[-2:], x.dtype + ) + output = model( + x, + timestep, + text, + prepared_conditioning=prepared, + skip_layers=skip_layers, + ) + manager.release_all() + torch.cuda.synchronize() + torch.testing.assert_close(output, reference, rtol=0, atol=0) + finally: + model.disable_offload() + manager.release_host_stores() + + +@pytest.mark.parametrize( + "guidance,expected_cfg", [(0.0, True), (0.5, True), (1.0, False), (5.0, True)] +) +@pytest.mark.parametrize("negative", [None, ""]) +def test_cfg_rule_applies_before_input_validation(guidance, expected_cfg, negative): + """Sub-unit guidance needs a negative branch before shared input validation. + + Previously only the model stage enabled it, so request validation and CFG + policy disagreed. Missing negative text must become the reference empty text. + """ + batch = Req( + sampling_params=MOSSImageSamplingParams( + prompt="test", + negative_prompt=negative, + guidance_scale=guidance, + generator_device="cpu", + ) + ) + assert batch.do_classifier_free_guidance is expected_cfg + result = InputValidationStage().forward( + batch, + SimpleNamespace( + pipeline_config=MOSSImagePipelineConfig(), + enable_cfg_parallel=False, + ), + ) + assert result.do_classifier_free_guidance is expected_cfg + assert result.negative_prompt == "" + + +VELOCITIES = { + (True, False): torch.tensor([1.0078125, -0.00390625]).reshape(1, 2, 1, 1), + (False, False): torch.tensor([-0.0078125, 0.015625]).reshape(1, 2, 1, 1), + (True, True): torch.tensor([0.00390625, -1.015625]).reshape(1, 2, 1, 1), + (False, True): torch.tensor([-1.0234375, 0.00390625]).reshape(1, 2, 1, 1), +} + + +@pytest.mark.parametrize( + "guidance,options,uncond_steps,extra_steps", + [ + (3.0, {"uncond_skip_layers": []}, (), ()), + (None, {}, (1, 2, 3), ()), + (3.0, {"uncond_skip_layers": [22], "slg_start": 0.0}, (0, 1, 2, 3), ()), + ( + 3.0, + {"uncond_skip_layers": [22], "slg_start": 0.01, "slg_stop": 1.0}, + (1, 2, 3), + (), + ), + ( + 3.0, + {"uncond_skip_layers": [22], "slg_start": 0.25, "slg_stop": 0.75}, + (1, 2), + (), + ), + ( + 5.0, + { + "slg_layers": [22], + "slg_scale": 3.0, + "slg_start": 0.01, + }, + (), + (1, 2, 3), + ), + ( + 5.0, + { + "uncond_skip_layers": [22], + "slg_layers": [22], + "slg_scale": 3.0, + "slg_start": 0.01, + }, + (1, 2, 3), + (1, 2, 3), + ), + ( + 1.0, + { + "slg_layers": [22], + "slg_scale": 3.0, + "slg_start": 0.25, + "slg_stop": 0.75, + }, + (), + (1, 2), + ), + (1.0, {"slg_layers": [22], "slg_scale": 1.0}, (), (1, 2, 3)), + (5.0, {"uncond_skip_layers": [], "slg_layers": [22], "slg_scale": 0.0}, (), ()), + (5.0, {"uncond_skip_layers": [], "slg_layers": [], "slg_scale": 3.0}, (), ()), + (5.0, {"uncond_skip_layers": [], "slg_layers": None, "slg_scale": 3.0}, (), ()), + ( + 5.0, + {"slg_layers": [22], "slg_scale": 3.0, "slg_start": 0.5, "slg_stop": 0.5}, + (), + (), + ), + (0.0, {"uncond_skip_layers": []}, (), ()), + (0.5, {"uncond_skip_layers": []}, (), ()), + ], +) +def test_guidance_formula_window_branch_count_and_request_isolation( + monkeypatch, guidance, options, uncond_steps, extra_steps +): + """Check reference branch topology, FP32 guidance and window boundaries.""" + if guidance is None: + params = MOSSImageSamplingParams(**options) + guidance = 3.0 # Recommended default from the reference recipe. + assert params.guidance_scale == guidance + else: + params = MOSSImageSamplingParams(guidance_scale=guidance, **options) + batch = Req( + sampling_params=params, + timesteps=torch.tensor([1000.0, 750.0, 500.0, 250.0]), + ) + config = MOSSImagePipelineConfig() + pos = {"encoder_hidden_states": torch.ones(1, 1, 2)} + neg = { + "encoder_hidden_states": -torch.ones(1, 1, 2), + **config.prepare_neg_cond_kwargs(batch, "cpu", None, torch.float32), + } + policy = CFGPolicy().build(batch, {}, pos, neg) + initial_kwargs = [dict(branch.kwargs) for branch in policy.branches] + stage = object.__new__(MOSSImageDenoisingStage) + calls = [] + + def predict(**kwargs): + conditional = bool(kwargs["encoder_hidden_states"][0, 0, 0] > 0) + skip = tuple(kwargs.get("skip_layers", ())) + assert batch.is_cfg_negative == (not conditional) + calls.append((conditional, skip)) + return VELOCITIES[(conditional, bool(skip))].clone() + + monkeypatch.setattr(stage, "_predict_noise", predict) + for index, timestep in enumerate(batch.timesteps): + start = len(calls) + actual = stage._predict_noise_with_cfg( + current_model=None, + latent_model_input=torch.zeros(1, 2, 1, 1), + timestep=timestep, + batch=batch, + timestep_index=index, + attn_metadata=None, + target_dtype=torch.float32, + current_guidance_scale=guidance, + cfg_policy=policy, + cfg_gate_state=None, + server_args=SimpleNamespace( + pipeline_config=config, enable_cfg_parallel=False + ), + guidance=None, + latents=torch.zeros(1, 2, 1, 1), + ) + conditional = VELOCITIES[(True, False)] + expected = conditional + expected_calls = [(True, ())] + if guidance != 1: + negative = VELOCITIES[(False, index in uncond_steps)] + expected = negative + guidance * (conditional - negative) + expected_calls.append((False, (22,) if index in uncond_steps else ())) + if index in extra_steps: + skipped = VELOCITIES[(True, True)] + if guidance == 1: + expected = skipped + expected = expected + params.slg_scale * (conditional - skipped) + expected_calls.append((True, (22,))) + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + assert calls[start:] == expected_calls + assert [branch.kwargs for branch in policy.branches] == initial_kwargs + + +@pytest.mark.parametrize( + "options,message", + [ + ({"uncond_skip_layers": 22}, "skip_layers"), + ({"slg_layers": [42]}, "skip_layers"), + ({"slg_scale": -1.0}, "slg_scale"), + ({"slg_scale": None}, "slg_scale"), + ({"slg_scale": "3"}, "slg_scale"), + ({"slg_scale": float("nan")}, "slg_scale"), + ({"slg_scale": float("inf")}, "slg_scale"), + ({"slg_start": -0.01}, "slg_start"), + ({"slg_stop": 1.01}, "slg_start"), + ({"slg_start": 0.8, "slg_stop": 0.2}, "slg_start"), + ({"slg_start": float("nan")}, "slg_start"), + ({"slg_stop": float("inf")}, "slg_start"), + ], +) +def test_invalid_guidance_is_rejected_before_encoding(options, message): + from sglang.multimodal_gen.runtime.pipelines_core.schedule_batch import Req + + stage = MOSSImageBeforeDenoisingStage(None, None, None) + batch = Req(sampling_params=MOSSImageSamplingParams(prompt="test", **options)) + with pytest.raises(ValueError, match=message): + stage.forward(batch, SimpleNamespace(pipeline_config=MOSSImagePipelineConfig())) + + +@pytest.mark.parametrize( + "mode,available_gib,explicit,expected", + [ + ("auto", 24, None, "layerwise-offload"), + ("auto", 39, None, "layerwise-offload"), + ("auto", 40, None, "resident"), + ("auto", 80, "component-offload", "component-offload"), + ("auto", 24, "resident", "resident"), + ("auto", 24, "layerwise-offload", "layerwise-offload"), + ("memory", 80, None, "layerwise-offload"), + ], +) +def test_pipeline_auto_uses_supported_encoder_offload( + monkeypatch, mode, available_gib, explicit, expected +): + from sglang.multimodal_gen.configs.pipeline_configs.base import PipelineConfig + from sglang.multimodal_gen.runtime.pipelines.moss_image import MOSSImagePipeline + from sglang.multimodal_gen.runtime.platforms import current_platform + from sglang.multimodal_gen.runtime.server_args import ServerArgs + + for name, value in { + "is_cpu": False, + "is_mps": False, + "is_cuda": True, + "get_device_total_memory": 80 * 1024**3, + "get_available_gpu_memory": available_gib, + "enable_dit_layerwise_offload_by_default": True, + }.items(): + monkeypatch.setattr( + current_platform, name, lambda *args, _value=value, **kwargs: _value + ) + monkeypatch.setattr( + PipelineConfig, "from_kwargs", lambda kwargs: MOSSImagePipelineConfig() + ) + args = ServerArgs.from_dict( + { + "model_path": "/fake", + "performance_mode": mode, + "component_residency": {"text_encoder": explicit} if explicit else None, + } + ) + pipe = object.__new__(MOSSImagePipeline) + pipe.modules = {} + pipe.initialize_pipeline(args) + assert args.residency_mode("text_encoder") == expected + if expected == "component-offload": + assert "text_encoder" not in (args.layerwise_offload_components or []) + assert not args.enable_torch_compile and not args.enable_cfg_parallel diff --git a/python/sglang/multimodal_gen/test/unit/test_moss_image_parallel.py b/python/sglang/multimodal_gen/test/unit/test_moss_image_parallel.py new file mode 100644 index 0000000000..2b4d52660f --- /dev/null +++ b/python/sglang/multimodal_gen/test/unit/test_moss_image_parallel.py @@ -0,0 +1,159 @@ +# SPDX-License-Identifier: Apache-2.0 + +import os +import subprocess +import sys +from types import SimpleNamespace +from unittest.mock import patch + +import pytest +import torch +import torch.distributed as dist + +from sglang.multimodal_gen.configs.models.dits.moss_image import ( + MOSSImageArchConfig, + MOSSImageDiTConfig, +) +from sglang.multimodal_gen.configs.pipeline_configs.moss_image import ( + MOSSImagePipelineConfig, +) +from sglang.multimodal_gen.configs.sample.moss_image import MOSSImageSamplingParams +from sglang.multimodal_gen.runtime.distributed.parallel_state import ( + maybe_init_distributed_environment_and_model_parallel, +) +from sglang.multimodal_gen.runtime.managers.forward_context import set_forward_context +from sglang.multimodal_gen.runtime.models.dits import moss_image +from sglang.multimodal_gen.runtime.pipelines_core.schedule_batch import Req +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.moss_image import ( + MOSSImageDenoisingStage, +) +from sglang.multimodal_gen.runtime.server_args import set_global_server_args + + +def _worker(mode): + set_global_server_args( + SimpleNamespace( + attention_backend="torch_sdpa", + attention_backend_config={}, + kv_gather_degree=1, + sp_split_auto=False, + enable_cfg_parallel=mode == "cfg", + ) + ) + maybe_init_distributed_environment_and_model_parallel( + tp_size=1, + sp_size=2 if mode == "sp" else 1, + ulysses_degree=2 if mode == "sp" else 1, + cfg_degree=2 if mode == "cfg" else 1, + ) + config = MOSSImageDiTConfig( + arch_config=MOSSImageArchConfig( + dim=64, + ffn_dim=128, + num_heads=4, + num_layers=2, + text_dim=32, + freq_dim=16, + latent_channels=8, + ) + ) + torch.manual_seed(42) + with patch.object(moss_image, "get_sp_world_size", return_value=1): + reference = moss_image.MOSSImageTransformer(config).eval() + candidate = moss_image.MOSSImageTransformer(config).eval() + candidate.load_state_dict(reference.state_dict()) + with torch.inference_mode(), set_forward_context(0, None): + for length in (4, 5, 7): + torch.manual_seed(length) + x, text = torch.randn(2, 8, 2, 3), torch.randn(2, length, 32) + timestep = torch.tensor([630.0]) + if mode == "sp": + for skip in ((), (0,), (1,)): + expected = reference(x, timestep, text, skip_layers=skip) + prepared = candidate.prepare_conditioning( + text, None, 2, 3, torch.float32, batch_samples=True + ) + actual = candidate( + x, + timestep, + text, + prepared_conditioning=prepared, + skip_layers=skip, + ) + torch.testing.assert_close(actual, expected, rtol=1e-5, atol=1e-5) + else: + pipeline = MOSSImagePipelineConfig(dit_config=config) + stage = object.__new__(MOSSImageDenoisingStage) + stage._predict_noise = lambda **kw: candidate( + kw["latent_model_input"], + kw["timestep"], + kw["encoder_hidden_states"], + skip_layers=kw.get("skip_layers", ()), + ) + for slg_scale in (0.0, 3.0): + params = MOSSImageSamplingParams( + uncond_skip_layers=[1], slg_layers=[0], slg_scale=slg_scale + ) + batch = Req( + sampling_params=params, timesteps=torch.tensor([1000.0, 630.0]) + ) + policy = pipeline.cfg_policy.build( + batch, + {}, + {"encoder_hidden_states": text}, + {"encoder_hidden_states": -text}, + ) + results = [ + stage._predict_noise_with_cfg( + current_model=candidate, + latent_model_input=x, + timestep=timestep, + batch=batch, + timestep_index=1, + attn_metadata=None, + target_dtype=torch.float32, + current_guidance_scale=3.0, + cfg_policy=policy, + cfg_gate_state=None, + server_args=SimpleNamespace( + pipeline_config=pipeline, enable_cfg_parallel=parallel + ), + guidance=None, + latents=x, + ) + for parallel in (False, True) + ] + torch.testing.assert_close(*results, rtol=0, atol=0) + dist.barrier() + dist.destroy_process_group() + + +@pytest.mark.parametrize("mode", ["sp", "cfg"]) +def test_two_rank_moss_image_matches_serial(mode): + result = subprocess.run( + [ + sys.executable, + "-m", + "torch.distributed.run", + "--standalone", + "--nproc-per-node=2", + __file__, + ], + env={ + **os.environ, + "CUDA_VISIBLE_DEVICES": "", + "SGLANG_DIFFUSION_PLATFORM_OVERRIDE": "cpu", + "MOSS_IMAGE_PARALLEL_WORKER": mode, + }, + capture_output=True, + text=True, + timeout=120, + ) + assert result.returncode == 0, result.stdout + result.stderr + + +if __name__ == "__main__": + if mode := os.environ.get("MOSS_IMAGE_PARALLEL_WORKER"): + _worker(mode) + else: + sys.exit(pytest.main([__file__, "-v"])) diff --git a/python/sglang/multimodal_gen/test/unit/test_qwen3_5_encoder.py b/python/sglang/multimodal_gen/test/unit/test_qwen3_5_encoder.py new file mode 100644 index 0000000000..2f2895538e --- /dev/null +++ b/python/sglang/multimodal_gen/test/unit/test_qwen3_5_encoder.py @@ -0,0 +1,272 @@ +# SPDX-License-Identifier: Apache-2.0 + +from types import SimpleNamespace + +import pytest +import torch +from torch.nn.attention import SDPBackend, sdpa_kernel + +from sglang.multimodal_gen.configs.models.encoders.qwen3_5 import Qwen3_5EncoderConfig +from sglang.multimodal_gen.runtime.loader.utils import set_default_torch_dtype +from sglang.multimodal_gen.runtime.managers.forward_context import set_forward_context +from sglang.multimodal_gen.runtime.models.encoders.qwen3_5 import Qwen3_5Model +from sglang.multimodal_gen.runtime.server_args import get_global_server_args + + +@pytest.fixture(autouse=True) +def restore_attention_backend(monkeypatch): + monkeypatch.setattr(get_global_server_args(), "attention_backend", "torch_sdpa") + + +@pytest.fixture +def small_text_encoder(): + from transformers import Qwen3_5Config, Qwen3_5Model + + config = Qwen3_5Config( + text_config=dict( + vocab_size=64, + hidden_size=64, + intermediate_size=128, + num_hidden_layers=2, + num_attention_heads=2, + num_key_value_heads=1, + head_dim=32, + linear_num_key_heads=2, + linear_num_value_heads=4, + linear_key_head_dim=32, + linear_value_head_dim=32, + max_position_embeddings=512, + layer_types=["linear_attention", "full_attention"], + rope_parameters={ + "rope_type": "default", + "rope_theta": 10000.0, + "partial_rotary_factor": 0.25, + "mrope_section": [1, 1, 2], + "mrope_interleaved": True, + }, + ), + vision_config=dict( + depth=1, + hidden_size=32, + intermediate_size=64, + num_heads=2, + patch_size=2, + temporal_patch_size=1, + out_hidden_size=64, + num_position_embeddings=16, + ), + ) + config._attn_implementation = "sdpa" + return Qwen3_5Model(config).eval() + + +def native_encoder(reference): + config = Qwen3_5EncoderConfig() + config.update_model_arch(reference.config.to_dict()) + config.post_diffusers_config_update() + with set_default_torch_dtype(reference.dtype), torch.device(reference.device): + model = Qwen3_5Model(config).eval() + loaded = model.load_weights(reference.state_dict().items()) + model.to(reference.device) + assert loaded == set(dict(model.named_parameters())) + return model + + +def cuda_reference(reference): + reference = reference.to("cuda") + # Match checkpoint loading: BF16 weights with FP32 derived RoPE buffers. + for parameter in reference.parameters(): + parameter.data = parameter.data.to(torch.bfloat16) + return reference + + +def test_native_encoder_registry_and_checkpoint(small_text_encoder): + from sglang.multimodal_gen.runtime.models.registry import ModelRegistry + + cls, _ = ModelRegistry.resolve_model_cls(["Qwen3_5Model"]) + assert cls is Qwen3_5Model + model = native_encoder(small_text_encoder) + assert model.config.hidden_size == small_text_encoder.config.text_config.hidden_size + assert not hasattr(model, "visual") + assert not model.should_materialize_checkpoint_weight( + "visual.patch_embed.proj.weight" + ) + for name, parameter in model.named_parameters(): + torch.testing.assert_close( + parameter, small_text_encoder.state_dict()[name], rtol=0, atol=0 + ) + with pytest.raises(KeyError): + model.load_weights([("language_model.invalid.weight", torch.zeros(1))]) + + +@pytest.mark.parametrize("backend", [None, "torch_sdpa", "fa"]) +def test_text_attention_default_and_explicit_selection(small_text_encoder, backend): + from sglang.multimodal_gen.runtime.platforms import AttentionBackendEnum + + if backend == "fa" and not torch.cuda.is_available(): + pytest.skip("FA selection requires CUDA") + get_global_server_args().attention_backend = backend + config = Qwen3_5EncoderConfig() + config.update_model_arch(small_text_encoder.config.to_dict()) + config.post_diffusers_config_update() + with set_default_torch_dtype(torch.bfloat16): + model = Qwen3_5Model(config) + expected = ( + AttentionBackendEnum.FA if backend == "fa" else AttentionBackendEnum.TORCH_SDPA + ) + assert model.language_model.layers[1].self_attn.attn.backend is expected + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA") +@pytest.mark.parametrize("length", [1, 17, 65, 129]) +@pytest.mark.parametrize("padding", [None, "left", "right"]) +@pytest.mark.parametrize("batch_size", [1, 2]) +def test_native_hybrid_encoder_matches_hf( + small_text_encoder, length, padding, batch_size +): + torch.manual_seed(0) + reference = cuda_reference(small_text_encoder) + model = native_encoder(reference) + ids = torch.randint(1, 40, (batch_size, length), device="cuda") + mask = torch.ones_like(ids) + if padding == "left": + mask[-1, : length // 3] = 0 + elif padding == "right" and length > 1: + mask[-1, -max(length // 3, 1) :] = 0 + positions = torch.arange(length, device="cuda")[None].expand(batch_size, -1) + 3 + with torch.inference_mode(), set_forward_context(0, None): + # Use math attention as the reference, including masked partial tiles. + with sdpa_kernel(SDPBackend.MATH): + expected = reference( + ids, attention_mask=mask, position_ids=positions, use_cache=False + ).last_hidden_state + result = model( + ids, attention_mask=mask, position_ids=positions, output_hidden_states=True + ) + assert ( + len(result.hidden_states) + == reference.config.text_config.num_hidden_layers + 1 + ) + valid = mask.bool() + torch.testing.assert_close( + result.last_hidden_state[valid], expected[valid], atol=0.04, rtol=0.01 + ) + # Every call starts a fresh recurrent state, including after a different length. + model(ids[:, :1], use_cache=False) + again = model( + inputs_embeds=model.language_model.embed_tokens(ids), + attention_mask=mask, + position_ids=positions, + return_dict=False, + )[0] + torch.testing.assert_close(again, result.last_hidden_state, atol=0, rtol=0) + + +def test_encoder_rejects_non_text_prefill(small_text_encoder): + model = native_encoder(small_text_encoder) + ids = torch.ones(1, 4, dtype=torch.long) + with pytest.raises(ValueError, match="cache"): + model(ids, use_cache=True) + with pytest.raises(ValueError, match="text inputs only"): + model(ids, pixel_values=torch.zeros(1)) + with pytest.raises(ValueError, match="exactly one"): + model(ids, inputs_embeds=torch.zeros(1, 4, 64)) + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA") +@pytest.mark.parametrize("length", [1, 13, 63, 64, 65, 96, 127, 128, 129, 2524, 4096]) +@pytest.mark.parametrize("dtype", [torch.bfloat16, torch.float32]) +@pytest.mark.parametrize("qk_norm", [False, True]) +def test_gdn_prefill_matches_hf_production_exactly(length, dtype, qk_norm): + from transformers.models.qwen3_5 import modeling_qwen3_5 + + from sglang.multimodal_gen.runtime.models.encoders.qwen3_5 import ( + _chunk_gated_delta_rule, + ) + + torch.manual_seed(0) + shape = (2, length, 4, 32) + q, k, v = [torch.randn(shape, device="cuda", dtype=dtype) for _ in range(3)] + q = q * torch.rsqrt(q.square().sum(-1, keepdim=True) + 1e-6) + k = k * torch.rsqrt(k.square().sum(-1, keepdim=True) + 1e-6) + g = -torch.rand(shape[:-1], device="cuda") + beta = torch.rand(shape[:-1], device="cuda", dtype=dtype) + with torch.inference_mode(): + expected, _ = modeling_qwen3_5.torch_chunk_gated_delta_rule( + q, k, v, g, beta, use_qk_l2norm_in_kernel=qk_norm + ) + actual = _chunk_gated_delta_rule(q, k, v, g, beta, use_qk_l2norm=qk_norm) + torch.testing.assert_close(actual, expected, rtol=0, atol=0) + + +@pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA") +@pytest.mark.parametrize("resident_layers", [0, 1]) +@pytest.mark.parametrize("host_embedding", [False, True]) +def test_native_layerwise_and_weight_updates( + small_text_encoder, monkeypatch, resident_layers, host_embedding +): + from sglang.multimodal_gen.runtime.managers.memory_managers import layerwise_offload + from sglang.multimodal_gen.runtime.post_training.weights_updater import ( + _load_weights_into_module, + ) + + torch.manual_seed(0) + encoder = native_encoder(cuda_reference(small_text_encoder)) + monkeypatch.setattr( + layerwise_offload, + "HOST_RESIDENT_TABLE_MIN_BYTES", + 0 if host_embedding else 2**30, + ) + tokens = [ + torch.randint(1, 40, (1, length), device="cuda") for length in (17, 5, 33, 7) + ] + with torch.inference_mode(), set_forward_context(0, None): + expected = [encoder(ids).last_hidden_state.cpu() for ids in tokens] + name = "language_model.layers.0.mlp.down_proj.weight" + changed_weight = small_text_encoder.state_dict()[name].cpu().clone() + 0.125 + encoder.configure_layerwise_offload( + SimpleNamespace( + performance_mode="manual", + pin_cpu_memory=True, + layerwise_tuning_for=lambda *args, **kwargs: ( + 1, + resident_layers, + "strided", + "forward", + ), + ), + component_name="text_encoder", + ) + [manager] = encoder.layerwise_offload_managers + assert manager.enabled and manager.num_layers == 2 + assert ( + encoder.language_model.embed_tokens.weight.device.type == "cpu" + ) == host_embedding + torch.cuda.synchronize() + try: + for start in (0, 2): + with ( + torch.cuda.stream(torch.cuda.Stream()), + torch.inference_mode(), + set_forward_context(0, None), + ): + encoder.prepare_for_next_req() + outputs = [ + encoder(ids).last_hidden_state for ids in tokens[start : start + 2] + ] + manager.release_all() + torch.cuda.synchronize() + for output, reference in zip(outputs, expected[start : start + 2]): + torch.testing.assert_close(output.cpu(), reference, rtol=0, atol=0) + _load_weights_into_module(encoder, [(name, changed_weight)]) + with torch.inference_mode(), set_forward_context(0, None): + encoder.prepare_for_next_req() + updated = encoder(tokens[0]).last_hidden_state.cpu() + manager.release_all() + encoder.disable_offload() + resident = encoder(tokens[0]).last_hidden_state.cpu() + torch.testing.assert_close(updated, resident, rtol=0, atol=0) + assert not torch.equal(updated, expected[0]) + finally: + encoder.disable_offload() + manager.release_host_stores() diff --git a/python/sglang/multimodal_gen/test/unit/test_text_encoding_cache.py b/python/sglang/multimodal_gen/test/unit/test_text_encoding_cache.py index f881252c2a..fd7ca81cae 100644 --- a/python/sglang/multimodal_gen/test/unit/test_text_encoding_cache.py +++ b/python/sglang/multimodal_gen/test/unit/test_text_encoding_cache.py @@ -15,7 +15,11 @@ from transformers import BatchEncoding from sglang.multimodal_gen.configs.models.encoders import BaseEncoderOutput from sglang.multimodal_gen.configs.pipeline_configs.base import TextConditioningOutput +from sglang.multimodal_gen.configs.pipeline_configs.moss_image import ( + MOSSImagePipelineConfig, +) from sglang.multimodal_gen.configs.sample.longlive2 import LongLive2SamplingParams +from sglang.multimodal_gen.configs.sample.moss_image import MOSSImageSamplingParams from sglang.multimodal_gen.configs.sample.sampling_params import SamplingParams from sglang.multimodal_gen.runtime.cache import conditioning from sglang.multimodal_gen.runtime.cache.conditioning import ConditioningCache @@ -32,6 +36,9 @@ from sglang.multimodal_gen.runtime.managers.memory_managers.component_residency_ ComponentOffloadStrategy, ) from sglang.multimodal_gen.runtime.models.encoders.base import TextEncoder +from sglang.multimodal_gen.runtime.models.schedulers.moss_image import ( + MOSSImageScheduler, +) from sglang.multimodal_gen.runtime.pipelines_core.executors.sync_executor import ( SyncExecutor, ) @@ -50,6 +57,9 @@ from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.l from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.ming_image import ( MingImageEncodingStage, ) +from sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages.moss_image import ( + MOSSImageBeforeDenoisingStage, +) from sglang.multimodal_gen.runtime.pipelines_core.stages.realtime.text_encoding import ( RealtimeTextEncodingStage, RealtimeTextState, @@ -245,11 +255,17 @@ def make_group_executor( encoder = ( (FullHiddenStateEncoder() if native else LibraryEncoder()).to(device).eval() ) - config = make_text_config() + config = ( + MOSSImagePipelineConfig() + if stage_type is MOSSImageBeforeDenoisingStage + else make_text_config() + ) config.supports_auto_residency = False config.vae_config = SimpleNamespace(use_temporal_scaling_frames=False) config.dit_config = SimpleNamespace( - arch_config=SimpleNamespace(num_frames_per_block=1) + arch_config=SimpleNamespace( + num_frames_per_block=1, num_layers=42, latent_channels=128 + ) ) args = make_server_args( pipeline_config=config, @@ -262,11 +278,15 @@ def make_group_executor( should_cpu_offload_component=lambda _: False, ) with patch(_GLOBAL_ARGS_PATCH, return_value=args): - stage = stage_type( - [encoder], [tokenizer if tokenizer is not None else object()] - ) + if stage_type is MOSSImageBeforeDenoisingStage: + stage = stage_type(encoder, tokenizer, MOSSImageScheduler()) + else: + stage = stage_type( + [encoder], [tokenizer if tokenizer is not None else object()] + ) stage._text_encode_dp_group = Mock(return_value=None) - stage.encode_text = partial(stage.encode_text, device=device) + if stage_type is not MOSSImageBeforeDenoisingStage: + stage.encode_text = partial(stage.encode_text, device=device) pipeline = SimpleNamespace( modules={"text_encoder": encoder}, _stage_name_mapping={"text": stage}, @@ -504,7 +524,12 @@ def test_grouped_longlive_conditioning_keeps_per_request_shot_metadata(): @pytest.mark.parametrize("fsdp", [False, True]) @pytest.mark.parametrize( - "stage_type", [MingImageEncodingStage, LingBotVideoTextEncodingStage] + "stage_type", + [ + MingImageEncodingStage, + LingBotVideoTextEncodingStage, + MOSSImageBeforeDenoisingStage, + ], ) @torch.no_grad() def test_custom_text_stages_preserve_group_reuse_and_request_metadata(fsdp, stage_type): @@ -533,6 +558,17 @@ def test_custom_text_stages_preserve_group_reuse_and_request_metadata(fsdp, stag tokenizer.side_effect = tokenize + if stage_type is MOSSImageBeforeDenoisingStage: + tokenizer.apply_chat_template.side_effect = lambda messages, **kwargs: messages[ + 0 + ]["content"] + tokenizer.side_effect = lambda text, **kwargs: BatchEncoding( + { + "input_ids": torch.tensor([[len(text), 2]]), + "attention_mask": torch.ones(1, 2, dtype=torch.long), + } + ) + with patch( "sglang.multimodal_gen.runtime.pipelines_core.stages.model_specific_stages." "ming_image.Qwen2VLImageProcessorPil.from_pretrained" @@ -543,14 +579,26 @@ def test_custom_text_stages_preserve_group_reuse_and_request_metadata(fsdp, stag encoder.dtype = torch.bfloat16 encoder.config = SimpleNamespace(projection_config={"img_gen_scales": [1]}) encoder.image_token = 99 + args.pipeline_config.dit_config.arch_config.num_layers = 42 + args.pipeline_config.dit_config.arch_config.in_channels = 128 args.pipeline_config.dit_config.arch_config.alignment_padding_mode = "zero_masked" args.pipeline_config.dit_config.arch_config.multi_frame_output = False def requests(): return [ Req( - sampling_params=SamplingParams( - prompt=prompt, negative_prompt="", height=64, width=64 + sampling_params=( + MOSSImageSamplingParams + if stage_type is MOSSImageBeforeDenoisingStage + else SamplingParams + )( + prompt=prompt, + negative_prompt="", + height=64, + width=64, + generator_device="cpu", + guidance_scale=1.0, + flow_shift=3.0, ), do_classifier_free_guidance=False, ) @@ -564,7 +612,12 @@ def test_custom_text_stages_preserve_group_reuse_and_request_metadata(fsdp, stag for run in range(2): outputs = executor.execute_group([stage], requests(), args) assert encoder.calls == 2 * (run + 1) - assert outputs[0].prompt_embeds[0] is outputs[2].prompt_embeds[0] + torch.testing.assert_close( + outputs[0].prompt_embeds[0], outputs[2].prompt_embeds[0], rtol=0, atol=0 + ) + if stage_type is MOSSImageBeforeDenoisingStage: + assert outputs[0].latents.data_ptr() != outputs[2].latents.data_ptr() + assert outputs[0].scheduler is not outputs[2].scheduler assert outputs[0].prompt_embeds is not outputs[2].prompt_embeds if stage_type is MingImageEncodingStage: assert all(output.extra["ming_frames"] == 1 for output in outputs) @@ -583,8 +636,13 @@ def get_negative_embedding_twice(stage, server_args, first_req, second_req=None) @pytest.mark.skipif(not torch.cuda.is_available(), reason="requires CUDA") @pytest.mark.parametrize("capacity", [0, 1, 4096]) +@pytest.mark.parametrize( + "stage_type", [LingBotVideoTextEncodingStage, MOSSImageBeforeDenoisingStage] +) @torch.no_grad() -def test_lingbot_cache_miss_prepares_offloaded_encoder(capacity, monkeypatch): +def test_custom_stage_cache_miss_prepares_offloaded_encoder( + capacity, stage_type, monkeypatch +): device = torch.device("cuda", torch.cuda.current_device()) monkeypatch.setattr( "sglang.multimodal_gen.runtime.managers.memory_managers." @@ -592,7 +650,9 @@ def test_lingbot_cache_miss_prepares_offloaded_encoder(capacity, monkeypatch): lambda: device, ) executor, stage, encoder, args = make_group_executor( - partial(LingBotVideoTextEncodingStage, transformer=torch.nn.Linear(1, 1)), + partial(LingBotVideoTextEncodingStage, transformer=torch.nn.Linear(1, 1)) + if stage_type is LingBotVideoTextEncodingStage + else stage_type, "cpu", capacity, ) @@ -621,13 +681,31 @@ def test_lingbot_cache_miss_prepares_offloaded_encoder(capacity, monkeypatch): manager.before_stage(stage, 0, batch, args) manager.begin_stage() with cache.scope(): - results.append(stage._encode_prompt("hello", device, torch.float32)) + if stage_type is MOSSImageBeforeDenoisingStage: + stage.tokenizer = Mock() + stage.tokenizer.apply_chat_template.side_effect = ( + lambda messages, **kwargs: messages[0]["content"] + ) + stage.tokenizer.side_effect = lambda text, **kwargs: BatchEncoding( + {"input_ids": torch.tensor([[1 if text == "hello" else 3, 2]])} + ) + batch.do_classifier_free_guidance = False + batch.num_outputs_per_prompt = 1 + stage._prepare_prompt_embeddings( + batch, ["hello", "different"], device, 4096 + ) + results.append((batch.prompt_embeds[0], batch.prompt_attention_mask)) + else: + results.append(stage._encode_prompt("hello", device, torch.float32)) manager.end_stage() manager.finish_request() assert encoder.embedding.weight.device.type == "cpu" assert results[-1][0].device == device expected_calls = 1 if capacity == 4096 else 2 - assert encoder.calls == strategy.prepare_for_use.call_count == expected_calls + assert strategy.prepare_for_use.call_count == expected_calls + assert encoder.calls == expected_calls * ( + 2 if stage_type is MOSSImageBeforeDenoisingStage else 1 + ) torch.testing.assert_close(results[0][0], results[1][0], rtol=0, atol=0) diff --git a/test/registered/kernels/ops/diffusion/test_activation.py b/test/registered/kernels/ops/diffusion/test_activation.py index 9ca776f2cb..d82484f3e5 100644 --- a/test/registered/kernels/ops/diffusion/test_activation.py +++ b/test/registered/kernels/ops/diffusion/test_activation.py @@ -16,14 +16,16 @@ import torch import torch.nn.functional as F from sglang.kernels.ops.diffusion import ( + can_use_fused_situ_softcap_mul, fused_bias_glu, fused_bias_silu, fused_packed_silu_mul_bitexact, fused_silu_mul_bitexact, + fused_situ_softcap_mul_bitexact, ) from sglang.test.ci.ci_register import register_cuda_ci -register_cuda_ci(est_time=6, stage="base-b-kernel-unit", runner_config="1-gpu-large") +register_cuda_ci(est_time=10, stage="base-b-kernel-unit", runner_config="1-gpu-large") pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA required") @@ -96,5 +98,125 @@ def test_packed_silu_mul_is_bit_exact(hidden, strided): assert torch.equal(fused_packed_silu_mul_bitexact(x), expected) +def _situ_reference(hidden, gate): + return (4.0 * torch.tanh(gate / 4.0) * torch.sigmoid(gate)) * ( + 25.0 * torch.tanh(hidden / 25.0) + ) + + +@pytest.mark.skipif(torch.version.hip is not None, reason="Requires CUDA PTX") +@pytest.mark.parametrize("shape", [(1, 13, 128), (2, 65, 8192), (1, 2524, 8192)]) +@pytest.mark.parametrize("packed", [False, True]) +def test_situ_preserves_bf16_rounding_and_projection_strides(shape, packed): + torch.manual_seed(0) + if packed: + projection = ( + torch.randn( + (*shape[:-1], 2 * shape[-1]), device="cuda", dtype=torch.bfloat16 + ) + * 5 + ) + hidden, gate = projection.chunk(2, -1) + else: + hidden = torch.randn(shape, device="cuda", dtype=torch.bfloat16) * 5 + gate = torch.randn_like(hidden) + assert can_use_fused_situ_softcap_mul(device=hidden.device, dtype=hidden.dtype) + actual = fused_situ_softcap_mul_bitexact(hidden, gate) + assert actual.is_contiguous() + assert torch.equal(actual, _situ_reference(hidden, gate)) + + +@pytest.mark.skipif(torch.version.hip is not None, reason="Requires CUDA PTX") +@pytest.mark.parametrize("operand", ["hidden", "gate"]) +@pytest.mark.parametrize( + "other", [-25.0, -4.0, -1.0, 0.0, 1.0, 4.0, 25.0, float("inf"), -float("inf")] +) +def test_situ_all_bf16_encodings(operand, other): + # Check the full lookup domain, including subnormals and signed zero, + # against positive, negative, zero and infinite companion factors. + values = ( + torch.arange(65536, device="cuda", dtype=torch.int32) + .to(torch.int16) + .view(torch.bfloat16) + .reshape(1, 1, -1) + ) + if operand == "hidden": + hidden, gate = values, torch.full_like(values, other) + else: + hidden, gate = torch.full_like(values, other), values + actual = fused_situ_softcap_mul_bitexact(hidden, gate) + expected = _situ_reference(hidden, gate) + nan = torch.isnan(expected) + assert torch.equal(torch.isnan(actual), nan) + assert torch.equal(actual[~nan].view(torch.int16), expected[~nan].view(torch.int16)) + + +@pytest.mark.skipif(torch.version.hip is not None, reason="Requires CUDA PTX") +def test_situ_cold_and_warm_tables_preserve_cuda_graph_replay(monkeypatch): + from sglang.kernels.ops.diffusion.activation import ( + situ_softcap_mul_bitexact as impl, + ) + + tables = {} + monkeypatch.setattr(impl, "_SITU_TABLES", tables) + hidden = torch.randn(1, 32, 8192, device="cuda", dtype=torch.bfloat16) + gate = torch.randn_like(hidden) + # Warm the direct kernel without constructing tables. + small = torch.randn(1, 1, 8192, device="cuda", dtype=torch.bfloat16) + fused_situ_softcap_mul_bitexact(small, small) + cold = torch.cuda.CUDAGraph() + with torch.cuda.graph(cold): + cold_out = fused_situ_softcap_mul_bitexact(hidden, gate) + assert not tables + fused_situ_softcap_mul_bitexact(hidden, gate) + pointers = tuple(t.data_ptr() for t in tables[hidden.device]) + warm = torch.cuda.CUDAGraph() + with torch.cuda.graph(warm): + warm_out = fused_situ_softcap_mul_bitexact(hidden, gate) + for scale in (1.0, 5.0): + hidden.copy_(torch.randn_like(hidden) * scale) + gate.copy_(torch.randn_like(gate) * scale) + cold.replay() + warm.replay() + expected = _situ_reference(hidden, gate) + assert torch.equal(cold_out, expected) + assert torch.equal(warm_out, expected) + assert tuple(t.data_ptr() for t in tables[hidden.device]) == pointers + + +@pytest.mark.skipif(torch.version.hip is not None, reason="Requires CUDA PTX") +def test_situ_tables_are_ready_for_other_streams(monkeypatch): + from sglang.kernels.ops.diffusion.activation import ( + situ_softcap_mul_bitexact as impl, + ) + + hidden = torch.randn(1, 32, 8192, device="cuda", dtype=torch.bfloat16) + gate = torch.randn_like(hidden) + fused_situ_softcap_mul_bitexact(hidden, gate) # Compile the lookup kernel first. + monkeypatch.setattr(impl, "_SITU_TABLES", {}) + producer, consumer = torch.cuda.Stream(), torch.cuda.Stream() + producer.wait_stream(torch.cuda.current_stream()) + consumer.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(producer): + torch.cuda._sleep(50_000_000) + fused_situ_softcap_mul_bitexact(hidden, gate) + # No wait on producer: published tables must already be usable. + with torch.cuda.stream(consumer): + actual = fused_situ_softcap_mul_bitexact(hidden, gate) + consumer.synchronize() + assert torch.equal(actual, _situ_reference(hidden, gate)) + + +def test_situ_rejects_unsupported_operands(): + hidden = torch.randn(1, 8, 64, device="cuda", dtype=torch.bfloat16) + for gate in (hidden.float(), hidden[:, :-1], hidden.cpu()): + with pytest.raises(ValueError, match="matching CUDA BF16"): + fused_situ_softcap_mul_bitexact(hidden, gate) + strided = hidden[..., ::2] + for x in (strided, hidden[:, :0]): + with pytest.raises(ValueError, match="matching CUDA BF16"): + fused_situ_softcap_mul_bitexact(x, x) + + if __name__ == "__main__": sys.exit(pytest.main([__file__, "-v"])) diff --git a/test/registered/kernels/ops/diffusion/test_model_fast_paths.py b/test/registered/kernels/ops/diffusion/test_model_fast_paths.py index 214cfdd09f..b85aecb3ce 100644 --- a/test/registered/kernels/ops/diffusion/test_model_fast_paths.py +++ b/test/registered/kernels/ops/diffusion/test_model_fast_paths.py @@ -2095,5 +2095,321 @@ def test_anima_rope_dispatch_and_fallback(): assert all(torch.equal(out, ref) for out, ref in zip(outputs, expected_fp32)) +@pytest.mark.skipif(not is_cuda(), reason="Requires CUDA PTX") +@pytest.mark.parametrize("packed", [False, True]) +def test_moss_image_situ_fusion_is_bit_exact_and_verified(monkeypatch, packed): + from sglang.kernels.ops.diffusion import BitExactFusionGate + from sglang.multimodal_gen.runtime.models.dits import moss_image + + gate_state = BitExactFusionGate("MOSSImage SiTU test") + monkeypatch.setattr(moss_image, "_SITU_FUSION", gate_state) + torch.manual_seed(0) + if packed: + projection = torch.randn(1, 19, 256, device="cuda", dtype=torch.bfloat16) + hidden, gate = projection.chunk(2, -1) + else: + hidden = torch.randn(1, 19, 128, device="cuda", dtype=torch.bfloat16) + gate = torch.randn_like(hidden) + expected = moss_image._situ_native(hidden, gate) + for _ in range(2): + assert torch.equal(moss_image._situ(hidden, gate), expected) + assert gate_state.verified and not gate_state.disabled + + +@pytest.mark.skipif(not is_cuda(), reason="Requires CUDA") +def test_moss_image_rope_fusion_is_bit_exact_and_verified(monkeypatch): + from sglang.kernels.ops.diffusion import BitExactFusionGate + from sglang.multimodal_gen.runtime.models.dits import moss_image + + gate_state = BitExactFusionGate("MOSSImage RoPE test") + monkeypatch.setattr(moss_image, "_ROPE_FUSION", gate_state) + torch.manual_seed(0) + x = torch.randn(1, 17, 2, 128, device="cuda", dtype=torch.bfloat16) + rope = moss_image._RoPE(128, 10000).cuda()(2, 4, 9, torch.device("cuda")) + rope = moss_image._prepare_rope(rope.to(x.dtype)) + expected = moss_image._rotate_native(x, rope) + for _ in range(2): + assert torch.equal(moss_image._rotate(x, rope), expected) + assert gate_state.verified and not gate_state.disabled + + +def test_moss_image_situ_fusion_mismatch_disables_fast_path(monkeypatch): + from sglang.kernels.ops.diffusion import BitExactFusionGate + from sglang.multimodal_gen.runtime.models.dits import moss_image + + gate_state = BitExactFusionGate("test SiTU") + monkeypatch.setattr(moss_image, "_SITU_FUSION", gate_state) + monkeypatch.setattr( + moss_image, "can_use_fused_situ_softcap_mul", lambda **kwargs: True + ) + calls = [] + + def incorrect(hidden, gate): + calls.append(1) + return torch.zeros_like(hidden) + + monkeypatch.setattr(moss_image, "fused_situ_softcap_mul_bitexact", incorrect) + hidden = torch.ones(1, 2, 4) + gate = torch.full_like(hidden, 2) + expected = moss_image._situ_native(hidden, gate) + for _ in range(2): + assert torch.equal(moss_image._situ(hidden, gate), expected) + assert gate_state.disabled and not gate_state.verified + assert len(calls) == 1 + + +def test_moss_image_rope_fusion_mismatch_disables_fast_path(monkeypatch): + from sglang.kernels.ops.diffusion import BitExactFusionGate + from sglang.multimodal_gen.runtime.models.dits import moss_image + + gate_state = BitExactFusionGate("test RoPE") + monkeypatch.setattr(moss_image, "_ROPE_FUSION", gate_state) + calls = [] + + def incorrect(x, cos, sin): + calls.append(1) + return torch.zeros_like(x) + + monkeypatch.setattr(moss_image, "fused_rope_rotate_half_bitexact", incorrect) + x = torch.ones(1, 3, 2, 16, device="cuda", dtype=torch.bfloat16) + rope = tuple( + torch.full((1, 3, 16), value, device=x.device, dtype=x.dtype) + for value in (0, 1) + ) + for _ in range(2): + assert torch.equal(moss_image._rotate(x, rope), x) + assert gate_state.disabled and not gate_state.verified + assert len(calls) == 1 + + +@torch.no_grad() +@pytest.mark.skipif(not is_cuda(), reason="Requires CUDA PTX") +@pytest.mark.parametrize("shape", [(1, 4096, 3072), (1, 97, 24, 128)]) +def test_moss_image_rmsnorm_fusion_is_bit_exact_and_verified(monkeypatch, shape): + from sglang.kernels.ops.diffusion import BitExactFusionGate + from sglang.multimodal_gen.runtime.models.dits import moss_image + + state = BitExactFusionGate("MOSSImage RMSNorm test", per_signature=True) + monkeypatch.setattr(moss_image, "_RMSNORM_FUSION", state) + norm = moss_image._RMSNorm(shape[-1]).to("cuda", torch.bfloat16) + norm.weight.copy_(torch.randn_like(norm.weight)) + x = torch.randn(shape, device="cuda", dtype=torch.bfloat16) + expected = norm.forward_native(x) + for _ in range(2): + assert torch.equal(norm(x), expected) + assert state.verified and not state.disabled + + +@pytest.mark.parametrize("failure", ["mismatch", "exception"]) +def test_moss_image_rmsnorm_failure_disables_fast_path(monkeypatch, failure): + from sglang.kernels.ops.diffusion import BitExactFusionGate + from sglang.multimodal_gen.runtime.models.dits import moss_image + + state = BitExactFusionGate("MOSSImage RMSNorm test", per_signature=True) + monkeypatch.setattr(moss_image, "_RMSNORM_FUSION", state) + monkeypatch.setattr( + moss_image, "can_use_rmsnorm_cast_before_weight", lambda **kwargs: True + ) + calls = [] + + def incorrect(x, weight): + calls.append(1) + if failure == "exception": + raise RuntimeError("kernel unavailable") + return torch.zeros_like(x) + + monkeypatch.setattr(moss_image, "rmsnorm_cast_before_weight_bitexact", incorrect) + norm = moss_image._RMSNorm(128) + x = torch.ones(1, 3, 128) + for _ in range(2): + assert torch.equal(norm(x), norm.forward_native(x)) + assert state.disabled and not state.verified and len(calls) == 1 + + +@torch.no_grad() +def test_moss_image_rmsnorm_unsupported_layout_uses_native(monkeypatch): + from sglang.kernels.ops.diffusion import BitExactFusionGate + from sglang.multimodal_gen.runtime.models.dits import moss_image + + state = BitExactFusionGate("MOSSImage RMSNorm test", per_signature=True) + monkeypatch.setattr(moss_image, "_RMSNORM_FUSION", state) + norm = moss_image._RMSNorm(128).to("cuda", torch.bfloat16) + x = torch.randn(2, 7, 3 * 128, device="cuda", dtype=torch.bfloat16)[..., :128] + assert torch.equal(norm(x), norm.forward_native(x)) + assert not state.verified and not state.disabled + + +@torch.no_grad() +@pytest.mark.skipif(not is_cuda(), reason="Requires CUDA JIT") +@pytest.mark.parametrize("batch", [1, 2]) +def test_moss_image_block_modulation_and_residual_match_eager(monkeypatch, batch): + from sglang.kernels.ops.diffusion import ( + can_use_modulate_scale_shift_cuda, + can_use_residual_gate_add_cuda, + modulate_scale_shift, + residual_gate_add, + ) + from sglang.multimodal_gen.runtime.models.dits import moss_image + + class ValueAttention(nn.Module): + def forward(self, q, k, v): + return v + + monkeypatch.setattr(moss_image, "LocalAttention", lambda **kwargs: ValueAttention()) + block = moss_image._Block(128, 256, 1).to("cuda", torch.bfloat16) + block.attention = ValueAttention() + x = torch.randn(batch, 19, 128, device="cuda", dtype=torch.bfloat16) + modulation = torch.randn(batch, 6, 128, device="cuda", dtype=x.dtype) + rope = ( + torch.zeros(batch, 19, 128, device="cuda", dtype=x.dtype), + torch.ones(batch, 19, 128, device="cuda", dtype=x.dtype), + ) + calls = [] + + def modulate(x, scale, shift): + calls.append(("modulate", can_use_modulate_scale_shift_cuda(x, scale, shift))) + return modulate_scale_shift(x, scale, shift) + + def residual(x, update, gate): + calls.append(("residual", can_use_residual_gate_add_cuda(x, update, gate))) + return residual_gate_add(x, update, gate) + + monkeypatch.setattr(moss_image, "modulate_scale_shift", modulate) + monkeypatch.setattr(moss_image, "residual_gate_add", residual) + actual = block(x, rope, modulation) + monkeypatch.setattr( + moss_image, + "modulate_scale_shift", + lambda x, s, b: x * (1 + s[:, None]) + b[:, None], + ) + monkeypatch.setattr(moss_image, "residual_gate_add", lambda x, h, g: x + h * g) + expected = block(x, rope, modulation) + assert torch.equal(actual, expected) + assert calls == [("modulate", batch == 1), ("residual", True)] * 2 + + +@torch.no_grad() +@pytest.mark.skipif(not is_cuda(), reason="Requires CUDA PTX and graph capture") +def test_moss_image_rmsnorm_verifies_each_regime_and_preserves_graph_capture( + monkeypatch, +): + from sglang.kernels.ops.diffusion import BitExactFusionGate + from sglang.multimodal_gen.runtime.models.dits import moss_image + + state = BitExactFusionGate("MOSSImage RMSNorm test", per_signature=True) + monkeypatch.setattr(moss_image, "_RMSNORM_FUSION", state) + token_norm = moss_image._RMSNorm(3072).to("cuda", torch.bfloat16) + for rows in [13, 17]: + x = torch.randn(1, rows, 3072, device="cuda", dtype=torch.bfloat16) + assert torch.equal(token_norm(x), token_norm.forward_native(x)) + assert len(state.verified_sigs) == 2 + + head_norm = moss_image._RMSNorm(128).to("cuda", torch.bfloat16) + x = torch.randn(1, 19, 128, device="cuda", dtype=torch.bfloat16) + stream = torch.cuda.Stream() + stream.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(stream): + for _ in range(3): + head_norm.forward_native(x) + stream.synchronize() + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + captured = head_norm(x) + graph.replay() + assert torch.equal(captured, head_norm.forward_native(x)) + # A previously verified width must not permit a host-synchronizing check + # for a new width inside capture. + assert len(state.verified_sigs) == 2 + + assert torch.equal(head_norm(x), head_norm.forward_native(x)) + assert len(state.verified_sigs) == 3 and not state.disabled + stream.wait_stream(torch.cuda.current_stream()) + fused_graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(fused_graph, stream=stream): + fused = head_norm(x) + for _ in range(2): + x.copy_(torch.randn_like(x)) + fused_graph.replay() + assert torch.equal(fused, head_norm.forward_native(x)) + + +@pytest.mark.skipif(torch.version.hip is not None, reason="Requires CUDA PTX") +@pytest.mark.parametrize("epilogue", ["modulate", "rope"]) +def test_moss_image_norm_epilogue_gate_and_graph_replay(monkeypatch, epilogue): + import sglang.multimodal_gen.runtime.models.dits.moss_image as moss_image + from sglang.kernels.ops.diffusion import BitExactFusionGate + + gate = BitExactFusionGate("test norm epilogue") + if epilogue == "modulate": + monkeypatch.setattr(moss_image, "_NORM_MOD_FUSION", gate) + norm = moss_image._RMSNorm(3072).cuda().bfloat16() + x = torch.randn(1, 33, 3072, device="cuda", dtype=torch.bfloat16) + scale = torch.randn(1, 3072, device="cuda", dtype=torch.bfloat16) + shift = torch.randn_like(scale) + call = lambda: moss_image._norm_modulate(norm, x, scale, shift) + reference = lambda: ( + norm.forward_native(x) * (1 + scale[:, None]) + shift[:, None] + ) + else: + monkeypatch.setattr(moss_image, "_NORM_ROPE_FUSION", gate) + norm = moss_image._RMSNorm(128).cuda().bfloat16() + x = torch.randn(1, 33, 3072, device="cuda", dtype=torch.bfloat16) + rope = tuple( + torch.randn(1, 33, 128, device="cuda", dtype=torch.bfloat16) + for _ in range(2) + ) + call = lambda: moss_image._norm_rope(norm, x, rope, 24) + reference = lambda: moss_image._rotate_native( + norm.forward_native(x.unflatten(-1, (24, 128))), rope + ).flatten(2) + with torch.no_grad(): + # The unverified graph must capture the existing fallback without a sync. + cold = torch.cuda.CUDAGraph() + with torch.cuda.graph(cold): + cold_out = call() + assert not gate.verified + assert torch.equal(call(), reference()) + assert gate.verified and not gate.disabled + hot = torch.cuda.CUDAGraph() + with torch.cuda.graph(hot): + hot_out = call() + for _ in range(2): + x.copy_(torch.randn_like(x)) + cold.replay() + hot.replay() + expected = reference() + assert torch.equal(cold_out, expected) + assert torch.equal(hot_out, expected) + + +@pytest.mark.parametrize("operation", ["situ", "rmsnorm"]) +@torch.no_grad() +def test_moss_image_selected_kernel_rejects_mismatched_operands(monkeypatch, operation): + """Invalid operands must not silently disable a selected fusion and run eager.""" + from sglang.kernels.ops.diffusion import BitExactFusionGate + from sglang.multimodal_gen.runtime.models.dits import moss_image + + x = torch.ones(1, 17, 128, device="cuda", dtype=torch.bfloat16) + if operation == "situ": + monkeypatch.setattr( + moss_image, + "_SITU_FUSION", + BitExactFusionGate("MOSSImage invalid input test"), + ) + with pytest.raises(ValueError): + moss_image._situ(x, x[:, :-1]) + assert not moss_image._SITU_FUSION.disabled + else: + monkeypatch.setattr( + moss_image, + "_RMSNORM_FUSION", + BitExactFusionGate("MOSSImage invalid input test"), + ) + norm = moss_image._RMSNorm(64).to(device="cuda", dtype=torch.bfloat16) + with pytest.raises(ValueError): + norm(x) + assert not moss_image._RMSNORM_FUSION.disabled + + if __name__ == "__main__": sys.exit(pytest.main([__file__, "-v"])) diff --git a/test/registered/kernels/ops/diffusion/test_norm.py b/test/registered/kernels/ops/diffusion/test_norm.py index f9ffb521bb..7269f7db47 100644 --- a/test/registered/kernels/ops/diffusion/test_norm.py +++ b/test/registered/kernels/ops/diffusion/test_norm.py @@ -713,5 +713,193 @@ def test_bias_residual_add_predicates(): assert not can_use_bias_residual_add(narrow, bias, torch.randn_like(narrow)) +# MOSSImage keeps the ATen FP32 mean and rounds before gamma. +@torch.no_grad() +@pytest.mark.parametrize( + "shape", [(1, 6620, 3072), (1, 4109, 24, 128), (2, 65, 3072), (1, 13, 128)] +) +@pytest.mark.parametrize("varying_exponent", [False, True]) +def test_rmsnorm_cast_before_weight_bitexact(shape, varying_exponent): + from sglang.kernels.ops.diffusion import ( + can_use_rmsnorm_cast_before_weight, + rmsnorm_cast_before_weight_bitexact, + ) + + x = torch.randn(shape, device=DEVICE, dtype=torch.bfloat16) + if varying_exponent: + # Mixed magnitudes expose reduction-order differences hidden by + # ordinary BF16 normal samples. + exponents = torch.randint(-12, 12, shape, device=DEVICE).float() + x = (x.float() * torch.exp2(exponents)).to(x.dtype) + weight = torch.randn(shape[-1], device=DEVICE, dtype=x.dtype) + expected = ( + x.float() * torch.rsqrt(x.float().square().mean(-1, keepdim=True) + 1e-6) + ).to(x.dtype) * weight + assert can_use_rmsnorm_cast_before_weight(device=x.device, dtype=x.dtype) + assert torch.equal(rmsnorm_cast_before_weight_bitexact(x, weight), expected) + + +@torch.no_grad() +def test_rmsnorm_cast_before_weight_extreme_values(): + from sglang.kernels.ops.diffusion import rmsnorm_cast_before_weight_bitexact + + # Every BF16 encoding, including signed zero, subnormals, infinities and + # NaNs. Isolate each value in a row so non-finite statistics do not hide + # the finite/subnormal cases. Also exercise every encoding as gamma. + values = ( + torch.arange(65536, device=DEVICE, dtype=torch.int32) + .to(torch.int16) + .view(torch.bfloat16) + ) + x = values[:, None].expand(-1, 128).contiguous() + for inputs, weight in [ + (x, torch.ones(128, device=DEVICE, dtype=x.dtype)), + (torch.randn(2, 65536, device=DEVICE, dtype=x.dtype), values), + ]: + expected = ( + inputs.float() + * torch.rsqrt(inputs.float().square().mean(-1, keepdim=True) + 1e-6) + ).to(inputs.dtype) * weight + actual = rmsnorm_cast_before_weight_bitexact(inputs, weight) + torch.testing.assert_close(actual, expected, rtol=0, atol=0, equal_nan=True) + finite = torch.isfinite(expected) + assert torch.equal( + actual.view(torch.int16)[finite], expected.view(torch.int16)[finite] + ) + + +def test_rmsnorm_cast_before_weight_guards(): + from sglang.kernels.ops.diffusion import ( + rmsnorm_cast_before_weight_bitexact, + ) + + x = torch.ones(2, 3, 128, device=DEVICE, dtype=torch.bfloat16) + weight = torch.ones(128, device=DEVICE, dtype=x.dtype) + for inputs, gamma in [ + (x.float(), weight), + (x, weight.float()), + (x.transpose(0, 1), weight), + (x[..., ::2], weight[::2]), + (x, weight[:-1]), + (x[:0], weight), + (x.cpu(), weight.cpu()), + (x, weight.cpu()), + ]: + # CPU tensors are rejected by the CUDA-only custom-op dispatcher. + with pytest.raises((ValueError, NotImplementedError)): + rmsnorm_cast_before_weight_bitexact(inputs, gamma) + + +@torch.no_grad() +@pytest.mark.parametrize("dim", [128, 256, 3072]) +@pytest.mark.parametrize("rows", [1, 15, 16, 17]) +def test_rmsnorm_cast_before_weight_reduction_boundaries(dim, rows): + from sglang.kernels.ops.diffusion import rmsnorm_cast_before_weight_bitexact + + # Nonzero, unaligned storage offsets remain contiguous; the reference + # casts to a freshly aligned FP32 buffer before its reduction. + x = torch.randn(rows * dim + 1, device=DEVICE, dtype=torch.bfloat16)[1:].view( + rows, dim + ) + weight = torch.randn(dim + 1, device=DEVICE, dtype=x.dtype)[1:] + x.mul_( + torch.exp2(torch.randint(-12, 12, x.shape, device=DEVICE).float()).to(x.dtype) + ) + expected = ( + x.float() * torch.rsqrt(x.float().square().mean(-1, keepdim=True) + 1e-6) + ).to(x.dtype) * weight + assert torch.equal(rmsnorm_cast_before_weight_bitexact(x, weight), expected) + + +def _moss_image_norm_eager(x, weight): + normalized = x.float() * torch.rsqrt( + x.float().square().mean(-1, keepdim=True) + 1e-6 + ) + return normalized.to(x.dtype) * weight + + +@pytest.mark.skipif(torch.version.hip is not None, reason="Requires CUDA PTX") +@pytest.mark.parametrize("epilogue", ["modulate", "rope"]) +@pytest.mark.parametrize("batch,seq", [(1, 16), (2, 17), (1, 3643)]) +@pytest.mark.parametrize("amplitude", [1.0, 1e-38, 1e19]) +def test_moss_image_norm_epilogues_exact(epilogue, batch, seq, amplitude): + from sglang.kernels.ops.diffusion import ( + rmsnorm_cast_before_weight_modulate_bitexact, + rmsnorm_cast_before_weight_rope_bitexact, + ) + + torch.manual_seed(0) + shape = (batch, seq, 3072) if epilogue == "modulate" else (batch, seq, 24, 128) + x = (torch.randn(shape, device="cuda") * amplitude).bfloat16() + weight = torch.randn(shape[-1], device="cuda", dtype=torch.bfloat16) + norm = _moss_image_norm_eager(x, weight) + if epilogue == "modulate": + scale = torch.randn(batch, 3072, device="cuda", dtype=torch.bfloat16) + shift = torch.zeros_like(scale) + expected = norm * (1 + scale[:, None]) + shift[:, None] + actual = rmsnorm_cast_before_weight_modulate_bitexact(x, weight, scale, shift) + else: + cos = torch.randn(batch * seq, 128, device="cuda", dtype=torch.bfloat16) + sin = torch.randn_like(cos) + lo, hi = norm.chunk(2, -1) + expected = norm * cos.view(batch, seq, 1, 128) + torch.cat( + (-hi, lo), -1 + ) * sin.view(batch, seq, 1, 128) + actual = rmsnorm_cast_before_weight_rope_bitexact(x, weight, cos, sin) + assert torch.equal(actual, expected) + + +@pytest.mark.skipif(torch.version.hip is not None, reason="Requires CUDA PTX") +def test_moss_image_norm_modulate_batched_views(): + from sglang.kernels.ops.diffusion import ( + rmsnorm_cast_before_weight_modulate_bitexact, + ) + + x = torch.randn(4, 17, 3072, device="cuda", dtype=torch.bfloat16) + weight = torch.randn(3072, device="cuda", dtype=torch.bfloat16) + modulation = torch.randn(4, 6, 3072, device="cuda", dtype=torch.bfloat16) + shift, scale = modulation[:, 0], modulation[:, 1] + expected = _moss_image_norm_eager(x, weight) * (1 + scale[:, None]) + shift[:, None] + assert torch.equal( + rmsnorm_cast_before_weight_modulate_bitexact(x, weight, scale, shift), expected + ) + with pytest.raises(ValueError, match="Unsupported MOSSImage"): + rmsnorm_cast_before_weight_modulate_bitexact( + x, weight, modulation.flatten(1)[:, ::6], shift + ) + + +@pytest.mark.skipif(torch.version.hip is not None, reason="Requires CUDA PTX") +@pytest.mark.parametrize("epilogue", ["modulate", "rope"]) +def test_moss_image_norm_epilogue_guards(epilogue): + from sglang.kernels.ops.diffusion import ( + can_use_rmsnorm_cast_before_weight_modulate, + can_use_rmsnorm_cast_before_weight_rope, + rmsnorm_cast_before_weight_modulate_bitexact, + rmsnorm_cast_before_weight_rope_bitexact, + ) + + if epilogue == "modulate": + x = torch.randn(1, 15, 3072, device="cuda", dtype=torch.bfloat16) + a = torch.randn(1, 3072, device="cuda", dtype=torch.bfloat16) + predicate, kernel = ( + can_use_rmsnorm_cast_before_weight_modulate, + rmsnorm_cast_before_weight_modulate_bitexact, + ) + else: + x = torch.randn(1, 1, 8, 128, device="cuda", dtype=torch.bfloat16) + a = torch.randn(1, 128, device="cuda", dtype=torch.bfloat16) + predicate, kernel = ( + can_use_rmsnorm_cast_before_weight_rope, + rmsnorm_cast_before_weight_rope_bitexact, + ) + weight = torch.ones(x.shape[-1], device="cuda", dtype=torch.bfloat16) + assert not predicate( + device=x.device, dtype=x.dtype, dim=x.shape[-1], rows=x.numel() // x.shape[-1] + ) + with pytest.raises(ValueError, match="Unsupported MOSSImage"): + kernel(x, weight, a, a) + + if __name__ == "__main__": sys.exit(pytest.main([__file__, "-v"]))