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/debug_utils/comparator/entrypoint.py
.py
from __future__ import annotations import argparse import sys import traceback as _traceback_module from pathlib import Path from typing import Any, Iterator, Optional, Union import polars as pl from sglang.srt.debug_utils.comparator.aligner.token_aligner.entrypoint import ( TokenAlignerResult, compute_maybe...
476
16,458
sglang
python/sglang/srt/debug_utils/comparator/bundle_comparator.py
.py
"""Compare two tensor bundles.""" from __future__ import annotations from pathlib import Path from typing import Any, Optional, Union import torch from sglang.srt.debug_utils.comparator.aligner.entrypoint.executor import ( AlignerResult, execute_aligner_plan, ) from sglang.srt.debug_utils.comparator.aligner...
437
14,606
sglang
python/sglang/srt/debug_utils/comparator/preset.py
.py
from __future__ import annotations PRESETS: dict[str, list[str]] = { "raw": [ "--grouping-skip-keys", ], "sglang_dev": [ "--grouping-skip-keys", "rank", ], "sglang_megatron": [ "--grouping-skip-keys", "rank", "step", "--token-aligner", ...
53
1,392
sglang
python/sglang/srt/debug_utils/comparator/meta_overrider.py
.py
"""Meta overrider: replace metadata fields without re-running dumps. Currently only overrides 'dims', but the design supports overriding additional meta fields (e.g. parallel_info) in the future. """ from __future__ import annotations import re from pathlib import Path from typing import Any, Literal, Optional impo...
108
3,320
sglang
python/sglang/srt/debug_utils/comparator/threshold_dsl.py
.py
import re from dataclasses import dataclass from functools import lru_cache from types import CodeType from typing import Optional ALLOWED_NAMES: tuple[str, ...] = ("rel", "max_abs", "mean_abs") _EVAL_GLOBALS: dict = {"__builtins__": {}} _DUMMY_ENV: dict[str, float] = {name: 1.0 for name in ALLOWED_NAMES} @dataclas...
85
2,619
sglang
python/sglang/srt/debug_utils/comparator/report_sink.py
.py
from __future__ import annotations import os import sys from pathlib import Path from typing import IO, Literal, Optional from rich.console import Console from sglang.srt.debug_utils.comparator.output_types import _OutputRecord Verbosity = Literal["minimal", "normal", "verbose"] class ReportSink: """Unified e...
92
2,727
sglang
python/sglang/srt/debug_utils/comparator/log_sink.py
.py
from __future__ import annotations from contextlib import contextmanager from typing import Generator from sglang.srt.debug_utils.comparator.output_types import BaseLog class LogSink: def __init__(self) -> None: self._stack: list[list[BaseLog]] = [] @contextmanager def context(self) -> Generato...
38
1,033
sglang
python/sglang/srt/debug_utils/comparator/bundle_matcher.py
.py
from __future__ import annotations import dataclasses from dataclasses import dataclass from typing import Any import polars as pl from sglang.srt.debug_utils.comparator.utils import Pair from sglang.srt.debug_utils.dump_loader import filter_rows @dataclass(frozen=True) class TensorFileInfo: filename: str ...
47
1,246
sglang
python/sglang/srt/debug_utils/comparator/output_formatter.py
.py
"""Formatting functions for comparator output records. Extracted from output_types.py to separate data-structure definitions from rendering / formatting logic. """ from __future__ import annotations from typing import TYPE_CHECKING, Literal from rich.console import Group from rich.markup import escape from rich.pan...
399
13,521
sglang
python/sglang/srt/debug_utils/comparator/per_token_visualizer.py
.py
"""Per-token relative difference heatmap generator. Produces a single PNG with rows = tensor names, columns = token positions, color = log10(rel_diff). """ from __future__ import annotations from pathlib import Path from typing import Optional from sglang.srt.debug_utils.comparator.output_types import ComparisonTen...
84
2,415
sglang
python/sglang/srt/debug_utils/comparator/aligner/axis_aligner.py
.py
from __future__ import annotations from typing import Optional import torch from einops import rearrange from sglang.srt.debug_utils.comparator.dims_spec import ( _FUSED_NAME_SEP, SEQ_DIM_NAME, TOKEN_DIM_NAME, DimSpec, _SingletonDimUtil, parse_dims, without_dim_names, ) from sglang.srt.de...
220
7,244
sglang
python/sglang/srt/debug_utils/comparator/aligner/unsharder/types.py
.py
from __future__ import annotations from typing import Annotated, Literal, Union from pydantic import Field, model_validator from sglang.srt.debug_utils.comparator.dims_spec import ParallelAxis from sglang.srt.debug_utils.comparator.utils import _FrozenBase class AxisInfo(_FrozenBase): axis_rank: int axis_s...
61
1,772
sglang
python/sglang/srt/debug_utils/comparator/aligner/unsharder/planner.py
.py
from collections import defaultdict from typing import NamedTuple, Optional from sglang.srt.debug_utils.comparator.aligner.unsharder.types import ( AxisInfo, ConcatParams, CpThdConcatParams, PickParams, ReduceSumParams, UnsharderParams, UnsharderPlan, ) from sglang.srt.debug_utils.comparato...
374
13,486
sglang
python/sglang/srt/debug_utils/comparator/aligner/unsharder/executor.py
.py
from dataclasses import dataclass, field from typing import Optional import torch from sglang.srt.debug_utils.comparator.aligner.unsharder.types import ( ConcatParams, CpThdConcatParams, PickParams, ReduceSumParams, UnsharderParams, UnsharderPlan, ) from sglang.srt.debug_utils.comparator.dims_...
191
5,811
sglang
python/sglang/srt/debug_utils/comparator/aligner/unsharder/parallel_info.py
.py
from typing import Optional from sglang.srt.debug_utils.comparator.aligner.unsharder.types import AxisInfo from sglang.srt.debug_utils.comparator.dims_spec import ParallelAxis _PARALLEL_INFO_KEYS = ("sglang_parallel_info", "megatron_parallel_info") def _is_error_sentinel(value: dict) -> bool: """Check if a para...
46
1,621
sglang
python/sglang/srt/debug_utils/comparator/aligner/reorderer/types.py
.py
from typing import Annotated, Literal, Union from pydantic import Field from sglang.srt.debug_utils.comparator.utils import _FrozenBase class ZigzagToNaturalParams(_FrozenBase): op: Literal["zigzag_to_natural"] = "zigzag_to_natural" dim_name: str cp_size: int class ZigzagToNaturalThdParams(_FrozenBase...
30
737
sglang
python/sglang/srt/debug_utils/comparator/aligner/reorderer/planner.py
.py
from typing import Optional from sglang.srt.debug_utils.comparator.aligner.reorderer.types import ( ReordererPlan, ZigzagToNaturalParams, ZigzagToNaturalThdParams, ) from sglang.srt.debug_utils.comparator.aligner.unsharder.types import AxisInfo from sglang.srt.debug_utils.comparator.dims_spec import ( ...
68
2,384
sglang
python/sglang/srt/debug_utils/comparator/aligner/reorderer/executor.py
.py
from typing import Optional import torch from sglang.srt.debug_utils.comparator.aligner.reorderer.types import ( ReordererPlan, ZigzagToNaturalParams, ZigzagToNaturalThdParams, ) from sglang.srt.debug_utils.comparator.dims_spec import ( apply_dim_names, get_dim_names, resolve_dim_by_name, ...
104
3,348
sglang
python/sglang/srt/debug_utils/comparator/aligner/entrypoint/types.py
.py
from __future__ import annotations from typing import Annotated, Optional, Union from pydantic import Discriminator from sglang.srt.debug_utils.comparator.aligner.axis_aligner import AxisAlignerPlan from sglang.srt.debug_utils.comparator.aligner.reorderer.types import ReordererPlan from sglang.srt.debug_utils.compar...
32
1,065
sglang
python/sglang/srt/debug_utils/comparator/aligner/entrypoint/planner.py
.py
from __future__ import annotations from typing import Any, Optional from sglang.srt.debug_utils.comparator.aligner.axis_aligner import ( AxisAlignerPlan, compute_axis_aligner_plan, ) from sglang.srt.debug_utils.comparator.aligner.entrypoint.types import ( AlignerPerStepPlan, AlignerPerStepSubPlan, ...
135
4,292
sglang
python/sglang/srt/debug_utils/comparator/aligner/entrypoint/executor.py
.py
from __future__ import annotations from dataclasses import dataclass, field from typing import NamedTuple, Optional import torch from sglang.srt.debug_utils.comparator.aligner.axis_aligner import ( execute_axis_aligner_plan, ) from sglang.srt.debug_utils.comparator.aligner.entrypoint.traced_types import ( Tr...
213
7,173
sglang
python/sglang/srt/debug_utils/comparator/aligner/entrypoint/traced_types.py
.py
"""Traced wrapper types that embed execution traces (ShapeSnapshots) into plan nodes. These types are created *after* execution, pairing each sub-plan with its observed shape snapshot so that downstream formatters never need to manually zip plan + trace by index. """ from __future__ import annotations from typing im...
38
1,003
sglang
python/sglang/srt/debug_utils/comparator/aligner/token_aligner/entrypoint.py
.py
from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Literal, Optional import polars as pl from sglang.srt.debug_utils.comparator.aligner.token_aligner.concat_steps.thd_seq_lens_loader import ( load_thd_seq_lens_only, ) from sglang.srt.debug_utils.compa...
133
4,378
sglang
python/sglang/srt/debug_utils/comparator/aligner/token_aligner/smart/types.py
.py
from __future__ import annotations from dataclasses import dataclass, field from typing import NamedTuple, Optional, Union from pydantic import model_validator from sglang.srt.debug_utils.comparator.dims_spec import TokenLayout from sglang.srt.debug_utils.comparator.utils import ( Pair, _check_equal_lengths,...
129
3,930
sglang
python/sglang/srt/debug_utils/comparator/aligner/token_aligner/smart/aux_plugins.py
.py
from __future__ import annotations from abc import ABC, abstractmethod from typing import Optional import torch from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.types import ( PositionalSeqId, SeqId, SGLangSeqId, TokenAlignerStepAux, ) from sglang.srt.debug_utils.comparator.dims_spe...
293
10,223
sglang
python/sglang/srt/debug_utils/comparator/aligner/token_aligner/smart/aux_loader.py
.py
from __future__ import annotations from pathlib import Path from typing import Any, Optional import polars as pl import torch from sglang.srt.debug_utils.comparator.aligner.entrypoint.executor import ( execute_sub_plans, ) from sglang.srt.debug_utils.comparator.aligner.entrypoint.planner import ( compute_per...
287
9,246
sglang
python/sglang/srt/debug_utils/comparator/aligner/token_aligner/smart/planner.py
.py
from __future__ import annotations from collections import defaultdict from typing import NamedTuple, Optional from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.types import ( SeqId, TokenAlignerPlan, TokenAlignerSeqInfo, TokenAlignerSeqsInfo, TokenLocator, ) from sglang.srt.debug...
136
4,525
sglang
python/sglang/srt/debug_utils/comparator/aligner/token_aligner/smart/executor.py
.py
from __future__ import annotations import torch from einops import rearrange from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.types import ( TokenAlignerPlan, TokenLocator, ) from sglang.srt.debug_utils.comparator.dims_spec import ( BATCH_DIM_NAME, SEQ_DIM_NAME, TOKEN_DIM_NAME, ...
151
4,810
sglang
python/sglang/srt/debug_utils/comparator/aligner/token_aligner/smart/seq_info_builder.py
.py
from __future__ import annotations from dataclasses import dataclass, field from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.types import ( SeqId, TokenAlignerGlobalAux, TokenAlignerSeqInfo, TokenAlignerSeqsInfo, TokenAlignerStepAux, TokenLocator, ) @dataclass class _SeqInf...
82
2,607
sglang
python/sglang/srt/debug_utils/comparator/aligner/token_aligner/concat_steps/__init__.py
.py
from sglang.srt.debug_utils.comparator.aligner.token_aligner.concat_steps.executor import ( execute_token_aligner_concat_steps, ) __all__ = [ "execute_token_aligner_concat_steps", ]
8
191
sglang
python/sglang/srt/debug_utils/comparator/aligner/token_aligner/concat_steps/executor.py
.py
from __future__ import annotations from typing import Optional import torch from sglang.srt.debug_utils.comparator.dims_spec import ( SEQ_DIM_NAME, TOKEN_DIM_NAME, get_dim_names, ) from sglang.srt.debug_utils.comparator.utils import Pair _UNNAMED_TOKEN_DIM_FALLBACK: int = 0 def execute_token_aligner_c...
46
1,583
sglang
python/sglang/srt/debug_utils/comparator/aligner/token_aligner/concat_steps/thd_seq_lens_loader.py
.py
from __future__ import annotations from pathlib import Path from typing import Optional import polars as pl from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.aux_loader import ( _detect_plugin, _load_and_align_aux_tensor, ) from sglang.srt.debug_utils.comparator.aligner.token_aligner.smart.a...
44
1,370
sglang
python/sglang/srt/debug_utils/comparator/visualizer/__init__.py
.py
from sglang.srt.debug_utils.comparator.visualizer.figure import ( # noqa: F401 generate_comparison_figure, )
4
114
sglang
python/sglang/srt/debug_utils/comparator/visualizer/figure.py
.py
"""Main orchestration logic for comparison figure generation.""" from __future__ import annotations from dataclasses import dataclass from pathlib import Path from typing import Callable, Optional import numpy as np import torch from sglang.srt.debug_utils.comparator.visualizer.preprocessing import ( _preproces...
117
3,500
sglang
python/sglang/srt/debug_utils/comparator/visualizer/preprocessing.py
.py
"""Tensor preprocessing and utility functions for visualization.""" from __future__ import annotations import math import re import numpy as np import torch _DOWNSAMPLE_THRESHOLD: int = 10_000_000 _SCATTER_SAMPLE_SIZE: int = 10_000 def _preprocess_tensor(tensor: torch.Tensor) -> torch.Tensor: t: torch.Tensor ...
102
2,732
sglang
python/sglang/srt/debug_utils/comparator/visualizer/panels.py
.py
"""Panel draw functions for tensor comparison visualization.""" from __future__ import annotations from typing import Optional import numpy as np import torch from sglang.srt.debug_utils.comparator.visualizer.figure import _PanelContext from sglang.srt.debug_utils.comparator.visualizer.preprocessing import ( _S...
227
6,604
sglang
python/sglang/srt/debug_utils/comparator/tensor_comparator/comparator.py
.py
from dataclasses import dataclass from typing import Optional import torch from sglang.srt.debug_utils.comparator.tensor_comparator.types import ( DEFAULT_PERCENTILES, DiffInfo, TensorComparisonInfo, TensorInfo, TensorStats, ) from sglang.srt.debug_utils.comparator.threshold_dsl import ( DiffT...
251
7,493
sglang
python/sglang/srt/debug_utils/comparator/tensor_comparator/types.py
.py
from typing import Optional from sglang.srt.debug_utils.comparator.utils import _StrictBase DEFAULT_PERCENTILES: tuple[int, ...] = (1, 5, 50, 95, 99) class TensorStats(_StrictBase): mean: float abs_mean: float std: float min: float max: float percentiles: dict[int, float] = {} class Tensor...
46
1,046
sglang
python/sglang/srt/debug_utils/comparator/tensor_comparator/__init__.py
.py
from sglang.srt.debug_utils.comparator.tensor_comparator.comparator import ( compare_tensor_pair, )
4
104
sglang
python/sglang/srt/debug_utils/comparator/tensor_comparator/formatter.py
.py
from __future__ import annotations from typing import TYPE_CHECKING, Literal, Optional from rich.markup import escape from sglang.srt.debug_utils.comparator.aligner.reorderer.types import ReordererPlan from sglang.srt.debug_utils.comparator.aligner.unsharder.types import UnsharderPlan from sglang.srt.debug_utils.com...
523
17,861
sglang
python/sglang/srt/debug_utils/comparator/dims_spec/types.py
.py
from __future__ import annotations from enum import Enum from typing import Optional from sglang.srt.debug_utils.comparator.utils import _FrozenBase TOKEN_DIM_NAME: str = "t" BATCH_DIM_NAME: str = "b" SEQ_DIM_NAME: str = "s" SQUEEZE_DIM_NAME: str = "1" class TokenLayout(Enum): T = "t" # single flat token dim ...
95
2,214
sglang
python/sglang/srt/debug_utils/comparator/dims_spec/modifier_parser.py
.py
from __future__ import annotations from typing import Optional from sglang.srt.debug_utils.comparator.dims_spec.types import ( _AXIS_LOOKUP, _QUALIFIER_LOOKUP, Ordering, ParallelAxis, ParallelModifier, Reduction, ) def _parse_modifier_token(modifier_token: str, dim_token: str) -> ParallelMod...
85
2,842
sglang
python/sglang/srt/debug_utils/comparator/dims_spec/__init__.py
.py
from sglang.srt.debug_utils.comparator.dims_spec.dim_parser import parse_dim from sglang.srt.debug_utils.comparator.dims_spec.dims_parser import ( _SingletonDimUtil, parse_dims, resolve_dim_names, ) from sglang.srt.debug_utils.comparator.dims_spec.tensor_naming import ( apply_dim_names, find_dim_ind...
52
1,129
sglang
python/sglang/srt/debug_utils/comparator/dims_spec/dim_parser.py
.py
from __future__ import annotations import re from typing import Optional from sglang.srt.debug_utils.comparator.dims_spec.modifier_parser import ( _parse_modifiers, ) from sglang.srt.debug_utils.comparator.dims_spec.types import ( SQUEEZE_DIM_NAME, DimSpec, ParallelModifier, ) _DIM_PATTERN = re.compi...
69
2,200
sglang
python/sglang/srt/debug_utils/comparator/dims_spec/tensor_naming.py
.py
from __future__ import annotations from typing import Optional import torch from sglang.srt.debug_utils.comparator.dims_spec.types import DimSpec _DIM_NAMES_ATTR = "_dim_names" def find_dim_index(dim_specs: list[DimSpec], name: str) -> Optional[int]: """Find index by name. Accepts both ``*``-form and ``___``-...
57
1,872
sglang
python/sglang/srt/debug_utils/comparator/dims_spec/comment_parser.py
.py
from __future__ import annotations import re from typing import NamedTuple, Optional from sglang.srt.debug_utils.comparator.dims_spec.types import ( _AXIS_LOOKUP, ParallelAxis, ) _DP_ALIAS_PATTERN = re.compile(r"^dp:=(\w+)$") _REPLICATED_PATTERN = re.compile(r"^(\w+):replicated$") class _CommentSuffix(Name...
60
2,002
sglang
python/sglang/srt/debug_utils/comparator/dims_spec/dims_parser.py
.py
from __future__ import annotations from typing import Optional from sglang.srt.debug_utils.comparator.dims_spec.comment_parser import ( _CommentSuffix, _parse_comment_suffix, ) from sglang.srt.debug_utils.comparator.dims_spec.dim_parser import parse_dim from sglang.srt.debug_utils.comparator.dims_spec.types i...
114
3,839
sglang
python/sglang/srt/debug_utils/schedule_simulator/simulator.py
.py
from dataclasses import dataclass from typing import Any, Dict, List, Optional from sglang.srt.debug_utils.schedule_simulator.gpu_state import GPUState, StepRecord from sglang.srt.debug_utils.schedule_simulator.metrics import MetricRecorder from sglang.srt.debug_utils.schedule_simulator.request import SimRequest from ...
123
4,559
sglang
python/sglang/srt/debug_utils/schedule_simulator/request.py
.py
from dataclasses import dataclass from typing import Optional @dataclass class SimRequest: request_id: str input_len: int output_len: int decoded_tokens: int = 0 group_id: Optional[str] = None prefix_len: int = 0 def seq_len(self) -> int: return self.input_len + self.decoded_token...
19
412
sglang
python/sglang/srt/debug_utils/schedule_simulator/__main__.py
.py
from sglang.srt.debug_utils.schedule_simulator.entrypoint import create_arg_parser, main if __name__ == "__main__": parser = create_arg_parser() args = parser.parse_args() main(args)
7
196
sglang
python/sglang/srt/debug_utils/schedule_simulator/__init__.py
.py
from sglang.srt.debug_utils.schedule_simulator.data_source import ( generate_gsp_requests, generate_random_requests, load_from_request_logger, ) from sglang.srt.debug_utils.schedule_simulator.entrypoint import create_arg_parser, main from sglang.srt.debug_utils.schedule_simulator.gpu_state import GPUState, ...
52
1,446
sglang
python/sglang/srt/debug_utils/schedule_simulator/entrypoint.py
.py
import argparse import json import random from typing import List from sglang.srt.debug_utils.schedule_simulator.data_source.data_loader import ( load_from_request_logger, ) from sglang.srt.debug_utils.schedule_simulator.data_source.data_synthesis import ( generate_gsp_requests, generate_random_requests, )...
169
6,229
sglang
python/sglang/srt/debug_utils/schedule_simulator/metrics.py
.py
from abc import ABC, abstractmethod from typing import Any, Callable, Dict, List from sglang.srt.debug_utils.schedule_simulator.gpu_state import GPUState class MetricRecorder(ABC): @abstractmethod def on_step_end(self, step: int, gpu_states: List[GPUState]) -> None: ... @abstractmethod def get_summa...
61
2,096
sglang
python/sglang/srt/debug_utils/schedule_simulator/gpu_state.py
.py
from dataclasses import dataclass, field from typing import List, Optional from sglang.srt.debug_utils.schedule_simulator.request import SimRequest @dataclass class StepRecord: step: int gpu_id: int running_count: int pending_count: int total_seq_len: int running_req_ids: List[str] = field(de...
71
2,401
sglang
python/sglang/srt/debug_utils/schedule_simulator/routers/round_robin_router.py
.py
from sglang.srt.debug_utils.schedule_simulator.request import SimRequest from sglang.srt.debug_utils.schedule_simulator.routers.base import RouterPolicy class RoundRobinRouter(RouterPolicy): def __init__(self, num_gpus: int): self._num_gpus = num_gpus self._counter = 0 def route(self, incomin...
14
448
sglang
python/sglang/srt/debug_utils/schedule_simulator/routers/__init__.py
.py
from sglang.srt.debug_utils.schedule_simulator.routers.base import RouterPolicy from sglang.srt.debug_utils.schedule_simulator.routers.random_router import RandomRouter from sglang.srt.debug_utils.schedule_simulator.routers.round_robin_router import ( RoundRobinRouter, ) from sglang.srt.debug_utils.schedule_simulat...
9
445
sglang
python/sglang/srt/debug_utils/schedule_simulator/routers/sticky_router.py
.py
import random from collections import defaultdict from sglang.srt.debug_utils.schedule_simulator.request import SimRequest from sglang.srt.debug_utils.schedule_simulator.routers.base import RouterPolicy class StickyRouter(RouterPolicy): def __init__(self, num_gpus: int): self._num_gpus = num_gpus ...
21
694
sglang
python/sglang/srt/debug_utils/schedule_simulator/routers/random_router.py
.py
import random from sglang.srt.debug_utils.schedule_simulator.request import SimRequest from sglang.srt.debug_utils.schedule_simulator.routers.base import RouterPolicy class RandomRouter(RouterPolicy): def __init__(self, num_gpus: int): self._num_gpus = num_gpus def route(self, incoming_request: SimR...
13
389
sglang
python/sglang/srt/debug_utils/schedule_simulator/routers/base.py
.py
from abc import ABC, abstractmethod from sglang.srt.debug_utils.schedule_simulator.request import SimRequest class RouterPolicy(ABC): @abstractmethod def route(self, incoming_request: SimRequest) -> int: ...
9
219
sglang
python/sglang/srt/debug_utils/schedule_simulator/schedulers/__init__.py
.py
from sglang.srt.debug_utils.schedule_simulator.schedulers.base import SchedulerPolicy from sglang.srt.debug_utils.schedule_simulator.schedulers.fifo_scheduler import ( FIFOScheduler, ) __all__ = ["SchedulerPolicy", "FIFOScheduler"]
7
237
sglang
python/sglang/srt/debug_utils/schedule_simulator/schedulers/fifo_scheduler.py
.py
from typing import TYPE_CHECKING from sglang.srt.debug_utils.schedule_simulator.schedulers.base import SchedulerPolicy if TYPE_CHECKING: from sglang.srt.debug_utils.schedule_simulator.gpu_state import GPUState class FIFOScheduler(SchedulerPolicy): def schedule(self, gpu_state: "GPUState") -> None: w...
17
637
sglang
python/sglang/srt/debug_utils/schedule_simulator/schedulers/base.py
.py
from abc import ABC, abstractmethod from typing import TYPE_CHECKING if TYPE_CHECKING: from sglang.srt.debug_utils.schedule_simulator.gpu_state import GPUState class SchedulerPolicy(ABC): @abstractmethod def schedule(self, gpu_state: "GPUState") -> None: ...
11
274
sglang
python/sglang/srt/debug_utils/schedule_simulator/data_source/__init__.py
.py
from sglang.srt.debug_utils.schedule_simulator.data_source.data_loader import ( load_from_request_logger, ) from sglang.srt.debug_utils.schedule_simulator.data_source.data_synthesis import ( generate_gsp_requests, generate_random_requests, ) __all__ = [ "load_from_request_logger", "generate_random_...
14
362
sglang
python/sglang/srt/debug_utils/schedule_simulator/data_source/data_synthesis.py
.py
import random from typing import List, Optional from sglang.srt.debug_utils.schedule_simulator.request import SimRequest def generate_random_requests( num_requests: int, input_len: int, output_len: int, range_ratio: float = 1.0, seed: Optional[int] = None, ) -> List[SimRequest]: if seed is no...
80
2,251
sglang
python/sglang/srt/debug_utils/schedule_simulator/data_source/data_loader.py
.py
import json from pathlib import Path from typing import List, Union from sglang.srt.debug_utils.schedule_simulator.request import SimRequest def load_from_request_logger(file_path: Union[str, Path]) -> List[SimRequest]: requests = [] file_path = Path(file_path) with file_path.open(encoding="utf-8") as f...
35
966
sglang
python/sglang/srt/entrypoints/warmup.py
.py
from __future__ import annotations import logging from typing import TYPE_CHECKING, List import numpy as np import tqdm from sglang.srt.disaggregation.utils import FAKE_BOOTSTRAP_HOST from sglang.srt.managers.io_struct import GenerateReqInput if TYPE_CHECKING: from sglang.srt.managers.tokenizer_manager import T...
162
5,614
sglang
python/sglang/srt/entrypoints/request_headers.py
.py
"""Override object fields based on _HEADER_OVERRIDES from header values. This mechanism allows upstream callers to leave the body opaque (no parse/merge/re-serialize). """ from fastapi import HTTPException # request header -> (target attribute, value type) _HEADER_OVERRIDES = { "x-override-rid": ("rid", str), ...
34
1,249
sglang
python/sglang/srt/entrypoints/harmony_utils.py
.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Adapted from vLLM: https://github.com/vllm-project/vllm/blob/1b9902806915040ac9b3029f2ab7522ec505afc3/vllm/entrypoints/harmony_utils.py # Slight differences in processing chat messages import datetime import log...
398
14,543
sglang
python/sglang/srt/entrypoints/ssl_utils.py
.py
"""Utilities for SSL certificate hot-reloading.""" import asyncio import logging import ssl from typing import Optional from watchfiles import awatch logger = logging.getLogger(__name__) class SSLCertRefresher: """Monitors SSL certificate files and reloads them when changed. Uses ``watchfiles.awatch()`` f...
89
3,026
sglang
python/sglang/srt/entrypoints/EngineBase.py
.py
from abc import ABC, abstractmethod from typing import Dict, Iterator, List, Literal, Optional, Tuple, Union import torch class EngineBase(ABC): """ Abstract base class for engine interfaces that support generation, weight updating, and memory control. This base class provides a unified API for both HTTP...
80
2,920
sglang
python/sglang/srt/entrypoints/engine_score_mixin.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...
112
5,074
sglang
python/sglang/srt/entrypoints/grpc_bridge.py
.py
"""Python-side bridge between the Rust gRPC server and TokenizerManager. The RuntimeHandle exposes synchronous methods that Rust can call via PyO3 (with a brief GIL acquisition). Response chunks are pushed into Rust-side channels via callback objects while all async work stays on the TokenizerManager's event loop. """...
808
29,651
sglang
python/sglang/srt/entrypoints/grpc_server.py
.py
""" Thin gRPC server wrapper — delegates to smg-grpc-servicer package. A lightweight HTTP sidecar is started alongside the gRPC server to expose: - /metrics (Prometheus, when --enable-metrics is set) - /start_profile, /stop_profile (profiling control) The sidecar is started on --smg-http-sidecar-port (default: --port...
264
10,188
sglang
python/sglang/srt/entrypoints/engine.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,847
73,933
sglang
python/sglang/srt/entrypoints/elastic_ep.py
.py
"""Elastic EP scaling HTTP endpoints for dp_attention deployments.""" import json from http import HTTPStatus from fastapi import APIRouter, Request from fastapi.responses import ORJSONResponse from sglang.srt.utils.auth import AuthLevel, auth_level router = APIRouter() @router.post("/scale_elastic_ep") @auth_lev...
88
2,774
sglang
python/sglang/srt/entrypoints/context.py
.py
# SPDX-License-Identifier: Apache-2.0 # Copied from vLLM import logging from abc import ABC, abstractmethod from typing import Union import orjson logger = logging.getLogger(__name__) try: from mcp import ClientSession except ImportError as e: mcp = e from openai_harmony import Author, Message, Role, Stream...
261
8,744
sglang
python/sglang/srt/entrypoints/sidecar.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...
131
4,148
sglang
python/sglang/srt/entrypoints/http_server.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,791
103,667
sglang
python/sglang/srt/entrypoints/engine_info_bootstrap_server.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...
106
3,809
sglang
python/sglang/srt/entrypoints/tool.py
.py
# SPDX-License-Identifier: Apache-2.0 import logging from abc import ABC, abstractmethod from typing import TYPE_CHECKING, Any import orjson from sglang.srt.entrypoints.search.exa_client import ( ExaClient, ExaSearchConfig, ) from sglang.srt.environ import envs from sglang.srt.utils import print_info_once, pr...
287
10,124
sglang
python/sglang/srt/entrypoints/http_server_engine.py
.py
import multiprocessing import time from typing import List, Optional, Tuple import requests import torch from sglang.srt.entrypoints.EngineBase import EngineBase from sglang.srt.entrypoints.http_server import launch_server from sglang.srt.server_args import ServerArgs from sglang.srt.utils import MultiprocessingSeria...
147
5,076
sglang
python/sglang/srt/entrypoints/v1_loads.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...
153
5,160
sglang
python/sglang/srt/entrypoints/http_request_decompression.py
.py
"""Pure-ASGI middleware that decompresses compressed request bodies. Gated on `SGLANG_ENABLE_REQUEST_DECOMPRESSION` and request header `x-body-compressed`, whose value names the method. For example, a caller that compressed the body with zstd sets the `x-body-compressed: zstd` header. """ import asyncio import io imp...
96
3,269
sglang
python/sglang/srt/entrypoints/search/exa_client.py
.py
# SPDX-License-Identifier: Apache-2.0 import asyncio from typing import Any, Optional import aiohttp import msgspec from sglang.srt.environ import envs from sglang.srt.utils import print_warning_once EXA_API_BASE_URL = "https://api.exa.ai" EXA_INTEGRATION_HEADER = "x-exa-integration" EXA_INTEGRATION_NAME = "sglang" ...
139
4,929
sglang
python/sglang/srt/entrypoints/openai/serving_rerank.py
.py
import heapq import logging import math from typing import Any, Dict, List, Optional, Union from fastapi import Request from fastapi.responses import ORJSONResponse from sglang.srt.entrypoints.openai.protocol import ( ChatCompletionMessageContentImagePart, ChatCompletionMessageContentTextPart, ChatComplet...
610
23,427
sglang
python/sglang/srt/entrypoints/openai/serving_completions.py
.py
from __future__ import annotations import logging import time from http import HTTPStatus from typing import TYPE_CHECKING, Any, AsyncGenerator, Dict, List, Optional, Union from fastapi import Request from fastapi.responses import ORJSONResponse, StreamingResponse from sglang.srt.entrypoints.openai.protocol import (...
647
26,616
sglang
python/sglang/srt/entrypoints/openai/audio_chunking.py
.py
"""Energy-aware audio chunking for ASR models with a bounded input window. Whisper-style encoders ingest a fixed-length window (30 s of audio = 3000 mel frames); the feature extractor silently truncates anything longer, so long audio must be split into independent chunks before prompting. Cutting blindly at the window...
103
3,927
sglang
python/sglang/srt/entrypoints/openai/utils.py
.py
import logging from typing import Any, Dict, List, Literal, Optional, Union import torch from sglang.srt.entrypoints.openai.protocol import ( CachedTokensDetails, ChatCompletionRequest, CompletionRequest, LogProbs, StreamOptions, ) logger = logging.getLogger(__name__) def to_openai_style_logpro...
193
6,276
sglang
python/sglang/srt/entrypoints/openai/serving_score.py
.py
import logging from typing import Union import torch from fastapi import Request from fastapi.responses import ORJSONResponse from sglang.srt.entrypoints.openai.protocol import ( ErrorResponse, ScoringRequest, ScoringResponse, UsageInfo, ) from sglang.srt.entrypoints.openai.serving_base import OpenAIS...
103
3,650
sglang
python/sglang/srt/entrypoints/openai/streaming_asr.py
.py
import asyncio import io import logging import re from dataclasses import dataclass from typing import Any, Dict, List, Optional import soundfile as sf from fastapi import Request from sglang.srt.entrypoints.openai.transcription_adapters.base import ( TranscriptionAdapter, ) from sglang.srt.managers.io_struct imp...
210
7,366
sglang
python/sglang/srt/entrypoints/openai/serving_tokenize.py
.py
import logging from http import HTTPStatus from typing import List, Optional, Union from fastapi import Request from sglang.srt.entrypoints.openai.protocol import ( DetokenizeRequest, DetokenizeResponse, ErrorResponse, TokenizeRequest, TokenizeResponse, ) from sglang.srt.entrypoints.openai.serving...
190
7,420
sglang
python/sglang/srt/entrypoints/openai/serving_responses.py
.py
# SPDX-License-Identifier: Apache-2.0 # Adapted from vLLM's OpenAIServingResponses """Handler for /v1/responses requests""" from __future__ import annotations import asyncio import json import logging import time from contextlib import AsyncExitStack from http import HTTPStatus from typing import TYPE_CHECKING, Any, ...
2,596
111,437
sglang
python/sglang/srt/entrypoints/openai/encoding_dsv4.py
.py
# Adapted from the DeepSeek-V4 release reference implementation. """ DeepSeek-V4 Encoding A self-contained implementation for encoding/decoding DeepSeek-V4 chat messages with tool calling, thinking mode, and quick instruction task support. """ import copy import json import re from typing import Any, Dict, List, Opti...
887
31,320
sglang
python/sglang/srt/entrypoints/openai/serving_embedding.py
.py
from __future__ import annotations import base64 import struct from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union import jinja2 from fastapi import Request from fastapi.responses import ORJSONResponse from sglang.srt.entrypoints.openai.protocol import ( EmbeddingObject, EmbeddingRequest, ...
309
12,246
sglang
python/sglang/srt/entrypoints/openai/serving_transcription.py
.py
# Copyright 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, so...
817
34,441
sglang
python/sglang/srt/entrypoints/openai/protocol.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,042
70,212
sglang
python/sglang/srt/entrypoints/openai/serving_classify.py
.py
from __future__ import annotations import logging import time import uuid from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union import torch import torch.nn.functional as F from fastapi import Request from fastapi.responses import ORJSONResponse from sglang.srt.entrypoints.openai.protocol import ( C...
205
7,134
sglang
python/sglang/srt/entrypoints/openai/chat_encoding.py
.py
"""Single home for the chat-encoding dispatch. Which encoder turns chat messages into prompt tokens is a property of the model, so the serving path and offline tools (benchmarks, evals) must resolve it here instead of re-deriving it from model architectures themselves. """ from __future__ import annotations import a...
197
6,452
sglang
python/sglang/srt/entrypoints/openai/serving_base.py
.py
from __future__ import annotations import json import logging import uuid from abc import ABC, abstractmethod from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Union import orjson from fastapi import HTTPException, Request from fastapi.responses import ORJSONResponse, StreamingResponse from sglang.srt.en...
294
10,920
sglang
python/sglang/srt/entrypoints/openai/serving_chat.py
.py
from __future__ import annotations import copy import json import logging import math import time import uuid from enum import Enum from http import HTTPStatus from typing import TYPE_CHECKING, Any, AsyncGenerator, Dict, List, Optional, Union class ThinkingMode(str, Enum): """Mode for message encoding - chat vs ...
2,584
108,568