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/test/scripted_runtime/context/req_starter.py
.py
from __future__ import annotations import uuid from typing import TYPE_CHECKING, List, Optional from sglang.test.scripted_runtime.context.http_post import ( _http_post_and_await_recv_msg, ) from sglang.test.scripted_runtime.req_handle import ScriptedReqHandle if TYPE_CHECKING: from sglang.test.scripted_runti...
74
2,459
sglang
python/sglang/test/scripted_runtime/context/http_post.py
.py
from __future__ import annotations import logging from typing import TYPE_CHECKING, Any, Callable, Dict, Optional if TYPE_CHECKING: from sglang.test.scripted_runtime.context.api import ScriptedContext logger = logging.getLogger(__name__) RECV_MSG_ARRIVAL_TIMEOUT_S: float = 60.0 def _http_post_and_await_recv_m...
53
1,229
sglang
python/sglang/test/scripted_runtime/context/__init__.py
.py
from sglang.test.scripted_runtime.context.api import ScriptedContext __all__ = ["ScriptedContext"]
4
100
sglang
python/sglang/test/scripted_runtime/context/queries.py
.py
from __future__ import annotations from typing import TYPE_CHECKING, Dict, Iterator, List, Optional if TYPE_CHECKING: from sglang.srt.managers.schedule_batch import Req from sglang.test.scripted_runtime.context.api import ScriptedContext def _get_all_reqs(ctx: ScriptedContext) -> Iterator[Req]: s = ctx....
140
4,440
sglang
python/sglang/test/scripted_runtime/context/engine.py
.py
from __future__ import annotations from typing import TYPE_CHECKING, Dict if TYPE_CHECKING: from sglang.test.scripted_runtime.context.api import ScriptedContext def engine_stats(ctx: ScriptedContext) -> Dict[str, int]: s = ctx.scheduler return { "kv_pool_free": s.token_to_kv_pool_allocator.avail...
17
488
sglang
python/sglang/test/scripted_runtime/context/radix.py
.py
from __future__ import annotations from typing import TYPE_CHECKING, Any, Callable, Dict from sglang.srt.mem_cache.swa_radix_cache import TreeNode as SWATreeNode from sglang.srt.mem_cache.unified_radix_cache import UnifiedTreeNode if TYPE_CHECKING: from sglang.test.scripted_runtime.context.api import ScriptedCon...
38
1,199
sglang
python/sglang/test/scripted_runtime/context/api.py
.py
from __future__ import annotations import logging from typing import TYPE_CHECKING, Dict, List, Literal, Optional from sglang.test.scripted_runtime.context import ( engine, lifecycle, queries, radix, ) from sglang.test.scripted_runtime.context.kv_pool_exhauster import ( ScriptedKvPoolExhauster, ) ...
165
5,646
sglang
python/sglang/test/scripted_runtime/context/kv_pool_exhauster.py
.py
from __future__ import annotations from typing import TYPE_CHECKING, List if TYPE_CHECKING: import torch from sglang.srt.managers.scheduler import Scheduler class ScriptedKvPoolExhauster: def __init__(self, scheduler: Scheduler) -> None: self.scheduler = scheduler self._held: List[torc...
35
967
sglang
python/sglang/test/external_models/custom_qwen2_vl.py
.py
from sglang.srt.models.qwen2_vl import ( Qwen2VLForConditionalGeneration as OriginalQwen2VLForConditionalGeneration, ) from sglang.srt.multimodal.processors.qwen_vl import QwenVLImageProcessor class Qwen2VLForConditionalGeneration(OriginalQwen2VLForConditionalGeneration): def __init__(self, config, quant_conf...
22
829
sglang
python/sglang/test/observability/fake_ray.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...
143
4,711
sglang
python/sglang/test/manual/disaggregation/test_chunked_prefill_abort.py
.py
import threading import time import unittest import uuid from typing import Any 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, DEFAULT_URL_FOR_TEST, CustomTestCase, popen_laun...
135
4,246
sglang
python/sglang/test/manual/disaggregation/test_disaggregation_chunked_prefill_abort.py
.py
import threading import time import unittest import uuid from typing import Any import requests from sglang.test.server_fixtures.disaggregation_fixture import ( PDDisaggregationServerBase, ) from sglang.test.test_utils import DEFAULT_SMALL_MODEL_NAME_FOR_TEST PD_EXTRA_ARGS = ["--max-running-requests", "4", "--ch...
110
3,514
sglang
python/sglang/test/manual/disaggregation/test_disaggregation_peer_liveness_abort.py
.py
import json import threading import time import unittest import uuid from concurrent.futures import ThreadPoolExecutor, TimeoutError, as_completed from typing import Any import requests from sglang.srt.environ import envs from sglang.test.server_fixtures.disaggregation_fixture import ( PDDisaggregationServerBase,...
317
10,524
sglang
python/sglang/test/server_fixtures/streaming_session_fixture.py
.py
"""Streaming-session test fixture. `TestStreamingSession` is the base class for all streaming-session tests (default config — Llama-3.1-8B, no spec). Variants in test_streaming_session.py and test_streaming_session_extra.py inherit it and only override `setUpClass`. Also exports: - ABORT_REPRO_* constants used by the...
445
17,025
sglang
python/sglang/test/server_fixtures/spec_eagle_fixture.py
.py
"""Unified EAGLE/EAGLE3 speculative-decoding server fixture. A single popen-server base whose launch is fully described by class attributes, so concrete test classes only flip knobs (overlap on/off, model, topk, page size, backend, env overrides). Pair it with the kits in ``sglang.test.kits.spec_server_kits`` to assem...
251
9,003
sglang
python/sglang/test/server_fixtures/dsa_mtp_fixture.py
.py
"""DSA model + MTP (EAGLE) speculative-decoding server fixture. Variants combine `DsaMtpServerBase` (server lifecycle) with `DsaMtpEvalConfigDefaults` (shared eval thresholds/params), `GSM8KMixin` and `SpecDecodingMixin`, then set `model` and per-variant overrides (`enable_dp_attention`, `mem_fraction_static`, `bs_1_s...
99
3,164
sglang
python/sglang/test/server_fixtures/default_fixture.py
.py
import logging import time from contextlib import contextmanager import requests from sglang.test.test_utils import ( DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, DEFAULT_URL_FOR_TEST, CustomTestCase, popen_launch_server, terminate_and_kill_process_tree, ) logger = logging.getLogger(__name__) @contextman...
74
1,955
sglang
python/sglang/test/server_fixtures/eagle_fixture.py
.py
import json import random import time import requests from sglang.test.test_utils import ( DEFAULT_DRAFT_MODEL_EAGLE, DEFAULT_TARGET_MODEL_EAGLE, DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, DEFAULT_URL_FOR_TEST, CustomTestCase, popen_launch_server, terminate_and_kill_process_tree, ) PROMPTS = [ ...
116
3,949
sglang
python/sglang/test/server_fixtures/pcg_spec_fixture.py
.py
"""Piecewise CUDA Graph + speculative decoding test fixture. Each variant tests PCG coexisting with one speculative-decoding algorithm (EAGLE3 / NEXTN / STANDALONE / NGRAM). Variants differ widely on model / server args / thresholds, so the base only abstracts the common shape: - launch a server with `server_args` (...
81
2,691
sglang
python/sglang/test/server_fixtures/standalone_fixture.py
.py
"""STANDALONE speculative-decoding server fixture. Variants combine this base with `CustomTestCase` and override class attributes (`attention_backend`, plus optional `speculative_eagle_topk` / `speculative_num_draft_tokens` / `disable_overlap` / `enable_deterministic_inference`) to select a backend, deterministic mode...
119
3,957
sglang
python/sglang/test/server_fixtures/hybrid_attn_backend_fixture.py
.py
"""Hybrid attention-backend (FA3 prefill + FlashInfer decode) test fixture. Variants combine `TestHybridAttnBackendBase` with their own `get_server_args()` / `accuracy_threshold` / `speculative_decode` knobs. Requires SM 90+ (H100); the base class wraps that in a `skipIf`. """ import unittest from types import Simpl...
104
3,381
sglang
python/sglang/test/server_fixtures/mmmu_fixture.py
.py
import logging import os import time from sglang.test.test_utils import ( DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, DEFAULT_URL_FOR_TEST, CustomTestCase, popen_launch_server, terminate_and_kill_process_tree, ) logger = logging.getLogger(__name__) # Set default mem_fraction_static to 0.8 DEFAULT_MEM_FRAC...
72
2,126
sglang
python/sglang/test/server_fixtures/ngram_fixture.py
.py
"""NGRAM speculative-decoding server fixture. Variants combine this base with `GSM8KMixin` and override `attention_backend` (required) plus optional `extra_args` to select a backend / pass extra flags. Example: from sglang.test.server_fixtures.ngram_fixture import NgramServerBase from sglang.test.kits.eval_ac...
75
2,326
sglang
python/sglang/test/server_fixtures/disaggregation_fixture.py
.py
import io import logging import os import shlex import time import warnings from typing import ClassVar, Optional from urllib.parse import urlparse import requests from sglang.srt.environ import envs from sglang.srt.utils import kill_process_tree from sglang.test.test_utils import ( DEFAULT_TIMEOUT_FOR_SERVER_LAU...
496
18,191
sglang
python/sglang/test/kernels/utils.py
.py
import sys from typing import Callable, List, Optional, Sequence import pytest from sglang.kernels.ops.communication.mp import multigpu_launch def multigpu_pytest_main( name: str, file: str, num_gpus: Sequence[int], *, pre_launch_fn: Optional[Callable[[List[int]], None]] = None, timeout: Opt...
65
2,551
sglang
python/sglang/test/kernels/deepseek_v4/common.py
.py
from __future__ import annotations from dataclasses import dataclass from typing import List, Literal, Optional, Tuple import torch from sglang.kernels.ops.attention.dsv4 import ( CompressorDecodePlan, CompressorPrefillPlan, ) from sglang.srt.utils import get_device @dataclass class LegacyContext: """P...
200
6,770
sglang
python/sglang/test/kernels/kv_canary/_constants.py
.py
from __future__ import annotations from sglang.kernels.ops.kv_canary.verify import CANARY_SLOT_BYTES # Default fixture sizes — small enough for fast tests, large enough that ring overflow / multi-req cases # stay realistic without bloating the assertion surface. DEFAULT_RING_CAPACITY: int = 64 DEFAULT_NUM_SLOTS: int ...
13
439
sglang
python/sglang/test/kernels/kv_canary/_invariants.py
.py
"""Ref/real-independent invariant assertions for kv_canary kernel tests. Each invariant only looks at the kernel's inputs and outputs (shape relationships, monotonicity, tail positions, etc.) — it must never re-implement the reference algorithm. Hand and fuzz tests both call into this module so a single contract viola...
521
20,563
sglang
python/sglang/test/kernels/kv_canary/_fixtures.py
.py
from __future__ import annotations import random from typing import Literal, Optional import torch from sglang.kernels.ops.kv_canary.verify import ( RealKvSource, VerifyPlan, ) from sglang.kernels.ops.kv_canary.write import WritePlan from sglang.test.kernels.kv_canary._constants import DEFAULT_NUM_SLOTS _DE...
232
7,226
sglang
python/sglang/test/kernels/kv_canary/_differential.py
.py
from __future__ import annotations from dataclasses import dataclass, replace from typing import Any, Callable, Iterator, Optional import torch from sglang.kernels.ops.kv_canary import consts from sglang.kernels.ops.kv_canary.plan import launch_canary_plan_kernels from sglang.kernels.ops.kv_canary.plan_ref import ( ...
547
21,011
sglang
python/sglang/test/kernels/kv_canary/_hand_oracle.py
.py
"""Hand-computed Python re-implementation of the real-kv-source fold, kept independent from ``verify_ref._splitmix64_fold_bytes_scalar`` so a ref / kernel co-regression cannot silently fix the diff comparison.""" from __future__ import annotations from sglang.kernels.ops.kv_canary.consts import splitmix64 def _fold...
32
1,250
sglang
python/sglang/test/kernels/kv_canary/_fuzz_driver.py
.py
from __future__ import annotations import random from typing import Any, Callable from sglang.test.kernels.kv_canary._differential import ( ShrinkResult, shrink_inputs, ) FUZZ_SEEDS_PR: tuple[int, ...] = (0,) def check_repro(inputs: Any, *, run_one_fn: Callable[[Any], Any]) -> bool: try: run_on...
46
1,262
sglang
python/sglang/test/kernels/kv_canary/_canary_helpers.py
.py
from __future__ import annotations from dataclasses import dataclass from typing import Optional import torch from sglang.kernels.ops.kv_canary import consts from sglang.kernels.ops.kv_canary.consts import splitmix64, splitmix64_mix3 from sglang.kernels.ops.kv_canary.verify import VerifyPlan from sglang.kernels.ops....
345
10,759
sglang
python/sglang/test/mock_model/utils.py
.py
from __future__ import annotations import io import subprocess from dataclasses import dataclass from typing import Any, Sequence from sglang.benchmark.serving import run_benchmark from sglang.srt.utils import kill_process_tree from sglang.test.test_utils import ( DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, DEFAULT_UR...
137
4,027
sglang
python/sglang/test/mock_model/perturb_e2e_base.py
.py
from __future__ import annotations import io import os from typing import ClassVar from sglang.test.kv_canary.e2e_base import CapturedServerE2EBase from sglang.test.kv_canary.utils import post_parallel_generate from sglang.test.mock_model.utils import ( MOCK_MODEL_PATH, mock_model_server_args, mock_model_...
58
1,640
sglang
python/sglang/test/ascend/npu_eval_accuracy_kit.py
.py
"""NPU accuracy test mixin. Wraps :class:`~sglang.test.kits.eval_accuracy_kit.GSM8KMixin` with: * 1% accuracy tolerance (threshold * 0.99) * Automatic retry (up to 3 attempts) Delegates to ``super().test_gsm8k()`` so community-side changes to eval setup, backend selection, or parameters are inherited automatically. ...
72
2,171
sglang
python/sglang/test/ascend/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,022
sglang
python/sglang/test/ascend/test_embedding_base.py
.py
import multiprocessing as mp from abc import ABC from typing import List, Optional, Tuple import torch from transformers import AutoConfig, AutoTokenizer from sglang.test.runners import DEFAULT_PROMPTS, HFRunner, SRTRunner from sglang.test.test_utils import get_similarities class BaseEmbeddingTest(ABC): """Base...
103
3,607
sglang
python/sglang/test/ascend/test_ascend_utils.py
.py
""" Common utilities for testing and benchmarking on NPU. This file contains the following weight path categories: - LLM model weights path - VLM model weights path - Embedding model weights path - Rerank model weights path - Reward model weights path Please remember to sort by variable name within each section. """ ...
962
34,240
sglang
python/sglang/test/ascend/output_capturer.py
.py
import os import select import threading class OutputCapturer: """Capture all console print information Class Description: Capture console output using low-level file descriptor redirection. Used to obtain print information from child processes, NPU processes, and underlying C/C++ mod...
118
4,122
sglang
python/sglang/test/ascend/run_eval.py
.py
import json import os from sglang.test.run_eval import run_eval_once from sglang.test.simple_eval_common import ( make_report, set_ulimit, ) def run_eval(args): # Lazy import to avoid circular dependency with test_utils from sglang.test.test_utils import dump_metric set_ulimit() if "OPENAI_...
123
4,267
sglang
python/sglang/test/ascend/test_no_hf_reward_base.py
.py
import multiprocessing as mp from abc import ABC import torch from sglang.test.runners import SRTRunner PROMPT = ( "What is the range of the numeric output of a sigmoid node in a neural network?" ) RESPONSE1 = "The output of a sigmoid node is bounded between -1 and 1." RESPONSE2 = "The output of a sigmoid node i...
60
1,955
sglang
python/sglang/test/ascend/gsm8k_ascend_mixin.py
.py
import os import subprocess from abc import ABC from types import SimpleNamespace from sglang.srt.utils import kill_process_tree from sglang.test.ascend.test_ascend_utils import write_results_to_github_step_summary from sglang.test.run_eval import run_eval from sglang.test.test_utils import ( DEFAULT_TIMEOUT_FOR_S...
117
3,977
sglang
python/sglang/test/ascend/disaggregation_utils.py
.py
import logging import os import time import warnings from urllib.parse import urlparse import requests 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_...
154
5,295
sglang
python/sglang/test/ascend/vlm_utils.py
.py
import os import warnings 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_TIMEOUT_FOR_SERVER_LAUNCH, DEFAULT_URL_FOR_TEST, CustomTestCase, popen_launch_server, ) class TestVLMModels...
98
2,810
sglang
python/sglang/test/ascend/test_mmlu.py
.py
import subprocess from types import SimpleNamespace from sglang.test.ascend.test_ascend_utils import write_results_to_github_step_summary from sglang.test.run_eval import run_eval class TestMMLU: mmlu_num_examples = 128 def test_mmlu(self): accuracy_mmlu_threshold = getattr(self, "accuracy_mmlu", 0...
42
1,457
sglang
python/sglang/test/ascend/test_npu_logging.py
.py
import os import re import tempfile import time import requests from sglang.srt.utils import kill_process_tree from sglang.test.ascend.test_ascend_utils import LLAMA_3_2_1B_INSTRUCT_WEIGHTS_PATH from sglang.test.test_utils import ( DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, DEFAULT_URL_FOR_TEST, CustomTestCase, ...
154
5,966
sglang
python/sglang/test/ascend/e2e/gen_dataset_fixed_len.py
.py
import json import os import random import string import numpy as np from PIL import Image from transformers import AutoTokenizer def load_jsonl(path): """Load data from a JSONL file, one JSON object per line.""" data = [] with open(path, "r", encoding="utf-8") as f: for line in f: li...
522
18,197
sglang
python/sglang/test/ascend/e2e/test_npu_performance_utils.py
.py
import glob import inspect import json import logging import os import re import shutil import subprocess import sys import threading import time from datetime import datetime from functools import wraps from urllib.parse import urlparse from sglang.srt.utils import kill_process_tree from sglang.test.ascend.e2e.gen_da...
1,414
51,709
sglang
python/sglang/test/ascend/e2e/run_npu_e2e_test.py
.py
import argparse import json import logging import os import random import re import string import subprocess import time import uuid import psutil import yaml from jinja2 import Template from kubernetes import client, config from kubernetes.client.rest import ApiException logging.basicConfig( level=logging.INFO, ...
893
32,405
sglang
python/sglang/test/ascend/e2e/test_npu_accuracy_utils.py
.py
import glob import inspect import json import logging import os import re import shutil import subprocess import sys import threading import time from datetime import datetime from urllib.parse import urlparse from sglang.srt.utils import kill_process_tree from sglang.test.ascend.e2e.test_npu_multi_node_utils import (...
751
26,309
sglang
python/sglang/test/ascend/e2e/test_npu_multi_node_utils.py
.py
import logging import os import re import socket import subprocess import threading import time from functools import wraps from types import SimpleNamespace from typing import Iterable, Union import requests from sglang.srt.utils import kill_process_tree from sglang.test.few_shot_gsm8k import run_eval as run_eval_gs...
1,082
36,731
sglang
python/sglang/test/kits/matched_stop_kit.py
.py
import json import requests MANY_NEW_TOKENS_PROMPT = """ Please write an extremely detailed and vivid fantasy story, set in a world full of intricate magic systems, political intrigue, and complex characters. Ensure that you thoroughly describe every scene, character's motivations, and the environment. Include long, ...
158
5,382
sglang
python/sglang/test/kits/unified_radix_cache_kit.py
.py
import random from types import SimpleNamespace from urllib.parse import urlparse from sglang.test.kl_multiturn_utils import ( test_input_output_logprobs_match_decode_cache_hit_helper, test_input_output_logprobs_match_helper, test_input_output_logprobs_match_prefill_cache_hit_helper, ) def _random_suffix...
129
4,819
sglang
python/sglang/test/kits/basic_api_contract_kit.py
.py
"""Basic HTTP / SSE API contract sanity kit. Probes that catch the server failing at the protocol layer: endpoints missing, 5xx returned, response schema broken, or OpenAI-compatible routes drifting from the spec. Mix into any ``CustomTestCase`` subclass that exposes ``self.base_url`` and ``self.process``. Override `...
88
3,189
sglang
python/sglang/test/kits/abort_timeout_kit.py
.py
import time from concurrent.futures import ThreadPoolExecutor, as_completed import requests # Safety timeout for all HTTP requests to prevent CI from hanging forever. _REQUEST_TIMEOUT = 60 class AbortAllMixin: """Test /abort_request with abort_all=True. Server needs sufficient --max-running-requests. "...
145
4,771
sglang
python/sglang/test/kits/regex_constrained_kit.py
.py
import json import requests class RegexConstrainedMixin: def _run_decode_regex( self, regex, prompt, return_logprob=False, top_logprobs_num=0, n=1, ): response = requests.post( self.base_url + "/generate", json={ ...
132
3,514
sglang
python/sglang/test/kits/spec_server_kits.py
.py
"""Reusable test-method mixins (kits) for EAGLE/EAGLE3 spec-decoding servers. Pair these with ``SpecEagleServerBase`` (sglang.test.server_fixtures.spec_eagle_fixture). Each kit is a cohesive group of ``test_*`` methods with no launch logic; concrete test classes mix in the fixture (which owns launch knobs) + whichever...
699
26,654
sglang
python/sglang/test/kits/eval_accuracy_kit.py
.py
from types import SimpleNamespace from typing import Optional import requests from sglang.test.run_eval import run_eval from sglang.test.test_utils import is_in_amd_ci, is_in_ci, write_github_step_summary _THRESHOLD_NOT_SET = float("nan") def _check_accept_length(test_case, base_url, threshold=None): """Print ...
420
14,720
sglang
python/sglang/test/kits/radix_cache_server_kit.py
.py
import random import requests def gen_radix_tree(num_nodes=400, chunk_len=256): num0 = num_nodes // 2 num1 = num_nodes - num0 nodes = [{"input_ids": [37] * 117, "decode_len": 217}] for _ in range(num0): parent = random.choice(nodes) unique_len = random.randint(0, chunk_len) de...
55
1,653
sglang
python/sglang/test/kits/cache_hit_kit.py
.py
import asyncio import json import time import aiohttp import requests from sglang.benchmark.datasets.random import sample_random_requests from sglang.benchmark.serving import RequestFuncOutput from sglang.benchmark.utils import get_tokenizer, remove_prefix AIOHTTP_TIMEOUT = aiohttp.ClientTimeout(total=20 * 60 * 60) ...
404
14,842
sglang
python/sglang/test/kits/kl_divergence_kit.py
.py
from sglang.test.kl_test_utils import ( test_input_output_logprobs_match_decode_cache_hit_helper, test_input_output_logprobs_match_prefill_cache_hit_helper, ) class KLDivergenceMixin: kl_div_thres: float kl_div_thres_decode: float | None = None kl_div_thres_prefill: float | None = None kl_div_...
46
1,717
sglang
python/sglang/test/kits/hellaswag_kit.py
.py
"""Hellaswag sanity kit. Runs hellaswag via the sgl frontend DSL bound to ``self.base_url`` and asserts accuracy above a threshold. Catches systematic regressions that pass every cheap single-prompt probe but tank multi-choice reasoning. Mix into a ``CustomTestCase`` subclass exposing ``self.base_url``. """ class H...
30
929
sglang
python/sglang/test/kits/json_constrained_kit.py
.py
import json from concurrent.futures import ThreadPoolExecutor import openai import requests class JSONConstrainedMixin: json_schema = json.dumps( { "type": "object", "properties": { "name": {"type": "string", "pattern": "^[\\w]+$"}, "population": {...
103
3,342
sglang
python/sglang/test/kits/basic_scheduler_stress_kit.py
.py
"""Basic scheduler / cache / streaming stress sanity kit. Probes that catch bugs which only fire under multi-request or large- prompt conditions: scheduler hangs, radix prefix-cache cross- contamination, chunked-prefill multi-chunk kernel crashes, and SSE streaming corruption. Mix into any ``CustomTestCase`` subclass...
136
5,316
sglang
python/sglang/test/kits/basic_decode_correctness_kit.py
.py
"""Basic decode correctness sanity kit. Probes that catch the model producing wrong output: weight load failure, sampling path bugs, KV / attention corruption, and cuda graph edge cases. Single-prompt coverage only -- dataset-driven accuracy gates belong to the consuming test class, not this kit. Mix into any ``Custo...
115
4,361
sglang
python/sglang/test/kits/json_mode_kit.py
.py
"""JSON mode (response_format json_object) test mixin. Host class must provide ``self.client`` (openai.Client) and ``self.model``. """ import json class JSONModeMixin: def test_json_mode_response(self): """json_object without a JSON-mentioning system prompt must still produce valid JSON.""" ...
76
2,722
sglang
python/sglang/test/kits/mmmu_vlm_kit.py
.py
import glob import json import os import shutil import subprocess import tempfile from pathlib import Path from types import SimpleNamespace from sglang.srt.utils import is_cuda, kill_process_tree from sglang.srt.utils.common import temp_set_env from sglang.test.test_utils import ( DEFAULT_TIMEOUT_FOR_SERVER_LAUNC...
474
16,824
sglang
python/sglang/test/kits/fwd_occupancy_kit.py
.py
"""Single-batch decode GPU occupancy sanity kit. Probes ``sglang:fwd_occupancy`` (a 0-100 percentage averaged over the last ``decode_log_interval`` batches; resets to NaN at window boundaries) under one long single-batch ``/generate`` request, and asserts median above a threshold. Single-batch is where CPU overhead do...
262
10,294
sglang
python/sglang/test/kits/anthropic_messages_kit.py
.py
"""Anthropic /v1/messages API test mixin. Host class must provide ``self.base_url`` (with or without a trailing /v1), ``self.api_key``, and ``self.model``. """ import json import anthropic import requests from sglang.srt.entrypoints.anthropic.protocol import AnthropicMessagesRequest from sglang.srt.entrypoints.anth...
547
20,489
sglang
python/sglang/test/kits/spec_decoding_kit.py
.py
import requests from sglang.test.send_one import BenchArgs, send_one_prompt from sglang.test.test_utils import is_in_ci, write_github_step_summary class SpecDecodingMixin: bs_1_speed_thres: float accept_length_thres: float bs_1_speed_attempts: int = 3 def test_bs_1_speed(self): args = BenchA...
33
1,174
sglang
python/sglang/test/kits/pause_generation_kit.py
.py
import time from concurrent.futures import ThreadPoolExecutor, as_completed import requests _REQUEST_TIMEOUT = 180 class PauseResumeInPlaceMixin: """Test pause/resume with in_place mode. Sends concurrent requests, pauses mid-generation, verifies no progress during the pause window, then resumes and ver...
112
4,042
sglang
python/sglang/test/kits/lm_eval_kit.py
.py
""" This module provides a mixin class for running lm-eval harness evaluations against SGLang servers """ import os from contextlib import contextmanager from pathlib import Path from typing import Any import numpy as np import requests import yaml from sglang.test.test_utils import dump_metric @contextmanager def...
121
3,821
sglang
python/sglang/test/kits/reasoning_kit.py
.py
import json import openai import requests from sglang.srt.parser.reasoning_parser import ReasoningParser from sglang.srt.utils.hf_transformers_utils import get_tokenizer class ReasoningTokenUsageMixin: """Mixin for reasoning_tokens usage tests. Required attributes on the test class: model: str ...
198
7,923
sglang
python/sglang/test/kits/ebnf_constrained_kit.py
.py
import json import requests class EBNFConstrainedMixin: ebnf_grammar = 'root ::= "test"' # Default grammar def _run_decode_ebnf( self, ebnf, expected_patterns, prompt, return_logprob=False, top_logprobs_num=0, n=1, ): response = requests....
226
8,387
sglang
python/sglang/test/kits/prefix_cache_branching_kit.py
.py
import requests class PrefixCacheBranchingMixin: cache_chunk_size: int @classmethod def send_request_helper(cls, text: str): response = requests.post( cls.base_url + "/generate", json={ "text": text, "sampling_params": { ...
51
1,773
sglang
python/sglang/test/kits/streaming_session_kit.py
.py
"""Streaming-session test method mixins. Pair these with `StreamingSessionServerBase` (from sglang.test.server_fixtures.streaming_session_fixture) to assemble a concrete test class. Per the sglang fixture/kit split: the fixture only launches the server; the kit owns the `test_*` methods. - `StreamingSessionKitMixin`:...
443
17,076
sglang
python/sglang/test/kits/attention_unittest/attention_methods/kda_attention.py
.py
from dataclasses import dataclass from types import SimpleNamespace import torch from torch import nn from sglang.srt.configs.mamba_utils import ( KimiLinearCacheParams, KimiLinearStateShape, Mamba2StateDType, ) from sglang.srt.configs.model_config import AttentionArch from sglang.srt.distributed.parallel...
1,168
39,833
sglang
python/sglang/test/kits/attention_unittest/attention_methods/gdn_attention.py
.py
from dataclasses import dataclass from types import SimpleNamespace import torch from torch import nn from sglang.srt.configs.mamba_utils import ( Mamba2CacheParams, Mamba2StateDType, Mamba2StateShape, ) from sglang.srt.configs.model_config import AttentionArch from sglang.srt.distributed.parallel_state_w...
1,126
36,921
sglang
python/sglang/test/kits/attention_unittest/attention_methods/mamba2_attention.py
.py
from dataclasses import dataclass from types import SimpleNamespace import torch import torch.nn.functional as F from torch import nn # Patch TP world size / rank before importing modules that read them at __init__. import sglang.srt.layers.linear as _linear_mod from sglang.srt.runtime_context import get_context, get...
1,089
39,202
sglang
python/sglang/test/kits/attention_unittest/attention_methods/dense_attention.py
.py
from dataclasses import dataclass from types import SimpleNamespace from typing import Any, List import torch import torch.nn.functional as F from torch import nn from sglang.srt.configs.model_config import AttentionArch from sglang.srt.distributed.parallel_state_wrapper import ParallelState from sglang.srt.layers.at...
1,294
43,844
sglang
python/sglang/test/kits/attention_unittest/attention_methods/dual_chunk_attention.py
.py
from dataclasses import dataclass from types import SimpleNamespace import torch from torch import nn from sglang.srt.distributed.parallel_state_wrapper import ParallelState from sglang.srt.layers.attention import ( dual_chunk_flashattention_backend as _dual_chunk_backend, ) from sglang.srt.layers.attention.atten...
1,605
55,511
sglang
python/sglang/test/kits/attention_unittest/attention_methods/mla_attention.py
.py
from dataclasses import dataclass from types import SimpleNamespace from typing import Any, List import torch import torch.nn.functional as F from torch import nn from sglang.srt.configs.model_config import AttentionArch from sglang.srt.distributed.parallel_state_wrapper import ParallelState from sglang.srt.layers.at...
1,216
39,492
sglang
python/sglang/test/kits/attention_unittest/attention_methods/dsa_attention.py
.py
from dataclasses import dataclass from types import SimpleNamespace from typing import Any import torch from torch import nn from sglang.srt.distributed.parallel_state_wrapper import ParallelState from sglang.srt.layers.attention.attention_registry import ATTENTION_BACKENDS from sglang.srt.layers.radix_attention impo...
1,848
65,954
sglang
python/sglang/test/kits/attention_unittest/attention_methods/lightning_attention.py
.py
from dataclasses import dataclass from types import SimpleNamespace import torch from torch import nn from sglang.srt.configs.mamba_utils import ( Mamba2CacheParams, Mamba2StateDType, Mamba2StateShape, ) from sglang.srt.configs.model_config import AttentionArch from sglang.srt.distributed.parallel_state_w...
1,073
36,477
sglang
python/sglang/test/kits/attention_unittest/attention_methods/dsv4_attention.py
.py
"""DSV4 attention fixture (SWA-only slice, compress_ratio=0). This is a narrow first slice covering the SWA path of `DeepseekV4AttnBackend`. The C4 (4x) and C128 (128x) compressor + indexer paths and speculative modes are explicit follow-ups. The reference is pure PyTorch: it unpacks the FP8-nope + BF16-rope cache wr...
1,687
67,340
sglang
python/sglang/test/kits/attention_unittest/runner_modes/split_op_runner.py
.py
from dataclasses import dataclass, replace from typing import Any, Callable import torch from sglang.srt.model_executor.forward_context import ForwardContext, forward_context from sglang.srt.model_executor.runner_backend_utils.breakable_cuda_graph.context import ( enable_breakable_cuda_graph, ) from sglang.srt.mo...
600
19,442
sglang
python/sglang/test/kits/attention_unittest/runner_modes/cuda_graph_decode_runner.py
.py
from dataclasses import dataclass from typing import Any, Callable import torch from sglang.srt.model_executor.forward_context import ForwardContext, forward_context from ..attention_methods.dense_attention import DEFAULT_DEVICE as DENSE_DEFAULT_DEVICE from ..attention_methods.dense_attention import DEFAULT_DTYPE as...
949
33,559
sglang
python/sglang/test/kits/attention_unittest/runner_modes/metadata_invariants.py
.py
"""Backend-agnostic assertions on `forward_metadata` after CG replay init. Catches corruption that the output-equality assertion misses — e.g., negative per-request lengths or non-monotonic indptr that happen to leave real-row output correct while corrupting padded-row scratch state. Usage from a CG runner kit: ...
104
3,598
sglang
python/sglang/test/kits/attention_unittest/runner_modes/speculative_draft_extend_runner.py
.py
# --- Imports added for the EAGLEDraftExtendCudaGraphRunner production # --- runner integration that lives below. from dataclasses import dataclass from types import SimpleNamespace from typing import Any, Callable from unittest.mock import patch import torch from torch import nn from sglang.srt.layers.logits_process...
1,008
34,281
sglang
python/sglang/test/kits/attention_unittest/runner_modes/speculative_cuda_graph_runner.py
.py
from dataclasses import dataclass from typing import Any, Callable, Literal, Optional import torch from sglang.srt.model_executor.forward_context import ForwardContext, forward_context from .cuda_graph_decode_runner import ( _init_cuda_graph_capture_metadata, _init_cuda_graph_replay_metadata, ) # How padded...
344
12,616
sglang
python/sglang/test/kits/attention_unittest/runner_modes/speculative_target_verify_runner.py
.py
from dataclasses import replace from typing import Literal import torch from sglang.srt.model_executor.forward_batch_info import CaptureHiddenMode from sglang.srt.model_executor.forward_context import ForwardContext, forward_context from sglang.srt.speculative.dflash_info import DFlashVerifyInput from sglang.srt.spec...
1,395
45,655
sglang
python/sglang/test/kits/attention_unittest/runner_modes/speculative_draft_runner.py
.py
from contextlib import contextmanager from dataclasses import dataclass from types import MethodType, SimpleNamespace from typing import Any, Callable from unittest.mock import patch import torch from torch import nn from sglang.srt.layers.logits_processor import LogitsProcessorOutput from sglang.srt.model_executor.c...
1,874
65,136
sglang
python/sglang/test/ci/ci_stress_utils.py
.py
"""Utilities for running stress tests with bench_serving.""" import subprocess from typing import List, Optional from sglang.srt.utils import kill_process_tree from sglang.test.test_utils import ( DEFAULT_TIMEOUT_FOR_SERVER_LAUNCH, is_in_ci, popen_launch_server, write_github_step_summary, ) class St...
225
7,457
sglang
python/sglang/test/ci/ci_register.py
.py
import ast import warnings from dataclasses import dataclass from enum import Enum, auto from typing import List, Optional, Tuple __all__ = [ "HWBackend", "CIRegistry", "collect_tests", "auto_partition", "register_cpu_ci", "register_cuda_ci", "register_amd_ci", "register_musa_ci", "...
421
13,893
sglang
python/sglang/test/ci/ci_utils.py
.py
import json import logging import os import re import subprocess import threading import time from dataclasses import dataclass from typing import Callable, Dict, List, Optional, Union from sglang.srt.debug_utils import cuda_coredump from sglang.srt.utils.common import kill_process_tree from sglang.test.ci.ci_register...
390
13,981
sglang
python/sglang/test/kv_canary/e2e_base.py
.py
from __future__ import annotations import io import os import string import time from typing import ClassVar, Literal, Optional from sglang.srt.kv_canary.config import CanaryMode from sglang.srt.kv_canary.runner.swa_divergence import SwaDivergenceLog from sglang.test.kv_canary.mode_config import _MODE_CONFIGS, _ModeC...
236
9,884
sglang
python/sglang/test/kv_canary/utils.py
.py
from __future__ import annotations from concurrent.futures import ThreadPoolExecutor import requests from sglang.srt.kv_canary.config import CanaryMode from sglang.test.kv_canary.mode_config import _ModeConfig def build_canary_server_args( *, kv_canary_mode: CanaryMode, mode_cfg: _ModeConfig, extra...
58
1,626
sglang
python/sglang/test/kv_canary/violation_log_utils.py
.py
from __future__ import annotations import fnmatch import re _VIOLATION_LINE_RE = re.compile( r"kv_canary violation: launch_tag=(\S+) fail_reason=(\S+)" ) def find_violation_in_log( log_text: str, *, launch_tag_patterns: tuple[str, ...], fail_reason: str, ) -> bool: for match in _VIOLATION_LI...
32
836
sglang
python/sglang/test/kv_canary/pp_fixture.py
.py
from __future__ import annotations from typing import ClassVar from sglang.test.kv_canary.consts import SWA_POOL_SERVER_ARGS from sglang.test.kv_canary.e2e_base import CanaryE2EBase PP_SIZE: int = 2 class CanaryPPFixture(CanaryE2EBase): model_mode: ClassVar[str] = "swa" workload_n_batches: ClassVar[int] =...
26
605