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 | scripts/lint/check_rust_ext_cache_prefix.py | .py | #!/usr/bin/env python3
"""Check that the rust-ext cache key stays in sync across its sites.
The build workflow looks up and saves cache entries under its own prefix and
hashed inputs; the download action restores with its own. Neither file can
reference the other, and a mismatch in EITHER half makes every pool silentl... | 67 | 2,428 |
sglang | scripts/lint/check_workflow_job_names.py | .py | #!/usr/bin/env python3
"""Check that required status check job names are unique across workflows.
Duplicate job names on the same commit allow a passing job in one workflow
to satisfy a required status check meant for a different workflow, bypassing
branch protection.
See: https://github.com/sgl-project/sglang/pull/2... | 59 | 1,784 |
sglang | scripts/lint/check_no_bare_pytest_main.py | .py | #!/usr/bin/env python3
import ast
import pathlib
import re
import sys
_PYTEST_MAIN = re.compile(r"pytest\s*\.\s*main")
def is_main_guard(node: ast.expr) -> bool:
if not isinstance(node, ast.Compare) or len(node.ops) != 1:
return False
if not isinstance(node.ops[0], ast.Eq):
return False
... | 155 | 4,472 |
sglang | scripts/lint/test_check_no_bare_pytest_main.py | .py | import pathlib
import tempfile
import unittest
from check_no_bare_pytest_main import find_bare_pytest_main
class TestFindBarePytestMain(unittest.TestCase):
def check_source(self, source: str) -> int | None:
with tempfile.TemporaryDirectory() as directory:
path = pathlib.Path(directory) / "exa... | 87 | 2,452 |
sglang | scripts/lint/check_no_registered_tests_in_package.py | .py | #!/usr/bin/env python3
"""
Pre-commit hook: reject CI-registered tests that live inside the importable
`sglang` package (python/sglang/).
Registered tests and benchmarks must live under test/registered/ (e.g.
test/registered/jit/ for JIT kernel tests and test/registered/jit/benchmark/
for JIT kernel benchmarks) so the... | 82 | 2,747 |
sglang | scripts/lint/check_registered_tests.py | .py | #!/usr/bin/env python3
"""
Pre-commit hook: validate CI registry calls under test/registered/.
1. Every test file must contain a CI registry call (register_cuda_ci,
register_amd_ci, etc.).
2. A CUDA test must register its suite via the modern
`stage=`/`runner_config=` form. The legacy single-string `suite=` is r... | 185 | 7,193 |
sglang | scripts/ci/update_est_time.py | .py | #!/usr/bin/env python3
"""Refresh est_time literals from sglang-ci-stats/model.json.
Usage:
python scripts/ci/update_est_time.py [--dry-run] \\
[--model-url URL] [--summary-file PATH]
"""
import argparse
import json
import re
import subprocess
import sys
from collections import defaultdict
from pathlib im... | 193 | 6,301 |
sglang | scripts/ci/list_stage_models.py | .py | #!/usr/bin/env python3
"""Build a per-stage model inventory for NVIDIA (CUDA) CI.
Emits a mapping `CI suite -> [HuggingFace model ids]` so the models a stage
exercises can be pre-warmed into a runner cache. The mapping is produced by
*static analysis* of the registered test files (no GPU, no sglang import), so
it can ... | 684 | 26,598 |
sglang | scripts/ci/test_list_stage_models.py | .py | """Unit tests for list_stage_models extraction logic.
Pure-logic tests (stdlib only, no GPU, no sglang import) so they run in the
ci-model-inventory workflow without installing dependencies:
python -m unittest discover -s scripts/ci -p 'test_list_stage_models.py'
Guards the recall/precision contract of the stati... | 601 | 24,003 |
sglang | scripts/ci/runner_configs.py | .py | """Emit runner_config setup for GitHub Actions $GITHUB_OUTPUT.
runner_configs.py <runner_config>
Per-field `key=value` lines (install / artifact_version /
install_timeout / rdma_devices). `runs_on` is intentionally omitted —
it carries the `$b200_runner` sentinel and is resolved via --map.
Called per s... | 61 | 1,815 |
sglang | scripts/ci/slurm/generate_matrix.py | .py | """
Reads nightly-configs.yaml and generates one matrix entry per recipe YAML,
where each srt-slurm recipe runs its full concurrency sweep as a single Slurm job.
conc-list in the config is documentation only and is not used to split jobs.
Output: JSON array written to stdout, consumed by the workflow setup job as
a d... | 99 | 3,165 |
sglang | scripts/ci/slurm/process_result.py | .py | """Process a raw srt-slurm benchmark result JSON into an aggregated format.
Usage (called once per result file):
RESULT_FILENAME=<path_without_.json> PREFILL_GPUS=<n> DECODE_GPUS=<n> \\
RECIPE_FILE=<path_to_recipe.yaml> python3 process_result.py
Required env vars:
RESULT_FILENAME - path to the resul... | 118 | 4,030 |
sglang | scripts/ci/slurm/analyze_logs_with_modal.py | .py | #!/usr/bin/env python3
"""Analyze srtslurm logs with opencode inside a Modal sandbox.
This script accepts either:
- a local log directory
- a `.tar.gz` bundle such as `multinode_server_logs.tar.gz`
It uploads the logs into an ephemeral Modal sandbox, installs and runs
opencode with an analysis prompt, and prints the ... | 377 | 11,875 |
sglang | scripts/ci/slurm/summarize.py | .py | """Print a markdown summary table from processed benchmark results.
Usage:
python3 summarize.py <results_dir>
Reads all agg_*.json files recursively from <results_dir> and prints a
markdown table to stdout (redirect to $GITHUB_STEP_SUMMARY to publish).
"""
import json
import sys
from pathlib import Path
from ta... | 129 | 3,131 |
sglang | scripts/ci/amd/amd_ci_warmup_aiter.py | .py | #!/usr/bin/env python3
"""
Warmup script to pre-build AITER JIT kernels.
This script triggers compilation of commonly used AITER kernels by importing
the relevant modules and calling functions with sample data. This avoids
timeouts during actual tests when kernels need to be compiled on first use.
Run this after clea... | 152 | 5,632 |
sglang | scripts/ci/amd/test_rccl_multi_gpu.py | .py | #!/usr/bin/env python3
"""
Simple RCCL test for multi-GPU communication.
This test verifies that RCCL can initialize and communicate across multiple GPUs.
"""
import os
import sys
import torch
import torch.distributed as dist
def test_rccl_allreduce():
"""Test basic RCCL allreduce operation across all GPUs."""
... | 62 | 1,737 |
sglang | scripts/ci/utils/docker_build_metadata_args.py | .py | import argparse
import datetime
import json
import sys
MOVING_TAGS = {"dev", "dev-cu12", "dev-cu13", "latest"}
def render_tag_template(tag: str, version: str, date: str, short_sha: str) -> str:
return (
tag.replace("{version}", version)
.replace("{date}", date)
.replace("{short_sha}", sho... | 120 | 3,386 |
sglang | scripts/ci/utils/update_rerun_test_status.py | .py | #!/usr/bin/env python3
"""
Update the per-batch status icon in a /rerun-test reply comment.
State machine for one batch line (anchored by a unique HTML-comment marker
written by the slash-command handler):
dispatched ⏳ ... <!--rrt:i--> (handler, on dispatch)
running 🔄 ... <!--rrt:i--> (s... | 140 | 4,643 |
sglang | scripts/ci/utils/runner_utilization_report.py | .py | #!/usr/bin/env python3
"""
Runner Utilization Report
Analyzes GitHub Actions job data to calculate runner utilization metrics.
Reports idle time, active time, and utilization percentage per runner label.
"""
import argparse
import json
import os
import random
import subprocess
import time
from collections import Coun... | 989 | 38,983 |
sglang | scripts/ci/utils/save_metrics.py | .py | #!/usr/bin/env python3
"""Collect and save performance metrics from nightly benchmark results.
This script reads benchmark result JSON files from performance result directories
and saves them with metadata for artifact collection in CI.
Usage:
python3 scripts/ci/utils/save_metrics.py \
--gpu-config 8-gpu-... | 246 | 7,977 |
sglang | scripts/ci/utils/compute_partitions.py | .py | """Sum est_time per per-commit suite and emit one $GITHUB_OUTPUT line
keyed by suite name. Consumed by pr-test.yml stage jobs as
`fromJson(needs.check-changes.outputs.partitions)['<suite>']`.
partitions={"base-b-test-1-gpu-small": {"size": 8, "arr": [0,...,7], "max_parallel": 2}, ...}
"""
import argparse
import g... | 290 | 11,256 |
sglang | scripts/ci/utils/slash_command_handler.py | .py | import glob
import json
import os
import re
import sys
import time
import unicodedata
from datetime import datetime, timezone
import requests
from github import Auth, Github
# Import scripts/ci/runner_configs.py (sibling-up dir) for runner_config -> runs_on lookup.
sys.path.insert(0, os.path.join(os.path.dirname(os.p... | 1,438 | 53,931 |
sglang | scripts/ci/utils/query_job_status.py | .py | #!/usr/bin/env python3
"""
Query GitHub Actions job status for specific jobs or generate runner fleet reports.
Usage:
# Per-job reports (original mode)
python scripts/ci/utils/query_job_status.py --job "stage-c-test-large-8-gpu-amd-mi35x"
python scripts/ci/utils/query_job_status.py --job "stage-c-test-larg... | 1,944 | 68,254 |
sglang | scripts/ci/utils/xpu_job_monitor.py | .py | #!/usr/bin/env python3
# Forked from scripts/ci/utils/query_job_status.py at SHA 1b3d8da82.
# XPU-owned copy — safe to modify for XPU-specific reporting needs without
# coordinating with the upstream monitor. Cherry-pick upstream fixes
# periodically (rate-limit handling, snapshot schema, metric fixes) via a
# manual d... | 1,948 | 68,203 |
sglang | scripts/ci/utils/cleanup_hf_cache.py | .py | #!/usr/bin/env python3
"""
Clean up stale HuggingFace cache artifacts from previous failed downloads.
This script removes incomplete marker files and temporary files from the
HuggingFace cache directory. These artifacts can accumulate from interrupted
or failed downloads and may interfere with future downloads.
"""
i... | 158 | 4,135 |
sglang | scripts/ci/utils/merge_metrics.py | .py | #!/usr/bin/env python3
"""Merge per-partition metrics into a consolidated metrics file.
This script reads all per-partition metric JSON files and consolidates them
into a single JSON file with run-level metadata.
Usage:
python3 scripts/ci/utils/merge_metrics.py \
--input-dir metrics/ \
--output co... | 142 | 3,977 |
sglang | scripts/ci/utils/ci_coverage_report.py | .py | #!/usr/bin/env python3
"""
CI Coverage Report Generator
Collects all CI test registrations from test/registered/ and generates
a coverage report organized by folder, backend, and suite.
Usage:
python scripts/ci/utils/ci_coverage_report.py [--output-format markdown|json]
"""
import argparse
import glob
import jso... | 677 | 26,150 |
sglang | scripts/ci/utils/test_runner_utilization_report.py | .py | """Unit tests for runner_utilization_report.classify_job.
Pure-logic tests (no GitHub API, stdlib only) so they run in the
runner-utilization workflow without installing dependencies:
python -m unittest discover -s scripts/ci/utils -p 'test_runner_utilization_report.py'
Regression guard for the queue-time undere... | 418 | 16,206 |
sglang | scripts/ci/utils/publish_traces.py | .py | """
Publish performance traces to GitHub repository
"""
import argparse
import base64
import json
import os
import sys
import time
import warnings
from urllib.error import HTTPError
from urllib.request import Request, urlopen
def is_rate_limit_error(e):
"""Check if an exception is a GitHub rate limit error (not ... | 518 | 18,443 |
sglang | scripts/ci/utils/diffusion/compute_diffusion_partitions.py | .py | #!/usr/bin/env python3
"""
Compute dynamic partitions for diffusion CI tests.
This script runs on lightweight CI runners without sglang dependencies and uses
AST parsing to extract parametrized cases plus standalone files from source.
"""
import argparse
import importlib.util
import json
import math
import os
import ... | 358 | 11,935 |
sglang | scripts/ci/utils/diffusion/verify_diffusion_coverage.py | .py | #!/usr/bin/env python3
"""
Verify 100% coverage of diffusion test cases.
This script checks that all expected test cases were executed across all partitions.
Designed to run in the CI summary job after all partition jobs complete.
Usage:
python scripts/ci/utils/diffusion/verify_diffusion_coverage.py --reports-dir... | 344 | 10,848 |
sglang | scripts/ci/utils/diffusion/publish_comparison_results.py | .py | """Publish SGLang-Diffusion nightly benchmark results to sgl-project/ci-data-diffusion repo.
Pushes comparison-results.json, dashboard.md, and chart PNG files to the
ci-data-diffusion repository for historical tracking. Chart PNGs are stored under
diffusion-comparisons/charts/ so they can be referenced via
raw.githubu... | 281 | 9,559 |
sglang | scripts/ci/utils/diffusion/run_comparison.py | .py | """Diffusion serving benchmark for SGLang-Diffusion nightly CI.
Launches an SGLang-Diffusion server for each test case, sends a single
request, measures end-to-end latency, and writes comparison-results.json.
The runner still supports extra frameworks via --frameworks, but the nightly
config tracks SGLang-Diffusion on... | 1,051 | 35,022 |
sglang | scripts/ci/utils/diffusion/generate_diffusion_dashboard.py | .py | """Generate a Markdown dashboard for SGLang-Diffusion nightly benchmarks.
Reads current comparison results + historical data from sgl-project/ci-data-diffusion repo
and produces a Markdown report with tables and trend charts saved as PNG files.
Usage:
python3 scripts/ci/utils/diffusion/generate_diffusion_dashboar... | 836 | 29,250 |
sglang | scripts/ci/utils/diffusion/save_diffusion_metrics.py | .py | #!/usr/bin/env python3
"""Collect and save diffusion performance metrics for artifact collection in CI.
This script reads diffusion test results from the pytest stash and saves them
with metadata for the performance dashboard.
Usage:
python3 scripts/ci/utils/diffusion/save_diffusion_metrics.py \
--gpu-con... | 164 | 4,867 |
sglang | scripts/ci/utils/diffusion/publish_diffusion_gt.py | .py | """
Publish diffusion CI ground-truth images to sgl-project/ci-data-diffusion
via the GitHub API (same pattern as publish_traces.py).
"""
import argparse
import base64
import hashlib
import io
import json
import os
import sys
from dataclasses import dataclass
from pathlib import Path
from urllib.error import HTTPError... | 526 | 17,437 |
sglang | scripts/ci/utils/diffusion/diffusion_case_parser.py | .py | #!/usr/bin/env python3
"""
AST-based parser for diffusion test cases.
This module parses the diffusion case source and run_suite.py using AST to
extract test case information without requiring sglang dependencies. The case
source file is discovered from ONE_GPU_CASES/TWO_GPU_CASES imports in
run_suite.py so CI keeps a... | 518 | 18,403 |
sglang | scripts/ci/cuda/warmup_server.py | .py | """
Full server warmup to pre-warm Triton autotuning and CUDA graph capture.
On cold H200 nodes (new nodes or after container recreation), CUDA graph capture
triggers Triton autotuning which takes ~330s per server launch. This script
launches actual servers with CUDA graphs enabled to cache the autotuned kernels,
so s... | 335 | 10,919 |
sglang | scripts/ci/cuda/warmup_deep_gemm.py | .py | """
Lightweight DeepGEMM JIT compilation warmup without loading model weights.
Reads model config.json from HF cache to derive kernel shapes, then compiles
DeepGEMM kernels directly. This avoids the expensive model weight loading step
that the full `sglang.compile_deep_gemm` requires.
Supports DeepSeek V2/V3 family m... | 607 | 22,380 |
sglang | scripts/release/bump_docs_install_version.py | .py | #!/usr/bin/env python3
import argparse
import re
import sys
from pathlib import Path
from utils import (
compare_versions,
get_repo_root,
normalize_version,
validate_version,
)
# Docs pages that pin a release branch in their "install from source" snippet,
# e.g. `git clone -b v0.5.12 https://github.c... | 150 | 4,859 |
sglang | scripts/release/bump_kernel_version.py | .py | #!/usr/bin/env python3
import argparse
from pathlib import Path
from utils import bump_version
def main():
parser = argparse.ArgumentParser(
description="Bump sgl-kernel version across all relevant files"
)
parser.add_argument(
"new_version",
help="New version (e.g., 0.3.12, 0.3.... | 34 | 922 |
sglang | scripts/release/utils.py | .py | import re
import sys
from pathlib import Path
from typing import List, Tuple
try:
import tomllib # Python 3.11+
except ImportError:
import tomli as tomllib # Fallback for older Python versions
def normalize_version(version: str) -> str:
"""Remove 'v' prefix from version string if present."""
return... | 221 | 7,650 |
sglang | scripts/release/check_kernel_version_to_sglang.py | .py | #!/usr/bin/env python3
"""
Check whether SGLang's kernel dependencies match the AOT source pyproject.
The dependent versions are read from python/pyproject.toml, engine.py, and
Dockerfile.
Sets GitHub Actions output variables to indicate if sync is needed.
"""
import os
import re
import sys
from pathlib import Path
... | 157 | 4,856 |
sglang | scripts/release/bump_flashinfer_version.py | .py | #!/usr/bin/env python3
import argparse
import re
import sys
from pathlib import Path
from utils import compare_versions, get_repo_root, normalize_version, validate_version
FILES_TO_UPDATE = [
Path("python/pyproject.toml"),
Path("docker/Dockerfile"),
Path("python/sglang/srt/entrypoints/engine.py"),
Pa... | 152 | 4,742 |
sglang | scripts/release/update_others_whl_index.py | .py | #!/usr/bin/env python3
import argparse
import html
import pathlib
import re
ROOT_LINK = '<a href="others/">others</a><br>'
OTHERS_HEADER = "<!DOCTYPE html>\n<h1>SGLang Other Files</h1>\n"
ASSET_URL_PREFIX = "https://github.com/sgl-project/whl/releases/download/"
SHA256_PATTERN = re.compile(r"[0-9a-fA-F]{64}")
TAG_PAT... | 107 | 3,592 |
sglang | scripts/release/test_utils.py | .py | #!/usr/bin/env python3
import unittest
from pathlib import Path
from utils import compare_versions, normalize_version, parse_version, validate_version
class TestVersionUtils(unittest.TestCase):
def test_normalize_version(self):
"""Test version normalization removes 'v' prefix."""
self.assertEqua... | 160 | 6,837 |
sglang | scripts/release/bump_kernel_version_to_sglang.py | .py | #!/usr/bin/env python3
"""
Bump SGLang's kernel dependencies to match the AOT source pyproject.
Updates:
- python/pyproject.toml
- python/sglang/srt/entrypoints/engine.py
- docker/Dockerfile
"""
import re
import sys
from pathlib import Path
try:
import tomllib # Python 3.11+
except ImportError:
import ... | 146 | 4,011 |
sglang | benchmark/bench_adaptive_speculative.py | .py | """Benchmark adaptive speculative decoding against static baselines.
Run the same workload against one adaptive server and one or more static
servers, then compare throughput, latency, and acceptance length.
Workloads:
- low: steady-state low-acceptance generation
- high: steady-state high-acceptance generation
- tra... | 264 | 8,311 |
sglang | benchmark/boolq/bench_sglang.py | .py | import argparse
import json
import time
import numpy as np
from sglang.lang.api import set_default_backend
from sglang.test.test_utils import (
add_common_sglang_args_and_parse,
select_sglang_backend,
)
from sglang.utils import read_jsonl
def get_example(lines, i, answer):
prompt = "Question: " + lines[... | 125 | 3,483 |
sglang | benchmark/boolq/convert_parquet_to_json.py | .py | import sys
import pyarrow.parquet as pq
def convert_parquet_to_json(input_file, output_file):
# read parquet file
table = pq.read_table(input_file)
# turn parquet data to dataframe
df = table.to_pandas()
# turn dataframe to json form
json_data = df.to_json(orient="records", lines=True)
... | 29 | 661 |
sglang | benchmark/mmmu/eval_utils.py | .py | """Response Parsing and Evaluation for various models"""
import argparse
import dataclasses
import json
import os
import pprint
import random
import re
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Dict, Optional
import numpy as np
import torch
from data_utils import (
CAT_SHO... | 732 | 25,776 |
sglang | benchmark/mmmu/bench_sglang.py | .py | """
Bench the sglang-hosted vLM with benchmark MMMU
Usage:
Host the VLM: python -m sglang.launch_server --model-path Qwen/Qwen2-VL-7B-Instruct --port 30000
Benchmark: python benchmark/mmmu/bench_sglang.py --port 30000 --concurrency 16
The eval output will be logged
"""
import argparse
import asyncio
import ... | 256 | 7,751 |
sglang | benchmark/mmmu/bench_hf.py | .py | import argparse
import PIL
import torch
from data_utils import save_json
from eval_utils import (
EvalArgs,
eval_result,
get_sampling_params,
prepare_samples,
process_result,
)
from tqdm import tqdm
from transformers import AutoModel, AutoProcessor, GenerationConfig
@torch.no_grad()
def eval_mmmu... | 180 | 5,998 |
sglang | benchmark/mmmu/data_utils.py | .py | """Utils for data load, save, and process (e.g., prompt construction)"""
import json
import os
import re
import yaml
DOMAIN_CAT2SUB_CAT = {
"Art and Design": ["Art", "Art_Theory", "Design", "Music"],
"Business": ["Accounting", "Economics", "Finance", "Manage", "Marketing"],
"Science": [
"Biology"... | 216 | 6,603 |
sglang | benchmark/bench_attention_sink/bench_attention_sink_triton.py | .py | import argparse
import torch
import triton
from sglang.kernels.ops.attention.decode_attention import (
decode_attention_fwd_grouped,
)
from sglang.kernels.ops.attention.extend_attention import extend_attention_fwd
# gpt oss
head_num = 64
head_dim = 64
head_kv_num = 8
@triton.testing.perf_report(
triton.tes... | 251 | 7,472 |
sglang | benchmark/hicache/bench_hicache_write_back.py | .py | from __future__ import annotations
import csv
import platform
from dataclasses import dataclass
from pathlib import Path
import torch
import triton.testing
from sgl_kernel.kvcacheio import (
transfer_kv_all_layer_lf_pf,
transfer_kv_all_layer_mla_lf_pf,
)
from sglang.kernels.ops.kvcache.hicache import (
c... | 392 | 12,733 |
sglang | benchmark/hicache/perf.py | .py | from __future__ import annotations
from typing import Any, Callable, NamedTuple
import torch
def jit_hicache_impl(
k_cache_dst: torch.Tensor,
v_cache_dst: torch.Tensor,
indices_dst: torch.Tensor,
k_cache_src: torch.Tensor,
v_cache_src: torch.Tensor,
indices_src: torch.Tensor,
item_bytes:... | 249 | 7,463 |
sglang | benchmark/hicache/data_processing.py | .py | import json
import os
import pickle
import random
from typing import List, Optional, Tuple, Union
import numpy as np
from nextqa import NExTQALoader
# from nextqa.video import , VideoPrompt
from tqdm.asyncio import tqdm
from transformers import PreTrainedTokenizerBase
from sglang.benchmark.datasets.common import (
... | 584 | 20,039 |
sglang | benchmark/hicache/bench_long_context.py | .py | import json
import queue
import time
import requests
from bench_multiturn import (
ReadyQueue,
WorkloadGenerator,
gen_payload,
log_to_jsonl_file,
parse_args,
)
from tqdm.asyncio import tqdm
from sglang.benchmark.utils import get_tokenizer
from sglang.test.kits.cache_hit_kit import async_request_sg... | 101 | 3,540 |
sglang | benchmark/hicache/bench_mix.py | .py | import argparse
import asyncio
import json
import logging
import os
import queue
import random
import threading
import time
from dataclasses import dataclass
from functools import wraps
import aiohttp
from sglang.bench_serving import RequestFuncOutput
from sglang.benchmark.datasets.random import sample_random_request... | 572 | 19,375 |
sglang | benchmark/hicache/bench_serving.py | .py | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adapted from https://github.com/vllm-project/vllm/blob/6366efc67b0aedd2c1721c14385370e50b297fb3/benchmarks/backend_request_func.py
# Adapted from https://github.com/vllm-project/vllm/blob/6366efc67b0aedd2c1721c1... | 1,032 | 37,268 |
sglang | benchmark/hicache/bench_warm_cache.py | .py | # Adapted from benchmark/hicache/bench_serving.py and python/sglang/bench_serving.py
"""
Benchmark warm-cache serving with exact shared-prefix control.
This benchmark is designed for cache-focused studies where each request has a
fixed total input length and an exactly controlled shared-prefix ratio. For each
shared-... | 674 | 22,598 |
sglang | benchmark/hicache/bench_multiturn.py | .py | import argparse
import asyncio
import json
import queue
import random
import threading
import time
from datetime import datetime
import numpy as np
import requests
from tqdm.asyncio import tqdm
from sglang.bench_serving import RequestFuncOutput
from sglang.benchmark.datasets.random import sample_random_requests
from ... | 756 | 30,353 |
sglang | benchmark/hicache/nextqa.py | .py | import os
import sys
from typing import List
import av
from datasets import load_dataset
def find_video_files(video_dir) -> List[str]:
if os.path.isfile(video_dir):
return [video_dir]
video_files = []
for root, dirs, files in os.walk(video_dir):
for file in files:
if file.end... | 160 | 5,152 |
sglang | benchmark/prefill_only/util.py | .py | """
Common utilities for SGLang benchmark scripts.
This module contains shared code for benchmarking different SGLang APIs
including scoring, embeddings, and other endpoints.
"""
import asyncio
import concurrent.futures
import json
import os
import random
from statistics import mean
from typing import Any, Callable, ... | 815 | 28,515 |
sglang | benchmark/prefill_only/bench_score.py | .py | """
SGLang Scoring Benchmark Script
This script benchmarks SGLang's scoring API performance using HTTP requests.
Current Features:
- HTTP-only implementation (open source compatible)
- Uses /v1/score API endpoint directly
- Single item scoring with batching support
- Configurable RPS, duration, and batch sizes
- Prog... | 193 | 6,270 |
sglang | benchmark/prefill_only/bench_embeddings.py | .py | """
SGLang Embeddings Benchmark Script
This script benchmarks SGLang's /v1/embeddings API performance using HTTP requests.
Features:
- HTTP-only implementation
- Uses /v1/embeddings API endpoint directly
- Configurable RPS, duration, and batch sizes
- Progress tracking and detailed metrics
- Poisson and constant requ... | 160 | 4,997 |
sglang | benchmark/bench_linear_attention/bench_gdn_qkv_split.py | .py | from __future__ import annotations
import argparse
import torch
from sglang.kernels.ops.attention.triton_gdn_fused_proj import (
fused_qkv_split_gdn_prefill,
)
DTYPES = {
"bf16": torch.bfloat16,
"fp16": torch.float16,
"fp32": torch.float32,
}
def parse_args():
parser = argparse.ArgumentParser(... | 142 | 4,207 |
sglang | benchmark/bench_linear_attention/bench_int8_checkpoint_reuse.py | .py | """Benchmark: int8 linear-attention checkpoint pool — prefix-reuse capacity & latency.
Drives a *running* SGLang server that serves a linear-attention (KDA / GDN) hybrid
model, and measures how prefix reuse — and the probe-phase prefill latency that
depends on it — holds up as the number of DISTINCT cached prefixes gr... | 166 | 6,738 |
sglang | benchmark/bench_linear_attention/bench_gdn_prefill.py | .py | """
Benchmark & Correctness: Triton GDN vs FlashInfer GDN (prefill).
Compares:
- Triton: sglang's chunk_gated_delta_rule (K-contiguous pool, pool-indexed)
- FlashInfer: flashinfer's chunk_gated_delta_rule (gather/scatter, 3D tensors)
The two kernels have different APIs:
- Triton: q/k/v=[1,T,H,D], g=logs... | 640 | 19,683 |
sglang | benchmark/bench_linear_attention/bench_cutedsl_kda_decode.py | .py | """Benchmark & Correctness: CuTe DSL KDA Decode vs Triton KDA Decode.
This benchmark assumes the production / Triton canonical state layout:
ssm_states.shape == (pool_size, HV, V, K)
Both the Triton baseline and the CuTe DSL candidate operate directly on that VK
layout. No transpose is performed anywhere in the b... | 484 | 14,772 |
sglang | benchmark/bench_linear_attention/bench_kda_decode.py | .py | """
Benchmark & Correctness: KDA Packed Decode vs Baseline Decode.
Compares:
- Baseline: split(mixed_qkv) -> view -> fused_sigmoid_gating_delta_rule_update(is_kda=True)
- Packed: fused_recurrent_kda_packed_decode (single fused kernel)
- Helion: helion_fused_recurrent_kda_packed_decode
Differences from the G... | 461 | 14,531 |
sglang | benchmark/bench_linear_attention/bench_gdn_prefill_cutedsl.py | .py | """
Benchmark & Correctness: Triton GDN vs CuTeDSL GDN (prefill, SM100 Blackwell).
Compares:
- Triton: sglang's chunk_gated_delta_rule (FLA chunkwise, fp32 state, K-contig pool)
- CuteDSL: ported vLLM #43273 chunk_gated_delta_rule_cutedsl (SM100 only)
The two kernels share the same math and the same g/beta conve... | 474 | 15,103 |
sglang | benchmark/bench_linear_attention/bench_kda_flashinfer_mtp.py | .py | """
Benchmark & Correctness: FlashInfer KDA (SM100) vs Triton KDA — decode & MTP verify.
Exercises the two real backend wrappers used by ``KDAKernelDispatcher``:
- ``FlashInferKDAKernel`` — wraps ``flashinfer.kda_decode.recurrent_kda``
(CuTe DSL, SM100/Blackwell only). Provides ``decode`` + ``target_verify``.
... | 321 | 12,511 |
sglang | benchmark/bench_linear_attention/bench_gdn_decode.py | .py | """
Benchmark & Correctness: GDN Packed Decode vs Baseline Decode.
Compares:
- Baseline: split(mixed_qkv) → view → fused_sigmoid_gating_delta_rule_update
- Packed: fused_recurrent_gated_delta_rule_packed_decode (single kernel)
The packed path eliminates:
- torch.split() + .view() tensor materialization
- Se... | 489 | 14,794 |
sglang | benchmark/bench_linear_attention/bench_fused_gate_cumsum.py | .py | """
Benchmark: Fused Gate+Cumsum vs Separate Gate + Cumsum.
Compares two paths:
- Separate: torch gate activation -> chunk_local_cumsum (2 steps)
- Fused: kda_gate_chunk_cumsum (single kernel)
Both produce the same output: cumsum of gate-activated g.
Usage:
python bench_fused_gate_cumsum.py
python ben... | 214 | 6,185 |
sglang | benchmark/bench_linear_attention/bench_kda_prefill_cutedsl.py | .py | """
Benchmark & Correctness: Triton KDA vs CuTeDSL KDA (prefill, SM100 Blackwell).
Compares:
- Triton: sglang's chunk_kda (FLA chunkwise gated delta rule, per-channel gate)
- CuteDSL: kda_blackwell pipeline (fused Triton prologue -> kkt_inv_uw -> h -> o)
- Helion: sglang's Helion chunk_kda
KDA differs from GD... | 418 | 14,372 |
sglang | benchmark/ocr/eval_utils.py | .py | """
Evaluation utilities for the OCR benchmark (olmOCR-bench test classes).
Implements:
- text_presence : short text segment must be present in OCR output
- text_absence : text (headers/footers/page numbers) must NOT appear
- natural_reading_order : two text spans must appear in correct relative order... | 632 | 23,982 |
sglang | benchmark/ocr/bench_sglang.py | .py | """
Benchmark DeepSeek-OCR-2 (and similar OCR VLMs) on olmOCR-bench via a running sglang server.
Usage:
# 0. Download the dataset (one-time, ~2 GB with PDFs via Git LFS)
hf download --repo-type dataset \\
allenai/olmOCR-bench --local-dir ./olmOCR-bench
# 1. Start the sglang server (matches run.sh)... | 728 | 25,552 |
sglang | benchmark/ocr/generate_report.py | .py | """
Generate a self-contained HTML verification report from olmOCR-bench results.
Requires results saved with --save-raw-outputs.
Usage:
# 1. Run benchmark with raw outputs saved
python benchmark/ocr/bench_sglang.py --port 30000 --split arxiv_math \\
--max-samples 20 --save-raw-outputs
# 2. Gener... | 382 | 14,877 |
sglang | benchmark/gsm8k/bench_sglang.py | .py | import argparse
import ast
import json
import os
import re
import time
import numpy as np
from datasets import load_dataset
from sglang.lang.api import set_default_backend
from sglang.test.test_utils import (
add_common_sglang_args_and_parse,
dump_bench_raw_result,
select_sglang_backend,
)
from sglang.uti... | 208 | 6,473 |
sglang | benchmark/scheduler/bench_token_storage.py | .py | """Benchmark `list[int]` vs `array.array('q')` storage for
`Req.origin_input_ids` / `Req.output_ids` over one request lifecycle.
Simulated steps (per batch):
1. ingest -- tokenizer list[int] -> storage container.
2. prefix_match -- scheduler radix-tree lookup; RadixKey.match()
z... | 335 | 11,111 |
sglang | benchmark/hellaswag/bench_sglang.py | .py | import argparse
import json
import os
import time
import numpy as np
from sglang.lang.api import set_default_backend
from sglang.test.test_utils import (
add_common_sglang_args_and_parse,
select_sglang_backend,
)
from sglang.utils import download_and_cache_file, read_jsonl
def get_one_example(lines, i, incl... | 110 | 3,240 |
sglang | benchmark/hf3fs/bench_client.py | .py | import concurrent.futures
import logging
import random
import time
from typing import List
import torch
from tqdm import tqdm
from sglang.srt.mem_cache.storage.hf3fs.hf3fs_usrbio_client import Hf3fsUsrBioClient
def print_stats(x: List[int]):
x = sorted(x)
lenx = len(x)
print(
f"mean = {sum(x)/le... | 163 | 4,832 |
sglang | benchmark/hf3fs/bench_zerocopy.py | .py | import threading
import time
import torch
from tqdm import tqdm
from sglang.srt.distributed import (
get_world_group,
init_distributed_environment,
initialize_model_parallel,
)
from sglang.srt.managers.cache_controller import (
HiCacheController,
PrefetchOperation,
StorageOperation,
)
from sgl... | 141 | 3,594 |
sglang | benchmark/hf3fs/bench_storage.py | .py | import json
import logging
import os
import random
import time
from typing import List
import torch
from tqdm import tqdm
from sglang.srt.mem_cache.storage.hf3fs.mini_3fs_metadata_server import (
Hf3fsLocalMetadataClient,
)
from sglang.srt.mem_cache.storage.hf3fs.storage_hf3fs import HiCacheHF3FS
def print_stat... | 259 | 7,297 |
sglang | benchmark/bench_rope/benchmark_rope_index.py | .py | # This script benchmarks MRotaryEmbedding.get_rope_index_glm4v (GLM4V mrope index builder).
# It generates synthetic multimodal input_ids + attention_mask (+ optional image/video grids),
# runs benchmarks.
#
# == Usage Examples ==
#
# python3 benchmark_rope_index.py --device cuda --num-tokens 1024 2048 --benchmark-iter... | 426 | 13,659 |
sglang | benchmark/llava_bench/bench_sglang.py | .py | import argparse
import json
import os
import time
import tqdm
import sglang as sgl
from sglang.test.test_utils import (
add_common_sglang_args_and_parse,
select_sglang_backend,
)
from sglang.utils import dump_state_text, read_jsonl
@sgl.function
def image_qa(s, image_file, question):
s += sgl.user(sgl.i... | 97 | 3,043 |
sglang | benchmark/llava_bench/download_images.py | .py | import os
# Create the 'images' directory if it doesn't exist
if not os.path.exists("images"):
os.makedirs("images")
# Base URL
base_url = "https://huggingface.co/datasets/liuhaotian/llava-bench-in-the-wild/resolve/main/images/"
# Loop through image numbers
for i in range(1, 25):
# Format the image number wi... | 21 | 589 |
sglang | benchmark/kernels/bench_fused_sigmoid_mul.py | .py | """Benchmark fused_sigmoid_mul: auto-dispatch vs PyTorch eager.
The auto-dispatch path uses a strided Triton kernel for Qwen3.5 MoE attention
output gates.
Both paths start from a strided 3D gate (from torch.chunk) to ensure
a fair comparison — the reshape/contiguous cost is included.
"""
import torch
import triton
... | 60 | 1,912 |
sglang | benchmark/kernels/bench_paged_mqa_metadata.py | .py | """Benchmark paged_mqa_metadata JIT kernel.
Reports per-shape median latency in µs via ``marker.do_bench`` (CUDA-graph
timing).
Shape axes:
- ``bs``: dense sweep from single-request decode (1) to large multi-block
batch (32768). Covers the three internal dispatch paths
(tiny ``bs<=64`` / small ``bs<=2048`` ... | 58 | 1,700 |
sglang | benchmark/kernels/bench_fused_rmsnorm_fp8_quant.py | .py | """Microbenchmark: fused RMSNorm + static per-tensor FP8 quant, comparing the
flashinfer default kernels against the CuTe-DSL kernels and the unfused
baseline (RMSNorm followed by a separate static FP8 quant).
Providers:
unfused RMSNorm.forward_cuda + static_quant_fp8
fused flashinfer rmsnorm_quant / f... | 186 | 6,689 |
sglang | benchmark/kernels/bench_fused_gate_sigmoid_mul_add.py | .py | """Benchmark fused_gate_sigmoid_mul_add: Triton kernel vs PyTorch eager.
Compares the fused Triton kernel against a plain PyTorch implementation
over the Qwen3.5 MoE target hidden size.
"""
import torch
import triton
from sglang.kernels.ops.elementwise.elementwise import fused_gate_sigmoid_mul_add
HIDDEN_DIMS = [40... | 61 | 2,096 |
sglang | benchmark/kernels/fused_moe_triton/benchmark_vllm_vs_sglang_fused_moe_triton.py | .py | # python3 benchmark/kernels/fused_moe_triton/benchmark_vllm_vs_sglang_fused_moe_triton.py --model /DeepSeek-V3/ --tp-size 8 --use-fp8-w8a8
import argparse
import torch
import triton
from vllm.model_executor.layers.fused_moe.fused_moe import fused_moe as fused_moe_vllm
from sglang.benchmark.bench_utils import run_benc... | 266 | 7,525 |
sglang | benchmark/kernels/fused_moe_triton/tuning_fused_moe_triton_sep.py | .py | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adapted from https://github.com/vllm-project/vllm/blob/main/benchmarks/kernels/benchmark_moe.py
import argparse
import dataclasses
import json
import os
import time
from contextlib import nullcontext
from dateti... | 1,125 | 38,957 |
sglang | benchmark/kernels/fused_moe_triton/benchmark_torch_compile_fused_moe.py | .py | # python3 benchmark/kernels/fused_moe_triton/benchmark_torch_compile_fused_moe.py --model /DeepSeek-V3/ --tp-size 8 --use-fp8-w8a8
import argparse
import torch
import triton
from torch.nn import functional as F
from transformers import AutoConfig
from sglang.benchmark.bench_utils import run_bench
from sglang.srt.comp... | 307 | 9,344 |
sglang | benchmark/kernels/fused_moe_triton/benchmark_sglang_fused_moe_triton.py | .py | # python3 benchmark/kernels/fused_moe_triton/sglang_fused_moe_triton.py --model /DeepSeek-V3/ --tp-size 8
import argparse
import torch
import triton
from common_utils import get_model_config
from sglang.benchmark.bench_utils import run_bench
from sglang.srt.distributed.parallel_state import (
destroy_distributed_... | 251 | 6,890 |
sglang | benchmark/kernels/fused_moe_triton/tuning_fused_moe_triton.py | .py | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adapted from https://github.com/vllm-project/vllm/blob/main/benchmarks/kernels/benchmark_moe.py
import argparse
import json
import time
from contextlib import nullcontext
from datetime import datetime
from typin... | 553 | 18,307 |
sglang | benchmark/kernels/fused_moe_triton/common_utils.py | .py | import json
from types import SimpleNamespace
from typing import Dict, List, TypedDict
import torch
from sglang.srt.layers.moe.moe_runner.triton_utils.fused_moe import get_config_dtype_str
from sglang.srt.layers.moe.moe_runner.triton_utils.fused_moe_triton_config import (
get_config_file_name,
)
from sglang.srt.u... | 340 | 11,736 |
sglang | benchmark/kernels/fused_moe_triton/tuning_client.py | .py | import argparse
import os
import time
import openai
"""
# Edit the code file srt/models/deepseek_v2.py in the Python site package and add the logic for saving topk_ids:
# import get_tensor_model_parallel_rank
# DeepseekV2MoE::forward_normal
if hidden_states.shape[0] >= 4096 and get_tensor_model_parallel_rank() == 0:
... | 72 | 2,063 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.