repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
sglang | python/sglang/srt/entrypoints/openai/tool_server.py | .py | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import logging
from abc import ABC, abstractmethod
from contextlib import AbstractAsyncContextManager, asynccontextmanager
from typing import Any
try:
from mcp import ClientSession
from mcp.client.sse imp... | 192 | 6,178 |
sglang | python/sglang/srt/entrypoints/openai/sse_utils.py | .py | """SSE chunk building utilities for OpenAI chat completions streaming."""
from __future__ import annotations
from typing import List, Optional, Union
import msgspec
_SSE_DATA_B = b"data: "
_SSE_NL_B = b"\n\n"
class StreamDelta(msgspec.Struct, omit_defaults=True):
"""Delta content for streaming responses.
... | 100 | 2,820 |
sglang | python/sglang/srt/entrypoints/openai/usage_processor.py | .py | from __future__ import annotations
from typing import Any, Dict, List, Mapping, Optional, final
from sglang.srt.entrypoints.openai.protocol import PromptTokensDetails, UsageInfo
@final
class UsageProcessor:
"""Stateless helpers that turn raw token counts into a UsageInfo."""
@staticmethod
def _details_... | 127 | 4,652 |
sglang | python/sglang/srt/entrypoints/openai/encoding_dsv32.py | .py | # Adapted from https://huggingface.co/deepseek-ai/DeepSeek-V3.2/blob/main/encoding/encoding_dsv32.py
import copy
import json
import re
from typing import Any, Dict, List, Optional, Tuple, Union
class DS32EncodingError(Exception):
pass
TOOLS_SYSTEM_TEMPLATE = """## Tools
You have access to a set of tools you can... | 472 | 15,972 |
sglang | python/sglang/srt/entrypoints/openai/transcription_adapters/qwen3_asr.py | .py | from __future__ import annotations
from sglang.srt.entrypoints.openai.protocol import (
TranscriptionRequest,
TranscriptionUsage,
TranscriptionVerboseResponse,
)
from sglang.srt.entrypoints.openai.transcription_adapters.base import (
TranscriptionAdapter,
register_transcription_adapter,
)
from sgla... | 70 | 2,277 |
sglang | python/sglang/srt/entrypoints/openai/transcription_adapters/__init__.py | .py | # Re-export the public API from base so callers can do:
# from ...transcription_adapters import TranscriptionAdapter, register_transcription_adapter
from sglang.srt.entrypoints.openai.transcription_adapters.base import ( # noqa: F401
TranscriptionAdapter,
register_transcription_adapter,
resolve_adapter,
... | 28 | 924 |
sglang | python/sglang/srt/entrypoints/openai/transcription_adapters/mimo_v2_asr.py | .py | from __future__ import annotations
from sglang.srt.entrypoints.openai.protocol import (
TranscriptionRequest,
TranscriptionUsage,
TranscriptionVerboseResponse,
)
from sglang.srt.entrypoints.openai.transcription_adapters.base import (
TranscriptionAdapter,
register_transcription_adapter,
)
@regist... | 47 | 1,484 |
sglang | python/sglang/srt/entrypoints/openai/transcription_adapters/whisper.py | .py | from __future__ import annotations
import logging
import re
from typing import List, Optional
from transformers.models.whisper.tokenization_whisper import LANGUAGES
from sglang.srt.entrypoints.openai.protocol import (
TranscriptionRequest,
TranscriptionSegment,
TranscriptionUsage,
TranscriptionVerbos... | 383 | 16,886 |
sglang | python/sglang/srt/entrypoints/openai/transcription_adapters/base.py | .py | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import List, Optional
from sglang.srt.entrypoints.openai.protocol import (
TranscriptionRequest,
TranscriptionUsage,
TranscriptionVerboseResponse,
)
class TranscriptionAdapter(ABC):
"""Abstract base for model-specific... | 199 | 7,212 |
sglang | python/sglang/srt/entrypoints/openai/realtime/__init__.py | .py | """Realtime transcription WebSocket package. Exposes the FastAPI WS entry."""
from sglang.srt.entrypoints.openai.realtime.handler import (
handle_realtime_transcription as handle_realtime_transcription,
)
| 6 | 210 |
sglang | python/sglang/srt/entrypoints/openai/realtime/protocol.py | .py | """Wire schema for Realtime WS transcription sessions."""
from __future__ import annotations
from typing import Literal, Optional, Union
from openai.types.realtime import SessionUpdateEvent as _SessionUpdateEvent
from openai.types.realtime.audio_transcription import (
AudioTranscription as _AudioTranscription,
)... | 79 | 2,697 |
sglang | python/sglang/srt/entrypoints/openai/realtime/session.py | .py | """WebSocket session for realtime ASR.
Pre-commit deltas reference the reserved current_item_id that the
subsequent input_audio_buffer.committed and conversation.item.created
events will announce — sglang-specific, deviates from OpenAI's
commit-only delta emission.
"""
from __future__ import annotations
import async... | 741 | 29,370 |
sglang | python/sglang/srt/entrypoints/openai/realtime/handler.py | .py | """WebSocket entry for realtime transcription.
Handles accept, concurrency, cleanup. Event loop is in session.py.
"""
from __future__ import annotations
import asyncio
import logging
from fastapi import WebSocket, WebSocketDisconnect
from openai.types.realtime import RealtimeErrorEvent
from openai.types.realtime.re... | 120 | 4,038 |
sglang | python/sglang/srt/entrypoints/anthropic/protocol.py | .py | """Pydantic models for Anthropic Messages API protocol.
Mirrors the shape of the official Anthropic Python SDK
(``anthropic-sdk-python``): ``ContentBlock``, ``Tool``, ``MessageStreamEvent``
and ``ContentBlockDelta`` are discriminated unions over the ``type`` field,
so each variant carries only the fields it actually u... | 519 | 15,802 |
sglang | python/sglang/srt/entrypoints/anthropic/serving.py | .py | """Handler for Anthropic Messages API requests.
Converts Anthropic requests to OpenAI ChatCompletion format, delegates to
OpenAIServingChat for processing, and converts responses back to Anthropic format.
"""
from __future__ import annotations
import asyncio
import json
import logging
import uuid
from typing import ... | 1,466 | 61,352 |
sglang | python/sglang/srt/entrypoints/ollama/smart_router.py | .py | """
Smart Router: Automatically routes requests between local Ollama and remote SGLang.
Uses an LLM judge to classify tasks as simple or complex, then routes accordingly:
- Simple tasks → Local Ollama (fast response)
- Complex tasks → Remote SGLang (powerful model)
Usage:
from sglang.srt.entrypoints.ollama.smart_... | 297 | 9,778 |
sglang | python/sglang/srt/entrypoints/ollama/protocol.py | .py | """
Ollama-compatible API protocol definitions.
These models match the Ollama API format:
https://github.com/ollama/ollama/blob/main/docs/api.md
"""
from typing import Any, Dict, List, Literal, Optional, Union
from pydantic import BaseModel, Field
class OllamaMessage(BaseModel):
"""Ollama message format."""
... | 138 | 3,564 |
sglang | python/sglang/srt/entrypoints/ollama/serving.py | .py | """
Ollama-compatible API serving handlers.
This module provides handlers that convert Ollama API requests to SGLang's
internal format and return Ollama-compatible responses.
"""
import time
from datetime import datetime, timezone
from typing import AsyncIterator, Union
import orjson
from fastapi import Request
from... | 350 | 12,808 |
sglang | python/sglang/srt/distributed/utils.py | .py | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adapted from https://github.com/vllm-project/vllm/blob/v0.6.4.post1/vllm/distributed/utils.py
# Copyright 2023 The vLLM team.
# Adapted from
# https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/core/tenso... | 263 | 10,028 |
sglang | python/sglang/srt/distributed/communication_op.py | .py | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adapted from https://github.com/vllm-project/vllm/blob/v0.6.4.post1/vllm/distributed/communication_op.py
from typing import Any, Dict, Optional, Tuple, Union
import torch
import torch.distributed
from .parall... | 108 | 3,873 |
sglang | python/sglang/srt/distributed/communication_tags.py | .py | from enum import IntEnum, unique
@unique
class P2PTag(IntEnum):
"""
Tags reserved for point-to-point communication protocols.
Communications introduced outside existing scheduler loops need explicit
tags to avoid being consumed by unrelated send/recv paths.
"""
DEFAULT = 0
HIRADIX_PP_SYN... | 16 | 428 |
sglang | python/sglang/srt/distributed/bootstrap.py | .py | import logging
import os
import time
from typing import List, Optional
import msgspec
import torch
import torch.distributed as dist
from sglang.srt.configs.model_config import ModelConfig
from sglang.srt.distributed import (
get_default_distributed_backend,
get_pp_group,
get_tp_group,
get_world_group,... | 280 | 9,507 |
sglang | python/sglang/srt/distributed/parallel_state_wrapper.py | .py | from dataclasses import dataclass
from typing import Optional
@dataclass(frozen=True, slots=True, kw_only=True)
class ParallelState:
tp_rank: int
tp_size: int
pp_rank: int
pp_size: int
dp_rank: Optional[int]
dp_size: int
attn_tp_rank: int
attn_tp_size: int
attn_cp_rank: int
att... | 52 | 1,243 |
sglang | python/sglang/srt/distributed/naive_distributed.py | .py | import pickle
import time
from pathlib import Path
from typing import Any, List, Optional
import pybase64
import torch
from sglang.srt.utils import MultiprocessingSerializer
class NaiveDistributed:
def __init__(self, rank: int, world_size: int, rendezvous: str):
self._rank = rank
self._world_siz... | 114 | 3,317 |
sglang | python/sglang/srt/distributed/parallel_state.py | .py | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adapted from https://github.com/vllm-project/vllm/blob/v0.6.4.post1/vllm/distributed/parallel_state.py
# Copyright 2023 The vLLM team.
# Adapted from
# https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/c... | 3,042 | 118,416 |
sglang | python/sglang/srt/distributed/device_communicators/cuda_wrapper.py | .py | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adapted from https://github.com/vllm-project/vllm/blob/v0.6.4.post1/vllm/distributed/device_communicators/cuda_wrapper.py
"""This file is a pure Python wrapper for the cudart library.
It avoids the need to comp... | 197 | 7,597 |
sglang | python/sglang/srt/distributed/device_communicators/triton_symm_mem_ag.py | .py | # SPDX-License-Identifier: Apache-2.0
"""Symmetric-memory ``multimem.st`` all-gather along the hidden (last) dim.
Each rank stores its ``[T, H/TP]`` shard into a multicast buffer in one NVLink
pass instead of an NCCL ring; ``create_state`` rendezvous once so launches are
CUDA-graph capturable.
"""
import logging
from... | 549 | 17,648 |
sglang | python/sglang/srt/distributed/device_communicators/shm_broadcast.py | .py | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adapted from https://github.com/vllm-project/vllm/blob/v0.6.4.post1/vllm/distributed/device_communicators/shm_broadcast.py
import logging
import os
import pickle
import time
from contextlib import contextmanage... | 520 | 21,672 |
sglang | python/sglang/srt/distributed/device_communicators/torch_symm_mem.py | .py | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adapted from https://github.com/vllm-project/vllm/blob/bf214ca22625e311a2c4c0dfbf7af19128f4919c/vllm/distributed/device_communicators/symm_mem.py
import logging
from typing import Optional, Union
import torch
i... | 186 | 6,755 |
sglang | python/sglang/srt/distributed/device_communicators/quick_all_reduce.py | .py | # SPDX-License-Identifier: Apache-2.0
import logging
import os
from enum import Enum
from functools import cache
from typing import Union
import torch
import torch.distributed as dist
from torch.distributed import ProcessGroup
import sglang.srt.distributed.device_communicators.custom_all_reduce_ops as ops
from sglan... | 268 | 9,910 |
sglang | python/sglang/srt/distributed/device_communicators/custom_all_reduce.py | .py | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adapted from https://github.com/vllm-project/vllm/blob/v0.6.4.post1/vllm/distributed/device_communicators/custom_all_reduce.py
import ctypes
import logging
from contextlib import contextmanager
from functools i... | 422 | 16,850 |
sglang | python/sglang/srt/distributed/device_communicators/pymscclpp.py | .py | import importlib
import logging
from contextlib import contextmanager
from typing import Optional, Union
import torch
import torch.distributed as dist
from torch.distributed import ProcessGroup, ReduceOp
from sglang.srt.compilation.compile_phase import (
get_pcg_capture_stream,
is_in_torch_compile_warmup,
)
f... | 395 | 15,075 |
sglang | python/sglang/srt/distributed/device_communicators/xpu_communicator.py | .py | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adapted from https://github.com/vllm-project/vllm/blob/v0.6.4.post1/vllm/distributed/device_communicators/xpu_communicator.py
import torch
import torch.distributed as dist
from torch.distributed import ProcessG... | 51 | 1,700 |
sglang | python/sglang/srt/distributed/device_communicators/custom_all_reduce_v2.py | .py | """JIT custom all-reduce (v2) over a decoupled storage plane.
The CUDA side is split into two independent pieces:
- ``Communicator``: a thin pointer holder over symmetric-memory workspaces
(push buffers, pull buffer, semaphores) plus a local push counter. All
storage is allocated and owned here, in Python.
- the ... | 491 | 20,926 |
sglang | python/sglang/srt/distributed/device_communicators/pynccl_allocator.py | .py | import ctypes
import logging
import os
import tempfile
import traceback
from contextlib import nullcontext
import torch
from torch.cuda.memory import (
CUDAPluggableAllocator,
_cuda_beginAllocateCurrentThreadToPool,
_cuda_endAllocateToPool,
_cuda_releasePool,
)
from sglang.srt.distributed.parallel_sta... | 438 | 15,652 |
sglang | python/sglang/srt/distributed/device_communicators/custom_all_reduce_utils.py | .py | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adapted from https://github.com/vllm-project/vllm/blob/v0.6.4.post1/vllm/distributed/device_communicators/custom_all_reduce_utils.py
import ctypes
import json
import logging
import os
import pickle
import subpr... | 520 | 19,439 |
sglang | python/sglang/srt/distributed/device_communicators/pynccl.py | .py | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adapted from https://github.com/vllm-project/vllm/blob/v0.6.4.post1/vllm/distributed/device_communicators/pynccl.py
import logging
from contextlib import contextmanager
from typing import Optional, Union
# ===... | 425 | 16,085 |
sglang | python/sglang/srt/distributed/device_communicators/all_reduce_utils.py | .py | MiB = 1024 * 1024
TORCH_SYMM_MEM_ALL_REDUCE_MAX_SIZES = {
9: {
2: 64 * MiB, # 64 MB
4: 64 * MiB, # 64 MB
6: 128 * MiB, # 128 MB
8: 128 * MiB, # 128 MB
},
10: {
2: 64 * MiB, # 64 MB
4: 64 * MiB, # 64 MB
6: 128 * MiB, # 128 MB
8: 128 * Mi... | 17 | 342 |
sglang | python/sglang/srt/distributed/device_communicators/custom_all_reduce_ops.py | .py | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adapted from https://github.com/vllm-project/vllm/blob/v0.6.4.post1/vllm/_custom_ops.py
import logging
from typing import List, Optional, Tuple
import torch
from sglang.srt.utils import is_cuda, is_hip, is_mus... | 167 | 4,786 |
sglang | python/sglang/srt/distributed/device_communicators/mooncake_transfer_engine.py | .py | from __future__ import annotations
import json
import logging
import os
from typing import TYPE_CHECKING, Dict, List, Optional, Union
from sglang.srt.environ import envs
from sglang.srt.utils.network import NetworkAddress, get_free_port, get_local_ip_auto
if TYPE_CHECKING:
from sglang.srt.server_args import Serv... | 358 | 12,414 |
sglang | python/sglang/srt/distributed/device_communicators/npu_communicator.py | .py | import torch
import torch.distributed as dist
from torch.distributed import ProcessGroup
from sglang.srt.utils import is_npu
_is_npu = is_npu()
if _is_npu:
from torch_npu import npu_dynamic_quant
class NpuCommunicator:
def __init__(self, group: ProcessGroup):
if not _is_npu:
self.disab... | 72 | 2,507 |
sglang | python/sglang/srt/distributed/device_communicators/hpu_communicator.py | .py | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adapted from https://github.com/vllm-project/vllm/blob/v0.6.4.post1/vllm/distributed/device_communicators/hpu_communicator.py
import torch
import torch.distributed as dist
from torch.distributed import ProcessG... | 52 | 1,835 |
sglang | python/sglang/srt/distributed/device_communicators/pynccl_wrapper.py | .py | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adapted from https://github.com/vllm-project/vllm/blob/v0.6.4.post1/vllm/distributed/device_communicators/pynccl.py
# This file is a pure Python wrapper for the NCCL library.
# The main purpose is to use NCCL c... | 670 | 22,604 |
sglang | python/sglang/srt/distributed/device_communicators/configs/custom_all_reduce_v2.py | .py | """Hand-tuned dispatch configs for the JIT custom all-reduce (v2).
Thresholds and block counts come from sweeps of
``test/registered/jit/benchmark/bench_custom_all_reduce.py`` on the listed
GPUs; ``get_all_reduce_config`` picks the table for the current arch and
world size.
"""
from functools import cache
from typing... | 197 | 7,361 |
sglang | python/sglang/srt/batch_invariant_ops/batch_invariant_ops.py | .py | # Adapted from https://github.com/thinking-machines-lab/batch_invariant_ops/blob/main/batch_invariant_ops/batch_invariant_ops.py
import contextlib
from collections import namedtuple
from collections.abc import Callable
from typing import Any, Dict, Tuple
import torch
import triton
import triton.language as tl
from s... | 1,062 | 33,607 |
sglang | python/sglang/srt/batch_invariant_ops/__init__.py | .py | # Adapted from https://github.com/thinking-machines-lab/batch_invariant_ops/blob/main/batch_invariant_ops/__init__.py
from .batch_invariant_ops import (
AttentionBlockSize,
disable_batch_invariant_mode,
enable_batch_invariant_mode,
get_batch_invariant_attention_block_size,
is_batch_invariant_mode_e... | 30 | 790 |
sglang | python/sglang/srt/connector/utils.py | .py | # SPDX-License-Identifier: Apache-2.0
import os
from pathlib import Path
from typing import Optional
from urllib.parse import urlparse
from sglang.srt.connector import BaseConnector
def parse_model_name(url: str) -> str:
"""
Parse the model name from the url.
Only used for db connector
"""
parse... | 36 | 983 |
sglang | python/sglang/srt/connector/remote_instance.py | .py | # SPDX-License-Identifier: Apache-2.0
import logging
from typing import Generator, Optional, Tuple
from urllib.parse import urlparse
import torch
import torch.distributed as dist
from sglang.srt.connector import BaseConnector
from sglang.srt.utils import init_custom_process_group
logger = logging.getLogger(__name__... | 83 | 2,757 |
sglang | python/sglang/srt/connector/__init__.py | .py | # SPDX-License-Identifier: Apache-2.0
import enum
import logging
from sglang.srt.connector.base_connector import (
BaseConnector,
BaseFileConnector,
BaseKVConnector,
)
from sglang.srt.connector.redis import RedisConnector
from sglang.srt.connector.remote_instance import RemoteInstanceConnector
from sglang... | 76 | 2,243 |
sglang | python/sglang/srt/connector/s3.py | .py | # SPDX-License-Identifier: Apache-2.0
import fnmatch
import os
from pathlib import Path
from typing import Generator, Optional, Tuple
import torch
from sglang.srt.connector import BaseFileConnector
def _filter_allow(paths: list[str], patterns: list[str]) -> list[str]:
return [
path
for path in ... | 123 | 3,743 |
sglang | python/sglang/srt/connector/base_connector.py | .py | # SPDX-License-Identifier: Apache-2.0
import os
import shutil
import signal
import tempfile
from abc import ABC, abstractmethod
from typing import Generator, List, Optional, Tuple
import torch
class BaseConnector(ABC):
"""
For fs connector such as s3:
<connector_type>://<path>/<filename>
For kv con... | 112 | 2,774 |
sglang | python/sglang/srt/connector/redis.py | .py | # SPDX-License-Identifier: Apache-2.0
import logging
from typing import Generator, List, Optional, Tuple
from urllib.parse import urlparse
import torch
from sglang.srt.connector import BaseKVConnector
from sglang.srt.connector.serde import create_serde
from sglang.srt.connector.utils import pull_files_from_db
logge... | 86 | 2,514 |
sglang | python/sglang/srt/connector/azure.py | .py | # SPDX-License-Identifier: Apache-2.0
import fnmatch
import os
from pathlib import Path
from typing import Generator, Optional, Tuple
import torch
from sglang.srt.connector import BaseFileConnector
def _filter_allow(paths: list[str], patterns: list[str]) -> list[str]:
return [
path
for path in ... | 128 | 4,308 |
sglang | python/sglang/srt/connector/serde/serde.py | .py | # SPDX-License-Identifier: Apache-2.0
import abc
from abc import ABC, abstractmethod
import torch
class Serializer(ABC):
@abstractmethod
def to_bytes(self, t: torch.Tensor) -> bytes:
"""
Serialize a pytorch tensor to bytes. The serialized bytes should contain
both the data and the m... | 44 | 1,004 |
sglang | python/sglang/srt/connector/serde/__init__.py | .py | # SPDX-License-Identifier: Apache-2.0
# inspired by LMCache
from typing import Optional, Tuple
import torch
from sglang.srt.connector.serde.safe_serde import SafeDeserializer, SafeSerializer
from sglang.srt.connector.serde.serde import Deserializer, Serializer
def create_serde(serde_type: str) -> Tuple[Serializer,... | 32 | 707 |
sglang | python/sglang/srt/connector/serde/safe_serde.py | .py | # SPDX-License-Identifier: Apache-2.0
from typing import Union
import torch
from safetensors.torch import load, save
from sglang.srt.connector.serde.serde import Deserializer, Serializer
class SafeSerializer(Serializer):
def __init__(self):
super().__init__()
def to_bytes(self, t: torch.Tensor) -... | 31 | 760 |
sglang | python/sglang/srt/multiplex/pdmux_context.py | .py | from dataclasses import dataclass, field
from typing import List
import torch
import yaml
STREAM_GROUPS = []
SM_COUNTS = []
SM_GROUP_NUM = 8 # Default number of SM groups
CURRENT_STREAM_IDX = 0
CURRENT_STREAM_GROUP = None
@dataclass
class PDMuxConfig:
sm_group_num: int = 8
manual_divisions: List[List[int]]... | 165 | 5,126 |
sglang | python/sglang/srt/multiplex/multiplexing_mixin.py | .py | """
Mixin class providing multiplexing scheduling logic
"""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Optional
import torch
import torch.distributed as dist
from torch.cuda.streams import ExternalStream
from sglang.srt.distributed.parallel_state import set_pdmux_status
from... | 231 | 9,638 |
sglang | python/sglang/srt/checkpoint_engine/__init__.py | .py | """
Checkpoint engine module for SGLang.
This module provides functionality for updating model weights via checkpoint engine.
"""
from sglang.srt.checkpoint_engine.update import main
__all__ = ["main"]
| 10 | 205 |
sglang | python/sglang/srt/checkpoint_engine/update.py | .py | """
Usage:
1) Launch the server with wait-for-initial-weights option in one terminal:
python -m sglang.launch_server --model-path /workspace/Qwen/Qwen3-4B/ --tensor-parallel-size 2 --port 19730 --load-format dummy --checkpoint-engine-wait-weights-before-ready --mem-fraction-static 0.7
2) Torchrun this script in ano... | 318 | 10,871 |
sglang | python/sglang/srt/checkpoint_engine/checkpoint_engine_worker.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... | 144 | 5,510 |
sglang | python/sglang/srt/model_executor/graph_shared_output.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING, Dict, Optional
import torch
from sglang.srt.model_executor.cuda_graph_config import Backend
if TYPE_CHECKING:
from sglang.srt.model_executor.model_runner import ModelRunner
class GraphSharedOutput:
"""``(max_rows, vocab)`` logits buffer,... | 67 | 2,088 |
sglang | python/sglang/srt/model_executor/hook_manager.py | .py | import fnmatch
import importlib
import logging
from typing import Any, Callable, List, Optional
import torch.nn as nn
logger = logging.getLogger(__name__)
def register_forward_hooks(model: nn.Module, hook_specs: List[dict[str, Any]]) -> None:
"""
hook_specs is a list of dicts from server_args.forward_hooks.... | 83 | 2,721 |
sglang | python/sglang/srt/model_executor/forward_batch_deepseek_mha_mixin.py | .py | # Mixin class for metadata management of Deepseek MHA forward (chunked prefix cache)
# More details can be found in python/sglang/srt/models/deepseek_common/attention_forward_methods/forward_mha.py
from typing import List, Optional
import torch
from sglang.kernels.ops.kvcache.kv_indices import (
create_chunked_p... | 226 | 9,848 |
sglang | python/sglang/srt/model_executor/graph_memory_usage.py | .py | from __future__ import annotations
from collections.abc import Mapping
GRAPH_MEMORY_USAGE_KEYS = (
"prefill",
"decode",
"target_verify",
"draft_prefill",
"draft_decode",
"draft_extend",
)
def empty_graph_memory_usage() -> dict[str, float]:
return dict.fromkeys(GRAPH_MEMORY_USAGE_KEYS, 0.... | 67 | 1,637 |
sglang | python/sglang/srt/model_executor/input_buffers.py | .py | from __future__ import annotations
import dataclasses
from dataclasses import dataclass, fields
from typing import Dict, Tuple
import torch
from sglang.srt.utils import is_npu
# Process-wide pool keyed by (name, numel, dtype, device); see share_input_buffer.
_PoolKey = Tuple[str, int, torch.dtype, torch.device]
_fo... | 99 | 3,836 |
sglang | python/sglang/srt/model_executor/cpu_graph_runner.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... | 1,023 | 37,131 |
sglang | python/sglang/srt/model_executor/cuda_graph_buffer_registry.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... | 989 | 39,710 |
sglang | python/sglang/srt/model_executor/pool_configurator.py | .py | """Memory pool configurators for profiling and sizing KV cache pools.
Each model architecture has its own configurator that computes pool sizes
from available GPU memory using a unified coeff+bias model:
available_bytes = max_tokens * coeff + bias
max_tokens = (available_bytes - bias) / coeff
Two entry point... | 951 | 40,443 |
sglang | python/sglang/srt/model_executor/cuda_graph_config.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... | 263 | 10,028 |
sglang | python/sglang/srt/model_executor/model_runner.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... | 2,103 | 84,781 |
sglang | python/sglang/srt/model_executor/forward_batch_info.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... | 1,835 | 77,856 |
sglang | python/sglang/srt/model_executor/forward_context.py | .py | """Per-forward-call control context.
Owns ForwardContext — a frozen dataclass holding control configs the model
layer reads at depth via get_forward_context(). The only mandatory field
today is attn_backend; pool refs are derived from attn_backend.*
(every backend caches them at __init__), so a published ForwardContex... | 85 | 2,892 |
sglang | python/sglang/srt/model_executor/mindspore_runner.py | .py | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the SGLang project
"""ms_runner launch MindSpore distributed modules."""
import logging
import multiprocessing as mp
import os
import sys
from pathlib import Path
import mindspore as ms
import torch
from mindspore._c_expression ... | 121 | 4,215 |
sglang | python/sglang/srt/model_executor/runner_backend_utils/__init__.py | .py | """Low-level primitives used by the CUDA graph backends.
Subpackages:
- breakable_cuda_graph: BreakableCUDAGraph + capture context,
eager_on_graph decorator, is_in_breakable_cuda_graph flag.
- piecewise_cuda_graph: shared piecewise context manager
(set_tc_piecewise_forward_context, is_in_tc_piecewise_cuda_... | 29 | 1,201 |
sglang | python/sglang/srt/model_executor/runner_backend_utils/tc_piecewise_cuda_graph/__init__.py | .py | """Piecewise CUDA graph utilities — shared between Breakable and tc_piecewise backends.
Public API:
- is_in_tc_piecewise_cuda_graph() — true while inside any piecewise capture.
- enable_tc_piecewise_cuda_graph() — context manager that toggles the flag.
- TcPiecewiseForwardContext + set_tc_piecewise_forward_conte... | 23 | 982 |
sglang | python/sglang/srt/model_executor/runner_backend_utils/tc_piecewise_cuda_graph/context_manager.py | .py | """CUDA graph capture context manager + forward-context propagation.
Owns two pieces of cross-cutting state used by *every* piecewise-style
backend (currently breakable + tc_piecewise):
* _in_tc_piecewise_cuda_graph — a process-global flag set true while we
are inside the capture or replay window of a piecewise CUD... | 132 | 4,788 |
sglang | python/sglang/srt/model_executor/runner_backend_utils/breakable_cuda_graph/cuda_utils.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... | 49 | 1,577 |
sglang | python/sglang/srt/model_executor/runner_backend_utils/breakable_cuda_graph/__init__.py | .py | """Breakable primitives — segmented CUDA graph capture with eager break points.
Public API (also reachable via the deeper module paths):
- BreakableCUDAGraph, BreakableCUDAGraphCapture — capture/replay
- eager_on_graph — decorator that marks a callable as a graph break
- break_graph — helper that inserts a bare ... | 22 | 865 |
sglang | python/sglang/srt/model_executor/runner_backend_utils/breakable_cuda_graph/breakable_cuda_graph.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... | 408 | 15,538 |
sglang | python/sglang/srt/model_executor/runner_backend_utils/breakable_cuda_graph/context.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... | 61 | 2,129 |
sglang | python/sglang/srt/model_executor/runner/base_cuda_graph_runner.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... | 161 | 6,045 |
sglang | python/sglang/srt/model_executor/runner/flashinfer_autotune.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... | 329 | 12,155 |
sglang | python/sglang/srt/model_executor/runner/prefill_cuda_graph_runner.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... | 1,793 | 80,519 |
sglang | python/sglang/srt/model_executor/runner/__init__.py | .py | """Phase-aware CUDA graph runners.
One concrete runner per phase. Each runner owns its phase-specific
shape semantics (decode → batch size; prefill → token count) and
delegates capture/replay mechanics to a pluggable
BaseCudaGraphBackend chosen via cuda_graph_config.
Public API:
- BaseRunner — minimal abstract base... | 56 | 2,292 |
sglang | python/sglang/srt/model_executor/runner/base_runner.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... | 686 | 27,878 |
sglang | python/sglang/srt/model_executor/runner/shape_key.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... | 38 | 1,411 |
sglang | python/sglang/srt/model_executor/runner/eager_runner.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... | 442 | 18,898 |
sglang | python/sglang/srt/model_executor/runner/decode_cuda_graph_runner.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... | 1,460 | 62,634 |
sglang | python/sglang/srt/model_executor/runner_backend/utils.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... | 125 | 4,779 |
sglang | python/sglang/srt/model_executor/runner_backend/cuda_graph_dedup_mixin.py | .py | """Shared CUDA graph executable-dedup plumbing for CUDA graph backends."""
from __future__ import annotations
import heapq
import logging
from dataclasses import dataclass, field
import torch
try:
from cuda.bindings import driver as cuda_drv
from cuda.bindings import runtime as cuda_rt
except ImportError:
... | 376 | 12,847 |
sglang | python/sglang/srt/model_executor/runner_backend/breakable_cuda_graph_backend.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... | 258 | 10,109 |
sglang | python/sglang/srt/model_executor/runner_backend/__init__.py | .py | """Capture-mechanism backends for CUDA graphs.
A backend owns *how* a captured artifact is produced and replayed for
one shape; it is phase-agnostic. Runners (cuda_graph_runner/) own
*what* data flows in and out.
Public API:
- BaseCudaGraphBackend — abstract interface.
- FullCudaGraphBackend — single torch.cuda.C... | 32 | 1,213 |
sglang | python/sglang/srt/model_executor/runner_backend/full_cuda_graph_backend.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... | 157 | 5,703 |
sglang | python/sglang/srt/model_executor/runner_backend/tc_piecewise_cuda_graph_backend.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... | 272 | 10,872 |
sglang | python/sglang/srt/model_executor/runner_backend/base_cuda_graph_backend.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... | 84 | 3,040 |
sglang | python/sglang/srt/model_executor/runner_utils/deepep_adapter.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... | 43 | 1,771 |
sglang | python/sglang/srt/model_executor/runner_utils/__init__.py | .py | """Low-level utilities used by the CUDA graph runners.
Mirror of cuda_graph_backend_utils/ for runner-side state — buffer
dataclasses, process-global capture flags, the speculative-shared
graph memory pool, and the DeepEP capture/replay adapter. Runners in
cuda_graph_runner/ import from here; nothing here should impor... | 32 | 1,125 |
sglang | python/sglang/srt/model_executor/runner_utils/buffers.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... | 443 | 17,588 |
sglang | python/sglang/srt/model_executor/runner_utils/capture_mode.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... | 79 | 2,687 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.