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
test/registered/unit/spec/test_adaptive_spec_params.py
.py
import json import tempfile import unittest from sglang.srt.speculative.adaptive_spec_params import ( AdaptiveSpeculativeParams, AdaptiveStepSlot, resolve_candidate_steps_from_config, ) from sglang.test.ci.ci_register import register_cpu_ci, register_xpu_ci register_cpu_ci(est_time=6, suite="base-a-test-c...
425
15,948
sglang
test/registered/unit/spec/test_spec_registry.py
.py
"""Unit tests for the speculative algorithm plugin registry.""" import unittest from types import SimpleNamespace from unittest.mock import MagicMock from sglang.srt.arg_groups.speculative_hook import handle_speculative_decoding from sglang.srt.speculative.spec_info import SpeculativeAlgorithm from sglang.srt.specula...
351
13,486
sglang
test/registered/unit/spec/test_ngram_mamba_verify_update.py
.py
import unittest from unittest.mock import MagicMock, patch import torch import sglang.srt from sglang.test.ci.ci_register import register_cpu_ci from sglang.test.test_utils import CustomTestCase register_cpu_ci(est_time=5, suite="base-a-test-cpu") class TestNgramLastCorrectStepIndices(CustomTestCase): def _com...
427
15,701
sglang
test/registered/unit/spec/test_eagle_seeded_coins.py
.py
"""Unit tests for the EAGLE verify coins (_verify_coins / _seeded_verify_coins). Locks the deterministic-coin contract behind seeded speculative sampling: identical (seed, seq_lens) inputs produce bitwise-identical coins, distinct seeds diverge, the column split (first draft_token_num columns -> rejection coins, last ...
164
6,650
sglang
test/registered/unit/spec/test_spec_utils_traverse_tree.py
.py
"""Regression test for spec_utils.traverse_tree calling xgrammar with tensors. xgrammar 0.2.0 tightened its FFI binding and rejects 0-d tensors where Python ints are expected. The dfs in traverse_tree recurses with `retrieve_next_token[curr]` and reads `draft_tokens[curr]`, both of which return 0-d tensors and must be...
112
4,753
sglang
test/registered/unit/spec/test_draft_construction_isolation.py
.py
"""A draft's construction decides for itself and leaves the process state alone. The shared-experts-fusion decision is per checkpoint: each MoE model's gate writes the ACTIVE moe flag (both ways) before its own layers build and read it, and ``draft_model_build_scope`` — which brackets every draft construction — record...
207
8,399
sglang
test/registered/unit/spec/test_dflash_extra_buffer_lazy.py
.py
"""Unit tests for DFLASH + mamba-radix-cache-strategy extra_buffer_lazy: server_args validation accepts the pairing, and DFlashVerifyInput.prepare_for_verify runs prepare_mamba_track_for_verify (the hook eagle/ngram/dspark already run) before ForwardBatch.init_new snapshots the track fields.""" import unittest from ty...
135
4,843
sglang
test/registered/unit/spec/test_eagle_worker_v2_topk1_fastpath.py
.py
"""Equivalence tests for the EagleDraftWorker topk=1 chain fast path. For topk=1 the draft tree degenerates to a chain, so `draft_forward` skips the cat/topk/sort/gather of the slow path and returns pre-allocated constants. These tests check that the pre-allocated `parent_list` / `top_scores_index` match the slow path...
361
15,133
sglang
test/registered/unit/spec/test_resolve_swa_kv_pool.py
.py
"""Unit tests for attention-backend SWA KV pool resolution.""" import unittest from unittest.mock import MagicMock from sglang.srt.layers.attention.flashinfer_backend import FlashInferAttnBackend from sglang.srt.layers.attention.trtllm_mha_backend import TRTLLMHAAttnBackend from sglang.srt.mem_cache.base_swa_memory_p...
99
3,908
sglang
test/registered/unit/spec/test_spec_cpu_overlap_constraint.py
.py
import unittest from types import SimpleNamespace from sglang.srt.arg_groups.speculative_hook import handle_speculative_decoding from sglang.srt.server_args import ServerArgs from sglang.test.ci.ci_register import register_cpu_ci from sglang.test.test_utils import CustomTestCase register_cpu_ci(est_time=20, suite="ba...
76
2,751
sglang
test/registered/unit/spec/test_ngram_corpus.py
.py
import json import os import tempfile import unittest import uuid import numpy as np from sglang.srt.speculative.cpp_ngram.external_corpus import ( iter_external_corpus_chunks, ) from sglang.srt.speculative.cpp_ngram.ngram_corpus import NgramCorpus from sglang.test.ci.ci_register import register_cpu_ci from sglan...
980
34,060
sglang
test/registered/unit/spec/test_fast_prefill_plan.py
.py
"""Equivalence tests for the sync-free `fast_prefill_plan`. `fast_prefill_plan` replaces FlashInfer's `BatchPrefillWithPagedKVCacheWrapper.plan` in the EAGLE draft-extend CUDA graph: upstream plan() does blocking `.to("cpu")` copies to build host scheduling metadata, while fast_prefill_plan takes that metadata as host...
188
7,006
sglang
test/registered/unit/spec/test_draft_per_runner_config.py
.py
"""What differs for a draft worker is resolved per runner, not on a config copy. The v2 spec workers used to write the draft's `context_length` onto the `ServerArgs` they share with the target, and the scheduler the draft's `load_format`; then both moved to a published copy of the config. Neither is a process-wide con...
215
8,888
sglang
test/registered/unit/tools/test_get_version_tag.py
.py
import importlib.util import sys import unittest from pathlib import Path from unittest.mock import patch REPO_ROOT = Path(__file__).resolve().parents[4] CI_REGISTER_PATH = REPO_ROOT / "python" / "sglang" / "test" / "ci" / "ci_register.py" VERSION_HELPER_PATH = REPO_ROOT / "python" / "tools" / "get_version_tag.py" PYP...
92
3,320
sglang
test/registered/unit/tools/test_docker_build_metadata_args.py
.py
import importlib.util import json import subprocess import unittest from pathlib import Path REPO_ROOT = Path(__file__).resolve().parents[4] CI_REGISTER_PATH = REPO_ROOT / "python" / "sglang" / "test" / "ci" / "ci_register.py" HELPER_PATH = REPO_ROOT / "scripts" / "ci" / "utils" / "docker_build_metadata_args.py" DOCKE...
203
7,166
sglang
test/registered/unit/observability/test_req_time_stats.py
.py
"""Unit tests for ReqTimeStats IPC serialization. ReqTimeStatsBase.__setstate__ rebases perf_counter fields onto the receiving process's clock anchor. Rebasing a field that was never stamped (0.0) turns the sentinel into a tiny epsilon (sender_diff - receiver_diff), which defeats == 0.0 / > 0.0 "was this stamped?" che...
45
1,736
sglang
test/registered/unit/observability/test_func_timer.py
.py
"""Unit tests for func_timer.py — no server, no model loading.""" from sglang.test.ci.ci_register import register_cpu_ci register_cpu_ci(est_time=6, suite="base-a-test-cpu") register_cpu_ci(est_time=7, suite="base-c-test-cpu") import asyncio import unittest from unittest.mock import MagicMock, patch import sglang.s...
84
2,688
sglang
test/registered/unit/observability/test_request_metrics_exporter.py
.py
"""Unit tests for request_metrics_exporter.py — no server, no model loading.""" from dataclasses import dataclass from typing import Any, Dict, List, Optional from sglang.test.ci.ci_register import register_cpu_ci register_cpu_ci(est_time=6, suite="base-a-test-cpu") register_cpu_ci(est_time=7, suite="base-c-test-cpu...
361
12,581
sglang
test/registered/unit/observability/test_ray_wrappers.py
.py
"""Unit tests for :mod:`sglang.srt.observability.ray_wrappers`. The wrapper module is designed to import cleanly even without Ray installed; we inject a fake ``ray``/``ray.util.metrics``/``ray.serve`` triple into ``sys.modules`` before importing the module so the tests run on the CPU CI runners that don't ship Ray. Th...
282
11,070
sglang
test/registered/unit/observability/test_stat_loggers_di.py
.py
"""Pure-CPU unit tests for ``ServerArgs.stat_loggers`` DI plumbing. These tests cover the small, in-process pieces of the ``stat_loggers`` dependency injection feature: * The four DI hook class attributes (``_counter_cls``/``_gauge_cls``/ ``_histogram_cls``/``_summary_cls``) default to ``None`` on every collector...
145
5,549
sglang
test/registered/unit/observability/test_forward_pass_metrics.py
.py
from sglang.srt.runtime_context import get_context, get_observability from sglang.test.ci.ci_register import register_cpu_ci register_cpu_ci(est_time=5, suite="base-a-test-cpu") import math import types import unittest from unittest.mock import patch from sglang.srt.disaggregation.utils import DisaggregationMode fro...
404
15,363
sglang
test/registered/unit/observability/test_startup_func_log_and_timer.py
.py
"""Unit tests for startup_func_log_and_timer.py — no server, no model loading.""" from sglang.test.ci.ci_register import register_cpu_ci register_cpu_ci(est_time=6, suite="base-a-test-cpu") register_cpu_ci(est_time=7, suite="base-c-test-cpu") import unittest from unittest.mock import MagicMock, patch import sglang....
142
4,878
sglang
test/registered/unit/observability/test_metrics_utils.py
.py
import unittest from sglang.srt.observability.utils import ( generate_buckets, two_sides_exponential_buckets, ) from sglang.test.ci.ci_register import register_cpu_ci register_cpu_ci(est_time=6, suite="base-a-test-cpu") register_cpu_ci(est_time=7, suite="base-c-test-cpu") class TestMetricsUtils(unittest.Tes...
134
5,082
sglang
test/registered/unit/observability/test_label_transform.py
.py
"""Unit tests for label_transform — no server, no model loading.""" from sglang.test.ci.ci_register import register_cpu_ci register_cpu_ci(est_time=6, suite="base-a-test-cpu") register_cpu_ci(est_time=7, suite="base-c-test-cpu") import unittest from sglang.srt.observability.label_transform import ( UNKNOWN_PRIO...
41
1,315
sglang
test/registered/unit/observability/test_cpu_monitor.py
.py
import threading import time import unittest from collections import namedtuple from unittest.mock import MagicMock, patch from sglang.test.ci.ci_register import register_cpu_ci register_cpu_ci(est_time=60, suite="base-a-test-cpu", nightly=True) register_cpu_ci(est_time=7, suite="base-c-test-cpu") class TestCpuMoni...
102
3,731
sglang
test/registered/unit/observability/test_trace.py
.py
"""Unit tests for trace.py — no server, no model loading.""" import os from sglang.test.ci.ci_register import register_cpu_ci register_cpu_ci(est_time=6, suite="base-a-test-cpu") import threading import unittest from unittest.mock import patch import sglang.srt.observability.trace as mod from sglang.srt.observabil...
568
20,882
sglang
test/registered/unit/function_call/test_function_call_parser.py
.py
import json import unittest import warnings from sglang.srt.entrypoints.openai.protocol import ( Function, Tool, ToolChoice, ToolChoiceFuncName, ) from sglang.srt.function_call.base_format_detector import BaseFormatDetector from sglang.srt.function_call.core_types import StreamingParseResult from sglan...
5,185
223,460
sglang
test/registered/unit/function_call/test_hermes_detector.py
.py
"""Unit tests for HermesDetector — no server, no model loading.""" import json from sglang.srt.entrypoints.openai.protocol import Function, Tool from sglang.srt.function_call.hermes_detector import HermesDetector from sglang.test.ci.ci_register import register_cpu_ci from sglang.test.test_utils import CustomTestCase ...
180
7,187
sglang
test/registered/unit/function_call/test_unknown_tool_name.py
.py
import json import logging import pytest from sglang.srt.entrypoints.openai.protocol import Function, Tool from sglang.srt.environ import envs from sglang.srt.function_call.base_format_detector import BaseFormatDetector from sglang.srt.function_call.core_types import StreamingParseResult from sglang.test.ci.ci_regist...
85
2,813
sglang
test/registered/unit/function_call/test_hunyuan_detector.py
.py
"""Unit tests for HunyuanDetector - no server, no model loading.""" import json import unittest from sglang.srt.entrypoints.openai.protocol import Function, Tool from sglang.srt.function_call.hunyuan_detector import HunyuanDetector from sglang.test.ci.ci_register import register_cpu_ci from sglang.test.test_utils imp...
663
26,289
sglang
test/registered/unit/function_call/test_parallel_tool_calls.py
.py
import json """ Test case for parallel tool call parsing. This test verifies that the parser correctly handles parallel tool calls with array parameters in JSON array format. Scenario: - Model outputs two parallel tool calls in JSON array format - Both tools have array parameters (e.g., "title": ["7.8.9 H-9 ..."]) -...
140
5,013
sglang
test/registered/unit/function_call/test_minimax_m3_detector.py
.py
import json import unittest from sglang.srt.entrypoints.openai.protocol import Function, Tool from sglang.srt.function_call.minimax_m3 import MINIMAX_NS_TOKEN, MinimaxM3Detector from sglang.test.ci.ci_register import register_cpu_ci from sglang.test.test_utils import CustomTestCase register_cpu_ci(est_time=7, suite="...
540
17,533
sglang
test/registered/unit/function_call/test_kimik3_structural_tag.py
.py
import json import sys import pytest import xgrammar as xgr from xgrammar.testing import _is_grammar_accept_string from sglang.srt.entrypoints.openai.protocol import ( ChatCompletionRequest, Function, Tool, ToolChoice, ToolChoiceFuncName, ) from sglang.srt.environ import ToolStrictLevel, envs from...
844
25,835
sglang
test/registered/unit/function_call/test_json_schema_constraint.py
.py
""" Tests for JSON schema constraint functionality used by JsonArrayParser """ import unittest import jsonschema from sglang.srt.entrypoints.openai.protocol import ( Function, Tool, ToolChoice, ToolChoiceFuncName, ) from sglang.srt.function_call.utils import ( _get_tool_schema_defs, get_json_...
628
23,202
sglang
test/registered/unit/function_call/test_minicpm5_detector.py
.py
import json import pytest from sglang.srt.entrypoints.openai.protocol import Function, Tool from sglang.srt.function_call.minicpm5_detector import ( MiniCPM5Detector, ) from sglang.test.ci.ci_register import register_cpu_ci register_cpu_ci(1.0, "base-a-test-cpu") def make_tools_weather(): return [ ...
290
8,606
sglang
test/registered/unit/function_call/test_muse_glimmer_detector.py
.py
"""Unit tests for the Muse Glimmer ATEM tool-call detector — no server, no model loading. The expectations here are pinned to the checkpoint's own ``response_template`` (``MUSE_GLIMMER_RESPONSE_SCHEMA`` in ``tokenizer_config.json``) and to the vendor's reference parser, with particular attention to channel scoping: an...
433
18,952
sglang
test/registered/unit/function_call/test_llama32_detector.py
.py
"""Unit tests for Llama32Detector — no server, no model loading.""" import json from sglang.srt.entrypoints.openai.protocol import Function, Tool from sglang.srt.function_call.llama32_detector import Llama32Detector from sglang.test.ci.ci_register import register_cpu_ci from sglang.test.test_utils import CustomTestCa...
193
7,802
sglang
test/registered/unit/function_call/test_poolside_v1_detector.py
.py
"""Unit tests for PoolsideV1Detector — no server, no model loading.""" import json from sglang.srt.entrypoints.openai.protocol import Function, Tool from sglang.srt.function_call.function_call_parser import FunctionCallParser from sglang.srt.function_call.poolside_v1_detector import PoolsideV1Detector from sglang.tes...
484
21,518
sglang
test/registered/unit/function_call/test_deepseekv4_detector.py
.py
"""Unit tests for DeepSeekV4Detector DSML streaming — no server, no model loading.""" from unittest.mock import patch from sglang.srt.entrypoints.openai.protocol import Function, Tool from sglang.srt.function_call.deepseekv4_detector import DeepSeekV4Detector from sglang.test.ci.ci_register import register_cpu_ci fro...
130
4,867
sglang
test/registered/unit/function_call/test_mistral_detector.py
.py
"""Unit tests for MistralDetector — no server, no model loading.""" import json from sglang.srt.entrypoints.openai.protocol import Function, Tool from sglang.srt.function_call.mistral_detector import MistralDetector from sglang.test.ci.ci_register import register_cpu_ci from sglang.test.test_utils import CustomTestCa...
225
8,900
sglang
test/registered/unit/function_call/test_normalize_json_schema_types.py
.py
"""Unit tests for tool-parameter schema alias normalization.""" import json import unittest from jsonschema import Draft202012Validator, SchemaError from sglang.srt.function_call.utils import normalize_json_schema_types from sglang.test.ci.ci_register import register_cpu_ci from sglang.test.test_utils import CustomT...
410
15,313
sglang
test/registered/unit/hardware_backend/mlx/test_muse_glimmer_mlx_model.py
.py
"""Unit tests for the Muse Glimmer MLX model file's load path — no weights, no server. End-to-end coverage needs the private packaged artifact, so the checkpoint-schema logic is pinned here with tiny synthetic weights instead: 1. ``flatten_rc_config`` — RC nested-config translation, including the two convention co...
279
11,399
sglang
test/registered/unit/hardware_backend/mlx/test_quantization.py
.py
"""Unit tests for MLX backend on-the-fly quantization. Covers: - mlx_q4 / mlx_q8 quantize fp16 weights to QuantizedLinear in-place - active-memory drops after quantization - /generate still works post-quantize - pre-quantized HF repos still load (regression guard for mlx_lm passthrough) - mlx_q4 flag on an a...
196
7,305
sglang
test/registered/unit/hardware_backend/mlx/test_mlx_quantization_override.py
.py
"""Unit tests for ``MlxQuantizationConfig.override_quantization_method``. The override is a classmethod over a dict; no mlx / Apple Silicon dependency. Runs on every CI platform and guards #25119 from regression. """ from __future__ import annotations import unittest from sglang.srt.layers.quantization.mlx import M...
107
3,920
sglang
test/registered/unit/hardware_backend/mlx/test_windowed_kv_cache.py
.py
"""Unit tests for the MLX windowed per-request attention KV cache. ``WindowedAttentionKVCache`` keeps only the trailing ``window`` tokens of a sliding-window layer. Every level is pinned against the full-history path it replaces: the cache arrays against a ``ContiguousAttentionKVCache`` trailing slice, the container ...
322
13,200
sglang
test/registered/unit/hardware_backend/mlx/test_scheduler_mixin.py
.py
"""Unit tests for the MLX overlap scheduler mixin (hardware_backend/mlx/scheduler_mixin.py). Covers: - Every MLX launch advances forward_ct and stamps forward_iter/launch_ts. - The profiler predicate runs before the async forward is enqueued, matching Scheduler.run_batch() so step-bounded profiling stops on th...
328
12,952
sglang
test/registered/unit/hardware_backend/mlx/test_sliding_window_attention.py
.py
"""Unit tests for MLX sliding-window attention support (gpt-oss style models). gpt-oss interleaves sliding-window and full-attention layers, names its softmax scale ``sm_scale``, and adds per-head attention sinks. These tests pin the three seams that make such models work on the MLX backend: 1. The attention contract...
531
22,009
sglang
test/registered/unit/hardware_backend/mlx/test_fused_swiglu.py
.py
"""Numerical equivalence and eligibility tests for the Path B fused swiglu kernel. Two groups: * Model-based equivalence (``@requires_model``): loads a small MoE model, runs the fused gate_qmv + silu + ×x_up kernel against the unfused reference (``mx.gather_qmm`` + ``nn.silu(gate) * x_up``) on both the unsor...
495
20,166
sglang
test/registered/unit/hardware_backend/mlx/test_runner_init_contract.py
.py
"""Guard the MLX initialize override against ModelRunner contract drift. MlxModelRunnerStub.initialize must stay callable exactly as ModelRunner invokes it. The check is signature-only and MLX-gated because importing the stub pulls in mlx.core. """ from __future__ import annotations import importlib.util import insp...
86
3,330
sglang
test/registered/unit/hardware_backend/mlx/test_mlx_sampling.py
.py
"""Unit tests for MLX in-graph sampling (hardware_backend/mlx/sampling.py).""" from __future__ import annotations import importlib.util import unittest from collections import Counter from sglang.test.ci.ci_register import register_cpu_ci, register_mlx_ci from sglang.test.test_utils import CustomTestCase register_c...
729
30,612
sglang
test/registered/unit/hardware_backend/mlx/test_max_running_requests.py
.py
"""Regression: MlxModelRunnerStub must honor --max-running-requests instead of hardcoding min(pool // 2, 4096). The stub previously ignored the flag, so MLX concurrency silently diverged from what the user requested (and from CUDA). On hybrid / linear-attention models the resolved concurrency must additionally be back...
328
13,902
sglang
test/registered/unit/hardware_backend/mlx/test_metal_profiler.py
.py
"""Unit tests for MLX Metal profiling patch (hardware_backend/mlx/profiler.py). Covers: - apply_metal_profiler_patches() replaces torch.profiler.profile - MLX path: MetalTorchProfiler.start/stop produces a .gputrace file - MPS path: MetalTorchProfiler wraps torch.mps.profiler.metal_capture - RuntimeError from ...
278
10,178
sglang
test/registered/unit/hardware_backend/mlx/test_mlx_pool_dtype.py
.py
"""Unit tests for MLX attention-KV pool dtype inference. The shared pool stores dequantized projection outputs, so its dtype must follow the model's compute dtype, not the packed integer dtype of QuantizedLinear weights. Storing float32 for quantized models (the old fallback) doubled pool bytes per slot for no precis...
111
3,944
sglang
test/registered/unit/hardware_backend/mlx/test_attention_patching.py
.py
"""Unit tests for MLX attention discovery and generic cache handling.""" from __future__ import annotations import importlib.util import unittest from collections import deque from types import SimpleNamespace from sglang.test.ci.ci_register import register_cpu_ci, register_mlx_ci register_cpu_ci(est_time=1, suite=...
1,545
57,143
sglang
test/registered/unit/hardware_backend/mlx/test_tp_worker_routing.py
.py
"""Unit tests for MLX extend-batch request routing in ``MlxTpModelWorker``. Regression guard for the single-token chunked-prefill continuation bug: a continuation whose final chunk is exactly one token (prompt length == k * chunked_prefill_size + 1) must be routed to the **extend** path, not the **decode** path. The ...
328
13,399
sglang
test/registered/unit/hardware_backend/mlx/test_swa_radix_pool.py
.py
"""Unit tests for sliding-window layers on the MLX radix/pool KV path. The shared ``MlxAttentionKVPool`` stores full-attention layers only, sliding-window layers keep window-bounded per-request storage, and a radix prefix hit on an SWA model recomputes the whole prefix. Scheduler bookkeeping stays in the unclamped co...
381
15,796
sglang
test/registered/unit/hardware_backend/mlx/test_mlx_remote_code_gate.py
.py
"""Unit tests for the MLX remote-code gate. mlx-lm executes ``config.json``'s ``model_file`` unconditionally at load time, so SGLang refuses such checkpoints before any checkpoint Python runs unless the server was started with ``--trust-remote-code``. The refusal tests prove non-execution with a sentinel ``model_file`...
187
6,981
sglang
test/registered/unit/hardware_backend/mlx/test_mlx_reference_correctness.py
.py
"""Reference-equivalence correctness for the MLX MoE execution path. The existing ``test/registered/models/test_qwen{2,3}_moe_mlx_correctness.py`` are black-box smoke tests: they only check that a served model emits *plausible* text ("Paris" appears, "4" appears). A subtly broken KV cache, slot allocator, or prefill-c...
272
11,455
sglang
test/registered/unit/hardware_backend/mlx/test_attn_dp_request_capacity.py
.py
"""Request-capacity accounting for pure DP and DP attention on MLX. ``max_running_requests`` is partitioned only when attention DP partitions a logical batch across multiple KV-cache owners. Pure data-parallel replicas own independent schedulers and caches, so each replica retains the full configured limit even when t...
137
4,441
sglang
test/registered/unit/hardware_backend/mlx/test_mlx_runner_pool_contract.py
.py
"""Guard the MLX stub's ``ModelRunner`` overrides against drift. The base ``ModelRunner.alloc_memory_pool`` runs ``_init_pools`` which asserts ``is_draft_worker`` (model_runner_kv_cache_mixin.py:409); the MLX stub manages its own KV cache via ``MlxAttentionKVPool`` and must short-circuit that GPU-allocation path. If ...
111
4,273
sglang
test/registered/unit/platforms/test_platform_interface.py
.py
""" Unit tests for SGLang platform abstraction layer. Tests DeviceMixin, SRTPlatform, PlatformEnum, CpuArchEnum, DeviceCapability, and the platform discovery / lazy initialization mechanism. """ from unittest.mock import MagicMock, patch import torch from sglang.srt.platforms import _load_platform_class, _resolve_p...
804
33,033
sglang
test/registered/unit/bench/test_mmmu_eval_utils.py
.py
import importlib.util import re import sys import types import unittest from pathlib import Path try: from sglang.test.ci.ci_register import register_cpu_ci from sglang.test.test_utils import CustomTestCase except ModuleNotFoundError: CustomTestCase = unittest.TestCase def register_cpu_ci(*args, **kwa...
245
7,951
sglang
test/registered/unit/bench/test_mixed_prefix_gsm8k.py
.py
import json import os import tempfile import unittest from typing import List, Tuple from sglang.test.ci.ci_register import register_cpu_ci from sglang.test.simple_eval_mixed_prefix_gsm8k import ( MixedPrefixGSM8KEval, get_one_example, ) from sglang.test.test_utils import CustomTestCase register_cpu_ci(est_ti...
180
6,491
sglang
test/registered/unit/bench/test_simple_eval_gsm8k.py
.py
import json import subprocess import tempfile import unittest from pathlib import Path from types import SimpleNamespace from unittest.mock import patch from sglang.test.ci.ci_register import register_cpu_ci from sglang.test.run_eval import _run_sgl_eval from sglang.test.test_utils import CustomTestCase register_cpu_...
223
8,446
sglang
test/registered/unit/eplb/test_balanced_packing.py
.py
"""Unit tests for balanced_packing — no server, no model loading.""" from sglang.test.ci.ci_register import register_cpu_ci register_cpu_ci(est_time=7, suite="base-a-test-cpu") import unittest import torch from sglang.srt.eplb.eplb_algorithms.deepseek import balanced_packing from sglang.test.test_utils import Cust...
154
6,953
sglang
test/registered/unit/eplb/test_compute_logical_to_rank_dispatch_physical_map.py
.py
"""Unit tests for compute_logical_to_rank_dispatch_physical_map — no server, no model loading.""" from sglang.test.ci.ci_register import register_cpu_ci register_cpu_ci(est_time=7, suite="base-a-test-cpu") import unittest import torch from sglang.srt.eplb.expert_location import ( _compute_logical_to_all_physic...
229
9,016
sglang
test/registered/unit/eplb/test_dispatch_dtype_preservation.py
.py
"""Unit tests for dtype preservation in topk_ids_logical_to_physical dispatch. Verifies that _topk_ids_logical_to_physical_static and _topk_ids_logical_to_physical_dynamic preserve the input topk_ids dtype even when the dispatch map uses a wider dtype (int64). This matters for backends like MORI that read expert indic...
146
6,271
sglang
test/registered/unit/eplb/test_waterfill_eplb.py
.py
"""Unit tests for Waterfill and EPLB updater compatibility.""" from sglang.test.ci.ci_register import register_cpu_ci register_cpu_ci(est_time=7, suite="base-a-test-cpu") import unittest from types import SimpleNamespace from unittest.mock import patch import torch from torch import nn from sglang.srt.layers.moe i...
141
5,319
sglang
test/registered/unit/server_args/test_mnnvl_auto_inference.py
.py
"""Unit tests for the MNNVL auto-inference gate. The TP8 best-throughput launch used to require exporting ``SGLANG_ENABLE_CUSTOM_ALL_REDUCE_V2_MULTINODE=1`` by hand. It is now capability-inferred; these cases pin the negative-branch contracts so a refactor cannot silently turn the predicate into always-true (engaging ...
90
3,877
sglang
test/registered/unit/server_args/test_resolution_is_reproducible.py
.py
"""Resolution is a pure function of the raw input plus this node's environment. The end state for the configuration tier keeps ``ServerArgs`` at the user's raw input and lets every process that publishes derive the resolved values itself (bags do not cross a process boundary — a child projects its own from the record ...
461
21,417
sglang
test/registered/unit/server_args/test_page_major_backend_allowlist.py
.py
# Copyright 2023-2026 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...
139
5,560
sglang
test/registered/unit/server_args/test_server_args.py
.py
import dataclasses import importlib import json import os import socket import tempfile import unittest from types import SimpleNamespace from unittest.mock import MagicMock, patch import sglang.srt.server_args as server_args_module from sglang.srt.arg_groups import pd_disaggregation_hook from sglang.srt.arg_groups.sp...
2,195
88,783
sglang
test/registered/unit/utils/test_field_validators.py
.py
import unittest from sglang.srt.utils.field_validators import ( validate_list_i64_1d, validate_optional_list_i64_1d_2d, ) from sglang.test.ci.ci_register import register_cpu_ci from sglang.test.test_utils import CustomTestCase register_cpu_ci(est_time=2, suite="base-a-test-cpu") class TestValidateListI64_1d...
102
3,683
sglang
test/registered/unit/utils/test_subprocess_watchdog.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...
142
4,221
sglang
test/registered/unit/utils/test_json_response.py
.py
import unittest import numpy as np import orjson from sglang.srt.utils.json_response import ( SGLangORJSONResponse, dumps_json, orjson_response, ) from sglang.test.ci.ci_register import register_cpu_ci register_cpu_ci(est_time=6, suite="base-a-test-cpu") register_cpu_ci(est_time=7, suite="base-c-test-cpu...
57
1,733
sglang
test/registered/unit/utils/test_patch_tokenizer.py
.py
import random import unittest from contextlib import contextmanager from transformers import AutoTokenizer from sglang.srt.utils.patch_tokenizer import ( _SpecialTokensCachePatcher, decode_without_hf_kwargs, unpatch_tokenizer, ) from sglang.test.ci.ci_register import register_cpu_ci register_cpu_ci(est_t...
207
7,074
sglang
test/registered/unit/utils/test_profile_merger.py
.py
""" Unit tests for the ProfileMerger implementation. Usage: python test_profile_merger.py python -m unittest test_profile_merger.py -v """ import gzip import json import os import shutil import tempfile import unittest from sglang.srt.managers.io_struct import ProfileReq, ProfileReqType from sglang.srt.utils...
339
12,561
sglang
test/registered/unit/utils/test_hf_transformers.py
.py
"""Unit tests for the sglang.srt.utils.hf_transformers subpackage. Tests cover the pure utility functions (compat patches, config helpers, context length, GGUF detection, etc.) that don't require actual model files. """ import inspect import tempfile import unittest from types import SimpleNamespace from unittest.moc...
707
26,512
sglang
test/registered/unit/utils/test_auth.py
.py
"""Unit tests for srt/utils/auth.py — no server, no model loading.""" import unittest from sglang.srt.utils.auth import ( AuthDecision, AuthLevel, auth_level, decide_request_auth, ) from sglang.test.ci.ci_register import register_cpu_ci from sglang.test.test_utils import CustomTestCase register_cpu_c...
309
10,324
sglang
test/registered/unit/utils/test_torch_npu_patch_utils.py
.py
import types import unittest from sglang.srt.utils.torch_npu_patch_utils import apply_torch_npu_patches from sglang.test.ci.ci_register import register_cpu_ci register_cpu_ci(est_time=1, suite="base-a-test-cpu") class TestTorchNpuPatchUtils(unittest.TestCase): def test_apply_torch_npu_patches_uses_targeted_api_...
42
1,369
sglang
test/registered/unit/utils/test_weight_checker.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...
769
29,602
sglang
test/registered/unit/utils/test_gauge_histogram.py
.py
from sglang.test.ci.ci_register import register_cpu_ci register_cpu_ci(est_time=6, suite="base-a-test-cpu") register_cpu_ci(est_time=7, suite="base-c-test-cpu") import unittest from sglang.srt.utils.gauge_histogram import BucketLabels class TestBucketLabels(unittest.TestCase): """Test BucketLabels with hardcod...
86
3,112
sglang
test/registered/unit/utils/test_weight_checker_comparator.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...
210
8,833
sglang
test/registered/unit/utils/test_invariants.py
.py
"""Unit tests for srt/utils/invariants.py -- CPU, no server. Covers the (bucket x level) crash matrix, the unconditional data layer, the throttled reporter, and self-registration / injection-coverage. """ import unittest from unittest import mock import torch from sglang.srt.environ import InvariantCheckLevel, envs...
156
5,811
sglang
test/registered/unit/utils/test_http_server_auth.py
.py
""" Unit tests for HTTP server admin auth. Usage: python3 -m pytest test/registered/unit/utils/test_http_server_auth.py -v """ import unittest from sglang.srt.utils.auth import AuthLevel, decide_request_auth from sglang.test.ci.ci_register import register_cpu_ci register_cpu_ci(est_time=6, suite="base-a-test-cp...
298
9,655
sglang
test/registered/unit/utils/test_hf_transformers_fastokens.py
.py
"""End-to-end verification that --tokenizer-backend=fastokens swaps the backend of the loaded tokenizer with fastokens' _TokenizerShim. """ import unittest from sglang.test.ci.ci_register import register_cpu_ci from sglang.test.test_utils import ( DEFAULT_SMALL_MODEL_NAME_FOR_TEST_QWEN, CustomTestCase, ) TOK...
65
2,060
sglang
test/registered/unit/utils/test_common.py
.py
import unittest from array import array import torch from sglang.srt.utils.common import ( flatten_arrays_to_int64_tensor, get_device_sm_nvidia_smi, get_nvidia_driver_version_str, ) from sglang.test.ci.ci_register import register_amd_ci, register_cuda_ci from sglang.test.test_utils import CustomTestCase ...
149
4,782
sglang
test/registered/unit/sampling/test_penaltylib.py
.py
"""Unit tests for srt/sampling/penaltylib/ — no server, no model loading.""" from sglang.test.ci.ci_register import register_cpu_ci register_cpu_ci(est_time=9, suite="base-a-test-cpu") register_cpu_ci(est_time=8, suite="base-c-test-cpu") import unittest from unittest.mock import MagicMock import torch from sglang....
522
20,825
sglang
test/registered/unit/sampling/test_sampling_batch_info.py
.py
"""Unit tests for srt/sampling/sampling_batch_info.py — no server, no model loading.""" from sglang.test.ci.ci_register import register_cpu_ci register_cpu_ci(est_time=9, suite="base-a-test-cpu") register_cpu_ci(est_time=8, suite="base-c-test-cpu") import unittest from types import SimpleNamespace from unittest.mock...
615
25,383
sglang
test/registered/unit/sampling/test_custom_logit_processor.py
.py
"""Unit tests for srt/sampling/custom_logit_processor.py — no server, no model loading.""" from sglang.test.ci.ci_register import register_cpu_ci register_cpu_ci(est_time=7, suite="base-a-test-cpu") register_cpu_ci(est_time=7, suite="base-c-test-cpu") import json import unittest from array import array from unittest...
472
20,266
sglang
test/registered/unit/sampling/test_sampling_params.py
.py
"""Unit tests for srt/sampling/sampling_params.py — no server, no model loading.""" from sglang.test.ci.ci_register import register_cpu_ci, register_xpu_ci register_cpu_ci(est_time=7, suite="base-a-test-cpu") register_cpu_ci(est_time=7, suite="base-c-test-cpu") register_xpu_ci(est_time=10, suite="stage-a-test-1-gpu-x...
540
21,918
sglang
test/registered/unit/constrained/test_e2e_constrained_reasoning.py
.py
""" End-to-end tests for strict reasoning + constrained decoding. Tests that the full pipeline works: - AC-5.1: Strict reasoning + JSON schema constrained generation - AC-5.2: Strict reasoning + tool call parsing (basic validation only) These tests launch a real server with a small model and verify the constrained de...
316
10,339
sglang
test/registered/unit/constrained/test_llguidance_batched_mask.py
.py
"""Bitwise parity tests for llguidance's regular-decode batched mask fill.""" import unittest from unittest.mock import MagicMock import torch from llguidance import LLTokenizer, grammar_from from sglang.srt.constrained.base_grammar_backend import GrammarRow from sglang.srt.constrained.llguidance_backend import Guid...
113
3,943
sglang
test/registered/unit/constrained/test_reasoner_grammar_backend.py
.py
import os import unittest from types import SimpleNamespace from unittest.mock import MagicMock import torch from sglang.srt.constrained.base_grammar_backend import BaseGrammarBackend from sglang.srt.constrained.reasoner_grammar_backend import ( ReasonerGrammarBackend, ReasonerGrammarObject, ) from sglang.srt...
592
22,020
sglang
test/registered/unit/constrained/test_token_filter_ops.py
.py
""" Unit tests for token filter operations (Triton and Torch paths). Verifies that both implementations produce identical bitmask output for the same inputs, ensuring parity across GPU and CPU paths. """ import unittest import torch from sglang.srt.constrained.torch_ops.token_filter_torch_ops import ( set_token...
147
4,885
sglang
test/registered/unit/constrained/test_grammar_manager.py
.py
""" Unit tests for sglang.srt.constrained.grammar_manager. Test Coverage: - GrammarManager initialization, queue management, len, clear - process_req_with_grammar: dispatch by constraint type (json, regex, ebnf, structural_tag), no-constraint requests, no-backend error, cache hits, cached invalid grammar abort - a...
834
30,776
sglang
test/registered/unit/constrained/test_utils.py
.py
""" Unit tests for sglang.srt.constrained.utils. Test Coverage: - is_legacy_structural_tag: legacy format detection, new format detection, missing fields, edge cases with assertion errors. Usage: python -m pytest test_utils.py -v """ import unittest from sglang.srt.constrained.utils import is_legacy_structura...
76
2,577
sglang
test/registered/unit/constrained/test_base_grammar_backend.py
.py
""" Unit tests for sglang.srt.constrained.base_grammar_backend. Test Coverage: - GrammarStats: default values, mutable default isolation - BaseGrammarObject: default behavior - InvalidGrammarObject: error message - BaseGrammarBackend: caching, dispatch routing, unsupported fallback, thread pool execution, cache hit/...
445
18,328
sglang
test/registered/unit/managers/test_schedule_batch_req_pool_indices.py
.py
import types import unittest from unittest.mock import MagicMock, patch import torch from sglang.test.ci.ci_register import register_cpu_ci from sglang.test.test_utils import maybe_stub_sgl_kernel maybe_stub_sgl_kernel() from sglang.srt.managers.hisparse_coordinator import HiSparseCoordinator # noqa: E402 from sgl...
96
3,960
sglang
test/registered/unit/managers/test_multi_tokenizer_mixin.py
.py
import unittest from sglang.test.ci.ci_register import register_cpu_ci from sglang.test.test_utils import maybe_stub_sgl_kernel maybe_stub_sgl_kernel() from sglang.srt.managers.io_struct import BatchStrOutput from sglang.srt.managers.multi_tokenizer_mixin import ( TokenizerWorker, _handle_output_by_index, ...
111
3,362