[diffusion] model: support MOSS-Image (#44325)

Co-authored-by: Mick Qian <mickqian@users.noreply.github.com>
This commit is contained in:
Zhang Yiyang (SII)
2026-10-15 19:23:56 +08:00
committed by GitHub
co-authored by Mick Qian
parent f7ad4345b8
commit 23c2a026db
27 changed files with 4853 additions and 24 deletions
@@ -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
@@ -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",
@@ -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
@@ -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
@@ -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)
@@ -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
@@ -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(
@@ -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
@@ -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("_", "")
],
)
@@ -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",
}
)
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
File diff suppressed because it is too large Load Diff
@@ -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"]))
@@ -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()
@@ -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)