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/utils/network.py | .py | from __future__ import annotations
import ipaddress
import logging
import os
import socket
import time
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import psutil
import zmq
logger = logging.getLogger(__name__)
def get_open_port() -> int:
from sglang.srt.environ import envs
p... | 579 | 20,079 |
sglang | python/sglang/srt/utils/bench_utils.py | .py | import os
import re
import sys
from contextlib import nullcontext
import torch
# NOTE copied and modified from DeepGEMM
class suppress_stdout_stderr:
def __enter__(self):
self.outnull_file = open(os.devnull, "w")
self.errnull_file = open(os.devnull, "w")
self.old_stdout_fileno_undup = sy... | 158 | 5,146 |
sglang | python/sglang/srt/utils/model_file_verifier.py | .py | """
Model File Verifier - Verify model file integrity using SHA256 checksums.
Example commands:
# Verify using HuggingFace model online metadata
python -m sglang.srt.utils.model_file_verifier verify --model-path /path/to/model --model-checksum Qwen/Qwen3-0.6B
# Verify using locally generated checksum
... | 285 | 8,072 |
sglang | python/sglang/srt/utils/cuda_vmm_transport_utils.py | .py | from __future__ import annotations
import logging
import os
import secrets
import socket
import threading
from collections.abc import Iterable, Sequence
from dataclasses import dataclass
import torch
from sglang.srt.cuda_vmm_utils import (
_FD_SEND_TIMEOUT_S,
VmmReservation,
_get_cuda_driver,
_recv_f... | 1,061 | 39,066 |
sglang | python/sglang/srt/utils/flatten.py | .py | """Flatten ragged (nested, variable-length) structures into flat value buffers
plus per-position length vectors — the columnar wire layout used by the embedded
Rust server's egress path (see ``managers/rust_server.py``).
The ``*Columns`` classes accumulate one batch column-family each: feed them one
request cell at a ... | 187 | 6,592 |
sglang | python/sglang/srt/utils/log_utils.py | .py | from __future__ import annotations
import json
import logging
import os
import socket
import sys
from datetime import datetime
from logging.handlers import TimedRotatingFileHandler
from typing import List, Optional, Union
import torch.distributed as dist
def create_log_targets(
*, targets: Optional[List[str]], ... | 75 | 2,203 |
sglang | python/sglang/srt/utils/weight_checker_comparator.py | .py | from typing import Iterable, NamedTuple, Optional, Tuple
import torch
from sglang.srt.layers.quantization.fp8 import Fp8LinearMethod, Fp8MoEMethod
from sglang.srt.layers.quantization.fp8_utils import (
block_quant_dequant,
inverse_transform_scale_ue8m0,
)
from sglang.srt.layers.quantization.modelopt_quant imp... | 175 | 6,633 |
sglang | python/sglang/srt/utils/offloader.py | .py | import logging
import os
from abc import ABC
from typing import Callable, Generator, List, Optional
import torch
from torch.func import functional_call
from sglang.srt.distributed.naive_distributed import (
NaiveDistributed,
get_naive_distributed,
set_naive_distributed,
)
from sglang.srt.layers.parameter ... | 584 | 19,361 |
sglang | python/sglang/srt/utils/rpd_utils.py | .py | # https://raw.githubusercontent.com/ROCm/rocmProfileData/refs/heads/master/tools/rpd2tracing.py
# commit 92d13a08328625463e9ba944cece82fc5eea36e6
def rpd_to_chrome_trace(
input_rpd, output_json=None, start="0%", end="100%", format="object"
):
import gzip
import sqlite3
if output_json is None:
i... | 451 | 20,517 |
sglang | python/sglang/srt/utils/auth.py | .py | """Auth utilities for HTTP servers.
This module is intentionally lightweight (no torch import) so it can be used in unit tests.
"""
from __future__ import annotations
import secrets
from dataclasses import dataclass
from enum import Enum
from typing import Any, Optional
@dataclass(frozen=True)
class AuthDecision:
... | 209 | 7,289 |
sglang | python/sglang/srt/utils/custom_op.py | .py | from __future__ import annotations
import inspect
from typing import Any, Callable, List, Optional, TypeVar, Union, overload
import torch
import torch.library
from sglang.kernel_api_logging import debug_torch_op
F = TypeVar("F", bound=Callable)
@overload
def register_custom_op(
fn: F,
*,
op_name: Opti... | 338 | 12,481 |
sglang | python/sglang/srt/utils/stale_shm_cleanup.py | .py | """Self-heal for leaked POSIX shared-memory segments in CI.
SGLang processes are torn down with SIGKILL (kill_process_tree, PDEATHSIG),
which skips every Python-level unlink path, so /dev/shm segments accumulate
until the tmpfs is full and the next scheduler init dies with SIGBUS.
Pid-stamped names (see _creator_pid)... | 131 | 4,093 |
sglang | python/sglang/srt/utils/phase_checker.py | .py | from __future__ import annotations
from enum import IntEnum
import torch
import triton
import triton.language as tl
from sglang.srt.environ import envs
def _phase_repr(phase: int | IntEnum) -> str:
if isinstance(phase, IntEnum):
return f"{phase.name}({int(phase)})"
return str(int(phase))
def _hos... | 110 | 3,773 |
sglang | python/sglang/srt/utils/nvjpeg_decoder.py | .py | """High-fidelity nvJPEG decoding for multimodal image processors."""
from __future__ import annotations
import queue
import threading
from functools import lru_cache
import torch
# A decoder retains roughly 15-25 MiB of device-side scratch space. Two
# decoders are enough to overlap JPEG decode without mirroring th... | 87 | 2,977 |
sglang | python/sglang/srt/utils/msgspec_utils.py | .py | from __future__ import annotations
import base64
import binascii
import dataclasses
from typing import Any
import msgspec
from pydantic_core import core_schema
class Base64Bytes:
"""Pydantic marker for HTTP JSON base64-encoded bytes fields."""
def __get_pydantic_core_schema__(self, source_type: Any, handle... | 116 | 3,549 |
sglang | python/sglang/srt/utils/torch_memory_saver_adapter.py | .py | import logging
from abc import ABC
from contextlib import contextmanager
try:
import torch_memory_saver
_memory_saver = torch_memory_saver.torch_memory_saver
import_error = None
except ImportError as e:
import_error = e
pass
logger = logging.getLogger(__name__)
class TorchMemorySaverAdapter(ABC... | 113 | 2,919 |
sglang | python/sglang/srt/utils/cudacore_pyspy_dump_utils.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... | 145 | 4,870 |
sglang | python/sglang/srt/utils/nvtx_pytorch_hooks.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... | 293 | 11,117 |
sglang | python/sglang/srt/utils/token_sequence_matcher.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... | 45 | 1,769 |
sglang | python/sglang/srt/utils/cuda_ipc_transport_utils.py | .py | """Compatibility imports for the multimodal CUDA IPC transport.
New code should import from :mod:`sglang.srt.multimodal.transport.cuda_ipc`.
"""
from sglang.srt.multimodal.transport.cuda_ipc import (
DEFER_CUDA_IPC_FEATURE_RECONSTRUCTION_KEY,
MM_FEATURE_CACHE_SIZE,
MM_ITEM_MEMORY_POOL_RECYCLE_INTERVAL,
... | 25 | 717 |
sglang | python/sglang/srt/utils/common.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... | 4,711 | 158,063 |
sglang | python/sglang/srt/utils/profile_merger.py | .py | """Merge Chrome trace files from multiple ranks (TP, DP, PP, EP) into a single trace."""
import glob
import gzip
import json
import logging
import os
import re
from typing import Any, Dict, List, Optional, Tuple
logger = logging.getLogger(__name__)
class ProfileMerger:
"""Merge profile traces from all paralleli... | 200 | 7,202 |
sglang | python/sglang/srt/utils/http_middleware_patch.py | .py | """
Fix @app.middleware("http") whose BaseHTTPMiddleware call_next replaces
ASGI ``receive``, breaking request.is_disconnected() and preventing
non-streaming request abort on client disconnect.
patch_app_http_middleware(app) replaces @app.middleware("http") with a
version whose call_next passes ``receive`` through unt... | 68 | 1,971 |
sglang | python/sglang/srt/utils/scheduler_status_logger.py | .py | from __future__ import annotations
import time
from typing import TYPE_CHECKING, List, Optional
import torch.distributed as dist
from sglang.srt.environ import envs
from sglang.srt.utils.log_utils import create_log_targets, log_json
if TYPE_CHECKING:
from sglang.srt.managers.schedule_batch import Req, ScheduleB... | 56 | 1,817 |
sglang | python/sglang/srt/utils/host_shared_memory.py | .py | import logging
from dataclasses import dataclass
from multiprocessing import shared_memory
from pathlib import Path
from typing import List, Optional
import numpy as np
import torch
from sglang.srt.distributed.naive_distributed import get_naive_distributed
from sglang.srt.utils import check_cuda_result
logger = logg... | 83 | 2,264 |
sglang | python/sglang/srt/utils/invariants.py | .py | """Value/index validity checks -- the invariant-check model.
Two layers per check:
* data layer (sanitize / containment): unconditional, branchless, ~free.
May live in `recover` here or inside the kernel (then `recover=None`).
* signal layer (detect + log/crash): gated by SGLANG_INVARIANT_CHECK
(off / warn... | 246 | 7,963 |
sglang | python/sglang/srt/utils/async_probe.py | .py | """Async invariant probes — fire torch._assert_async without CPU sync.
All probes are gated on SGLANG_ENABLE_ASYNC_ASSERT (default off in prod).
When the gate is on, a violation surfaces as an assertion at the next CUDA
sync point instead of as a silent NaN cascade or illegal-address crash.
"""
import logging
from ty... | 150 | 5,279 |
sglang | python/sglang/srt/utils/gauge_histogram.py | .py | """Gauge with gt/le bucket labels for Grafana heatmap visualization.
Unlike Prometheus Histogram which uses cumulative buckets, this uses
non-cumulative buckets (gt < value <= le) suitable for heatmap display.
Note: Keep in sync with Rust implementation in
sgl-model-gateway/src/observability/gauge_histogram.rs
"""
i... | 77 | 2,666 |
sglang | python/sglang/srt/utils/json_response.py | .py | """Utilities for JSON serialization in HTTP responses."""
from typing import Any
import orjson
from fastapi.responses import Response
# Keep response serialization behavior consistent across endpoints:
# - Support non-string dictionary keys used in some metadata payloads.
# - Support numpy scalars/arrays without pre... | 31 | 1,041 |
sglang | python/sglang/srt/utils/aio_rwlock.py | .py | import asyncio
class RWLock:
def __init__(self):
# Protects internal state
self._lock = asyncio.Lock()
# Condition variable used to wait for state changes
self._cond = asyncio.Condition(self._lock)
# Number of readers currently holding the lock
self._readers = 0
... | 105 | 3,093 |
sglang | python/sglang/srt/utils/profile_utils.py | .py | import logging
import os
import time
from abc import ABC
from dataclasses import dataclass
from pathlib import Path
from typing import Callable, Dict, List, Optional
import torch
from sglang.srt.distributed.parallel_state_wrapper import ParallelState
from sglang.srt.environ import envs
from sglang.srt.managers.io_str... | 456 | 15,265 |
sglang | python/sglang/srt/utils/hf_transformers_patches.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... | 466 | 17,280 |
sglang | python/sglang/srt/utils/torch_npu_patch_utils.py | .py | from collections.abc import Sequence
from typing import Any
def apply_torch_npu_patches(torch_npu: Any, patches: Sequence[Sequence[Any]]) -> None:
"""Apply torch_npu patches across old and new torch_npu patch APIs."""
if hasattr(torch_npu, "_apply_patches"):
torch_npu._apply_patches(patches)
r... | 18 | 540 |
sglang | python/sglang/srt/utils/tensor_bridge.py | .py | # Copied and adapted from: https://github.com/vllm-project/vllm-metal
# SPDX-License-Identifier: Apache-2.0
"""Tensor bridge between MLX and PyTorch.
Provides zero-copy conversion when possible using Apple Silicon's unified memory.
"""
from __future__ import annotations
import logging
from functools import lru_cache... | 229 | 6,762 |
sglang | python/sglang/srt/utils/device_timer.py | .py | from collections import deque
from contextlib import contextmanager, nullcontext
from dataclasses import dataclass
from typing import Callable, Deque, Dict, List, Optional
import torch
def device_timer_ctx(timer: Optional["DeviceTimer"], category: str):
"""Timing context for one forward segment; no-op when the t... | 107 | 3,379 |
sglang | python/sglang/srt/utils/aiter.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... | 58 | 1,990 |
sglang | python/sglang/srt/utils/hf_transformers/__init__.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... | 69 | 2,307 |
sglang | python/sglang/srt/utils/hf_transformers/gguf_native.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... | 259 | 9,312 |
sglang | python/sglang/srt/utils/hf_transformers/common.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... | 628 | 21,934 |
sglang | python/sglang/srt/utils/hf_transformers/processor.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... | 388 | 13,433 |
sglang | python/sglang/srt/utils/hf_transformers/tokenizer.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... | 635 | 24,852 |
sglang | python/sglang/srt/utils/hf_transformers/config.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... | 287 | 10,488 |
sglang | python/sglang/srt/utils/hf_transformers/mistral_utils.py | .py | # Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/transformers_utils/configs/mistral.py
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import json
import tempfile
from functools import lru_cache
from pathlib import Path
from typing import Any,... | 638 | 23,987 |
sglang | python/sglang/srt/sampling/sampling_params.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... | 333 | 13,031 |
sglang | python/sglang/srt/sampling/sampling_batch_info.py | .py | from __future__ import annotations
import dataclasses
import logging
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
import torch
import sglang.srt.sampling.penaltylib as penaltylib
from sglang.srt.constrained.base_grammar_backend import (
BaseGrammarObject,
GrammarMask,
GrammarRow,
)
... | 496 | 18,851 |
sglang | python/sglang/srt/sampling/custom_logit_processor.py | .py | import json
from abc import ABC, abstractmethod
from array import array
from functools import lru_cache
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set
import dill
import orjson
import torch
if TYPE_CHECKING:
from sglang.srt.managers.schedule_batch import Req
@lru_cache(maxsize=None)
def _cache... | 219 | 7,376 |
sglang | python/sglang/srt/sampling/penaltylib/repetition_penalty.py | .py | import torch
from sglang.srt.sampling.penaltylib.orchestrator import _BatchedPenalizer
from sglang.srt.utils import get_compiler_backend, is_npu
_is_npu = is_npu()
@torch.compile(dynamic=True, backend=get_compiler_backend(), disable=_is_npu)
def apply_scaling_penalties(logits, scaling_penalties):
logits[:] = to... | 81 | 2,690 |
sglang | python/sglang/srt/sampling/penaltylib/__init__.py | .py | from sglang.srt.sampling.penaltylib.frequency_penalty import BatchedFrequencyPenalizer
from sglang.srt.sampling.penaltylib.min_new_tokens import BatchedMinNewTokensPenalizer
from sglang.srt.sampling.penaltylib.orchestrator import BatchedPenalizerOrchestrator
from sglang.srt.sampling.penaltylib.presence_penalty import B... | 14 | 619 |
sglang | python/sglang/srt/sampling/penaltylib/frequency_penalty.py | .py | import torch
from sglang.srt.sampling.penaltylib.orchestrator import _BatchedPenalizer
class BatchedFrequencyPenalizer(_BatchedPenalizer):
"""
Frequency penalizer penalizes tokens based on their frequency in the output.
"""
def _is_required(self) -> bool:
return any(
req.sampling... | 64 | 2,141 |
sglang | python/sglang/srt/sampling/penaltylib/min_new_tokens.py | .py | import torch
from sglang.srt.sampling.penaltylib.orchestrator import _BatchedPenalizer
class BatchedMinNewTokensPenalizer(_BatchedPenalizer):
"""
Min new tokens penalizer penalizes tokens based on the length of the output.
"""
def _is_required(self) -> bool:
return any(
req.sampl... | 101 | 3,796 |
sglang | python/sglang/srt/sampling/penaltylib/presence_penalty.py | .py | import torch
from sglang.srt.sampling.penaltylib.orchestrator import _BatchedPenalizer
class BatchedPresencePenalizer(_BatchedPenalizer):
"""
Presence penalizer penalizes tokens based on their presence in the output.
"""
def _is_required(self) -> bool:
return any(
req.sampling_pa... | 64 | 2,114 |
sglang | python/sglang/srt/sampling/penaltylib/orchestrator.py | .py | from __future__ import annotations
import abc
import weakref
from typing import TYPE_CHECKING, Optional, Set, Type
import torch
if TYPE_CHECKING:
from sglang.srt.managers.schedule_batch import ScheduleBatch
class BatchedPenalizerOrchestrator:
def __init__(
self,
vocab_size: int,
bat... | 296 | 9,555 |
sglang | python/sglang/srt/constrained/xgrammar_backend.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... | 440 | 16,305 |
sglang | python/sglang/srt/constrained/utils.py | .py | from typing import Dict
def is_legacy_structural_tag(obj: Dict) -> bool:
# test whether an object is a legacy structural tag
# see `StructuralTagResponseFormat` at `sglang.srt.entrypoints.openai.protocol`
if obj.get("structures", None) is not None:
assert obj.get("triggers", None) is not None
... | 13 | 418 |
sglang | python/sglang/srt/constrained/reasoner_grammar_backend.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... | 336 | 13,665 |
sglang | python/sglang/srt/constrained/grammar_manager.py | .py | from __future__ import annotations
import logging
import time
from concurrent import futures
from typing import TYPE_CHECKING, List
import torch
from sglang.srt.constrained.base_grammar_backend import (
InvalidGrammarObject,
create_grammar_backend,
)
from sglang.srt.constrained.reasoner_grammar_backend impor... | 312 | 12,656 |
sglang | python/sglang/srt/constrained/llguidance_backend.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... | 311 | 11,201 |
sglang | python/sglang/srt/constrained/outlines_jump_forward.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... | 201 | 6,823 |
sglang | python/sglang/srt/constrained/outlines_backend.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... | 191 | 6,900 |
sglang | python/sglang/srt/constrained/base_grammar_backend.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... | 406 | 14,002 |
sglang | python/sglang/srt/constrained/torch_ops/token_filter_torch_ops.py | .py | # Copyright 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 writing, so... | 64 | 2,138 |
sglang | python/sglang/srt/managers/io_struct.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,499 | 100,381 |
sglang | python/sglang/srt/managers/cache_controller.py | .py | from __future__ import annotations
"""
Copyright 2023-2025 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 la... | 1,253 | 49,064 |
sglang | python/sglang/srt/managers/tokenizer_manager.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... | 3,670 | 159,061 |
sglang | python/sglang/srt/managers/multimodal_processor.py | .py | # TODO: also move pad_input_ids into this module
import importlib
import inspect
import logging
import pkgutil
from sglang.srt.configs.model_config import ModelImpl
from sglang.srt.multimodal.processors.base_processor import BaseMultimodalProcessor
from sglang.srt.server_args import ServerArgs
logger = logging.getLog... | 89 | 3,337 |
sglang | python/sglang/srt/managers/schedule_policy.py | .py | from __future__ import annotations
import logging
from array import array
from sglang.srt.environ import envs
from sglang.srt.managers.prefill_delayer import PrefillDelayerSinglePassExecutor
from sglang.srt.runtime_context import get_disagg
from sglang.srt.utils import get_bool_env_var, is_hip
_ROUTING_KEY_POLICY_DE... | 1,501 | 62,823 |
sglang | python/sglang/srt/managers/utils.py | .py | from __future__ import annotations
import dataclasses
import logging
import re
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, List, Optional, Union
import msgspec
import torch
from sglang.srt.constants import HEALTH_CHECK_RID_PREFIX
from sglang.srt.eplb.expert_distribution import ExpertDist... | 396 | 17,265 |
sglang | python/sglang/srt/managers/embed_types.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... | 59 | 2,317 |
sglang | python/sglang/srt/managers/mm_schedule.py | .py | """Multimodal embedding scheduling and cache coordination."""
from dataclasses import dataclass, field
from typing import Callable, Dict, List, Optional, Tuple
import torch
from sglang.srt.managers.schedule_batch import MultimodalDataItem
from sglang.srt.mem_cache.multimodal_cache import EmbeddingResult, MultiModalS... | 660 | 25,991 |
sglang | python/sglang/srt/managers/scheduler_input_blocker.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... | 107 | 3,748 |
sglang | python/sglang/srt/managers/scheduler.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... | 5,088 | 219,400 |
sglang | python/sglang/srt/managers/overlap_utils.py | .py | from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Optional, Sequence
import msgspec
import torch
from sglang.kernels.ops.speculative.gather_spec_extras import gather_spec_extras
from sglang.srt.environ import envs
from sglang.srt.utils import is_cuda, is_hip,... | 534 | 22,479 |
sglang | python/sglang/srt/managers/data_parallel_controller.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... | 867 | 35,076 |
sglang | python/sglang/srt/managers/tokenizer_manager_score_mixin.py | .py | import logging
import math
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple, Union
import torch
from sglang.srt.configs.model_config import is_cross_encoding_pooler_model
from sglang.srt.managers.embed_types import PositionalEmbeds
from sglang.srt.managers.io_struct import Embeddi... | 781 | 32,610 |
sglang | python/sglang/srt/managers/rust_server.py | .py | """Embedded Rust server lifecycle for the scheduler.
The Rust server replaces the Python api-server + `TokenizerManager` +
`DetokenizerManager` stack (hence this module sits beside them in `managers/`),
running them as Rust threads inside the scheduler process. This wrapper keeps
all `SGLANG_RUST_SERVER` plumbing — st... | 783 | 35,839 |
sglang | python/sglang/srt/managers/disagg_service.py | .py | """Start bootstrap/kv-store-related server"""
import os
from sglang.srt.disaggregation.utils import (
DisaggregationMode,
KVClassType,
TransferBackend,
get_kv_class,
)
from sglang.srt.server_args import ServerArgs
def start_disagg_service(
server_args: ServerArgs,
):
# Start kv bootstrap ser... | 57 | 1,968 |
sglang | python/sglang/srt/managers/prefill_delayer.py | .py | import dataclasses
import logging
import time
from collections import deque
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, NamedTuple, Optional
import torch
from sglang.srt.environ import envs
from sglang.srt.utils import get_bool_env_var
if TYPE_CHECKING:
from sglang.srt.observabilit... | 485 | 19,126 |
sglang | python/sglang/srt/managers/tokenizer_control_mixin.py | .py | from __future__ import annotations
import asyncio
import hashlib
import logging
import time
import uuid
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
import fastapi
from sglang.srt.managers.communicator import FanOutCommunicator
from sglang.srt.managers.io_struct import (
AddExternalCorpusRe... | 935 | 38,223 |
sglang | python/sglang/srt/managers/detokenizer_manager.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... | 538 | 22,357 |
sglang | python/sglang/srt/managers/configure_logging.py | .py | """
Copyright 2023-2025 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 writing, softwar... | 71 | 2,456 |
sglang | python/sglang/srt/managers/communicator.py | .py | from __future__ import annotations
import asyncio
import copy
import logging
from typing import Callable, Generic, List, Optional, TypeVar
logger = logging.getLogger(__name__)
T = TypeVar("T")
class FanOutCommunicator(Generic[T]):
"""Fan-out request + collect response primitive over zmq.
One send is fanne... | 111 | 3,807 |
sglang | python/sglang/srt/managers/schedule_batch.py | .py | from __future__ import annotations
from sglang.srt.dllm.config import DllmConfig
from sglang.srt.model_executor.forward_batch_info import ForwardBatch
from sglang.srt.runtime_context import (
get_exec,
get_schedule,
get_serving,
get_spec,
mamba_cache_chunk_size,
mamba_checkpoint_grid,
mamba... | 3,402 | 142,915 |
sglang | python/sglang/srt/managers/mm_utils.py | .py | """
Multi-modality utils
"""
import copy
import hashlib
import os
import pickle
import sys
from abc import abstractmethod
from collections import defaultdict
from multiprocessing import shared_memory
from typing import Any, Dict, List, Literal, Optional, Tuple
import numpy as np
import torch
from torch import nn
fro... | 1,466 | 57,094 |
sglang | python/sglang/srt/managers/min_free_slots_delayer.py | .py | from typing import Optional
def resolve_min_free_slots(
user_value: Optional[int],
max_running_requests: int,
is_dflash_family: bool = False,
) -> Optional[int]:
"""Resolve the min-free-slots threshold (None = disabled).
An explicit user value always wins, capped by max_running_requests
(<= 1... | 39 | 1,522 |
sglang | python/sglang/srt/managers/multi_tokenizer_mixin.py | .py | from __future__ import annotations
# 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 a... | 813 | 34,303 |
sglang | python/sglang/srt/managers/async_dynamic_batch_tokenizer.py | .py | """
Asynchronous dynamic batch tokenizer for SGLang.
This module provides an async tokenizer with dynamic batching capabilities
to reduce tokenization overhead when multiple requests arrive concurrently.
"""
import asyncio
import logging
from concurrent.futures import ThreadPoolExecutor
from functools import partial
... | 172 | 7,249 |
sglang | python/sglang/srt/managers/hisparse_coordinator.py | .py | # to be combined with the sparse coordinator class and sparse algorithm family
import logging
from typing import Dict, List, NamedTuple, Optional, Tuple, Union
import torch
from sglang.kernels.ops.kvcache.hisparse import (
copy_cache_planned_mla,
load_cache_to_device_buffer_dsv4_mla,
load_cache_to_device... | 1,051 | 43,818 |
sglang | python/sglang/srt/managers/tp_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... | 710 | 28,270 |
sglang | python/sglang/srt/managers/scheduler_pp_mixin.py | .py | from __future__ import annotations
import logging
import math
import time
from array import array
from collections import defaultdict, deque
from dataclasses import dataclass
from typing import TYPE_CHECKING, Dict, List, Optional, Tuple
import numpy as np
import torch
import torch.distributed
from tqdm import tqdm
f... | 1,655 | 69,429 |
sglang | python/sglang/srt/managers/load_snapshot.py | .py | """Load snapshot: publish scheduler load metrics for DP balancing and /v1/loads.
Architecture
------------
Each scheduler periodically publishes a ``LoadSnapshot`` containing its
current load metrics (running reqs, tokens, throughput, ...). Two
transport backends are supported:
**SHM mode** (single-node, default)::... | 660 | 22,706 |
sglang | python/sglang/srt/managers/scheduler_components/output_streamer.py | .py | from __future__ import annotations
import logging
from dataclasses import dataclass, field
from typing import (
TYPE_CHECKING,
Any,
Callable,
List,
Optional,
)
import torch
import zmq
from sglang.srt.disaggregation.utils import DisaggregationMode
from sglang.srt.distributed.parallel_state_wrapper... | 684 | 30,340 |
sglang | python/sglang/srt/managers/scheduler_components/invariant_checker.py | .py | from __future__ import annotations
import logging
from collections import deque
from dataclasses import dataclass, field
from typing import (
TYPE_CHECKING,
Callable,
Deque,
List,
Optional,
Tuple,
)
import torch
from sglang.srt.disaggregation.utils import DisaggregationMode
from sglang.srt.en... | 486 | 19,574 |
sglang | python/sglang/srt/managers/scheduler_components/memory_usage.py | .py | from __future__ import annotations
from collections.abc import Mapping
from sglang.srt.model_executor.graph_memory_usage import merge_graph_memory_usage
def combine_graph_memory_usage(
target: Mapping[str, float] | None,
draft: Mapping[str, float] | None,
) -> dict[str, float]:
return merge_graph_memory... | 42 | 1,230 |
sglang | python/sglang/srt/managers/scheduler_components/metrics_reporter.py | .py | from __future__ import annotations
import dataclasses
import logging
import math
import tempfile
import time
from collections import defaultdict
from dataclasses import dataclass
from typing import TYPE_CHECKING, List, Optional, Tuple, Union
from sglang.srt.disaggregation.utils import DisaggregationMode
from sglang.s... | 1,165 | 49,639 |
sglang | python/sglang/srt/managers/scheduler_components/request_receiver.py | .py | from __future__ import annotations
from dataclasses import dataclass
from http import HTTPStatus
from typing import (
TYPE_CHECKING,
Any,
Callable,
List,
Optional,
Union,
)
import zmq
from torch.distributed import barrier
from sglang.srt.disaggregation.utils import prepare_abort
from sglang.s... | 299 | 11,221 |
sglang | python/sglang/srt/managers/scheduler_components/profiler_manager.py | .py | from __future__ import annotations
import gc
import logging
import os
import time
from dataclasses import dataclass
from pathlib import Path
from typing import (
TYPE_CHECKING,
Any,
Callable,
List,
Optional,
)
import torch
from sglang.srt.environ import envs
from sglang.srt.managers.io_struct imp... | 464 | 17,415 |
sglang | python/sglang/srt/managers/scheduler_components/batch_result_processor.py | .py | from __future__ import annotations
import logging
from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
Callable,
List,
Optional,
Tuple,
Union,
)
import torch
from sglang.srt.disaggregation.utils import DisaggregationMode
from sglang.srt.environ import envs
from sglang.srt.lay... | 1,276 | 53,208 |
sglang | python/sglang/srt/managers/scheduler_components/flush_wrapper.py | .py | import logging
import time
from typing import Callable, Optional, Tuple
from sglang.srt.managers.io_struct import FlushCacheReqInput, FlushCacheReqOutput
from sglang.srt.managers.scheduler_components.ipc_channels import (
SchedulerIpcChannels,
)
class SchedulerFlushWrapper:
def __init__(
self,
... | 66 | 2,133 |
sglang | python/sglang/srt/managers/scheduler_components/logprob_result_processor.py | .py | from __future__ import annotations
import logging
from dataclasses import dataclass
from typing import (
List,
Tuple,
)
import torch
from sglang.srt.configs.model_config import ModelConfig
from sglang.srt.layers.logits_processor import LogitsProcessorOutput
from sglang.srt.managers.io_struct import build_fla... | 378 | 15,933 |
sglang | python/sglang/srt/managers/scheduler_components/weight_updater.py | .py | from __future__ import annotations
import hashlib
import logging
import time
import traceback
from contextlib import contextmanager
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, Iterator, Optional, Tuple
import msgspec
import torch
from sglang.srt.constants import (
GPU_MEMORY_... | 358 | 14,787 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.