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 | experimental/sgl-router/tests/e2e/k8s_integration/test_lifecycle.py | .py | """Worker lifecycle integration tests.
Covers:
1. Scaling replicas up — new EndpointSlice entries are discovered.
2. Scaling replicas down — removed endpoints are deregistered.
3. Router restart — after the router pod is killed, the Deployment restarts
it and it re-lists the existing EndpointSlice entries without d... | 151 | 4,779 |
sglang | experimental/sgl-router/tests/e2e/k8s_integration/conftest.py | .py | """Pytest configuration for sgl-router K8s integration tests.
These tests require:
- A kind cluster named 'sgl-router-kind'
- The sgl-router:e2e and sgl-router-fake-worker:e2e images loaded into kind
- kubectl configured to use the kind-sgl-router-kind context
Setup: ./tests/e2e/k8s_integration/setup.sh
Teardo... | 252 | 7,261 |
sglang | experimental/sgl-router/tests/e2e/chat_completions/test_load_based_policy.py | .py | # SPDX-FileCopyrightText: Copyright (c) 2026 The SGLang Authors
# SPDX-License-Identifier: Apache-2.0
"""Real-GPU acceptance coverage for ``policy = "load_based"``."""
from __future__ import annotations
import re
import threading
import time
import httpx
import pytest
from infra.gateway import Gateway
from infra.mo... | 152 | 4,957 |
sglang | experimental/sgl-router/tests/e2e/chat_completions/test_validation.py | .py | """Basic chat-completions correctness — ported from SMG's
``e2e_test/chat_completions/test_validation.py``, narrowed to the
subset that exercises sgl-router (not SMG's per-message validators).
The shape:
- single-worker regular-mode router
- non-streaming + streaming chat completion
- assistant message non-empty... | 99 | 3,580 |
sglang | experimental/sgl-router/tests/e2e/chat_completions/test_two_router_convergence.py | .py | # SPDX-FileCopyrightText: Copyright (c) 2026 The SGLang Authors
# SPDX-License-Identifier: Apache-2.0
"""Content-based cross-router routing test for cache-aware-zmq.
Two routers + two SGLang workers + one shared model. Each router runs an
independent ``cache_aware_zmq`` policy whose ``KvEventIndex`` subscribes
to **b... | 259 | 10,939 |
sglang | sgl-model-gateway/bindings/python/setup.py | .py | import os
import warnings
from setuptools import setup
with_rust = os.environ.get("SGLANG_ROUTER_BUILD_WITH_RUST", None)
with_rust = with_rust is None or (not with_rust.lower() in ["0", "false", "no"])
rust_extensions = []
if with_rust:
from setuptools_rust import Binding, RustExtension
rust_extensions.appe... | 29 | 651 |
sglang | sgl-model-gateway/bindings/python/tests/test_arg_parser.py | .py | """
Unit tests for argument parsing functionality in sglang_router.
These tests focus on testing the argument parsing logic in isolation,
without starting actual router instances.
"""
from types import SimpleNamespace
import pytest
from sglang_router.launch_router import RouterArgs, parse_router_args
from sglang_rou... | 638 | 23,960 |
sglang | sgl-model-gateway/bindings/python/tests/test_pyo3_binding.py | .py | """
Tests that exercise the PyO3 boundary directly (no mocking of `_Router`).
These guard against drift between the Python `RouterArgs` dataclass, the
`Router.from_args` mapping, and the Rust `Router::new` signature in lib.rs.
The tests construct `_Router` without dispatching to remote workers, so they
run quickly and... | 727 | 26,429 |
sglang | sgl-model-gateway/bindings/python/tests/test_validation.py | .py | """
Unit tests for validation logic in sglang_router.
These tests focus on testing the validation logic in isolation,
including parameter validation, URL validation, and configuration validation.
"""
from unittest.mock import MagicMock, patch
import pytest
from sglang_router.launch_router import RouterArgs, launch_r... | 510 | 19,265 |
sglang | sgl-model-gateway/bindings/python/tests/test_router_config.py | .py | """
Unit tests for router configuration validation and setup.
These tests focus on testing the router configuration logic in isolation,
including validation of configuration parameters and their interactions.
"""
from unittest.mock import MagicMock, patch
import pytest
from sglang_router.launch_router import RouterA... | 424 | 16,350 |
sglang | sgl-model-gateway/bindings/python/tests/test_startup_sequence.py | .py | """
Unit tests for startup sequence logic in sglang_router.
These tests focus on testing the startup sequence logic in isolation,
including router initialization, configuration validation, and startup flow.
"""
import logging
from unittest.mock import MagicMock, patch
import pytest
from sglang_router.launch_router i... | 1,062 | 41,973 |
sglang | sgl-model-gateway/bindings/python/tests/conftest.py | .py | """
Pytest configuration for sglang_router Python binding tests.
These are unit tests that run without GPU resources or external dependencies.
"""
import pytest
def pytest_configure(config):
"""Configure pytest markers."""
config.addinivalue_line(
"markers", "unit: mark test as a unit test (no GPU r... | 15 | 336 |
sglang | sgl-model-gateway/bindings/python/src/sglang_router/mini_lb.py | .py | """
Minimal HTTP load balancer for prefill and decode servers for testing.
"""
import asyncio
import ipaddress
import logging
import random
import urllib
import warnings
from http import HTTPStatus
from itertools import chain
from typing import Optional
import aiohttp
import orjson
import uvicorn
from fastapi import ... | 463 | 16,640 |
sglang | sgl-model-gateway/bindings/python/src/sglang_router/launch_server.py | .py | import argparse
import asyncio
import copy
import logging
import multiprocessing as mp
import os
import random
import signal
import sys
import time
from typing import List
import requests
from setproctitle import setproctitle
from sglang_router.launch_router import RouterArgs, launch_router
from sglang.srt.server_arg... | 214 | 6,575 |
sglang | sgl-model-gateway/bindings/python/src/sglang_router/router_args.py | .py | import argparse
import dataclasses
import logging
import os
from typing import Dict, List, Optional
try:
from sglang_router.sglang_router_rs import get_available_tool_call_parsers
except ModuleNotFoundError:
logging.warning(
"sglang_router_rs is not available, get_available_tool_call_parsers will retur... | 1,157 | 46,234 |
sglang | sgl-model-gateway/bindings/python/src/sglang_router/__main__.py | .py | """
Allow running the CLI via: python -m sglang_router
"""
from sglang_router.cli import main
if __name__ == "__main__":
main()
| 9 | 134 |
sglang | sgl-model-gateway/bindings/python/src/sglang_router/__init__.py | .py | from sglang_router.version import __version__
__all__ = ["__version__"]
| 4 | 73 |
sglang | sgl-model-gateway/bindings/python/src/sglang_router/router.py | .py | import logging
from typing import Optional
from sglang_router.router_args import RouterArgs
logger = logging.getLogger(__name__)
from sglang_router.sglang_router_rs import (
BackendType,
HistoryBackendType,
PolicyType,
PyApiKeyEntry,
PyControlPlaneAuthConfig,
PyJwtConfig,
PyOracleConfig,
... | 342 | 15,834 |
sglang | sgl-model-gateway/bindings/python/src/sglang_router/launch_router.py | .py | import argparse
import logging
import sys
from typing import List, Optional
import setproctitle
from sglang_router.mini_lb import MiniLoadBalancer
from sglang_router.router_args import RouterArgs
logger = logging.getLogger("router")
try:
from sglang_router.router import Router
except ImportError:
Router = No... | 110 | 3,616 |
sglang | sgl-model-gateway/bindings/python/src/sglang_router/cli.py | .py | #!/usr/bin/env python3
"""
SGLang Model Gateway CLI
Provides convenient command-line interface for launching the router and server.
Usage:
smg launch [args] # Launch router only
smg server [args] # Launch router + server
smg --help # Show help
"""
import argparse
import ... | 108 | 3,338 |
sglang | sgl-model-gateway/scripts/generate_vision_golden.py | .py | #!/usr/bin/env python3
"""Generate golden outputs for vision processor testing.
This script generates reference outputs from HuggingFace transformers
that are used to verify the Rust image preprocessors produce identical results.
Usage:
# Generate all golden outputs
python scripts/generate_vision_golden.py
... | 695 | 23,273 |
sglang | sgl-model-gateway/scripts/run_benchmarks.py | .py | #!/usr/bin/env python3
"""
SGLang Router Benchmark Runner
A Python script to run Rust benchmarks with various options and modes.
Replaces the shell script for better maintainability and integration.
"""
import argparse
import os
import subprocess
import sys
import time
from pathlib import Path
from typing import Dict... | 251 | 8,626 |
sglang | sgl-model-gateway/e2e_test/conftest.py | .py | """Pytest configuration for E2E tests.
Tests run serially under plain pytest. ModelPool / GPUAllocator stay
thread-safe so re-introducing parallelism (e.g. via pytest-xdist) is
still a tractable option; pytest-parallel was previously used but its
thread dispatch leaked fixture references and caused model_pool
deadlock... | 226 | 7,406 |
sglang | sgl-model-gateway/e2e_test/embeddings/test_correctness.py | .py | """Embedding correctness tests.
Tests that embeddings from the router match HuggingFace reference embeddings.
Validates numerical correctness including tokenization and inference.
Source: Migrated from e2e_grpc/basic/test_embedding_correctness.py
Usage:
pytest e2e_test/embeddings/test_correctness.py -v
pytes... | 281 | 11,431 |
sglang | sgl-model-gateway/e2e_test/embeddings/test_basic.py | .py | """Basic embedding API tests.
Tests the embedding functionality through the router with both gRPC and HTTP backends.
Source: Migrated from e2e_grpc/basic/test_embedding_server.py
Usage:
pytest e2e_test/embeddings/test_basic.py -v
pytest e2e_test/embeddings/test_basic.py -v -k "grpc"
"""
from __future__ impo... | 167 | 5,754 |
sglang | sgl-model-gateway/e2e_test/infra/model_pool.py | .py | """Model pool for managing pre-loaded models across GPUs."""
from __future__ import annotations
import logging
import os
import signal
import subprocess
import threading
import time
from dataclasses import dataclass, field
from typing import TYPE_CHECKING
import httpx
if TYPE_CHECKING:
import openai
from .cons... | 1,232 | 45,641 |
sglang | sgl-model-gateway/e2e_test/infra/gateway.py | .py | """Gateway class for managing sgl-model-gateway router instances."""
from __future__ import annotations
import logging
import os
import subprocess
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any
import httpx
from .constants import DEFAULT_HOST, DEFAULT_ROUTER_TIMEOUT, ENV_SHOW_ROUTER_... | 596 | 20,315 |
sglang | sgl-model-gateway/e2e_test/infra/model_specs.py | .py | """Model specifications for E2E tests.
Each model spec defines:
- model: HuggingFace model path or local path
- memory_gb: Estimated GPU memory required
- tp: Tensor parallelism size (number of GPUs needed)
- features: List of features this model supports (for test filtering)
"""
from __future__ import annotations
i... | 152 | 5,193 |
sglang | sgl-model-gateway/e2e_test/infra/simple_eval_common.py | .py | # Adapted from https://github.com/openai/simple-evals/
"""Common utilities for simple evaluations."""
from __future__ import annotations
import logging
import os
import resource
import time
from collections import defaultdict
from dataclasses import dataclass, field
from multiprocessing.pool import ThreadPool
from ty... | 496 | 13,664 |
sglang | sgl-model-gateway/e2e_test/infra/simple_eval_mmlu.py | .py | # Adapted from https://github.com/openai/simple-evals/
"""
MMLU Evaluation - Measuring Massive Multitask Language Understanding
Dan Hendrycks et al. https://arxiv.org/abs/2009.03300
"""
from __future__ import annotations
import random
import re
from typing import TYPE_CHECKING
import pandas
from . import simple_eva... | 133 | 4,727 |
sglang | sgl-model-gateway/e2e_test/infra/__init__.py | .py | """Infrastructure for parallel GPU test execution."""
from .constants import ( # Enums; Convenience sets; Fixture parameters; Defaults; Environment variables
CLOUD_RUNTIMES,
DEFAULT_HOST,
DEFAULT_MODEL,
DEFAULT_ROUTER_TIMEOUT,
DEFAULT_STARTUP_TIMEOUT,
ENV_BACKENDS,
ENV_MODEL,
ENV_MODEL... | 145 | 3,622 |
sglang | sgl-model-gateway/e2e_test/infra/constants.py | .py | """Constants and enums for E2E test infrastructure."""
from enum import Enum
class ConnectionMode(str, Enum):
"""Worker connection protocol."""
HTTP = "http"
GRPC = "grpc"
class WorkerType(str, Enum):
"""Worker specialization type."""
REGULAR = "regular"
PREFILL = "prefill"
DECODE = "... | 75 | 1,847 |
sglang | sgl-model-gateway/e2e_test/infra/gpu_allocator.py | .py | """GPU detection and slot allocation for parallel test execution."""
from __future__ import annotations
import logging
import os
import socket
import threading
import time
from contextlib import contextmanager
from dataclasses import dataclass
logger = logging.getLogger(__name__)
# Try to import nvidia-ml-py for GP... | 451 | 15,908 |
sglang | sgl-model-gateway/e2e_test/infra/gpu_monitor.py | .py | """GPU utilization monitoring for benchmarks.
This module provides a low-impact GPU monitor that runs in a separate process
and collects utilization samples using NVML.
"""
from __future__ import annotations
import json
import logging
import os
import time
from multiprocessing import Process
from pathlib import Path... | 330 | 9,933 |
sglang | sgl-model-gateway/e2e_test/infra/process_utils.py | .py | """Process management utilities for E2E tests."""
from __future__ import annotations
import logging
import os
import signal
import subprocess
import time
import requests
logger = logging.getLogger(__name__)
def kill_process_tree(pid: int, sig: int = signal.SIGTERM) -> None:
"""Kill a process and all its child... | 192 | 6,043 |
sglang | sgl-model-gateway/e2e_test/infra/run_eval.py | .py | """MMLU evaluation runner for E2E tests.
Simplified evaluation runner that uses local eval implementations
with cleaner logging for CI/CD environments.
Usage:
from infra.run_eval import run_eval
from types import SimpleNamespace
args = SimpleNamespace(
base_url="http://127.0.0.1:30000",
m... | 139 | 3,808 |
sglang | sgl-model-gateway/e2e_test/benchmarks/test_pd_perf.py | .py | """PD (prefill/decode disaggregation) router performance benchmark test."""
import pytest
@pytest.mark.e2e
@pytest.mark.workers(prefill=2, decode=2)
@pytest.mark.parametrize("setup_backend", ["pd"], indirect=True)
class TestPDPerf:
"""Performance benchmark for PD disaggregation router."""
def test_pd_perf(s... | 32 | 1,299 |
sglang | sgl-model-gateway/e2e_test/benchmarks/test_regular_perf.py | .py | """Regular router performance benchmark test."""
import pytest
@pytest.mark.e2e
@pytest.mark.workers(count=4)
@pytest.mark.gateway(policy="cache_aware")
@pytest.mark.parametrize("setup_backend", ["http", "grpc"], indirect=True)
class TestRegularPerf:
"""Performance benchmark for regular (non-PD) router."""
... | 30 | 1,150 |
sglang | sgl-model-gateway/e2e_test/benchmarks/summarize.py | .py | """Generate benchmark summary for GitHub Actions."""
from __future__ import annotations
import os
import sys
from pathlib import Path
from results import BenchmarkResult, GPUUtilization
def discover_benchmarks(base_dir: Path) -> list[tuple[Path, str]]:
"""Auto-discover benchmark folders and their result JSON f... | 120 | 4,329 |
sglang | sgl-model-gateway/e2e_test/benchmarks/results.py | .py | """Benchmark result dataclasses for parsing genai-bench and GPU monitor output."""
from __future__ import annotations
import json
from dataclasses import dataclass
from pathlib import Path
@dataclass
class BenchmarkResult:
"""Parsed benchmark metrics from genai-bench output."""
ttft_mean: float
e2e_lat... | 99 | 3,222 |
sglang | sgl-model-gateway/e2e_test/benchmarks/conftest.py | .py | """Benchmark-specific fixtures."""
from __future__ import annotations
import logging
import os
import shutil
import subprocess
import time
from pathlib import Path
import pytest
from infra import GPUMonitor, should_monitor_gpu, terminate_process
from .results import BenchmarkResult
logger = logging.getLogger(__nam... | 223 | 6,576 |
sglang | sgl-model-gateway/e2e_test/fixtures/setup_backend.py | .py | """Backend setup fixtures for E2E tests.
This module provides fixtures for launching gateways/routers for different backends.
"""
from __future__ import annotations
import logging
import os
from typing import TYPE_CHECKING
import pytest
if TYPE_CHECKING:
from infra import ModelPool
from .markers import get_ma... | 496 | 17,366 |
sglang | sgl-model-gateway/e2e_test/fixtures/__init__.py | .py | """Fixtures for E2E tests.
This package contains modular pytest fixtures split by responsibility:
- hooks.py: Pytest collection hooks and marker registration
- pool.py: Model pool fixtures (session-scoped worker management)
- setup_backend.py: Backend setup fixtures (class/function-scoped)
- markers.py: Helper utiliti... | 52 | 1,475 |
sglang | sgl-model-gateway/e2e_test/fixtures/hooks.py | .py | """Pytest hooks for E2E test collection and validation.
This module handles:
- Test collection: Scanning markers to determine required workers
- GPU validation: Ensuring sufficient GPUs for test requirements
- Marker registration: Defining custom pytest markers
"""
from __future__ import annotations
import logging
i... | 498 | 18,369 |
sglang | sgl-model-gateway/e2e_test/fixtures/ports.py | .py | """Legacy port utilities.
DEPRECATED: This module will be removed during e2e_response_api migration.
Use infra.get_open_port() instead.
"""
import socket
def find_free_port() -> int:
"""Return an available TCP port on localhost."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(... | 15 | 372 |
sglang | sgl-model-gateway/e2e_test/fixtures/markers.py | .py | """Marker helper utilities for E2E tests.
This module provides helper functions for extracting values from pytest markers.
"""
from __future__ import annotations
from typing import Any
import pytest
def get_marker_value(
request: pytest.FixtureRequest,
marker_name: str,
arg_index: int = 0,
default... | 58 | 1,534 |
sglang | sgl-model-gateway/e2e_test/fixtures/pool.py | .py | """Model pool fixtures for E2E tests.
This module provides session-scoped fixtures for managing SGLang worker processes.
Workers are expensive to start (~30-60s each), so they're kept running across tests.
"""
from __future__ import annotations
import atexit
import logging
import os
import threading
from typing impo... | 243 | 8,045 |
sglang | sgl-model-gateway/e2e_test/k8s_integration/test_reconciliation.py | .py | """Integration tests for K8s service discovery and reconciliation.
Tests verify that:
1. The K8s watcher correctly discovers new pods
2. Stale workers are removed after pod deletion (watcher or reconciliation)
3. All pods are eventually discovered and tracked consistently
4. Prometheus discovery metrics are emitted co... | 507 | 17,656 |
sglang | sgl-model-gateway/e2e_test/k8s_integration/fake_worker.py | .py | """Minimal fake worker that mimics an SGLang worker for integration testing.
Responds to:
GET /health -> 200 OK
GET /v1/models -> {"data": [{"id": "fake-model", "owned_by": "sglang"}]}
GET /server_info, /get_server_info -> {"model_path": ..., "version": ..., "tp_size... | 82 | 2,690 |
sglang | sgl-model-gateway/e2e_test/k8s_integration/test_cross_namespace.py | .py | """Cross-namespace service discovery integration test.
When the gateway is started without --service-discovery-namespace, the K8s
API client falls through to Api::all (sgl-model-gateway/src/service_discovery.rs:279),
watching pods in every namespace. That path requires a ClusterRole rather
than the namespace-scoped Ro... | 267 | 9,303 |
sglang | sgl-model-gateway/e2e_test/k8s_integration/test_pd_type_change.py | .py | """Integration test for PD mode pod type change during hostNetwork rollout.
Scenario: With hostNetwork, the pod IP = node IP. During a rolling update,
an old prefill pod is deleted and a new decode pod comes up on the same node
with the same IP but a new UID. The gateway must:
1. Remove the stale prefill worker (via ... | 317 | 10,534 |
sglang | sgl-model-gateway/e2e_test/k8s_integration/test_lifecycle.py | .py | """Worker lifecycle integration tests.
Covers three scenarios that the existing reconciliation/PD tests don't:
1. Gateway pod restart with persistent workers — verifies the K8s watcher
re-discovers existing pods after the gateway restarts, with no duplicate
registrations.
2. Pod IP change (same pod name, new IP... | 555 | 21,645 |
sglang | sgl-model-gateway/e2e_test/k8s_integration/test_multi_model.py | .py | """Multi-model selector isolation integration test.
Two gateways watch the same namespace with disjoint --selector values
(model=llama vs model=qwen). Each must register only the workers carrying
its own label and ignore the other gateway's pool — proving that
PodInfo::should_include (sgl-model-gateway/src/service_dis... | 205 | 7,331 |
sglang | sgl-model-gateway/e2e_test/k8s_integration/conftest.py | .py | """Pytest configuration for K8s integration tests.
These tests require:
- A kind cluster named 'smg-test'
- The smg-gateway:test image loaded into kind
- kubectl configured to use the kind-smg-test context
Setup: ./e2e_test/k8s_integration/setup.sh
Teardown: ./e2e_test/k8s_integration/setup.sh teardown
"""
fro... | 344 | 10,781 |
sglang | sgl-model-gateway/e2e_test/router/test_worker_api.py | .py | """Tests for gateway worker management APIs.
Tests the gateway's worker management endpoints:
- GET /workers - List all workers
- POST /add_worker - Add a worker dynamically
- POST /remove_worker - Remove a worker dynamically
- GET /v1/models - List available models
Usage:
pytest e2e_test/router/test_worker_api.p... | 226 | 7,954 |
sglang | sgl-model-gateway/e2e_test/router/test_pd_mmlu.py | .py | """MMLU evaluation tests for PD (Prefill-Decode) disaggregated routing.
PD disaggregation separates prefill and decode phases across different
workers for improved throughput and resource utilization.
Requirements:
- sgl_kernel package
- GPUs: num_prefill + num_decode (default: 2 GPUs for 1+1)
- Optional:... | 62 | 1,868 |
sglang | sgl-model-gateway/e2e_test/router/test_mmlu.py | .py | """MMLU evaluation tests for router functionality.
Tests the router's ability to handle MMLU benchmark evaluations across
different backend configurations (gRPC and HTTP workers).
Usage:
# Run with gRPC backend only
pytest e2e_test/router/test_mmlu.py -v
# Run with specific backend
pytest e2e_test/ro... | 77 | 2,247 |
sglang | sgl-model-gateway/e2e_test/responses/test_tools_call.py | .py | """Tool calling tests for Response API.
Tests for function calling functionality, tool choices and MCP calling
functionality across different backends.
Source: Migrated from e2e_response_api/features/test_tools_call.py
"""
from __future__ import annotations
import json
import logging
import time
import pytest
log... | 903 | 30,958 |
sglang | sgl-model-gateway/e2e_test/responses/test_structured_output.py | .py | """Structured output tests for Response API.
Tests for text.format field with json_object and json_schema formats.
Source: Migrated from e2e_response_api/features/test_structured_output.py
"""
from __future__ import annotations
import json
import logging
import pytest
logger = logging.getLogger(__name__)
# ====... | 290 | 10,553 |
sglang | sgl-model-gateway/e2e_test/responses/test_state_management.py | .py | """State management tests for Response API.
Tests both previous_response_id and conversation-based state management.
These tests work across local (gRPC) and cloud (OpenAI, xAI) backends.
Source: Migrated from e2e_response_api/features/test_state_management.py
"""
from __future__ import annotations
import logging
... | 350 | 12,691 |
sglang | sgl-model-gateway/e2e_test/responses/__init__.py | .py | """Response API E2E tests.
Tests for the Response API endpoints including:
- Basic CRUD operations for responses and conversations
- State management (previous_response_id, conversation-based)
- Streaming events and output validation
- Structured output (json_schema)
- Tool calling (function tools and MCP)
"""
| 10 | 313 |
sglang | sgl-model-gateway/e2e_test/responses/test_streaming_events.py | .py | """Streaming events tests for Response API.
Tests for streaming event validation including:
- Zero-based output_index for content
- OutputItemDone event emission and output array construction
- Reasoning content with proper output_index
Source: Migrated from e2e_response_api/features/test_streaming_events.py
"""
fro... | 257 | 9,513 |
sglang | sgl-model-gateway/e2e_test/responses/test_basic_crud.py | .py | """Basic CRUD tests for Response API.
Tests for Response and Conversation CRUD operations against cloud backends.
Source: Migrated from e2e_response_api/features/test_basic_crud.py
"""
from __future__ import annotations
import logging
import time
import openai
import pytest
from openai import OpenAI
from openai.ty... | 442 | 15,612 |
sglang | sgl-model-gateway/e2e_test/chat_completions/test_reasoning_content.py | .py | """Reasoning Content E2E Tests.
Tests for chat completions with reasoning content (DeepSeek R1 reasoning parser).
Source: Migrated from e2e_grpc/features/test_reasoning_content.py
"""
from __future__ import annotations
import logging
import pytest
logger = logging.getLogger(__name__)
# =========================... | 166 | 5,652 |
sglang | sgl-model-gateway/e2e_test/chat_completions/test_function_calling.py | .py | """Function Calling E2E Tests.
Tests for OpenAI-compatible function calling and tool choice functionality.
Source: Migrated from e2e_grpc/function_call/test_openai_function_calling.py
and e2e_grpc/function_call/test_tool_choice.py
"""
from __future__ import annotations
import json
import logging
import ope... | 1,542 | 60,378 |
sglang | sgl-model-gateway/e2e_test/chat_completions/test_enable_thinking.py | .py | """Enable Thinking E2E Tests.
Tests for chat completions with enable_thinking feature (Qwen3 reasoning).
Source: Migrated from e2e_grpc/features/test_enable_thinking.py
"""
from __future__ import annotations
import json
import logging
import pytest
import requests
logger = logging.getLogger(__name__)
# API key i... | 169 | 6,357 |
sglang | sgl-model-gateway/e2e_test/chat_completions/test_validation.py | .py | """Validation E2E Tests.
Tests for validation features like ignore_eos and large token handling.
Source: Migrated from e2e_grpc/validation/test_openai_server_ignore_eos.py
and e2e_grpc/validation/test_large_max_new_tokens.py
"""
from __future__ import annotations
import logging
import threading
import time
... | 168 | 6,432 |
sglang | sgl-model-gateway/e2e_test/chat_completions/test_openai_server.py | .py | """Chat Completions API E2E Tests - OpenAI Server Compatibility.
Tests for OpenAI-compatible chat completions API through the gateway.
Source: Migrated from e2e_grpc/basic/test_openai_server.py
"""
from __future__ import annotations
import json
import logging
import pytest
logger = logging.getLogger(__name__)
#... | 317 | 12,299 |
sglang | rust/sglang-mm/tests/test_integration.py | .py | import io
import os
import sys
import numpy as np
import torch
from PIL import Image
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "bench"))
from bench_parity import make_photo_like
from sglang.srt.multimodal.inkling.image_processing import InklingImageProcessor
from sglang.srt.multimodal.inkling.... | 87 | 2,802 |
sglang | rust/sglang-mm/tests/test_golden.py | .py | import glob
import os
import numpy as np
import pytest
from sglang.srt.multimodal._core import inkling as _rs_inkling
GOLDEN_DIR = os.environ.get(
"INKLING_MM_GOLDEN_DIR",
os.path.join(os.path.dirname(__file__), "..", "tests", "golden"),
)
GOLDENS = sorted(glob.glob(os.path.join(GOLDEN_DIR, "golden_*.npz")))... | 46 | 1,502 |
sglang | rust/sglang-mm/tests/test_resize_parity.py | .py | import math
import time
from typing import Optional
import numpy as np
import pytest
from PIL import Image
from sglang.srt.multimodal._core import common as _rs_common
from sglang.srt.multimodal._core import inkling as _rs_inkling
def py_scaled_dims(
width: int,
height: int,
frac: Optional[float],
c... | 161 | 5,213 |
sglang | rust/sglang-mm/tests/test_hash_fetch.py | .py | import asyncio
import base64
import io
import os
import sys
import time
from types import SimpleNamespace
import numpy as np
import soundfile as sf
import torch
from PIL import Image
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "bench"))
from bench_parity import make_photo_like
from sglang.srt.ma... | 109 | 3,579 |
sglang | rust/sglang-mm/tests/generate_golden.py | .py | import io
import os
import sys
import numpy as np
import torch
from PIL import Image
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "bench"))
from bench_parity import PS, make_photo_like, ref_patchify
OUT = (
sys.argv[1]
if len(sys.argv) > 1
else os.path.join(os.path.dirname(__file__), ... | 41 | 1,011 |
sglang | rust/sglang-mm/bench/bench_parity.py | .py | import io
import time
import numpy as np
import torch
from PIL import Image
from sglang.srt.multimodal._core import inkling as _rs_inkling
from sglang.srt.multimodal.inkling.image_processing import (
IMAGE_MEAN,
IMAGE_STD,
PAD_NORM,
_encode_image_bytes,
_fill_patches_numba,
)
PS = 40
def ref_pa... | 160 | 5,103 |
sglang | python/setup.py | .py | """sglang build hooks.
Rust extensions are auto-discovered from the cargo workspace in ../rust: every
crate whose Cargo.toml declares
[package.metadata.sglang]
python-module = "sglang.srt.<pkg>._core" # import path inside the wheel
debug = false # optional RustExtension knob... | 204 | 7,370 |
sglang | python/tools/get_version_tag.py | .py | #!/usr/bin/env python3
"""Resolve the correct version tag for setuptools-scm.
Called by setuptools-scm via git_describe_command in pyproject.toml.
Outputs either a bare tag (e.g., "v0.5.10") for exact-match commits,
or a `git describe --long` string (e.g., "v0.5.10-2-gabcdef0") for
untagged commits. Both formats are a... | 172 | 6,164 |
sglang | python/sglang/bench_one_batch_server.py | .py | """Deprecated import path for ``sglang.benchmark.one_batch_server``.
``python -m sglang.bench_one_batch_server`` and
``from sglang.bench_one_batch_server import ...`` still work, but the
implementation now lives in ``sglang.benchmark.one_batch_server``.
Update references to the new path.
"""
import warnings
from sgl... | 24 | 742 |
sglang | python/sglang/check_env.py | .py | """Check environment configurations and dependency versions."""
import importlib.metadata
import os
import resource
import subprocess
import sys
from abc import abstractmethod
from collections import OrderedDict, defaultdict
import torch
from sglang.srt.utils import is_hip, is_mps, is_musa, is_npu
def is_cuda_v2()... | 595 | 18,066 |
sglang | python/sglang/bench_offline_throughput.py | .py | """Deprecated import path for ``sglang.benchmark.offline_throughput``.
``python -m sglang.bench_offline_throughput`` and
``from sglang.bench_offline_throughput import ...`` still work, but the
implementation now lives in ``sglang.benchmark.offline_throughput``.
Update references to the new path.
"""
import warnings
... | 24 | 760 |
sglang | python/sglang/utils.py | .py | """Common utilities"""
import importlib
import json
import logging
import os
import random
import ssl
import subprocess
import sys
import time
import traceback
import urllib.request
import warnings
import weakref
from collections import OrderedDict
from concurrent.futures import ThreadPoolExecutor
from functools impor... | 706 | 22,267 |
sglang | python/sglang/compile_deep_gemm.py | .py | """
Compile DeepGEMM Kernels for a model with specify server arguments
This script launches a server for capturing DeepGEMM calls and then compiles the kernels.
It accepts server arguments (the same as launch_server.py).
Usage:
python3 -m sglang.compile_deep_gemm --model deepseek-ai/DeepSeek-V3 --tp 8 --trust-remote-... | 220 | 8,114 |
sglang | python/sglang/launch_server.py | .py | """Launch the inference server."""
import asyncio
import os
import sys
import warnings
from sglang.srt.server_args import prepare_server_args
from sglang.srt.utils import kill_process_tree
from sglang.srt.utils.common import suppress_noisy_warnings
suppress_noisy_warnings()
def run_server(server_args):
"""Run ... | 74 | 2,321 |
sglang | python/sglang/profiler.py | .py | """
Run live profiling.
Usage:
python3 -m sglang.profiler
"""
import argparse
import json
import os
import time
from argparse import ArgumentParser
from pathlib import Path
from typing import List, Optional
import requests
PROFILER_DIR = os.getenv("SGLANG_TORCH_PROFILER_DIR", "/tmp")
def run_profile(
url: Opt... | 159 | 4,401 |
sglang | python/sglang/__init__.py | .py | # SGLang public APIs
# sglang.srt.environ must run before the rest of this file's imports
# (hf_transformers_patches, lang.api, ...), which pull in torch and
# FlashInfer: those claim these cache dirs early, and the first value set is
# the one that sticks. Safe here -- environ has no heavy dependency (no torch).
from... | 125 | 3,205 |
sglang | python/sglang/version.py | .py | try:
from sglang._version import __version__, __version_tuple__
except ImportError:
try:
import importlib.metadata
__version__ = importlib.metadata.version("sglang")
__version_tuple__ = tuple(__version__.split("."))
except Exception:
try:
import pathlib
... | 25 | 852 |
sglang | python/sglang/bench_serving.py | .py | """Deprecated import path for ``sglang.benchmark.serving``.
``python -m sglang.bench_serving`` and ``from sglang.bench_serving import ...``
still work, but the implementation now lives in ``sglang.benchmark.serving``.
Update references to the new path.
"""
import warnings
from sglang.benchmark.serving import * # no... | 23 | 661 |
sglang | python/sglang/_mps_stub.py | .py | """Stub implementations for APIs missing from ``torch.mps``.
``torch.mps`` lacks several APIs that ``torch.cuda`` provides (``Stream``,
``set_device``, ``get_device_properties``, …). Rather than scattering
``hasattr`` / ``getattr`` guards throughout the codebase, we monkey-patch
``torch.mps`` once at startup so that ... | 271 | 7,910 |
sglang | python/sglang/global_config.py | .py | """Global configurations"""
# FIXME: deprecate this file and move all usage to sglang.srt.environ or sglang.__init__.py
class GlobalConfig:
"""
Store some global constants.
"""
def __init__(self):
# Verbosity level
# 0: do not output anything
# 2: output final text after ever... | 30 | 767 |
sglang | python/sglang/_triton_stub.py | .py | """
Mock triton module for platforms where triton is not available (e.g., macOS/MPS).
This module provides stub implementations of triton APIs so that modules which
import triton at the top level can be loaded without error. The actual triton
kernels are never executed on these platforms – alternative backends (e.g. ... | 229 | 7,555 |
sglang | python/sglang/kernel_api_logging.py | .py | """Kernel API crash debugging helpers for SGLang.
This module was developed with reference to FlashInfer's kernel API logging utility:
https://github.com/flashinfer-ai/flashinfer/blob/main/flashinfer/api_logging.py
"""
from __future__ import annotations
import fnmatch
import functools
import inspect
import json
impo... | 518 | 16,874 |
sglang | python/sglang/bench_one_batch.py | .py | """Deprecated import path for ``sglang.benchmark.one_batch``.
``python -m sglang.bench_one_batch`` and ``from sglang.bench_one_batch import ...``
still work, but the implementation now lives in ``sglang.benchmark.one_batch``.
Update references to the new path.
"""
import warnings
from sglang.benchmark.one_batch impo... | 23 | 679 |
sglang | python/sglang/lang/tracer.py | .py | """Tracing a program."""
import uuid
from typing import Any, Dict, List, Optional
from sglang.lang.backend.base_backend import BaseBackend
from sglang.lang.interpreter import ProgramState, ProgramStateGroup
from sglang.lang.ir import (
SglArgument,
SglConstantText,
SglExpr,
SglExprList,
SglFork,
... | 280 | 8,175 |
sglang | python/sglang/lang/choices.py | .py | from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Any, Dict, List, Optional
import numpy as np
@dataclass
class ChoicesDecision:
decision: str
meta_info: Optional[Dict[str, Any]] = None
class ChoicesSamplingMethod(ABC):
@property
def requires_unconditional_lo... | 165 | 6,234 |
sglang | python/sglang/lang/interpreter.py | .py | """The interpreter that executes SGL programs"""
import asyncio
import contextvars
import copy
import multiprocessing
import queue
import threading
import uuid
import warnings
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from typing import Any, Callable, Dict, List, Optional
... | 1,099 | 36,148 |
sglang | python/sglang/lang/ir.py | .py | """The intermediate representation."""
import dataclasses
import inspect
import warnings
from typing import List, Optional, Union
from sglang.global_config import global_config
from sglang.lang.choices import ChoicesSamplingMethod
REGEX_INT = r"[-+]?[0-9]+[ \n]*"
REGEX_FLOAT = r"[-+]?[0-9]*\.?[0-9]+[ \n]*"
REGEX_BOO... | 644 | 20,046 |
sglang | python/sglang/lang/chat_template.py | .py | import re
from dataclasses import dataclass
from enum import Enum, auto
from typing import Callable, Dict, List, Tuple
class ChatTemplateStyle(Enum):
PLAIN = auto()
LLAMA2 = auto()
@dataclass
class ChatTemplate:
name: str
default_system_prompt: str
role_prefix_and_suffix: Dict[str, Tuple[str, st... | 680 | 23,039 |
sglang | python/sglang/lang/api.py | .py | """Public APIs of the language."""
import re
from typing import Callable, List, Optional, Union
from sglang.global_config import global_config
from sglang.lang.backend.base_backend import BaseBackend
from sglang.lang.choices import ChoicesSamplingMethod, token_length_normalized
from sglang.lang.ir import (
SglExp... | 293 | 7,448 |
sglang | python/sglang/lang/backend/openai.py | .py | import dataclasses
import logging
import time
import warnings
from typing import List, Optional, Union
import numpy as np
from sglang.lang.backend.base_backend import BaseBackend
from sglang.lang.chat_template import ChatTemplate, get_chat_template_by_model_path
from sglang.lang.choices import ChoicesDecision, Choice... | 476 | 16,422 |
sglang | python/sglang/lang/backend/crusoe.py | .py | import os
from typing import Optional
from sglang.lang.backend.openai import OpenAI
from sglang.lang.chat_template import ChatTemplate
CRUSOE_BASE_URL = "https://managed-inference-api-proxy.crusoecloud.com/v1/"
class Crusoe(OpenAI):
"""SGLang backend for Crusoe managed inference.
Crusoe exposes an OpenAI-c... | 44 | 1,394 |
sglang | python/sglang/lang/backend/base_backend.py | .py | from typing import List, Optional, Union
from sglang.lang.chat_template import get_chat_template
from sglang.lang.choices import ChoicesDecision, ChoicesSamplingMethod
from sglang.lang.interpreter import StreamExecutor
from sglang.lang.ir import SglSamplingParams
class BaseBackend:
def __init__(self) -> None:
... | 83 | 1,975 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.