Skip to content
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions docs/docs/advanced_features/server_arguments.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2306,6 +2306,24 @@ Please consult the documentation below and [server_args.py](https://github.com/s
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.05)"}}>Number of layers per group in offloading.</td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.02)"}}>`-1`</td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.05)"}}>Type: int</td>
</tr>
<tr>
<td style={{padding: "9px 12px", fontWeight: 500, backgroundColor: "rgba(255,255,255,0.02)"}}>`--ple-offload-embedding`</td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.05)"}}>Keep the Qwen4-Exp PLE n-gram embedding table in host memory instead of device memory; the gather kernel reads it from a host pointer. Enabled by default for BF16 Qwen4-Exp on CUDA; `--no-ple-offload-embedding` disables it.</td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.02)"}}>`None`</td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.05)"}}>Type: bool</td>
</tr>
<tr>
<td style={{padding: "9px 12px", fontWeight: 500, backgroundColor: "rgba(255,255,255,0.02)"}}>`--ple-offload-backend`</td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.05)"}}>Host storage for the offloaded PLE table: `pinned` (CPU pinned memory) or `file` (a sparse file-backed mmap under `--ple-offload-dir`, read directly by the gather kernel). Use `file` on unified-memory devices such as GB10 / DGX Spark, where pinned host memory comes out of the same pool as the weights; it requires a device that reports `cudaDevAttrPageableMemoryAccessUsesHostPageTables`.</td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.02)"}}>`pinned`</td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.05)"}}>Type: str</td>
</tr>
<tr>
<td style={{padding: "9px 12px", fontWeight: 500, backgroundColor: "rgba(255,255,255,0.02)"}}>`--ple-offload-dir`</td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.05)"}}>Directory for the file-backed PLE table when `--ple-offload-backend` is `file`. The file is sparse and rewritten on every startup; keep it on fast local storage (NVMe). Rewriting an existing table can be much slower than filling a fresh sparse file. Before restarting, stop all servers using that directory and remove its `ple_table_*.bin` files to avoid this startup cost.</td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.02)"}}>`$SGLANG_CACHE_DIR/ple/<model path>`</td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.05)"}}>Type: str</td>
</tr>
<tr>
<td style={{padding: "9px 12px", fontWeight: 500, backgroundColor: "rgba(255,255,255,0.02)"}}>`--offload-num-in-group`</td>
Expand Down
25 changes: 25 additions & 0 deletions docs/docs/references/environment_variables.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,31 @@ SGLang supports various environment variables that can be used to configure its
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.05)"}}>Cache directory for model weights and other data. Also the default root for compiled-kernel caches: Triton, Inductor, FlashInfer, the CUDA driver and DeepGEMM are pointed under it unless their own env vars (`TRITON_CACHE_DIR`, `TORCHINDUCTOR_CACHE_DIR`, `FLASHINFER_WORKSPACE_BASE`, `CUDA_CACHE_PATH`, `SGLANG_DG_CACHE_DIR`) are set explicitly</td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.02)"}}><code>~/.cache/sglang</code></td>
</tr>
<tr>
<td style={{padding: "9px 12px", fontWeight: 500, backgroundColor: "rgba(255,255,255,0.02)"}}><code>SGLANG_QWEN4_PLE_FILE_DIR</code></td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.05)"}}>Default directory for the file-backed Qwen4-Exp PLE table (`--ple-offload-backend file`); one subdirectory per model path is created under it</td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.02)"}}><code>{SGLANG_CACHE_DIR}/ple</code></td>
</tr>
<tr>
<td style={{padding: "9px 12px", fontWeight: 500, backgroundColor: "rgba(255,255,255,0.02)"}}><code>SGLANG_QWEN4_PLE_FILE_PREFETCH</code></td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.05)"}}>Hint the page cache (`posix_fadvise(WILLNEED)`) with the rows a prefill-sized PLE gather is about to read from the file-backed table. Set to `0` to disable</td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.02)"}}><code>1</code></td>
</tr>
<tr>
<td style={{padding: "9px 12px", fontWeight: 500, backgroundColor: "rgba(255,255,255,0.02)"}}><code>SGLANG_QWEN4_PLE_FILE_SKIP_DEVICE_CHECK</code></td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.05)"}}>Skip the load-time check that the device reads pageable host memory through the host page tables (`cudaDevAttrPageableMemoryAccessUsesHostPageTables`) before using the file-backed PLE table; only for devices that cannot be queried</td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.02)"}}><code>0</code></td>
</tr>
<tr>
<td style={{padding: "9px 12px", fontWeight: 500, backgroundColor: "rgba(255,255,255,0.02)"}}><code>SGLANG_QWEN4_PLE_FILE_RSS_BUDGET_GB</code></td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.05)"}}>Cap (GiB) on the resident set of the file-backed PLE mapping. A row fault maps a whole page-cache folio, so the mapping otherwise creeps towards the full table and consumes the free memory that sizes the KV pool; over the cap the pages are dropped with `MADV_DONTNEED` and stay in the page cache. Set to `0` to disable</td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.02)"}}><code>8.0</code></td>
</tr>
<tr>
<td style={{padding: "9px 12px", fontWeight: 500, backgroundColor: "rgba(255,255,255,0.02)"}}><code>SGLANG_QWEN4_PLE_FILE_RSS_INTERVAL_S</code></td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.05)"}}>How often the file-backed PLE mapping's resident set is compared against `SGLANG_QWEN4_PLE_FILE_RSS_BUDGET_GB`</td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.02)"}}><code>30.0</code></td>
</tr>
<tr>
<td style={{padding: "9px 12px", fontWeight: 500, backgroundColor: "rgba(255,255,255,0.02)"}}><code>SGLANG_CUTE_AOT_CACHE_DIR</code></td>
<td style={{padding: "9px 12px", backgroundColor: "rgba(255,255,255,0.05)"}}>Trusted directory for persistent CuTe DSL AOT objects shared across process restarts. Artifacts are namespaced by source, runtime ABI, host platform, and target GPU architecture. Set to an empty string to keep compilation process-local. Only use a directory writable by trusted users because SGLang loads cached object files into the process.</td>
Expand Down
5 changes: 3 additions & 2 deletions python/sglang/kernels/jit/csrc/moe/route_radix.cuh
Original file line number Diff line number Diff line change
Expand Up @@ -142,9 +142,10 @@ SGL_DEVICE void route_radix_block(const RouteRadixParams& params, typename Large
// radix math below is fp32 either way — only the load width differs.
AlignedVector<packed_t<TScore>, kVecSize / 2> scores_vec;

// prefetch bias (frozen weight) before the PDL wait
bias_vec.load(params.bias, tx);
// Bias may be produced by a preceding cast or fill kernel (the caller
// does not guarantee a frozen weight), so wait before loading either input.
PDLWaitPrimary<kUsePDL>();
bias_vec.load(params.bias, tx);
scores_vec.load(scores, tx);

#pragma unroll
Expand Down
14 changes: 8 additions & 6 deletions python/sglang/kernels/ops/moe/moe_fused_gate.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,17 +127,19 @@ def _router_triton_kernel(
mask_m = offs_m < M
mask_n = offs_n < N

# Prefetch a real bias before the PDL wait. Plain softmax routing has no
# bias, so keep the zero value in registers rather than materializing and
# clearing a device tensor for every routing call.
# PDL may start this grid before prior kernel stores are visible. Bias can
# be produced by a preceding cast or fill kernel, so wait before loading
# either bias or scores.
if USE_PDL:
tl.extra.cuda.gdc_wait()

# Plain softmax routing has no bias, so keep the zero value in registers
# rather than materializing and clearing a device tensor per call.
if HAS_BIAS:
bias = tl.load(bias_ptr + offs_n, mask=mask_n, other=0.0).to(tl.float32)
else:
bias = tl.zeros([BLOCK_N], dtype=tl.float32)

if USE_PDL:
tl.extra.cuda.gdc_wait()

row_ptr = scores_ptr + offs_m[:, None] * stride_sm + offs_n[None, :] * stride_sn
mask2d = mask_m[:, None] & mask_n[None, :]
scores = tl.load(row_ptr, mask=mask2d, other=0.0).to(
Expand Down
24 changes: 24 additions & 0 deletions python/sglang/srt/arg_groups/fields/exec_.py
Original file line number Diff line number Diff line change
Expand Up @@ -879,6 +879,30 @@ class ExecOffload(msgspec.Struct):
),
] = None

ple_offload_backend: A[
str,
Arg(
help="Host storage for the offloaded Qwen4 PLE n-gram table. "
"'pinned' (default) uses CPU pinned memory. 'file' maps a sparse "
"file under --ple-offload-dir and lets the gather kernel read it "
"directly; use it on unified-memory devices (e.g. GB10 / DGX Spark) "
"where pinned host memory comes out of the same pool as the model "
"weights. Requires a device that reports "
"cudaDevAttrPageableMemoryAccessUsesHostPageTables.",
choices=["pinned", "file"],
),
] = "pinned"
ple_offload_dir: A[
Optional[str],
Arg(
help="Directory for the file-backed PLE table when "
"--ple-offload-backend is 'file'. Defaults to "
"$SGLANG_CACHE_DIR/ple/<model path>, one directory per checkpoint. "
"The file is sparse and reused across restarts; put it on fast "
"local storage (NVMe).",
),
] = None


class ExecDllm(msgspec.Struct):
"""Namespace ``exec.dllm``."""
Expand Down
6 changes: 6 additions & 0 deletions python/sglang/srt/arg_groups/memory_hook.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ def handle_offload_compatibility(server_args: Any) -> None:
"would stage the pinned PLE embedding back to the device."
)

if cfg.ple_offload_backend == "file" and cfg.ple_offload_embedding is False:
raise ValueError(
"--ple-offload-backend file requires --ple-offload-embedding: "
"the file-backed table is the offloaded table."
)


def handle_gpu_memory_settings(server_args: Any, gpu_mem):
"""
Expand Down
35 changes: 33 additions & 2 deletions python/sglang/srt/arg_groups/model_overrides/qwen3_moe.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,18 @@
logger = logging.getLogger(__name__)


def _mixed_precision_moe_quant_algos(hf_config: Any) -> set:
"""quant_algo values ModelOpt MIXED_PRECISION assigns to `*.experts` layers."""
quantization_config = getattr(hf_config, "quantization_config", None)
if not isinstance(quantization_config, dict):
return set()
return {
str(info.get("quant_algo", "")).upper()
for name, info in quantization_config.get("quantized_layers", {}).items()
if ".experts" in name and isinstance(info, dict)
}


@_register_for(
"Qwen3MoeForCausalLM",
"Qwen3VLMoeForConditionalGeneration",
Expand All @@ -38,8 +50,27 @@ def _qwen3_moe_family_overrides(server_args: Any, hf_config: Any) -> dict:
):
overrides["quantization"] = quant_method
quantization = quant_method
if (
(quantization in ("fp8", "modelopt_fp4") or quantization is None)
has_w4a16_moe_layers = (
quantization == "modelopt_mixed"
and "W4A16_NVFP4" in _mixed_precision_moe_quant_algos(hf_config)
)
if has_w4a16_moe_layers:
# trtllm-gen only has the W4A4 NVFP4 MoE path.
if cfg.moe_runner_backend not in ("auto", "marlin"):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we preserve the supported CuTe DSL v2 W4A16 path here?

On SM100, a Qwen mixed checkpoint containing W4A16_NVFP4 experts now rejects an explicit --moe-runner-backend flashinfer_cutedsl, even with --moe-a2a-backend none and SGLANG_FLASHINFER_CUTEDSL_NVFP4_W4A16=1. The existing CuTe DSL runner already selects w4a16 and passes BF16 activations directly.

A focused comparison of the override function confirms that the base preserves this explicit backend, while this head raises ValueError. This verifies the configuration regression; I have not run this mixed-checkpoint combination on a GPU.

Could we keep auto -> marlin, allow the supported explicit CuTe DSL W4A16 configuration, and add a regression case to test_model_overrides.py? This does not affect the GB10 + flashinfer_cutlass configuration tested in this PR.

raise ValueError(
"W4A16_NVFP4 MoE layers require --moe-runner-backend=marlin."
)
if cfg.moe_runner_backend == "auto":
overrides["moe_runner_backend"] = "marlin"
logger.info(
"Use marlin as MoE runner backend for "
f"{hf_config.architectures[0]} with W4A16_NVFP4 MoE layers"
)
elif (
(
quantization in ("fp8", "modelopt_fp4", "modelopt_mixed")
or quantization is None
)
and cfg.moe_a2a_backend == "none"
and cfg.moe_runner_backend == "auto"
):
Expand Down
6 changes: 6 additions & 0 deletions python/sglang/srt/configs/qwen4_exp.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ def __init__(
ngram_vocab_size_base=20000000,
make_ngram_vocab_size_divisible_by=128,
ple_offload_embedding=False,
ple_offload_backend="pinned",
ple_offload_dir=None,
ple_embedding_dtype=None,
index_share_for_mtp_iteration=True,
rope_parameters=None,
Expand Down Expand Up @@ -68,6 +70,10 @@ def __init__(
self.ngram_vocab_size_base = ngram_vocab_size_base
self.make_ngram_vocab_size_divisible_by = make_ngram_vocab_size_divisible_by
self.ple_offload_embedding = ple_offload_embedding
# Host storage for the offloaded table: "pinned" or "file" (a sparse
# file-backed mmap for unified-memory devices); see --ple-offload-backend.
self.ple_offload_backend = ple_offload_backend
self.ple_offload_dir = ple_offload_dir
# "float8_e4m3fn" keeps fp8 PLE tables fp8-resident; text_config-scoped.
self.ple_embedding_dtype = ple_embedding_dtype
# Draft decode steps reuse the draft-extend indexer top-k (IndexShare).
Expand Down
12 changes: 12 additions & 0 deletions python/sglang/srt/environ.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,18 @@ class Envs:
# Bitwise-exact, shape-guarded Qwen4 PLE decode fusion. Unsupported inputs
# and phases fall back to the original implementation.
SGLANG_ENABLE_QWEN4_PLE_FUSION = EnvBool(True)
# --ple-offload-backend file: where the sparse, file-backed PLE table lives
# (deterministic name, reused across restarts), whether prefill-sized
# gathers hint the page cache first, and an escape hatch for the device
# attribute check (pageable host memory reachable through host page tables).
SGLANG_QWEN4_PLE_FILE_DIR = EnvStr(lambda: _default_cache_subdir("ple"))
SGLANG_QWEN4_PLE_FILE_PREFETCH = EnvBool(True)
SGLANG_QWEN4_PLE_FILE_SKIP_DEVICE_CHECK = EnvBool(False)
# Faulting rows in maps whole page-cache folios, so the mapping creeps
# towards full residency (~45 KB/token) and eats the free memory that
# sizes the KV pool. Cap its resident set; 0 disables the trim.
SGLANG_QWEN4_PLE_FILE_RSS_BUDGET_GB = EnvFloat(8.0)
SGLANG_QWEN4_PLE_FILE_RSS_INTERVAL_S = EnvFloat(30.0)
SGLANG_PREFETCH_BLOCK_SIZE_MB = EnvInt(16)
SGLANG_GEMMA_OUT_OF_PLACE_POSITION_MUTATION = EnvBool(False)
SGLANG_ENABLE_WEIGHT_LOADER_V2 = EnvBool(False)
Expand Down
12 changes: 12 additions & 0 deletions python/sglang/srt/layers/quantization/fp8.py
Original file line number Diff line number Diff line change
Expand Up @@ -2453,6 +2453,18 @@ def create_moe_runner(
else:
moe_runner_backend = MoeRunnerBackend.TRITON

if (
moe_runner_backend.is_flashinfer_cutlass()
or moe_runner_backend.is_flashinfer_cutedsl()
):
# Neither runner has an fp8 MoE path; they get pinned globally for
# NVFP4 experts on sm120, so run this layer's fp8 experts on triton.
logger.info(
"Fp8MoEMethod has no %s path; using triton for its fp8 experts.",
moe_runner_backend.name,
)
moe_runner_backend = MoeRunnerBackend.TRITON

if (
moe_runner_backend.is_deep_gemm()
or moe_runner_backend.is_triton()
Expand Down
25 changes: 25 additions & 0 deletions python/sglang/srt/layers/quantization/modelopt_quant.py
Original file line number Diff line number Diff line change
Expand Up @@ -802,12 +802,14 @@ def __init__(
nvfp4_config: ModelOptFp4Config,
nvfp4a16_config: ModelOptFp4Config,
mxfp8_config: Fp8Config,
fp8_block_config: Fp8Config,
) -> None:
super().__init__(kv_cache_quant_algo, exclude_modules, packed_modules_mapping)
self.quantized_layers = quantized_layers
self.fp8_config = fp8_config
self.fp8_pb_wo_config = fp8_pb_wo_config
self.mxfp8_config = mxfp8_config
self.fp8_block_config = fp8_block_config
self.nvfp4_config = nvfp4_config
self.nvfp4a16_config = nvfp4a16_config

Expand Down Expand Up @@ -864,6 +866,9 @@ def from_config(cls, config: Dict[str, Any]) -> ModelOptMixedPrecisionConfig:
exclude_modules = quantization_section.get("exclude_modules")
quantized_layers = quantization_section.get("quantized_layers", {})

# ModelOpt emits `ignore: []` or omits it; is_layer_skipped iterates it.
exclude_modules = list(exclude_modules or [])

if quant_algo != "MIXED_PRECISION":
raise ValueError(
"ModelOptMixedPrecisionConfig only supports MIXED_PRECISION checkpoints."
Expand Down Expand Up @@ -904,6 +909,13 @@ def from_config(cls, config: Dict[str, Any]) -> ModelOptMixedPrecisionConfig:
packed_modules_mapping=packed_modules_mapping,
use_mxfp8=True,
)
# ModelOpt FP8_BLOCK_SCALES: 128x128 block fp8 with weight_scale_inv.
fp8_block_config = Fp8Config(
is_checkpoint_fp8_serialized=True,
activation_scheme="dynamic",
weight_block_size=[128, 128],
packed_modules_mapping=packed_modules_mapping,
)
nvfp4_config = ModelOptFp4Config(
is_checkpoint_nvfp4_serialized=True,
kv_cache_quant_algo=kv_cache_quant_algo,
Expand All @@ -928,6 +940,7 @@ def from_config(cls, config: Dict[str, Any]) -> ModelOptMixedPrecisionConfig:
fp8_config=fp8_config,
fp8_pb_wo_config=fp8_pb_wo_config,
mxfp8_config=mxfp8_config,
fp8_block_config=fp8_block_config,
nvfp4_config=nvfp4_config,
nvfp4a16_config=nvfp4a16_config,
)
Expand Down Expand Up @@ -986,9 +999,17 @@ def _quantized_layer_prefix_candidates(prefix: str) -> Tuple[str, ...]:
candidates.append(
"language_model.model." + prefix[len("model.language_model.") :]
)
candidates.append("model." + prefix[len("model.language_model.") :])
elif prefix.startswith("model."):
# VL models such as Qwen4-Exp name the text stack `model.layers.*`
# while ModelOpt keys it `model.language_model.layers.*`.
candidates.append("model.language_model." + prefix[len("model.") :])

return tuple(dict.fromkeys(candidates))

def resolve_quant_algo(self, prefix: str) -> Optional[str]:
return self._resolve_quant_algo(prefix)

def get_quant_method(
self, layer: torch.nn.Module, prefix: str
) -> Optional[QuantizeMethodBase]:
Expand All @@ -1010,6 +1031,8 @@ def get_quant_method(
return ModelOptFp8LinearMethod(self.fp8_config)
if quant_algo == "FP8_PB_WO":
return Fp8LinearMethod(self.fp8_pb_wo_config)
if quant_algo == "FP8_BLOCK_SCALES":
return Fp8LinearMethod(self.fp8_block_config)
if quant_algo == "MXFP8":
return Fp8LinearMethod(self.mxfp8_config)
if quant_algo == "NVFP4":
Expand Down Expand Up @@ -1039,6 +1062,8 @@ def get_quant_method(
return ModelOptFp8MoEMethod(self.fp8_config)
if quant_algo == "MXFP8":
return Fp8MoEMethod(self.mxfp8_config)
if quant_algo == "FP8_BLOCK_SCALES":
return Fp8MoEMethod(self.fp8_block_config)
if quant_algo == "NVFP4":
return ModelOptNvFp4FusedMoEMethod(self.nvfp4_config)
if quant_algo == "W4A16_NVFP4":
Expand Down
Loading
Loading