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 | python/sglang/srt/kv_canary/runner/sweep.py | .py | from __future__ import annotations
import logging
from collections.abc import Callable
from typing import TYPE_CHECKING, Optional
from sglang.srt.kv_canary.buffer_group import CanaryBufferGroup, PoolKind
from sglang.srt.kv_canary.config import CanaryConfig
from sglang.srt.kv_canary.endpoint import CanaryEndpoint
from... | 85 | 2,919 |
sglang | python/sglang/srt/kv_canary/runner/violation_reporter.py | .py | from __future__ import annotations
import logging
from sglang.kernels.ops.kv_canary.consts import FailReason
from sglang.kernels.ops.kv_canary.verify import CanaryLaunchTag
from sglang.srt.kv_canary.config import CanaryConfig, CanaryMode
from sglang.srt.kv_canary.state import CanaryDeviceState
logger = logging.getLo... | 164 | 5,641 |
sglang | python/sglang/srt/kv_canary/runner/violation_manager.py | .py | from __future__ import annotations
from collections.abc import Callable
import torch
from sglang.srt.kv_canary.config import CanaryConfig
from sglang.srt.kv_canary.runner.future_tensor import DelayedDeviceHostHandler
from sglang.srt.kv_canary.runner.violation_reporter import ViolationReporter
from sglang.srt.kv_cana... | 45 | 1,627 |
sglang | python/sglang/srt/kv_canary/runner/stats_logger.py | .py | from __future__ import annotations
import logging
from collections.abc import Callable
from typing import Any, Optional
import torch
from sglang.kernels.ops.kv_canary.verify import CanaryLaunchTag
from sglang.srt.kv_canary.config import CanaryConfig
from sglang.srt.kv_canary.runner.future_tensor import DelayedDevice... | 67 | 2,393 |
sglang | python/sglang/srt/kv_canary/runner/canary_manager.py | .py | from __future__ import annotations
import contextlib
import logging
from contextlib import contextmanager
from typing import TYPE_CHECKING, Iterator, Optional, Sequence
import torch
from sglang.kernels.ops.kv_canary.verify import CanaryLaunchTag
from sglang.srt.environ import envs
from sglang.srt.kv_canary.buffer_gr... | 296 | 12,373 |
sglang | python/sglang/srt/kv_canary/runner/kernel_launcher.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING, Callable, Optional
import torch
from sglang.kernels.ops.kv_canary.consts import (
RealKvHashMode,
)
from sglang.kernels.ops.kv_canary.plan import launch_canary_plan_kernels
from sglang.kernels.ops.kv_canary.verify import (
CanaryLaunchTag,
... | 183 | 6,118 |
sglang | python/sglang/srt/kv_canary/token_oracle/oracle_manager.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING
import torch
from sglang.srt.kv_canary.expected_inputs import ExpectedInputs
from sglang.srt.kv_canary.token_oracle.oracle import TokenOracle
if TYPE_CHECKING:
from sglang.srt.model_executor.forward_batch_info import ForwardBatch
class TokenO... | 111 | 3,758 |
sglang | python/sglang/srt/kv_canary/token_oracle/install.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from sglang.srt.kv_canary.token_oracle.oracle import HashOracle
from sglang.srt.kv_canary.token_oracle.oracle_manager import TokenOracleManager
from sglang.srt.kv_canary.token_oracle.sampler import install_oracle_sampler
if TYPE_CHECKING:
... | 23 | 778 |
sglang | python/sglang/srt/kv_canary/token_oracle/oracle.py | .py | from __future__ import annotations
from dataclasses import dataclass
from typing import Protocol
import torch
class TokenOracle(Protocol):
"""Deterministic (generalized_req_id, position) -> token_id mapping."""
def expected_tokens(
self, *, generalized_req_ids: torch.Tensor, positions: torch.Tensor... | 51 | 1,440 |
sglang | python/sglang/srt/kv_canary/token_oracle/sampler.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING, List
import torch
from sglang.srt.kv_canary.perturb.next_token_swap import maybe_perturb_swap_next_tokens
from sglang.srt.kv_canary.token_oracle.oracle import TokenOracle
from sglang.srt.kv_canary.token_oracle.oracle_manager import (
TokenOracl... | 60 | 2,198 |
sglang | python/sglang/srt/kv_canary/pool_patcher/utils.py | .py | from __future__ import annotations
import functools
from typing import Any, Callable
_WRAPPED_MARKER_ATTR = "_kv_canary_wrapped_by"
def wrap_method(
obj: object,
method_name: str,
*,
wrapper: Callable[..., Any],
) -> None:
"""Replace ``obj.method_name`` with a closure that delegates to ``wrapper... | 43 | 1,636 |
sglang | python/sglang/srt/kv_canary/pool_patcher/buf_info_splice.py | .py | from __future__ import annotations
from typing import Any, Callable, List, Tuple
import torch
from sglang.srt.kv_canary.buffer_group import CanaryBufferGroup
from sglang.srt.kv_canary.pool_patcher.utils import wrap_method
BufInfoTriple = Tuple[List[int], List[int], List[int]]
def patch_buf_info_method(
pool: ... | 78 | 2,356 |
sglang | python/sglang/srt/kv_canary/pool_patcher/buffer_alloc.py | .py | from __future__ import annotations
import sys
from typing import Tuple
import torch
from sglang.kernels.ops.kv_canary.consts import RealKvHashMode
from sglang.kernels.ops.kv_canary.verify import (
CANARY_SLOT_BYTES,
RealKvSource,
)
from sglang.srt.kv_canary.config import CanaryConfig
_PARTIAL_REAL_KV_READ_B... | 116 | 3,407 |
sglang | python/sglang/srt/kv_canary/pool_patcher/api.py | .py | from __future__ import annotations
import logging
from typing import Callable, Dict, Type
import torch
from sglang.srt.kv_canary.buffer_group import CanaryBufferGroup
from sglang.srt.kv_canary.config import CanaryConfig
from sglang.srt.kv_canary.pool_patcher.adapters.dsv4 import attach_dsv4
from sglang.srt.kv_canary... | 75 | 2,539 |
sglang | python/sglang/srt/kv_canary/pool_patcher/adapters/swa.py | .py | from __future__ import annotations
from typing import Optional
import torch
from sglang.srt.kv_canary.buffer_group import CanaryBufferGroup, PoolKind
from sglang.srt.kv_canary.pool_patcher.buf_info_splice import patch_buf_info_method
from sglang.srt.kv_canary.pool_patcher.buffer_alloc import (
alloc_canary_buf,
... | 85 | 2,471 |
sglang | python/sglang/srt/kv_canary/pool_patcher/adapters/mha.py | .py | from __future__ import annotations
import torch
from sglang.srt.kv_canary.buffer_group import CanaryBufferGroup, PoolKind
from sglang.srt.kv_canary.pool_patcher.buf_info_splice import patch_buf_info_method
from sglang.srt.kv_canary.pool_patcher.buffer_alloc import (
alloc_canary_buf,
make_row_source,
)
def ... | 49 | 1,482 |
sglang | python/sglang/srt/kv_canary/pool_patcher/adapters/dsv4.py | .py | from __future__ import annotations
import torch
from sglang.srt.kv_canary.buffer_group import CanaryBufferGroup, PoolKind
from sglang.srt.kv_canary.pool_patcher.buf_info_splice import patch_buf_info_method
from sglang.srt.kv_canary.pool_patcher.buffer_alloc import alloc_canary_buf
def attach_dsv4(
*,
pool: ... | 54 | 1,659 |
sglang | python/sglang/benchmark/one_batch.py | .py | """
Benchmark the latency of running a single static batch without a server.
This script does not launch a server and uses the low-level APIs.
It accepts server arguments (the same as launch_server.py) and benchmark arguments (e.g., batch size, input lengths).
# Usage (latency test)
## with dummy weights:
python -m s... | 1,064 | 37,514 |
sglang | python/sglang/benchmark/offline_throughput.py | .py | """
Benchmark the throughput in the offline mode.
It accepts server arguments (the same as launch_server.py) and benchmark arguments (the same as serving.py).
# Usage
## Sharegpt dataset with default args
python -m sglang.benchmark.offline_throughput --model-path meta-llama/Meta-Llama-3.1-8B-Instruct --num-prompts 10
... | 587 | 20,106 |
sglang | python/sglang/benchmark/utils.py | .py | import json
import os
import resource
from json import JSONDecodeError
from typing import Dict, List, Optional, Union
import requests
from tqdm.asyncio import tqdm
from transformers import (
AutoProcessor,
AutoTokenizer,
PreTrainedTokenizer,
PreTrainedTokenizerFast,
)
def remove_prefix(text: str, pre... | 157 | 4,740 |
sglang | python/sglang/benchmark/dspark_sts_fit.py | .py | from __future__ import annotations
import argparse
import glob
import logging
import math
from pathlib import Path
from typing import Optional
import torch
from sglang.srt.speculative.dspark_components.dspark_sts import (
DSparkStsCalibration,
)
logger = logging.getLogger(__name__)
_EPS_PROB = 1e-8
def defau... | 228 | 7,227 |
sglang | python/sglang/benchmark/endpoint.py | .py | """Connection target for HTTP benchmark scripts.
Owns the launch-vs-connect decision in one place: a benchmark only needs a base
URL, which comes either from a server we launch or one already running.
"""
import dataclasses
import multiprocessing
import os
import time
from typing import Callable, Optional
import req... | 128 | 4,282 |
sglang | python/sglang/benchmark/bench_utils.py | .py | """Triton do_bench/do_bench_cudagraph compatible wrapper using flashinfer.testing.bench_gpu_time."""
import numpy as np
from flashinfer.testing import bench_gpu_time
def run_bench(
fn,
use_cuda_graph: bool = True,
quantiles=(0.5, 0.2, 0.8),
warmup_ms: int = 25,
rep_ms: int = 100,
):
"""Return... | 24 | 676 |
sglang | python/sglang/benchmark/dspark_sps_profiler.py | .py | # /// script
# requires-python = ">=3.10"
# dependencies = ["msgspec", "requests", "plotly", "kaleido", "numpy"]
# ///
from __future__ import annotations
import argparse
import importlib.util
import json
import logging
import math
import random
import statistics
import threading
import time
from pathlib import Path
fr... | 1,578 | 55,319 |
sglang | python/sglang/benchmark/one_batch_server.py | .py | """
Benchmark the latency of running a single batch with a server.
This script launches a server and uses the HTTP interface.
It accepts server arguments (the same as launch_server.py) and benchmark arguments (e.g., batch size, input lengths).
Usage:
python3 -m sglang.benchmark.one_batch_server --model meta-llama/Met... | 1,265 | 50,222 |
sglang | python/sglang/benchmark/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... | 2,753 | 105,453 |
sglang | python/sglang/benchmark/datasets/longbench_v2.py | .py | import random
from argparse import Namespace
from dataclasses import dataclass
from typing import List, Optional
from transformers import PreTrainedTokenizerBase
from sglang.benchmark.datasets.common import BaseDataset, DatasetRow
LONGBENCH_V2_REPO_ID = "THUDM/LongBench-v2"
LONGBENCH_V2_DEFAULT_OUTPUT_LEN = 10 # an... | 105 | 2,945 |
sglang | python/sglang/benchmark/datasets/custom.py | .py | import json
import os
import random
from argparse import Namespace
from dataclasses import dataclass
from typing import List, Optional
import numpy as np
from transformers import PreTrainedTokenizerBase
from sglang.benchmark.datasets.common import (
ASSISTANT_SUFFIX,
BaseDataset,
DatasetRow,
)
from sglang... | 148 | 4,766 |
sglang | python/sglang/benchmark/datasets/__init__.py | .py | from typing import Dict, Type
from sglang.benchmark.datasets.agentic_trace import AgenticTraceDataset
from sglang.benchmark.datasets.common import BaseDataset, DatasetRow
from sglang.benchmark.datasets.custom import CustomDataset
from sglang.benchmark.datasets.generated_shared_prefix import (
GeneratedSharedPrefix... | 54 | 2,010 |
sglang | python/sglang/benchmark/datasets/mooncake.py | .py | import asyncio
import json
import os
import time
from argparse import Namespace
from dataclasses import dataclass
from typing import AsyncGenerator, Dict, List
from transformers import PreTrainedTokenizerBase
from sglang.benchmark.datasets.common import (
MOONCAKE_DATASET_URL,
BaseDataset,
DatasetRow,
)
f... | 124 | 4,218 |
sglang | python/sglang/benchmark/datasets/random.py | .py | import json
import random
from argparse import Namespace
from dataclasses import dataclass
from typing import List
import numpy as np
from transformers import PreTrainedTokenizerBase
from sglang.benchmark.datasets.common import (
SHAREGPT_FILENAME,
SHAREGPT_REPO_ID,
BaseDataset,
DatasetRow,
comput... | 168 | 5,505 |
sglang | python/sglang/benchmark/datasets/image.py | .py | import io
import random
import warnings
from argparse import Namespace
from dataclasses import dataclass
from typing import List, Optional, Tuple
import numpy as np
import pybase64
from PIL import Image
from transformers import AutoProcessor
from sglang.benchmark.datasets.common import (
BaseDataset,
DatasetR... | 390 | 14,305 |
sglang | python/sglang/benchmark/datasets/agentic_trace.py | .py | import json
import os
from argparse import Namespace
from dataclasses import dataclass
from typing import List, Optional
import numpy as np
from transformers import PreTrainedTokenizerBase
from sglang.benchmark.datasets.common import BaseDataset, DatasetRow
# Per-turn output length when --sharegpt-output-len is not ... | 115 | 3,961 |
sglang | python/sglang/benchmark/datasets/openai_dataset.py | .py | import json
from argparse import Namespace
from dataclasses import dataclass
from typing import List, Optional
import numpy as np
from transformers import PreTrainedTokenizerBase
from sglang.benchmark.datasets.common import BaseDataset, DatasetRow
@dataclass
class OpenAIDataset(BaseDataset):
dataset_path: str
... | 114 | 4,121 |
sglang | python/sglang/benchmark/datasets/speed_bench.py | .py | """SPEED-Bench (nvidia/SPEED-Bench) dataset for the SGLang serving benchmark.
Reads the pre-downloaded throughput_1k JSONL produced by prepare_speed_bench.sh
(or equivalent), optionally filtering by category (low_entropy / mixed /
high_entropy) and fixing the output length.
CLI args consumed:
--dataset-path ... | 103 | 3,833 |
sglang | python/sglang/benchmark/datasets/mmmu.py | .py | import io
import random
from argparse import Namespace
from dataclasses import dataclass
from typing import List, Optional
import pybase64
from datasets import load_dataset
from transformers import AutoProcessor, AutoTokenizer
from sglang.benchmark.datasets.common import BaseDataset, DatasetRow
from sglang.benchmark.... | 125 | 4,285 |
sglang | python/sglang/benchmark/datasets/common.py | .py | import random
from abc import ABC, abstractmethod
from argparse import Namespace
from dataclasses import dataclass
from functools import lru_cache
from typing import Any, Dict, List, Optional
import numpy as np
ASSISTANT_SUFFIX = "Assistant:"
SHAREGPT_REPO_ID = "anon8231489123/ShareGPT_Vicuna_unfiltered"
SHAREGPT_FIL... | 104 | 3,697 |
sglang | python/sglang/benchmark/datasets/generated_shared_prefix.py | .py | import math
import pickle
import random
import uuid
from argparse import Namespace
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import List, Optional
import numpy as np
from tqdm.asyncio import tqdm
from transformers import PreTrainedTokenizerBase
from sglang.be... | 329 | 12,258 |
sglang | python/sglang/benchmark/datasets/sharegpt.py | .py | import json
import random
from argparse import Namespace
from dataclasses import dataclass
from typing import List, Optional
import numpy as np
from transformers import PreTrainedTokenizerBase
from sglang.benchmark.datasets.common import (
ASSISTANT_SUFFIX,
SHAREGPT_FILENAME,
SHAREGPT_REPO_ID,
BaseDat... | 152 | 4,665 |
sglang | python/sglang/cli/generate.py | .py | import argparse
from sglang.cli.utils import get_is_diffusion_model, get_model_path
def generate(args, extra_argv):
# If help is requested, show generate subcommand help without requiring --model-path
if any(h in extra_argv for h in ("-h", "--help")):
from sglang.multimodal_gen.runtime.entrypoints.cl... | 34 | 1,255 |
sglang | python/sglang/cli/main.py | .py | import argparse
from sglang.cli.utils import get_git_commit_hash
from sglang.version import __version__
def version(args, extra_argv):
print(f"sglang version: {__version__}")
print(f"git revision: {get_git_commit_hash()[:7]}")
def main():
parser = argparse.ArgumentParser()
# complex sub commands
... | 47 | 1,181 |
sglang | python/sglang/cli/utils.py | .py | import json
import logging
import os
import subprocess
from functools import lru_cache
from huggingface_hub import HfApi
from sglang.srt.environ import envs
from sglang.utils import (
has_diffusion_overlay_registry_match,
load_diffusion_overlay_registry_from_env,
)
logger = logging.getLogger(__name__)
@lru... | 152 | 5,096 |
sglang | python/sglang/cli/killall.py | .py | #!/usr/bin/env python3
"""Kill SGLang processes on CUDA_VISIBLE_DEVICES GPUs (CI mode only).
Called at the start of every CI job to clean up orphaned processes from
previous (possibly cancelled) runs. Requires SGLANG_IS_IN_CI=true.
For local/non-CI usage, use scripts/killall_sglang.sh instead.
Usage:
python kill... | 458 | 15,043 |
sglang | python/sglang/cli/serve_backends.py | .py | # SPDX-License-Identifier: Apache-2.0
"""Extension API and discovery for ``sglang serve`` backends.
Out-of-tree projects register a zero-argument factory in the
``sglang.serve_backends`` entry point group. The factory returns a
:class:`ServeBackend`; its entry point name becomes a valid ``--model-type``.
The module ... | 232 | 8,483 |
sglang | python/sglang/cli/serve.py | .py | # SPDX-License-Identifier: Apache-2.0
import argparse
import logging
import os
from sglang.cli.serve_backends import (
SERVE_BACKEND_API_VERSION,
ServeBackend,
ServeBackendDetection,
ServeBackendRegistry,
ServeRequest,
)
from sglang.cli.utils import get_is_diffusion_model, get_model_path, try_get_... | 208 | 6,717 |
sglang | python/sglang/test/simple_eval_mixed_prefix_gsm8k.py | .py | # Adapted from https://github.com/openai/simple-evals/
# Hand-rolled GSM8K scorer kept only for the mixed-prefix KV-correctness test,
# which needs randomized completion-style prefixes sgl-eval does not produce.
import ast
import random
import re
from typing import Optional
from sglang.test import simple_eval_common ... | 159 | 5,685 |
sglang | python/sglang/test/kl_multiturn_utils.py | .py | """Enhanced multi-turn KL divergence test helpers."""
from __future__ import annotations
import time
from typing import Callable
from sglang.test.kl_test_utils import (
_extract_output_logprobs,
_flush_cache,
_generate,
_get_input_logprobs,
compare_kl_divergence,
get_input_ids,
)
__all__ = [... | 531 | 18,103 |
sglang | python/sglang/test/nightly_bench_utils.py | .py | import json
import os
from typing import List, Optional
from pydantic import BaseModel
# TODO:
# There is huge redundancy between BenchmarkResult and BenchOneCaseResult, and redundancy between to_markdown_row, generate_markdown_report, get_report_summary.
# We should refactor them to reduce the code duplication.
# 1.... | 131 | 5,213 |
sglang | python/sglang/test/otel_collector.py | .py | """Lightweight in-process OTLP collector for tracing tests.
Provides a minimal OTLP collector that receives traces via gRPC (with HTTP
fallback) and stores them in memory for test assertions, eliminating the need
for Docker-based opentelemetry-collector and file I/O.
Usage::
collector = LightweightOtlpCollector(... | 260 | 10,184 |
sglang | python/sglang/test/test_marlin_utils.py | .py | """
Adapted from
https://github.com/vllm-project/vllm/blob/020f58abcdea65302225663130d08fd8f4dd755a/vllm/model_executor/layers/quantization/utils/marlin_utils_test.py
"""
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
"""Utility functions used for tests and b... | 217 | 6,908 |
sglang | python/sglang/test/simple_eval_humaneval.py | .py | # Adapted from https://github.com/openai/simple-evals/
"""
HumanEval: Evaluating Large Language Models Trained on Code
Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan and Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards and Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray and ... | 132 | 5,700 |
sglang | python/sglang/test/simple_eval_common.py | .py | # Adapted from https://github.com/openai/simple-evals/
import os
import resource
import time
from collections import defaultdict
from dataclasses import dataclass, field
from multiprocessing.pool import ThreadPool
from typing import Any, Dict, List, Optional, Tuple
import httpx
import jinja2
import numpy as np
import... | 666 | 20,285 |
sglang | python/sglang/test/lora_utils.py | .py | import dataclasses
import random
from typing import List, Optional
import torch
from sglang.test.runners import HFRunner, SRTRunner
from sglang.test.test_utils import calculate_rouge_l
@dataclasses.dataclass
class LoRAAdaptor:
name: str
prefill_tolerance: float = None
decode_tolerance: float = None
... | 941 | 34,973 |
sglang | python/sglang/test/simple_eval_mmlu.py | .py | # Adapted from https://github.com/openai/simple-evals/
"""
Measuring Massive Multitask Language Understanding
Dan Hendrycks, Collin Burns, Steven Basart, Andy Zou, Mantas Mazeika, Dawn Song, Jacob Steinhardt
https://arxiv.org/abs/2009.03300
"""
import random
import re
from typing import Optional
import pandas
from ... | 126 | 4,529 |
sglang | python/sglang/test/doc_patch.py | .py | """
Do some monkey patch to make the documentation compilation faster and more reliable.
- Avoid port conflicts
- Reduce the server launch time
- Limit GPU memory usage to allow multiple servers on the same machine
"""
import weakref
import nest_asyncio
nest_asyncio.apply()
import sglang.srt.server_args as server_... | 65 | 1,905 |
sglang | python/sglang/test/test_programs.py | .py | """This file contains the SGL programs used for unit testing."""
import asyncio
import json
import re
import time
import numpy as np
import sglang as sgl
from sglang.srt.utils import is_hip
from sglang.utils import download_and_cache_file, read_jsonl
_is_hip = is_hip()
def test_few_shot_qa():
@sgl.function
... | 623 | 20,770 |
sglang | python/sglang/test/logprob_test_utils.py | .py | """Deterministic batch-shape coverage for the input-logprob sweeps."""
import itertools
def coverage_cases(menu, max_seqs):
"""Every singleton, every ordered pair, and wider heterogeneous cases.
`menu` order is load-bearing: width >= 3 walks it cyclically, so reordering
it changes which wide combination... | 23 | 954 |
sglang | python/sglang/test/nightly_utils.py | .py | """Utilities for running nightly performance benchmarks."""
import json
import os
import subprocess
import time
from typing import List, Optional, Tuple
import requests
from sglang.srt.utils import kill_process_tree
from sglang.test.nightly_bench_utils import BenchmarkResult, generate_markdown_report
from sglang.tes... | 338 | 11,944 |
sglang | python/sglang/test/simple_eval_mmmu_vlm.py | .py | """
MMMU evaluation for VLMs using the run_eval simple-evals interface.
"""
from __future__ import annotations
import base64
import io
import re
from typing import List, Optional, Tuple
from datasets import concatenate_datasets, load_dataset
from PIL import Image
from sglang.test import simple_eval_common as commo... | 475 | 16,567 |
sglang | python/sglang/test/cache_consistency_jitter.py | .py | """Cache/scheduling consistency test: score the same token contexts repeatedly
and require bitwise-identical greedy output tokens and top-k logprobs.
The workload generates a continuation for each independently sampled prefix,
then submits shuffled requests starting from different cuts of that
continuation. This score... | 491 | 18,657 |
sglang | python/sglang/test/layer_ut_utils.py | .py | """Shared fixture plumbing for layer-level backend parity UTs.
Hand-written quantization references (oracle side) live in quant_ref_utils.
"""
import os
import torch
def init_single_process_dist(master_port: int = 29632, backend: str = "gloo"):
"""world=1 dist + model-parallel groups; srt layers require them e... | 75 | 2,511 |
sglang | python/sglang/test/test_deepep_utils.py | .py | # Copy from deepseek-ai/DeepEP/tests/test_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):
# NOTES: you may rewrite this function with your own cluster settings
ip = os.getenv("MAS... | 220 | 7,448 |
sglang | python/sglang/test/test_deterministic.py | .py | """
Batch the same prompt in random batch sizes, and test if the results are consistent across different trials.
Usage:
# Single mode: test determinism with varying batch sizes
python3 -m sglang.test.test_deterministic --n-trials 50 --test-mode single
# Prefix mode: test with shared prefixes
python3 -m sglang.test.te... | 739 | 27,634 |
sglang | python/sglang/test/hicache_spec_storage_common.py | .py | """Shared helpers for HiCache storage + EAGLE3 speculative decoding tests."""
import json
import os
import subprocess
from typing import Dict, List
import psutil
import requests
from sglang.benchmark.utils import get_tokenizer
from sglang.srt.utils import kill_process_tree
from sglang.test.test_utils import (
DE... | 274 | 9,296 |
sglang | python/sglang/test/simple_eval_longbench_v2.py | .py | # Adapted from https://github.com/openai/simple-evals/
"""
LongBench v2: Towards Deeper Understanding and Reasoning on Realistic Long-Context Multitasks
Yushi Bai, Shangqing Tu, Jiajie Zhang, Hao Peng, Xiaozhi Wang, Xin Lv, Shulin Cao, Jiazheng Xu, Lei Hou, Yuxiao Dong, Jie Tang, Juanzi Li
https://arxiv.org/abs/2412.1... | 345 | 12,169 |
sglang | python/sglang/test/gpt_oss_common.py | .py | import json
import os
from concurrent.futures import ThreadPoolExecutor
from types import SimpleNamespace
from typing import Dict, List, Literal, Optional
import requests
from sglang.srt.utils import is_hip, kill_process_tree
from sglang.test.run_eval import run_eval
from sglang.test.test_utils import (
DEFAULT_T... | 154 | 5,386 |
sglang | python/sglang/test/chunked_prefill_test_utils.py | .py | from __future__ import annotations
import time
from types import SimpleNamespace
from typing import ClassVar, List, Optional
from sglang.test.run_eval import run_eval
from sglang.test.server_fixtures.disaggregation_fixture import (
PDDisaggregationServerBase,
)
from sglang.test.test_utils import (
DEFAULT_TIM... | 130 | 4,022 |
sglang | python/sglang/test/tool_call_test_runner.py | .py | import json
from dataclasses import dataclass
from typing import List, Optional
import openai
from sglang.srt.utils import kill_process_tree
from sglang.test.test_utils import (
DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
DEFAULT_URL_FOR_TEST,
ModelLaunchSettings,
popen_launch_server,
)
@dataclass
class Tool... | 404 | 12,822 |
sglang | python/sglang/test/simple_eval_aime25.py | .py | # Adapted from https://github.com/openai/simple-evals/
"""
AIME 2025 - American Invitational Mathematics Examination 2025
Dataset: opencompass/AIME2025
https://huggingface.co/datasets/opencompass/AIME2025
The American Invitational Mathematics Examination (AIME) is a challenging
competition math exam. All answers are ... | 125 | 4,352 |
sglang | python/sglang/test/few_shot_gsm8k_engine.py | .py | """
.. deprecated::
This module is deprecated. Use ``sglang.test.run_eval`` with
``eval_name="gsm8k"`` instead, which routes through the unified
Chat API evaluation framework with dump_metric support.
"""
import argparse
import ast
import asyncio
import re
import time
import warnings
from typing import Opt... | 158 | 4,286 |
sglang | python/sglang/test/send_one.py | .py | """
Run one test prompt.
Usage:
python3 -m sglang.test.send_one
python3 -m sglang.test.send_one --profile --profile-steps 5
python3 -m sglang.test.send_one --profile --profile-by-stage
python3 -m sglang.test.send_one --stop "<|separator|>" "<|eos|>" --max-new-tokens 2048
"""
import argparse
import dataclasses
import ... | 272 | 9,600 |
sglang | python/sglang/test/quant_ref_utils.py | .py | """Hand-written quantization-format references for backend parity UTs.
Deliberately independent of sglang.srt -- never replace with srt imports;
the tests use these to check srt.
"""
import torch
FLOAT8_E4M3_MAX = 448.0
FLOAT4_E2M1_MAX = 6.0
kE2M1ToFloat = torch.tensor(
[0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0],... | 71 | 2,525 |
sglang | python/sglang/test/scripted_runtime_chunked_helpers.py | .py | from __future__ import annotations
from typing import Any, Dict, List
DEFAULT_CHUNK_SIZE: int = 256
DEFAULT_MAX_STEPS: int = 400
VERY_LONG_PROMPT_LEN: int = 8 * DEFAULT_CHUNK_SIZE
SMALL_MODEL: str = "Qwen/Qwen3-0.6B"
def base_engine_kwargs(
*,
model_path: str = SMALL_MODEL,
chunked_prefill_size: int ... | 161 | 5,070 |
sglang | python/sglang/test/run_combined_tests.py | .py | import time
from typing import List, Optional
from sglang.test.accuracy_test_runner import (
AccuracyTestParams,
AccuracyTestResult,
run_accuracy_test,
write_accuracy_github_summary,
)
from sglang.test.nightly_utils import NightlyBenchmarkRunner
from sglang.test.performance_test_runner import (
Per... | 257 | 9,528 |
sglang | python/sglang/test/simple_eval_math.py | .py | # Adapted from https://github.com/openai/simple-evals/
"""
Measuring Mathematical Problem Solving With the MATH Dataset
Dan Hendrycks, Collin Burns, Saurav Kadavath, Akul Arora, Steven Basart, Eric Tang, Dawn Song, Jacob Steinhardt
https://arxiv.org/abs/2103.03874
"""
import random
import re
from typing import Option... | 78 | 2,722 |
sglang | python/sglang/test/performance_test_runner.py | .py | from dataclasses import dataclass, field
from typing import List, Optional, Tuple
from sglang.test.nightly_bench_utils import BenchmarkResult
from sglang.test.nightly_utils import NightlyBenchmarkRunner
from sglang.test.test_utils import DEFAULT_URL_FOR_TEST, ModelLaunchSettings
@dataclass
class PerformanceTestParam... | 247 | 8,646 |
sglang | python/sglang/test/few_shot_gsm8k.py | .py | """
Run few-shot GSM-8K evaluation.
.. deprecated::
This module is deprecated. Use ``sglang.test.run_eval`` with
``eval_name="gsm8k"`` instead, which routes through the unified
Chat API evaluation framework with dump_metric support.
Usage:
python3 -m sglang.test.few_shot_gsm8k --num-questions 200
"""
imp... | 167 | 4,803 |
sglang | python/sglang/test/run_eval.py | .py | """
Usage:
python3 -m sglang.test.run_eval --port 30000 --eval-name mmlu --num-examples 10
"""
import argparse
import json
import os
import statistics
import subprocess
import time
import uuid
from pathlib import Path
from sglang.test.simple_eval_common import (
ChatCompletionSampler,
CompletionSampler,
E... | 556 | 20,153 |
sglang | python/sglang/test/precision_baseline_store.py | .py | """HF dataset store for nightly precision-regression baselines.
Layout: ``<model>/<YYYY>/<MM>/<DD>/run-<sglang_sha7>/{meta.json,
comparator_report.jsonl, tensors/*.pt}``. Root ``manifest.jsonl`` has one
row per run; rows carry a ``push_index`` so fetch picks the latest push
regardless of file order (prune may rewrite ... | 414 | 13,614 |
sglang | python/sglang/test/accuracy_test_runner.py | .py | from dataclasses import dataclass
from types import SimpleNamespace
from typing import List, Optional, Tuple
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,
ModelLaunchSett... | 249 | 7,754 |
sglang | python/sglang/test/cpu_test_utils.py | .py | import itertools
import math
import torch
import torch.nn.functional as F
precision = {
torch.bfloat16: 1e-2,
torch.float16: 1e-3,
torch.float32: 1e-5,
}
BLOCK_N, BLOCK_K = 64, 128
factor_for_scale = 1e-3
fp8_max, fp8_min = 400, -400
def parametrize(**params):
def decorator(func):
def wrap... | 660 | 21,139 |
sglang | python/sglang/test/runners.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... | 962 | 38,116 |
sglang | python/sglang/test/test_deterministic_utils.py | .py | import unittest
from sglang.test.test_deterministic import BenchArgs, test_deterministic
from sglang.test.test_utils import (
DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
DEFAULT_URL_FOR_TEST,
CustomTestCase,
popen_launch_server,
terminate_and_kill_process_tree,
)
DEFAULT_MODEL = "Qwen/Qwen3-8B"
COMMON_SERV... | 77 | 2,362 |
sglang | python/sglang/test/kl_test_utils.py | .py | import inspect
import json
import os
import random
import numpy as np
import requests
from sglang.srt.utils.hf_transformers_utils import get_tokenizer
# LongBench V2 dataset configuration
# Reference: https://github.com/THUDM/LongBench
LONGBENCH_V2_DATASET = "THUDM/LongBench-v2"
LONGBENCH_V2_SPLIT = "train"
DEFAULT_... | 384 | 12,685 |
sglang | python/sglang/test/vlm_utils.py | .py | import io
import os
from concurrent.futures import ThreadPoolExecutor
import numpy as np
import openai
import pybase64
import requests
from PIL import Image
from sglang.test.test_utils import (
DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH,
DEFAULT_URL_FOR_TEST,
CustomTestCase,
popen_launch_server,
terminate_... | 651 | 23,218 |
sglang | python/sglang/test/test_utils.py | .py | """Common utilities for testing and benchmarking"""
import argparse
import asyncio
import copy
import doctest
import importlib.util
import inspect
import json
import logging
import os
import random
import re
import shlex
import subprocess
import sys
import threading
import time
import unittest
from concurrent.futures ... | 2,600 | 84,565 |
sglang | python/sglang/test/simple_eval_mgsm.py | .py | # Adapted from https://github.com/openai/simple-evals/
"""
MGSM: Multilingual Grade School Math Benchmark (MGSM) is a benchmark of grade-school math problems.
Language Models are Multilingual Chain-of-Thought Reasoners
Freda Shi, Mirac Suzgun, Markus Freitag, Xuezhi Wang, Suraj Srivats, Soroush Vosoughi, Hyung Won Chu... | 204 | 10,266 |
sglang | python/sglang/test/simple_eval_gpqa.py | .py | # Adapted from https://github.com/openai/simple-evals/
"""
GPQA: A Graduate-Level Google-Proof Q&A Benchmark
David Rein, Betty Li Hou, Asa Cooper Stickland, Jackson Petty, Richard Yuanzhe Pang, Julien Dirani, Julian Michael, Samuel R. Bowman
https://arxiv.org/abs/2311.12022
"""
import random
import re
from typing imp... | 98 | 3,400 |
sglang | python/sglang/test/xpu/simple_eval_gsm8k_xpu_mixin.py | .py | """simple-evals GSM8K accuracy mixin for Intel XPU nightly tests.
Launches an SGLang server with XPU flags, then calls ``sglang.test.run_eval``
with ``eval_name="gsm8k"`` so the ``simple_eval_gsm8k.GSM8KEval`` evaluator
scores the run.
Subclasses set ``model``, ``tp_size``, ``accuracy``, and may override
``other_args... | 121 | 4,337 |
sglang | python/sglang/test/xpu/test_xpu_utils.py | .py | """Helpers shared by XPU nightly model tests.
The summary writer mirrors `python/sglang/test/ascend/test_ascend_utils.py`
so XPU and Ascend nightly runs render the same Markdown table in
`$GITHUB_STEP_SUMMARY`.
"""
from sglang.test.test_utils import is_in_ci, write_github_step_summary
HEADER = """
| Model | Server |... | 51 | 1,770 |
sglang | python/sglang/test/scripted_runtime/io_struct.py | .py | from __future__ import annotations
import dataclasses
import json
from dataclasses import dataclass
from typing import Any, Tuple, Union
@dataclass(frozen=True, slots=True)
class RunScript:
fn_path: str
args: Tuple[Any, ...] = ()
@dataclass(frozen=True, slots=True)
class Shutdown:
pass
@dataclass(fr... | 52 | 901 |
sglang | python/sglang/test/scripted_runtime/utils.py | .py | from __future__ import annotations
import importlib
import sys
from typing import Callable, Optional
import zmq
def close_zmq_socket(socket: zmq.Socket, ctx: zmq.Context) -> None:
socket.setsockopt(zmq.LINGER, 0)
socket.close()
ctx.term()
def ensure_script_importable(sys_path_entry: Optional[str]) -> ... | 34 | 970 |
sglang | python/sglang/test/scripted_runtime/scheduler_hook.py | .py | from __future__ import annotations
import logging
import sys
import time
import traceback
from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING, Generator, List, Optional, Tuple
import zmq
from sglang.srt.environ import envs
from sglang.srt.managers.io_struct import sock_recv, s... | 242 | 8,156 |
sglang | python/sglang/test/scripted_runtime/background_http_poster.py | .py | from __future__ import annotations
import asyncio
import logging
import threading
from concurrent.futures import Future
from typing import Any, Coroutine, Optional
import aiohttp
logger = logging.getLogger(__name__)
JOIN_TIMEOUT_S: float = 10.0
class BackgroundHttpPoster:
def __init__(self) -> None:
... | 69 | 2,215 |
sglang | python/sglang/test/scripted_runtime/tokenizer_recv_proxy.py | .py | from __future__ import annotations
import time
from collections import deque
from typing import Any, Callable
import zmq
from sglang.srt.managers.io_struct import (
BatchTokenizedEmbeddingReqInput,
BatchTokenizedGenerateReqInput,
TokenizedEmbeddingReqInput,
TokenizedGenerateReqInput,
sock_recv,
)... | 79 | 2,306 |
sglang | python/sglang/test/scripted_runtime/req_handle.py | .py | from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, Optional
from sglang.test.scripted_runtime.context.radix import _node_lock_ref
if TYPE_CHECKING:
from sglang.srt.managers.schedule_batch import Req
from sglang.test.scripted_runtime.context.api import Scrip... | 59 | 1,530 |
sglang | python/sglang/test/scripted_runtime/http_server.py | .py | from __future__ import annotations
import multiprocessing as mp
import os
import tempfile
import time
from pathlib import Path
from typing import Any, Callable, Dict, Optional, Tuple
import requests
import zmq
from sglang.srt.entrypoints.http_server import launch_server
from sglang.srt.environ import envs
from sglan... | 261 | 8,772 |
sglang | python/sglang/test/scripted_runtime/test_case.py | .py | from __future__ import annotations
from typing import Any, ClassVar, Dict
from sglang.test.scripted_runtime.http_server import ScriptedHttpServer
from sglang.test.test_utils import CustomTestCase
class ScriptedTestCase(CustomTestCase):
ENGINE_KWARGS: ClassVar[Dict[str, Any]] = {}
server: ClassVar[Scripted... | 30 | 792 |
sglang | python/sglang/test/scripted_runtime/context/lock_ref_exhauster.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING, Any, List
from sglang.test.scripted_runtime.context.radix import _node_lock_ref
if TYPE_CHECKING:
from sglang.srt.managers.scheduler import Scheduler
class ScriptedLockRefExhauster:
def __init__(self, scheduler: Scheduler) -> None:
... | 50 | 1,480 |
sglang | python/sglang/test/scripted_runtime/context/lifecycle.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING, Literal
from sglang.srt.managers.io_struct import (
AbortReq,
ContinueGenerationReqInput,
FlushCacheReqInput,
PauseGenerationReqInput,
)
from sglang.test.scripted_runtime.context.http_post import (
_http_post_and_await_recv_msg,
... | 86 | 2,037 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.