repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
sglang
benchmark/kernels/lora_csgmv/tune_lora_csgmv.py
.py
""" Auto-tuning script for LoRA CSGMV (Chunked Segmented Matrix-Vector) kernels. LoRA adds low-rank adapters to linear layers. The two kernels are: - Shrink (lora_a): x @ A^T, projecting from input_dim down to rank - Expand (lora_b): (x @ A^T) @ B^T, projecting from rank back up to output_dim Terminology / dimens...
748
24,635
sglang
benchmark/kernels/deepseek/benchmark_cute_dsl_fp8_paged_mqa_logits.py
.py
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 from __future__ import annotations import argparse import sys import numpy as np import torch import sglang.kernels.ops.attention.dsa.cutedsl_paged_mqa_logits # noqa: F401 from sg...
362
13,817
sglang
benchmark/kernels/deepseek/benchmark_deepgemm_fp8_group_gemm.py
.py
from typing import Tuple import deep_gemm import torch import triton import triton.language as tl from deep_gemm import calc_diff from deep_gemm.utils.layout import get_mn_major_tma_aligned_tensor # Import shared functionality from the regular GEMM benchmark from sglang.benchmark.bench_utils import run_bench from sgl...
489
16,361
sglang
benchmark/kernels/deepseek/benchmark_q8kv8_kv_gather.py
.py
#!/usr/bin/env python3 """Microbenchmark: Q8KV8 sparse-prefill KV gather overhaul. Compares the legacy gather (``gather_dequant_requant_fp8_paged_legacy``: fresh ``torch.zeros`` destination + one program per (token, 128-elem slice)) against the new gather (``gather_dequant_requant_fp8_paged``: no pre-zeroing needed, f...
263
10,583
sglang
benchmark/kernels/deepseek/benchmark_deepgemm_fp8_gemm_blackwell.py
.py
import argparse from typing import Tuple import torch import triton from deep_gemm import ceil_div from flashinfer.gemm import gemm_fp8_nt_groupwise from sglang.benchmark.bench_utils import run_bench from sglang.kernels.ops.quantization.fp8_kernel import ( sglang_per_token_group_quant_fp8, w8a8_block_fp8_matm...
331
9,900
sglang
benchmark/kernels/deepseek/benchmark_q8kv8_q_prep.py
.py
#!/usr/bin/env python3 """Microbenchmark: Q8KV8 sparse-prefill q-prep β€” old path vs born-fp8 fused path. Old path (production default): 1. q_nope_out = torch.bmm(q_nope.transpose(0, 1), w_kc).transpose(0, 1) (cublas bf16 bmm, writes bf16 [H, T, N] to DRAM) 2. concat_and_cast_q_fp8_pad(q_fp8, q_nope_out,...
487
17,843
sglang
benchmark/kernels/deepseek/benchmark_deepgemm_fp8_gemm.py
.py
from typing import Tuple import deep_gemm import tilelang import tilelang.language as T import torch import triton from deep_gemm import ceil_div from deep_gemm.utils.layout import get_mn_major_tma_aligned_tensor from vllm.model_executor.layers.quantization.utils.fp8_utils import ( w8a8_block_fp8_matmul as vllm_w8...
403
13,163
sglang
benchmark/kernels/decoding_attention_triton/triton_flashinfer_cudnn.py
.py
import itertools import math import cudnn import torch import torch.utils.benchmark as benchmark from flashinfer import BatchDecodeWithPagedKVCacheWrapper from sglang.kernels.ops.attention.decode_attention import decode_attention_fwd from sglang.kernels.ops.attention.flashinfer_backend import should_use_tensor_core ...
404
12,105
sglang
benchmark/kernels/elementwise/benchmark_concat_mla.py
.py
import torch import triton import triton.language as tl from sgl_kernel import concat_mla_k as concat_mla_k_cuda from sglang.benchmark.bench_utils import run_bench DEVICE = triton.runtime.driver.active.get_active_torch_device() num_local_heads = 128 qk_nope_head_dim = 128 qk_rope_head_dim = 64 def create_data(num_...
199
5,883
sglang
benchmark/kernels/sliding_window_attention_triton/bench_triton_swa_kernel.py
.py
import itertools import torch import torch.nn.functional as F import triton.testing as tt from sglang.benchmark.bench_utils import run_bench from sglang.kernels.ops.attention.extend_attention import extend_attention_fwd def extend_attention_fwd_torch( q: torch.Tensor, # [extend_tokens, H_Q, D] k: torch.Ten...
295
9,330
sglang
benchmark/kernels/quantization/tuning_block_wise_kernel.py
.py
# Copyright 2025 SGLang Team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, so...
535
16,424
sglang
benchmark/kernels/quantization/bench_int8_quant.py
.py
import argparse import torch import triton from vllm._custom_ops import scaled_int8_quant as vllm_scaled_int8_quant from sglang.benchmark.bench_utils import run_bench from sglang.kernels.ops.quantization.int8_kernel import per_token_quant_int8 @torch.compile(backend="inductor") def torch_int8_quant(x): int8_max...
96
2,895
sglang
benchmark/kernels/deepep/tuning_deepep.py
.py
# MODIFIED FROM https://github.com/deepseek-ai/DeepEP/blob/main/tests/test_internode.py """ Example usage: python tuning_deepep.py --nnodes 4 --node-rank $MY_NODE_RANK --master-addr 1.2.3.4 Then check `deepep_tuned.json` """ import argparse import json import time from copy import deepcopy from pathlib import Path #...
481
19,961
sglang
benchmark/kernels/deepep/deepep_utils.py
.py
# ADAPTED FROM https://github.com/deepseek-ai/DeepEP/blob/main/tests/utils.py import os import sys from typing import Optional import numpy as np import torch import torch.distributed as dist def init_dist(local_rank: int, num_local_ranks: int, args): ip = args.master_addr port = args.master_port num_no...
219
7,334
sglang
benchmark/kernels/scheduler_batch/benchmark_write_req_to_token_pool_triton.py
.py
import itertools import os import torch import triton import triton.language as tl from sglang.benchmark.bench_utils import run_bench @triton.jit def write_req_to_token_pool_triton( req_to_token_ptr, # [max_batch, max_context_len] req_pool_indices, pre_lens, seq_lens, extend_lens, out_cache...
343
10,481
sglang
benchmark/kernels/scheduler_batch/benchmark_get_last_loc_triton.py
.py
import os import torch import triton import triton.language as tl from sglang.benchmark.bench_utils import run_bench @torch.compile(dynamic=True) def get_last_loc_torch( req_to_token: torch.Tensor, req_pool_indices_tensor: torch.Tensor, prefix_lens_tensor: torch.Tensor, ) -> torch.Tensor: return tor...
172
4,782
sglang
benchmark/kernels/verify_splitkv_triton/bench_verify_splitkv.py
.py
"""Micro-benchmark: split-KV EAGLE-verify kernel vs extend_attention_fwd. Times ``verify_splitkv_fwd`` against the baseline ``extend_attention_fwd`` on the verify shape (a few draft-token queries over a long prefix KV) across context lengths and head dims, and reports the per-kernel latency, the speedup, and the achie...
153
5,329
sglang
benchmark/kernels/flashinfer_allreduce_fusion/benchmark_fused_collective.py
.py
# Modified from https://github.com/vllm-project/vllm/blob/237e1fb887c7f5a579420fa0295097f24b006594/benchmarks/kernels/benchmark_fused_collective.py """ Benchmark for FlashInfer fused collective operations vs standard operations. This benchmark compares: 1. FlashInfer's trtllm_allreduce_fusion (fused allreduce + rmsno...
1,314
46,321
sglang
benchmark/kernels/all_reduce/benchmark_fused_ar_rms_amd.py
.py
""" Benchmark fused allreduce+rmsnorm on AMD with correctness checks. This script targets the same fused op used by SGLang: `tensor_model_parallel_fused_allreduce_rmsnorm`. It reports: - eager mode latency (prefill-like) - graph mode latency (decode-like) - fused availability (whether fused path returns non-None) - c...
537
17,644
sglang
benchmark/kernels/all_reduce/benchmark_torch_symm_mem.py
.py
"""For Now, TORCH_SYMM_MEM is only supported on following limited tp case SM90: { 2: 64 * MiB, # 64 MB 4: 64 * MiB, # 64 MB 6: 128 * MiB, # 128 MB 8: 128 * MiB, # 128 MB }, SM100: { 2: 64 * MiB, # 64 MB 4: 64 * MiB, # 64 MB 6: 128 * MiB, # 128 MB 8: 128 * MiB, # 128 MB } export...
249
7,910
sglang
benchmark/kernels/all_reduce/benchmark_aiter.py
.py
""" Benchmark SGLang vs Aiter custom all-reduce across message sizes. Usage: torchrun --nproc_per_node=2 benchmark_aiter.py torchrun --nproc_per_node=4 benchmark_aiter.py torchrun --nproc_per_node=8 benchmark_aiter.py """ import argparse import os import sys import time from typing import List, Optional, T...
331
9,790
sglang
benchmark/kernels/all_reduce/benchmark_fused_ar_rms_quant_amd.py
.py
""" Benchmark fused AllReduce + RMSNorm + per-group FP8 quant on AMD with correctness checks. This script targets the three op paths used by SGLang on ROCm/aiter for Qwen3.5-FP8 style models: 1. Split (3 kernels) - reference: tensor_model_parallel_all_reduce -> RMSNorm -> aiter per-1x128 quant. 2. Fu...
541
19,991
sglang
benchmark/kernels/all_reduce/benchmark_all_reduce.py
.py
""" Benchmark SGLang custom all-reduce vs Torch symm-mem all-reduce across message sizes. Usage: torchrun --nproc_per_node=2 benchmark_all_reduce.py torchrun --nproc_per_node=4 benchmark_all_reduce.py torchrun --nproc_per_node=8 benchmark_all_reduce.py """ import argparse import os import sys import time f...
352
10,759
sglang
benchmark/kernels/all_reduce/benchmark_mscclpp.py
.py
"""For Now, MSCCL is only supported on TP16 and TP8 case export WORLD_SIZE=1 export RANK=0 export MASTER_ADDR=127.0.0.1 export MASTER_PORT=12345 torchrun --nproc_per_node gpu \ --nnodes $WORLD_SIZE \ --node_rank $RANK \ --master_addr $MASTER_ADDR \ --master_port $MASTER_PORT benchmark/kernels/all_reduce/benchmark_msc...
232
7,517
sglang
benchmark/kernels/attention/sm90_config_search.py
.py
"""Search feasible SM90 fwd/bwd attention configs for given (head_dim, head_dim_v). Enumerates tile sizes, swap modes, atom layouts, and staging options. Checks GMMA divisibility, register budget, and shared memory budget. Usage: python benchmark/kernels/attention/sm90_config_search.py --headdim 128 python be...
424
14,260
sglang
benchmark/kernels/attention/fa4_benchmark_utils.py
.py
# Copyright (c) 2023, Tri Dao. """Useful functions for writing test code.""" import torch import torch.utils.benchmark as benchmark def benchmark_forward( fn, *inputs, repeats=10, desc="", verbose=True, amp=False, amp_dtype=torch.float16, **kwinputs, ): """Use Pytorch Benchmark on...
282
7,467
sglang
benchmark/kernels/attention/bench_flash_attention_fp8.py
.py
# Benchmark FP8 attention for FA4 (CuTe-DSL) on SM100. # # Run (recommended): # python benchmark/kernels/attention/bench_flash_attention_fp8.py # # Notes: # - This is intended to be used while bringing up FP8 support for SM100. # - FP8 correctness depends on descales + max-offset scaling being implemented in the SM10...
488
17,608
sglang
benchmark/kernels/attention/bench_gdn_replayssm_decode.py
.py
"""Microbenchmark: buffered output-only GDN decode (ReplaySSM Part A) vs. the existing packed GDN decode kernel. Compares per-step decode latency of ``fused_recurrent_gated_delta_rule_packed_decode`` (writes the full recurrent state S every step) against ``fused_recurrent_gdn_replayssm_decode`` at L in {1, 8, 16} (wri...
167
6,302
sglang
benchmark/kernels/all_gather/benchmark_aiter.py
.py
""" Benchmark SGLang logical TP all-gather against Aiter custom all-gather. This benchmark is intended for captured logits all-gather shapes such as ``1,32320;2,32320;4,32320`` and for correctness coverage across metadata integer dtypes. It compares the current RCCL ``dist.all_gather_into_tensor`` route with Aiter's c...
440
15,348
sglang
benchmark/fla/benchmark_layernorm_gated.py
.py
from typing import Optional import numpy as np import torch # Import the function to benchmark from sglang.kernels.ops.attention.fla.layernorm_gated import ( _layer_norm_fwd as layer_norm_fwd, ) from sglang.kernels.ops.attention.fla.layernorm_gated import ( rms_norm_ref, ) def benchmark_layer_norm_fwd( ...
316
10,039
sglang
benchmark/bench_pynccl_allocator/bench_segment_tracking.py
.py
""" Benchmark for comparing CPU overhead of segment tracking methods: 1. nccl_allocator_register_segments_with_comm() - C++ registration with index tracking 2. torch.cuda.memory.memory_snapshot() - PyTorch memory snapshot Usage: python benchmark/bench_pynccl_allocator/bench_segment_tracking.py --num-segments 50 --...
211
5,930
sglang
benchmark/asr/bench_sglang.py
.py
import argparse import asyncio import base64 import io import json import time from statistics import mean, median import httpx import librosa import numpy as np import soundfile from datasets import load_dataset from evaluate import load from openai import AsyncOpenAI, OpenAI from transformers import AutoTokenizer ...
405
12,120
sglang
benchmark/lora/launch_server.py
.py
import argparse import os DEFAULT_BASE_MODEL_PATH = "meta-llama/Llama-2-7b-hf" DEFAULT_LORA_PATH = "winddude/wizardLM-LlaMA-LoRA-7B" DEFAULT_NUM_LORAS = 4 def launch_server(args): base_path = args.base_model_path lora_path = args.lora_path if args.base_only: cmd = f"python3 -m sglang.launch_serv...
110
3,165
sglang
benchmark/lora/lora_bench.py
.py
# Copyright 2023-2024 SGLang Team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
502
17,941
sglang
benchmark/io/bench_input_ids_validator.py
.py
"""Microbenchmark: cost of validating `input_ids` during FastAPI body binding. Compares two validators on a single `input_ids` field: - GenerateReqInputPydanticValidator: default pydantic walk (per-element type check) - GenerateReqInputCustomValidator: C-loop validator (validate_optional_list_i64_1d_2d) Usage: py...
68
1,849
sglang
benchmark/mmlu/bench_sglang.py
.py
import argparse import json import os import subprocess import tarfile import time import numpy as np import pandas as pd import tiktoken from sglang.test.test_utils import ( add_common_sglang_args_and_parse, dump_bench_raw_result, select_sglang_backend, ) SCRIPT_DIR = os.path.dirname(os.path.abspath(__f...
211
5,977
sglang
benchmark/mmlu/bench_hf.py
.py
""" Usage: python3 bench_hf.py --model-path meta-llama/Llama-2-7b-hf --data-dir data --ntrain 5 """ import argparse import json import os import time import numpy as np import pandas as pd import torch from tqdm import tqdm from transformers import AutoModelForCausalLM, AutoTokenizer choices = ["A", "B", "C", "D"] ...
152
4,531
sglang
3rdparty/amd/tuning/benchmark_moe_rocm.py
.py
import argparse import json import os import sys import torch import torch.nn.functional as F import triton import triton.language as tl from tqdm import tqdm from transformers import AutoConfig from sglang.srt.layers.moe.moe_runner.triton_utils.fused_moe import ( fused_moe, get_config_file_name, ) padding_s...
379
12,345
sglang
3rdparty/amd/wheel/sgl-kernel/rocm_hipify.py
.py
from pathlib import Path import torch from torch.utils.cpp_extension import CUDAExtension root = Path(__file__).parent.resolve() include_dirs = [ root / "include", root / "include" / "impl", root / "csrc", ] sources = [ "csrc/allreduce/custom_all_reduce.hip", "csrc/allreduce/deterministic_all_re...
42
1,079
sglang
test/run_suite.py
.py
import argparse import glob import json import os import sys from typing import Dict, List, Optional import tabulate from sglang.test.ci.ci_register import ( CIRegistry, HWBackend, auto_partition, collect_tests, ) from sglang.test.ci.ci_utils import run_unittest_files HW_MAPPING = { "cpu": HWBack...
471
15,809
sglang
test/srt/models/test_inkling_per_expert_sync.py
.py
"""CPU unit test for Inkling per-expert RL weight-sync loading. Exercises ``_load_per_expert_param`` on a simulated EP x MoE-TP grid (parallel helpers monkeypatched, no process groups) and checks every (ep_rank, tp_rank) against a reference fused stack built directly from the full per-expert weights: - EP: global e...
174
6,667
sglang
test/manual/test_triton_moe_wna16.py
.py
from typing import Optional import pytest import torch from sglang.srt.layers.activation import SiluAndMul from sglang.srt.layers.moe.moe_runner.triton_utils.fused_moe import fused_moe from sglang.srt.layers.moe.topk import TopKConfig, select_experts from sglang.srt.server_args import ServerArgs, set_global_server_ar...
253
8,389
sglang
test/manual/test_modelopt_fp8kvcache.py
.py
import unittest from sglang.srt.layers.quantization.kv_cache import BaseKVCacheMethod from sglang.srt.layers.quantization.modelopt_quant import ( ModelOptFp8Config, ModelOptFp8KVCacheMethod, ) from sglang.test.test_utils import CustomTestCase class TestModelOptFp8KVCacheMethod(CustomTestCase): def test_k...
30
961
sglang
test/manual/test_deepseek_chat_templates.py
.py
""" Unit tests for DeepSeek chat template tool call handling. Tests verify that the DeepSeek chat templates (v3, v3.1, v3.2) correctly handle both dict and string types for tool['function']['arguments'] without double-escaping, addressing issue #11700. """ import os import unittest from jinja2 import Template clas...
319
12,326
sglang
test/manual/test_health_check.py
.py
import unittest from sglang.test.test_utils import ( DEFAULT_SMALL_MODEL_NAME_FOR_TEST, DEFAULT_URL_FOR_TEST, CustomTestCase, popen_launch_server, ) class TestHealthCheck(CustomTestCase): def test_health_check(self): """Test that metrics endpoint returns data when enabled""" with ...
29
784
sglang
test/manual/test_cross_node_scheduler_info_sync.py
.py
#!/usr/bin/env python3 """ Test cross-node scheduler_infos synchronization for remote weight loading. Simulates multi-node setups on a single machine using different GPU subsets. Validates that scheduler_infos are correctly synced across nodes via Gloo. IMPORTANT: For multi-node tests, start both nodes within a few s...
205
5,957
sglang
test/manual/test_moe_quant_once.py
.py
"""Standalone GPU test for SGLANG_OPT_MOE_QUANT_ONCE (quantize the MoE input once, feed both the fused shared-expert GEMM and the routed triton runner). CUDA_VISIBLE_DEVICES=0 python test/manual/test_moe_quant_once.py Verifies, against the double-quant baseline: (1) quant equivalence: the row-padded quantize-o...
275
10,747
sglang
test/manual/test_sagemaker_server.py
.py
""" python3 -m unittest test_sagemaker_server.TestSageMakerServer.test_chat_completion """ import json import unittest import requests from sglang.srt.utils import kill_process_tree from sglang.srt.utils.hf_transformers_utils import get_tokenizer from sglang.test.test_utils import ( DEFAULT_SMALL_MODEL_NAME_FOR_...
184
6,233
sglang
test/manual/test_tokenizer_batch_encode.py
.py
""" Unit tests for enable_tokenizer_batch_encode feature. This tests the batch tokenization functionality which allows processing multiple text inputs in a single batch for improved performance. Usage: python3 -m unittest test_tokenizer_batch_encode.TestTokenizerBatchEncode.test_batch_validation_constraints python3 -...
124
4,537
sglang
test/manual/test_wave_attention_backend.py
.py
""" Usage: python3 -m unittest test_wave_attention_backend.TestWaveAttnBackend.test_mmlu """ import unittest from types import SimpleNamespace from sglang.srt.utils import kill_process_tree from sglang.test.run_eval import run_eval from sglang.test.test_utils import ( DEFAULT_MODEL_NAME_FOR_TEST, DEFAULT_TIME...
62
1,576
sglang
test/manual/test_torch_flex_attention_backend.py
.py
""" Usage: python3 -m unittest test_torch_flex_attention_backend.TestTorchFlexAttnBackend.test_gsm8k """ import unittest from types import SimpleNamespace from sglang.srt.utils import kill_process_tree from sglang.test.run_eval import run_eval from sglang.test.test_utils import ( DEFAULT_MODEL_NAME_FOR_TEST, ...
50
1,328
sglang
test/manual/test_triton_attention_rocm_mla.py
.py
import random import unittest import torch from sglang.kernels.ops.attention.decode_attention import ( decode_attention_fwd_grouped, ) from sglang.kernels.ops.attention.rocm_mla_decode_rope import ( decode_attention_fwd_grouped_rope, ) from sglang.srt.layers.rotary_embedding import DeepseekScalingRotaryEmbedd...
260
7,630
sglang
test/manual/test_two_batch_overlap.py
.py
import unittest from types import SimpleNamespace import requests from sglang.srt.batch_overlap.two_batch_overlap import ( compute_split_seq_index, compute_split_token_index, ) from sglang.srt.environ import envs from sglang.srt.model_executor.forward_batch_info import ForwardMode from sglang.srt.utils import...
153
5,111
sglang
test/manual/test_models_from_modelscope.py
.py
import os import shutil import subprocess import unittest from unittest import mock from sglang.srt.utils import prepare_model_and_tokenizer from sglang.test.test_utils import CustomTestCase class TestDownloadFromModelScope(CustomTestCase): @classmethod def setUpClass(cls): cls.model = "iic/nlp_lstm...
41
1,312
sglang
test/manual/test_deepseek_v31.py
.py
import unittest from sglang.test.accuracy_test_runner import AccuracyTestParams from sglang.test.performance_test_runner import PerformanceTestParams from sglang.test.run_combined_tests import run_combined_tests from sglang.test.test_utils import ModelLaunchSettings DEEPSEEK_V31_MODEL_PATH = "deepseek-ai/DeepSeek-V3....
71
2,202
sglang
test/manual/test_async_dynamic_batch_tokenizer.py
.py
""" Unit tests for AsyncDynamicbatchTokenizer. Tests the async dynamic batching functionality for tokenization, including batch efficiency, timeout handling, and error cases. """ import asyncio import logging import sys import time from unittest.mock import Mock import pytest from transformers import AutoTokenizer ...
297
10,844
sglang
test/manual/test_config_integration.py
.py
""" Test script to verify SGLang config file integration. """ import argparse import os import sys import tempfile import pytest import yaml from sglang.srt.server_args import ServerArgs, prepare_server_args from sglang.srt.server_args_config_parser import ConfigArgumentMerger @pytest.fixture def merger(): """...
167
5,296
sglang
test/manual/test_vlm_accuracy.py
.py
""" """ import unittest from typing import List, Optional import numpy as np import torch import torch.nn.functional as F from transformers import AutoModel, AutoProcessor, AutoTokenizer from sglang.srt.configs.model_config import ModelConfig from sglang.srt.distributed.parallel_state_wrapper import ParallelState fr...
319
11,306
sglang
test/manual/test_create_custom_4d_mask.py
.py
""" Unit tests for _create_custom_4d_mask (commit a475156d). Verifies: 1. Numerical accuracy of the new vectorised implementation against the original loop-based reference. 2. Wall-clock performance improvement on a range of (batch, seq_len) sizes. On CUDA the benchmark uses cuda events for precise GPU t...
533
18,731
sglang
test/manual/test_modelopt.py
.py
import unittest from types import SimpleNamespace import torch from sglang.srt.utils import kill_process_tree from sglang.test.run_eval import run_eval from sglang.test.test_utils import ( DEFAULT_MODEL_NAME_FOR_MODELOPT_QUANT_ACCURACY_TEST_FP8, DEFAULT_MODEL_NAME_FOR_MODELOPT_QUANT_ACCURACY_TEST_FP8_REVISION...
59
1,735
sglang
test/manual/test_kda_spec_integration.py
.py
import concurrent.futures import time import requests BASE_URL = "http://localhost:30000" SHARED_PREFIX = "You are a helpful assistant. " * 20 def test_normal_inference_no_regression(): resp = requests.post( f"{BASE_URL}/generate", json={ "text": "What is 2+2?", "sampling...
72
2,105
sglang
test/manual/test_tokenizer_manager.py
.py
""" Unit tests for TokenizerManager helper methods. This tests the refactored tokenization functionality including input format detection, tokenizer input preparation, result extraction logic, and ReqState text buffering. Usage: python3 -m unittest test_tokenizer_manager.TestInputFormatDetection python3 -m unittest t...
485
18,421
sglang
test/manual/test_weight_loader_v2_equiv.py
.py
# Copyright 2023-2025 SGLang Team # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writin...
112
3,599
sglang
test/manual/test_mla_tp.py
.py
import unittest from types import SimpleNamespace import torch from sglang.srt.utils import kill_process_tree from sglang.test.run_eval import run_eval from sglang.test.test_utils import ( DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, DEFAULT_URL_FOR_TEST, CustomTestCase, popen_launch_server, ) class TestDeeps...
73
1,951
sglang
test/manual/test_logprobs.py
.py
""" Logprobs Accuracy Test for SGLang ====================== With deterministic/batch invariant kernels, we can ensure that SGLang produces exactly the same logprobs results for identical inputs. However, logprobs are highly sensitive to GPU hardware, kernels, torch versions, and other factors, so we cannot maintain a...
528
20,696
sglang
test/manual/test_forward_pass_metrics.py
.py
""" Manual test for Forward Pass Metrics (FPM) ZMQ PUB/SUB path. Tests: 1. Schema encode/decode roundtrip 2. _FpmPublisherThread ZMQ PUB -> ZMQ SUB end-to-end 3. Heartbeat emission on idle """ import sys import time import zmq def test_schema_roundtrip(): from sglang.srt.observability.forward_pass_metrics impo...
192
5,139
sglang
test/manual/test_whisper_cuda_graph.py
.py
""" Test Whisper model with CUDA graph support. This test verifies that: 1. Whisper model works correctly with CUDA graph enabled (default) 2. Cross-attention KV cache is properly managed through RadixAttention 3. Output is consistent between CUDA graph and non-CUDA-graph modes Usage: python test_whisper_cuda_gra...
162
5,321
sglang
test/manual/test_torch_tp.py
.py
import unittest from sglang.test.test_utils import ( DEFAULT_SMALL_MODEL_NAME_FOR_TEST, CustomTestCase, is_in_ci, run_bench_offline_throughput, ) class TestTorchTP(CustomTestCase): def test_torch_native_llama(self): output_throughput = run_bench_offline_throughput( DEFAULT_SMA...
31
784
sglang
test/manual/test_get_weights_by_name.py
.py
import gc import unittest import numpy as np import requests from transformers import AutoModelForCausalLM import sglang as sgl from sglang.srt.utils import get_device from sglang.test.test_utils import ( DEFAULT_MODEL_NAME_FOR_TEST, DEFAULT_SMALL_MODEL_NAME_FOR_TEST, DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, ...
186
6,234
sglang
test/manual/test_kv_events.py
.py
import time import unittest import requests import zmq from msgspec.msgpack import Decoder from sglang.srt.disaggregation.kv_events import ( AllBlocksCleared, BlockRemoved, BlockStored, KVEventBatch, ) from sglang.srt.utils import kill_process_tree from sglang.test.test_utils import ( DEFAULT_MLA_...
436
16,728
sglang
test/manual/test_fim_completion.py
.py
import unittest import openai from sglang.srt.utils import kill_process_tree from sglang.srt.utils.hf_transformers_utils import get_tokenizer from sglang.test.test_utils import ( DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, DEFAULT_URL_FOR_TEST, CustomTestCase, popen_launch_server, ) class TestFimCompletion(C...
73
2,255
sglang
test/manual/test_w4a8_deepseek_v3.py
.py
import os import unittest from types import SimpleNamespace import requests from sglang.srt.utils import kill_process_tree from sglang.test.run_eval import run_eval from sglang.test.test_utils import ( DEFAULT_DEEPSEEK_W4AFP8_MODEL_FOR_TEST, DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, DEFAULT_URL_FOR_TEST, Cus...
248
6,881
sglang
test/manual/test_weight_version.py
.py
""" Test weight version functionality. This test suite verifies the weight_version feature implementation including: 1. Default weight_version setting 2. /get_weight_version endpoint 3. /update_weight_version endpoint 4. /generate request meta_info contains weight_version 5. OpenAI API response metadata contains weigh...
228
8,372
sglang
test/manual/test_weight_validation.py
.py
""" Unit tests for weight validation and cache cleanup logic. Tests the fix for issue #14754 - ensuring that missing shards do not trigger entire cache deletion, which can cause race conditions in multi-process scenarios. """ import json import os import struct import tempfile import unittest from sglang.srt.model_l...
187
7,458
sglang
test/manual/test_schedule_policy.py
.py
import unittest from array import array from sglang.srt.managers.schedule_batch import Req, ScheduleBatch from sglang.srt.managers.schedule_policy import ( CacheAgnosticPolicy, CacheAwarePolicy, SchedulePolicy, ) from sglang.srt.mem_cache.radix_cache import RadixCache from sglang.srt.sampling.sampling_para...
332
12,315
sglang
test/manual/test_quick_allreduce.py
.py
import multiprocessing import os import random import socket import unittest from typing import Any import ray import torch import torch.distributed as dist import sglang.srt.distributed.device_communicators.custom_all_reduce_ops as ops from sglang.srt.distributed import init_distributed_environment from sglang.srt.d...
416
15,983
sglang
test/manual/test_srt_engine_with_quant_args.py
.py
import unittest import sglang as sgl from sglang.test.test_utils import DEFAULT_SMALL_MODEL_NAME_FOR_TEST, CustomTestCase class TestSRTEngineWithQuantArgs(CustomTestCase): def test_1_quantization_args(self): # we only test fp8 because other methods are currently dependent on vllm. We can add other meth...
38
1,109
sglang
test/manual/test_dsa_alias_cli_registry_env.py
.py
""" Manual test for step 01: NSA β†’ DSA user-facing alias layer. Tests: 1. CLI: --dsa-* non-CP canonical flags write to dsa_* attrs 2. Registry: "dsa" key creates the backend; "nsa" key triggers DeprecationWarning 3. Env: SGLANG_DSA_* canonical vars work 4. Env: SGLANG_NSA_* deprecated vars fall back to SGLANG_...
263
9,318
sglang
test/manual/test_mori_transfer_engine_e2e.py
.py
import os import subprocess import unittest import requests from sglang.test.server_fixtures.disaggregation_fixture import ( PDDisaggregationServerBase, ) from sglang.test.test_utils import ( DEFAULT_SMALL_MODEL_NAME_FOR_TEST, DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, popen_launch_pd_server, ) class TestMo...
294
8,884
sglang
test/manual/test_crusoe_backend.py
.py
""" Manual tests for the Crusoe managed inference backend. Requires CRUSOE_API_KEY to be set in the environment. Run all tests: python3 -m unittest test/manual/test_crusoe_backend.py Run a single test: python3 -m unittest test_crusoe_backend.TestCrusoeBackend.test_mt_bench """ import unittest from sglang i...
80
2,045
sglang
test/manual/test_glm_46_fp8.py
.py
import unittest from sglang.test.accuracy_test_runner import AccuracyTestParams from sglang.test.performance_test_runner import PerformanceTestParams from sglang.test.run_combined_tests import run_combined_tests from sglang.test.test_utils import ModelLaunchSettings GLM_4_6_FP8_MODEL_PATH = "zai-org/GLM-4.6-FP8" cl...
60
1,794
sglang
test/manual/test_ray_engine.py
.py
"""Integration tests for RayEngine and Ray HTTP server (requires GPU + Ray). Tests the Ray actor scheduler backend: - Offline inference via Engine(use_ray=True) inside a Ray actor on a placement group - Data parallel (DP) and DP attention support - Custom placement_group and SGLANG_RAY_BUNDLE_INDICES for fine-gr...
736
24,789
sglang
test/manual/test_vertex_endpoint.py
.py
""" python3 -m unittest test_vertex_endpoint.TestVertexEndpoint.test_vertex_generate """ import unittest from http import HTTPStatus import requests from sglang.srt.utils import kill_process_tree from sglang.test.test_utils import ( DEFAULT_SMALL_MODEL_NAME_FOR_TEST, DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, DE...
65
1,869
sglang
test/manual/test_forward_split_prefill.py
.py
""" Test forward_split_prefill functionality. Usage: python3 -m unittest test_forward_split_prefill.TestForwardSplitPrefill or python3 test_forward_split_prefill.py """ import unittest from array import array import numpy as np import torch from sglang.benchmark.one_batch import TreeCacheNamespace from sglang.srt.c...
310
11,596
sglang
test/manual/test_expert_location_updater.py
.py
import os import traceback import unittest from dataclasses import dataclass from typing import List import torch import torch.distributed import torch.multiprocessing as mp from torch.multiprocessing import Process from sglang.srt.eplb import expert_location_updater from sglang.srt.utils import get_device from sglan...
259
8,362
sglang
test/manual/test_custom_allreduce.py
.py
import os import random import socket import unittest from typing import Any import ray import torch import torch.distributed as dist from sglang.srt.distributed import init_distributed_environment from sglang.srt.distributed.communication_op import ( # noqa tensor_model_parallel_all_reduce, ) from sglang.srt.di...
183
6,641
sglang
test/manual/test_qwen3_235b.py
.py
import unittest from sglang.test.accuracy_test_runner import AccuracyTestParams from sglang.test.performance_test_runner import PerformanceTestParams from sglang.test.run_combined_tests import run_combined_tests from sglang.test.test_utils import ModelLaunchSettings, is_blackwell_system QWEN3_235B_FP8_MODEL_PATH = "Q...
108
3,447
sglang
test/manual/test_weight_cache_e2e.py
.py
"""E2E test for WeightCacheDaemon with real model loading. Launches TP daemons that load a real model, export IPC handles, and verifies the client can fetch and import them. Usage: # With a small model (single GPU): python test/manual/test_weight_cache_e2e.py --model-path /path/to/model --tp-size 1 # Wit...
378
12,530
sglang
test/manual/test_expert_distribution.py
.py
import tempfile import unittest from pathlib import Path import requests import torch from sglang.srt.environ import envs from sglang.srt.utils import kill_process_tree from sglang.test.test_utils import ( DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, DEFAULT_URL_FOR_TEST, CustomTestCase, popen_launch_server, ) ...
102
3,757
sglang
test/manual/test_kda_target_verify.py
.py
import torch def test_kda_target_verify_equivalence(): from sglang.kernels.ops.attention.fla.fused_sigmoid_gating_recurrent import ( fused_sigmoid_gating_delta_rule_update, ) B, HV, K, V = 2, 4, 64, 64 N = 4 device = "cuda" dtype = torch.float32 torch.manual_seed(42) q = torc...
217
8,045
sglang
test/manual/layers/test_fused_sigmoid_mul.py
.py
import itertools import pytest import torch from sglang.kernels.ops.elementwise.elementwise import fused_sigmoid_mul DTYPES = [torch.float16, torch.bfloat16] TOKEN_COUNTS = [1, 2, 4, 8, 16, 64, 512, 1024, 2048, 4096, 8192] HIDDEN_DIMS = [2048, 3072, 4096, 6144] NUM_HEADS = [1, 28] def _reference(attn_output, gate)...
135
4,420
sglang
test/manual/layers/test_layernorm.py
.py
import itertools import unittest import torch from sglang.srt.layers.layernorm import GemmaRMSNorm, LayerNorm, RMSNorm from sglang.test.test_utils import CustomTestCase class TestRMSNorm(CustomTestCase): DTYPES = [torch.half, torch.bfloat16] NUM_TOKENS = [7, 83, 4096] HIDDEN_SIZES = [768, 769, 770, 771,...
186
6,161
sglang
test/manual/layers/test_fused_gate_sigmoid_mul_add.py
.py
import itertools import pytest import torch from sglang.kernels.ops.elementwise.elementwise import fused_gate_sigmoid_mul_add DTYPES = [torch.float16, torch.bfloat16] TOKEN_COUNTS = [1, 2, 4, 8, 16, 64, 512, 1024, 2048, 4096, 8192] HIDDEN_DIMS = [2048, 3072, 4096, 6144] def _reference(hidden_states, gate_weight, s...
74
2,564
sglang
test/manual/layers/test_activation.py
.py
import itertools import unittest import torch from sglang.srt.layers.activation import GeluAndMul, QuickGELU from sglang.srt.utils import is_hip from sglang.test.test_utils import CustomTestCase _is_hip = is_hip() class TestGeluAndMul(CustomTestCase): DTYPES = [torch.half, torch.bfloat16] NUM_TOKENS = [7, ...
106
3,140
sglang
test/manual/layers/moe/bench_mxfp4_sm90_kernels.py
.py
"""Benchmark MXFP4 MoE kernels on H100/H200: SGLang Marlin vs FlashInfer cutlass. Compares per-call latency of: * Marlin path : ``fused_marlin_moe(...)`` after Marlin weight repack * FlashInfer : ``cutlass_fused_moe(use_w4_group_scaling=True, ...)`` (PR #3084's SM90 mixed-input path) Bot...
367
12,410
sglang
test/manual/layers/moe/test_moe_runners_4gpu.py
.py
import os import unittest from types import SimpleNamespace from sglang.srt.utils import kill_process_tree from sglang.test.run_eval import run_eval from sglang.test.test_utils import ( DEFAULT_URL_FOR_TEST, CustomTestCase, popen_launch_server, ) class TestMoERunner4GPU(CustomTestCase): BASE_URL = DE...
118
3,411
sglang
test/manual/layers/moe/test_moe_runners_1gpu.py
.py
import os import unittest from types import SimpleNamespace from sglang.srt.utils import kill_process_tree from sglang.test.run_eval import run_eval from sglang.test.test_utils import ( DEFAULT_MODEL_NAME_FOR_TEST_FP8_WITH_MOE, DEFAULT_MODEL_NAME_FOR_TEST_MOE_NVFP4, DEFAULT_MODEL_NAME_FOR_TEST_MXFP4_WITH_M...
212
6,755
sglang
test/manual/layers/attention/dsa/test_index_buf_accessor.py
.py
""" Correctness tests for DSA Indexer K/S Buffer Access with Fused Triton Kernels. This test verifies that the optimized Triton implementations (GetK, GetS, GetKAndS) produce identical results to the torch_fast baseline implementations. Test coverage: - GetK.triton() vs GetK.torch_fast() - GetS.triton() vs GetS.torch...
592
21,805
sglang
test/manual/layers/attention/dsa/test_act_quant_triton.py
.py
""" Unit tests comparing TileLang and Triton implementations of activation quantization. Tests both accuracy and performance. """ import time from typing import Tuple import pytest import torch from sglang.kernels.ops.attention.dsa.tilelang_kernel import act_quant from sglang.kernels.ops.attention.dsa.triton_kernel ...
282
8,023
sglang
test/manual/layers/attention/dsa/test_get_k_scale_triton_kernel.py
.py
import torch from sglang.kernels.ops.attention.dsa.index_buf_accessor import ( _get_k_and_s_triton_kernel, ) def golden_torch_gen( seq_len_tensor: torch.Tensor, buffer_indexer: torch.Tensor, buffer: torch.Tensor, index_head_dim, page_size, ): dim_split = page_size * index_head_dim tor...
192
5,861