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/configs/kimi_k3.py | .py | from transformers.configuration_utils import PretrainedConfig
from sglang.srt.configs.kimi_linear import KimiLinearConfig
class KimiK3VisionConfig(PretrainedConfig):
model_type = "kimi_k3_vision"
def __init__(
self,
patch_size: int = 14,
init_pos_emb_height: int = 64,
init_po... | 125 | 4,665 |
sglang | python/sglang/srt/configs/linear_attn_model_registry.py | .py | """Registry for linear attention hybrid models (softmax + linear attention).
External models can register themselves without modifying SGLang core files:
from sglang.srt.configs.linear_attn_model_registry import (
register_linear_attn_model, LinearAttnModelSpec,
)
register_linear_attn_model(Linea... | 78 | 2,615 |
sglang | python/sglang/srt/configs/interns2_mobius.py | .py | from typing import ClassVar
from sglang.srt.configs.qwen3_5 import (
Qwen3_5MoeConfig,
Qwen3_5MoeTextConfig,
Qwen3_5MoeVisionConfig,
)
class InternS2MobiusVisionConfig(Qwen3_5MoeVisionConfig):
model_type = "interns2_mobius"
def __init__(self, **kwargs):
super().__init__(**kwargs)
class... | 55 | 1,767 |
sglang | python/sglang/srt/configs/kimi_k25.py | .py | """
Kimi K25 Model Configuration.
"""
from transformers import DeepseekV3Config
from transformers.configuration_utils import PretrainedConfig
class KimiK25VisionConfig(PretrainedConfig):
"""Vision configuration for K2-VL (vision tower + mm projector).
Args:
Vision Tower Parameters:
patch... | 172 | 6,929 |
sglang | python/sglang/srt/compilation/compilation_config.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.10.0/vllm/compilation/compilation_config.py
from typing import Callable, List, Optional
SPLIT_OPS = []
def register_split_op(op_name: Optional[str] =... | 62 | 1,889 |
sglang | python/sglang/srt/compilation/cuda_piecewise_backend.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.10.0/vllm/compilation/cuda_piecewise_backend.py
import dataclasses
import logging
from contextlib import ExitStack
from typing import Any, Callable, Opt... | 223 | 9,501 |
sglang | python/sglang/srt/compilation/compile.py | .py | import inspect
import logging
import os
import sys
import types
from dataclasses import dataclass
from typing import Any, Callable, Optional, Union
import torch
from sglang.srt.compilation.compilation_config import CompilationConfig
from sglang.srt.model_executor.runner_backend_utils.tc_piecewise_cuda_graph import (
... | 243 | 8,699 |
sglang | python/sglang/srt/compilation/weak_ref_tensor.py | .py | from typing import Any, Union
import torch
from sglang.srt.utils.common import is_cuda, is_hip, is_musa, is_npu, is_xpu
if is_cuda() or is_hip() or is_musa() or is_xpu():
from sgl_kernel import weak_ref_tensor
elif is_npu():
from torch_npu._C import _weak_ref_tensor as weak_ref_tensor
else:
raise NotImpl... | 31 | 1,013 |
sglang | python/sglang/srt/compilation/fix_functionalization.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.10.0/vllm/compilation/fix_functionalization.py
import logging
import operator
from collections.abc import Iterable
from typing import Optional, Union
i... | 137 | 5,263 |
sglang | python/sglang/srt/compilation/compiler_interface.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.10.0/vllm/compilation/compiler_interface.py
import contextlib
import copy
import hashlib
import os
from contextlib import ExitStack
from typing import A... | 511 | 19,931 |
sglang | python/sglang/srt/compilation/pass_manager.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.10.0/vllm/compilation/pass_manager.py
import logging
from torch import fx as fx
from sglang.srt.compilation.fix_functionalization import FixFunctional... | 69 | 2,320 |
sglang | python/sglang/srt/compilation/inductor_pass.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.10.0/vllm/compilation/inductor_pass.py
import hashlib
import inspect
import json
import logging
import time
import types
from contextlib import contextm... | 143 | 4,148 |
sglang | python/sglang/srt/compilation/compile_phase.py | .py | """torch.compile-internal phase markers used by the tc_piecewise backend.
Two pieces of state, both private to the torch.compile path (the
``cuda_piecewise_backend`` FX backend and the runner that drives it):
* ``_in_torch_compile_warmup`` — true during the warmup-compile loop
where we run the compiled callable to ... | 58 | 1,727 |
sglang | python/sglang/srt/compilation/npu_piecewise_backend.py | .py | from contextlib import ExitStack
from typing import Any, Callable
from unittest.mock import patch
import torch
import torch.fx as fx
from sglang.srt.compilation.compilation_config import CompilationConfig
from sglang.srt.compilation.compilation_counter import compilation_counter
from sglang.srt.compilation.cuda_piece... | 110 | 4,406 |
sglang | python/sglang/srt/compilation/compilation_counter.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.10.0/vllm/compilation/compilation_counter.py
import copy
import dataclasses
from contextlib import contextmanager
@dataclasses.dataclass
class Compila... | 50 | 1,730 |
sglang | python/sglang/srt/compilation/torch_compile_decoration.py | .py | """torch.compile decoration helpers used by the decode-Full path under
``--enable-torch-compile``.
``patch_model`` wraps the model forward with ``torch.compile`` for batch
sizes that fall in the compile bucket list and returns the raw forward
otherwise. ``set_torch_compile_config`` flips the inductor/dynamo config
fla... | 84 | 2,837 |
sglang | python/sglang/srt/compilation/backend.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.10.0/vllm/compilation/backend.py
import ast
import dataclasses
import logging
import os
import pprint
import time
from collections.abc import Sequence
... | 476 | 15,602 |
sglang | python/sglang/srt/compilation/xpu_piecewise_backend.py | .py | from contextlib import ExitStack
from typing import Any
from unittest.mock import patch
import torch
from sglang.srt.compilation.compilation_counter import compilation_counter
from sglang.srt.compilation.compile_phase import (
get_pcg_capture_stream,
is_in_torch_compile_warmup,
)
from sglang.srt.compilation.c... | 113 | 4,472 |
sglang | python/sglang/srt/compilation/fx_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.10.0/vllm/compilation/fx_utils.py
import operator
from collections.abc import Iterable, Iterator
from typing import Optional
from torch import fx
from ... | 86 | 2,980 |
sglang | python/sglang/srt/plugins/__init__.py | .py | """
SGLang Unified Plugin Framework.
Supports two types of plugins via setuptools entry_points:
1. Hardware Platform Plugins (sglang.srt.platforms) - register custom hardware platforms
2. General Plugins (sglang.srt.plugins) - inject hooks into functions/methods, replace classes, etc.
Plugins are discovered automatic... | 142 | 5,037 |
sglang | python/sglang/srt/plugins/hook_registry.py | .py | """
Hook registry for SGLang plugins.
Provides before/after/around/replace hooks that can be applied to any
function, method, or class in the sglang codebase. Hooks are registered
during plugin loading and applied before the engine starts.
Usage:
from sglang.srt.plugins.hook_registry import HookRegistry, HookType... | 431 | 16,278 |
sglang | python/sglang/srt/lora/utils.py | .py | from dataclasses import dataclass
from enum import Enum
from typing import Iterable, List, Optional, Set, Tuple, Union
import torch
from sglang.srt.model_executor.forward_batch_info import ForwardBatch
from sglang.srt.utils.hf_transformers_utils import AutoConfig
@dataclass
class MoELoRABatchInfo:
# Per-request... | 621 | 22,750 |
sglang | python/sglang/srt/lora/lora_moe_runners.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 writin... | 557 | 19,588 |
sglang | python/sglang/srt/lora/lora_drainer.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... | 192 | 6,904 |
sglang | python/sglang/srt/lora/mem_pool.py | .py | import logging
import re
from typing import (
Callable,
Dict,
Iterable,
Iterator,
List,
Optional,
Set,
Tuple,
Union,
overload,
)
import torch
from sglang.srt.distributed import (
divide,
get_pp_group,
)
from sglang.srt.environ import envs
from sglang.srt.lora.eviction_p... | 1,540 | 67,841 |
sglang | python/sglang/srt/lora/lora.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... | 540 | 23,879 |
sglang | python/sglang/srt/lora/lora_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... | 109 | 3,988 |
sglang | python/sglang/srt/lora/lora_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... | 1,043 | 46,213 |
sglang | python/sglang/srt/lora/lora_registry.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... | 264 | 10,391 |
sglang | python/sglang/srt/lora/deepseek_mla_correction.py | .py | """LoRA correction for absorbed-MLA ``kv_b_proj``.
The absorbed-MLA path in ``DeepseekV2AttentionMLA`` bypasses
``kv_b_proj.forward()`` and folds the K/V contribution into two BMMs against
the pre-computed ``w_kc`` / ``w_vc`` weights, so a standard
``ColumnParallelLinearWithLoRA`` wrapper would never see the activatio... | 116 | 4,202 |
sglang | python/sglang/srt/lora/lora_moe_runner_marlin.py | .py | """Marlin MoE runner core with hook support for LoRA injection.
Uses Marlin int4/int8 kernels for the base MoE projections.
LoRA deltas are injected via hooks.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
import torch
from sglang.srt.layers.moe.moe_runner.base import MoeRunnerConfig
from... | 214 | 7,534 |
sglang | python/sglang/srt/lora/eviction_policy.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... | 140 | 5,315 |
sglang | python/sglang/srt/lora/layers.py | .py | from typing import Dict, Optional, Union
import torch
import torch.nn.functional as F
from torch import nn
from sglang.srt.distributed import (
split_tensor_along_last_dim,
tensor_model_parallel_all_gather,
tensor_model_parallel_all_reduce,
)
from sglang.srt.environ import envs
from sglang.srt.layers.line... | 1,325 | 52,281 |
sglang | python/sglang/srt/lora/lora_overlap_loader.py | .py | import logging
from enum import Enum, auto
from typing import Dict, Optional
import torch
from torch.cuda import Event as CudaEvent
from torch.cuda import Stream as CudaStream
from torch.cuda import StreamContext as CudaStreamContext
from sglang.srt.lora.lora_manager import LoRAManager
logger = logging.getLogger(__n... | 96 | 3,555 |
sglang | python/sglang/srt/lora/trtllm_lora_temp/environ.py | .py | """Local env registry for the experimental TRT-LLM LoRA fast path.
Every flag here is gated by the single global master switch
``SGLANG_EXPERIMENTAL_LORA_OPTI`` (defined in ``sglang.srt.environ``). When it is
off, every local flag reads ``False``.
Fine-grained switches live here beside their consumers.
Default polic... | 128 | 5,447 |
sglang | python/sglang/srt/lora/trtllm_lora_temp/specialized_expand.py | .py | """Rank-specialized LoRA-B expand for virtual-expert LoRA.
The kernel here was originally a chunk in ``lora/triton_ops/virtual_experts.py``.
It is rank-specialized: the ``R`` dimension (LoRA rank) is a Triton
``constexpr``, so each rank value used at runtime gets its own JIT-compiled
specialization.
Called from :mod:... | 242 | 9,329 |
sglang | python/sglang/srt/lora/trtllm_lora_temp/shared_add_overlap.py | .py | """Overlap the MoE shared-expert add with the down-LoRA shrink (gemm A).
In the Qwen dual-stream decode path (``Qwen2MoeSparseMoeBlock.forward_normal_dual_stream``)
the shared expert runs on the main stream while the routed experts + trtllm LoRA
MoE run on the alt stream; ``final_hidden_states += shared_output`` then ... | 124 | 5,594 |
sglang | python/sglang/srt/lora/trtllm_lora_temp/attention.py | .py | """Two-stream attention LoRA forward implementations (O7 + O8).
These are monkey-patched onto :class:`QKVParallelLinearWithLoRA` and
:class:`RowParallelLinearWithLoRA` by
:func:`sglang.srt.lora.trtllm_lora_temp.install_two_stream_overrides` when
``SGLANG_LORA_TWO_STREAM=1``. The saved-original forward methods are
pres... | 283 | 10,927 |
sglang | python/sglang/srt/lora/trtllm_lora_temp/sgl_fp8_moe.py | .py | """FP8 MoE dispatch using LoRA-capable block-scale wrappers."""
from __future__ import annotations
from typing import TYPE_CHECKING
import torch
if TYPE_CHECKING:
from sglang.srt.layers.moe.moe_runner.base import MoeRunnerConfig
from sglang.srt.layers.moe.moe_runner.flashinfer_trtllm import (
FlashI... | 246 | 10,520 |
sglang | python/sglang/srt/lora/trtllm_lora_temp/__init__.py | .py | """Two-stream LoRA overlap (O1 + O7 + O8 + O9) — installed as a monkey-patch.
Activates when env ``SGLANG_LORA_TWO_STREAM=1``. Triggered exactly once via
:func:`install_two_stream_overrides` (called at end of ``sglang/srt/lora/layers.py``).
When enabled, these call sites are redirected to side-stream-overlapped versi... | 233 | 9,974 |
sglang | python/sglang/srt/lora/trtllm_lora_temp/experimental_sgl_trtllm_moe.py | .py | from typing import Optional
import torch
from sglang.srt.utils.custom_op import register_custom_op
def _fake_fp8_block_scale_moe(
routing_logits: torch.Tensor,
routing_bias: Optional[torch.Tensor],
hidden_states: torch.Tensor,
hidden_states_scale: torch.Tensor,
gemm1_weights: torch.Tensor,
g... | 204 | 7,115 |
sglang | python/sglang/srt/lora/trtllm_lora_temp/lora_dispatch.py | .py | """experimental_sgl_trtllm MoE LoRA dispatch (original single-stream).
This is the LoRA-enabled fused-experts path added by the trtllm-lora work — it
was originally a function in ``layers/moe/moe_runner/flashinfer_trtllm.py`` and
is now hosted here so that file holds only a re-export. The function name
remains ``fused... | 620 | 26,150 |
sglang | python/sglang/srt/lora/trtllm_lora_temp/lora_layer.py | .py | """experimental_sgl_trtllm-specific bits of ``FusedMoEWithLoRA``.
This file holds the two trtllm-specific code blocks that used to be inlined
inside the ``FusedMoEWithLoRA`` class in ``lora/layers.py``:
- :func:`init_experimental_sgl_trtllm_lora` — builds the FP8 block-scale
``FlashInferTrtllmFp8MoeQuantInfo`` ... | 215 | 9,957 |
sglang | python/sglang/srt/lora/trtllm_lora_temp/moe_overlap.py | .py | """Two-stream MoE LoRA dispatch (O1).
Monkey-patches ``fused_experts_none_to_experimental_sgl_trtllm_fp8_lora`` in
``layers/moe/moe_runner/flashinfer_trtllm.py`` (when
``SGLANG_LORA_TWO_STREAM=1``) so the gate_up LoRA shrink+expand runs on a
side stream concurrent with the main-stream FP8 quant.
Batches that don't qu... | 787 | 35,073 |
sglang | python/sglang/srt/lora/trtllm_lora_temp/deepseek_mla_correction.py | .py | """LoRA correction for absorbed-MLA ``kv_b_proj``.
The absorbed-MLA path in ``DeepseekV2AttentionMLA`` bypasses
``kv_b_proj.forward()`` and folds the K/V contribution into two BMMs against
the pre-computed ``w_kc`` / ``w_vc`` weights, so a standard
``ColumnParallelLinearWithLoRA`` wrapper would never see the activatio... | 239 | 9,739 |
sglang | python/sglang/srt/lora/trtllm_lora_temp/inkling_dense.py | .py | """Temporary optimized shared-sink LoRA execution for Inkling."""
from __future__ import annotations
import torch
from sglang.srt.environ import envs
from sglang.srt.models.inkling_common.kernels.comm import symm_mem_all_reduce
def allow_inkling_moe_two_stream(
shared_experts, routed_experts, num_tokens: int
)... | 256 | 8,848 |
sglang | python/sglang/srt/lora/trtllm_lora_temp/sgl_backend.py | .py | """Registers the ``experimental_sgl_trtllm`` MoE fused-func.
``MoeRunner.__init__`` requires a registered fused-func at CONSTRUCTION time even
for the LoRA case, because LoRA is attached *after* the MoE layer is built (so
``lora_enabled`` is False inside ``MoeRunner.__init__``). At run time the runner
skips this for t... | 27 | 1,025 |
sglang | python/sglang/srt/lora/trtllm_lora_temp/merged_column.py | .py | """Two-stream MergedColumnParallelLinear LoRA forward (O9).
Monkey-patched onto :class:`MergedColumnParallelLinearWithLoRA` by
:func:`sglang.srt.lora.trtllm_lora_temp.install_two_stream_overrides` when
``SGLANG_LORA_TWO_STREAM=1``. Covers the merged-column LoRA modules not handled
by O7 (QKV) / O8 (o_proj) / O1 (MoE e... | 95 | 3,688 |
sglang | python/sglang/srt/lora/torch_ops/lora_ops.py | .py | from typing import Optional
import torch
def sgemm_lora_a_embedding_fwd(
inputs: torch.Tensor,
weights: torch.Tensor,
weight_indices: torch.Tensor,
seg_len_tensor: torch.Tensor,
lora_ranks: torch.Tensor,
scaling_tensor: torch.Tensor,
vocab_size: int,
) -> torch.Tensor:
total_seq_len =... | 147 | 4,281 |
sglang | python/sglang/srt/lora/torch_ops/__init__.py | .py | from typing import Optional
import torch
from sglang.srt.lora.utils import LoRABatchInfo
from .graph_lora_ops import (
sgemm_lora_a_embedding_graph_fwd,
sgemm_lora_a_graph_fwd,
sgemm_lora_b_graph_fwd,
)
from .lora_ops import sgemm_lora_a_embedding_fwd as sgemm_lora_a_embedding_control_fwd
from .lora_ops ... | 110 | 2,807 |
sglang | python/sglang/srt/lora/torch_ops/graph_lora_ops.py | .py | from typing import Optional
import torch
import torch.nn.functional as F
def sgemm_lora_a_embedding_graph_fwd(
inputs: torch.Tensor,
weights: torch.Tensor,
weight_indices: torch.Tensor,
seg_len_tensor: torch.Tensor,
scaling_tensor: torch.Tensor,
vocab_size: int,
) -> torch.Tensor:
total_s... | 121 | 3,619 |
sglang | python/sglang/srt/lora/backend/triton_backend.py | .py | import dataclasses
from typing import List, Optional, Tuple
import torch
from sglang.kernels.ops.gemm.embedding_lora_a import embedding_lora_a_fwd
from sglang.kernels.ops.gemm.gate_up_lora_b import gate_up_lora_b_fwd
from sglang.kernels.ops.gemm.qkv_lora_b import qkv_lora_b_fwd
from sglang.kernels.ops.gemm.sgemm_lora... | 430 | 16,374 |
sglang | python/sglang/srt/lora/backend/torch_backend.py | .py | from dataclasses import dataclass
from typing import Optional
import torch
from sglang.srt.lora.backend.base_backend import BaseLoRABackend
from sglang.srt.lora.torch_ops import (
sgemm_lora_a_embedding_fwd,
sgemm_lora_a_fwd,
sgemm_lora_b_fwd,
)
from sglang.srt.lora.utils import LoRABatchInfo, generate_se... | 304 | 10,236 |
sglang | python/sglang/srt/lora/backend/lmhead_mixing.py | .py | from typing import List, Optional, Tuple
from sglang.srt.environ import envs
from sglang.srt.lora.utils import LoRABatchInfo, build_lm_head_pass_segments
from sglang.srt.model_executor.forward_batch_info import ForwardBatch
class LoRABackendLmHeadMixing:
def init_lm_head_config(self):
self.lm_head_batch_... | 65 | 2,606 |
sglang | python/sglang/srt/lora/backend/base_backend.py | .py | from typing import Optional, Tuple, Union
import torch
import triton
import triton.language as tl
from sglang.srt.lora.backend.lmhead_mixing import LoRABackendLmHeadMixing
from sglang.srt.lora.utils import LoRABatchInfo, MoELoRABatchInfo
from sglang.srt.model_executor.forward_batch_info import ForwardBatch
class Ba... | 472 | 17,640 |
sglang | python/sglang/srt/lora/backend/ascend_backend.py | .py | import torch
from sglang.srt.lora.backend.base_backend import BaseLoRABackend
from sglang.srt.lora.utils import LoRABatchInfo
from sglang.srt.model_executor.forward_batch_info import ForwardBatch
from sglang.srt.utils import is_npu
if is_npu():
import sgl_kernel_npu # noqa: F401
import torch_npu # noqa: F40... | 281 | 9,106 |
sglang | python/sglang/srt/lora/backend/chunked_backend.py | .py | import dataclasses
from typing import List, Optional, Tuple
import torch
from sglang.kernels.ops.gemm.chunked_embedding_lora_a import (
chunked_embedding_lora_a_forward,
)
from sglang.kernels.ops.gemm.chunked_sgmv_expand import chunked_sgmv_lora_expand_forward
from sglang.kernels.ops.gemm.chunked_sgmv_shrink impo... | 567 | 22,552 |
sglang | python/sglang/srt/lora/backend/lora_registry.py | .py | import logging
from typing import Type
from sglang.srt.lora.backend.base_backend import BaseLoRABackend
logger = logging.getLogger(__name__)
LORA_SUPPORTED_BACKENDS = {}
def register_lora_backend(name):
def decorator(fn):
LORA_SUPPORTED_BACKENDS[name] = fn
return fn
return decorator
@reg... | 62 | 1,512 |
sglang | python/sglang/srt/lora/marlin_lora_temp/moe_runner.py | .py | """Experimental Marlin MoE-LoRA execution."""
from __future__ import annotations
from typing import TYPE_CHECKING
import torch
from sglang.srt.lora.marlin_lora_temp.policy import (
use_post_reduce_down_delta,
)
from sglang.srt.utils import is_cuda
if TYPE_CHECKING:
from sglang.srt.layers.moe.moe_runner.bas... | 877 | 34,266 |
sglang | python/sglang/srt/lora/marlin_lora_temp/policy.py | .py | """Static correctness policy for the experimental Marlin MoE-LoRA path.
Keep these checks free of CUDA imports so they can be covered by CPU-only unit
tests. The backend deliberately supports a narrow configuration: widening it
requires implementing the corresponding Marlin activation/EP semantics first.
"""
from __... | 110 | 4,214 |
sglang | python/sglang/srt/lora/marlin_lora_temp/activation.py | .py | """Fused ``silu(gate + Δgate) * (up + Δup)`` for the experimental marlin MoE-LoRA path.
Replaces the stock sequence (in-place LoRA delta add over ``[T, 2N]`` +
``silu_and_mul``) with a single kernel: one read of the GEMM output, one read
of the delta, one write of the activation — and it lets the delta live in its
own... | 63 | 2,012 |
sglang | python/sglang/srt/lora/marlin_lora_temp/lora_layer.py | .py | """LoRA hooks for the experimental Marlin MoE runner."""
from __future__ import annotations
from typing import TYPE_CHECKING
import torch
from sglang.srt.lora.marlin_lora_temp.policy import (
validate_experimental_sgl_marlin_contract,
)
if TYPE_CHECKING:
from sglang.srt.layers.moe.token_dispatcher import S... | 65 | 2,020 |
sglang | python/sglang/srt/lora/marlin_lora_temp/direct_decode.py | .py | """No-sort B200 decode kernels for Inkling routed MoE LoRA.
The contract is BF16 CUDA, M<=32, top-k 6, rank 32, up to four slots, TP-local
intermediate 384 or 768, and non-EP expert IDs in ``[0, E)``.
"""
from __future__ import annotations
import torch
import triton
import triton.language as tl
ROUTER_TOPK = 6
RANK... | 243 | 7,061 |
sglang | python/sglang/srt/lora/marlin_lora_temp/sgl_backend.py | .py | """Register the no-LoRA alias for ``experimental_sgl_marlin``."""
from sglang.srt.layers.moe.moe_runner.base import register_fused_func
@register_fused_func("none", "experimental_sgl_marlin")
def fused_experts_none_to_experimental_sgl_marlin(
dispatch_output, quant_info, runner_config
):
from sglang.srt.laye... | 13 | 466 |
sglang | python/sglang/srt/lora/marlin_lora_temp/shared_outer.py | .py | """Shared-outer reduction primitives for Marlin MoE LoRA.
For Inkling adapters, gate/up LoRA-A and down LoRA-B are shared by every
routed expert. The gate shrink can therefore run once per token, while the
down rank vectors can be gamma-weighted and summed before the shared expand.
"""
from __future__ import annotat... | 468 | 14,571 |
sglang | python/sglang/srt/parser/harmony_parser.py | .py | import re
from dataclasses import dataclass
from typing import Iterator, List, Optional, Tuple
@dataclass
class Event:
"""Represents a parsed event from the Harmony stream."""
event_type: str
content: str
raw_text: str = None # Original text including structural markers
@dataclass
class Token:
... | 589 | 23,227 |
sglang | python/sglang/srt/parser/inkling_tokenizer.py | .py | from __future__ import annotations
from collections.abc import Mapping
from dataclasses import dataclass
from typing import Any
END_OF_TEXT = "<|endoftext|>"
MESSAGE_USER = "<|message_user|>"
MESSAGE_MODEL = "<|message_model|>"
MESSAGE_SYSTEM = "<|message_system|>"
MESSAGE_TOOL = "<|message_tool|>"
CONTENT_TEXT = "<|... | 106 | 3,445 |
sglang | python/sglang/srt/parser/jinja_template_utils.py | .py | """Template utilities for Jinja template processing.
This module provides utilities for analyzing and processing Jinja chat templates,
including content format detection and message processing.
"""
import logging
import jinja2
import transformers.utils.chat_template_utils as hf_chat_utils
from sglang.srt.utils impo... | 241 | 10,120 |
sglang | python/sglang/srt/parser/template_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... | 389 | 15,271 |
sglang | python/sglang/srt/parser/inkling_renderer.py | .py | from __future__ import annotations
import json
import math
from collections.abc import Mapping, Sequence
from typing import Any, Protocol
from sglang.srt.parser.inkling_tokenizer import (
AUDIO_END,
AUDIO_TOKEN_ID,
CONTENT_AUDIO_INPUT,
CONTENT_IMAGE,
CONTENT_INVOKE_TOOL_JSON,
CONTENT_MODEL_END... | 333 | 12,208 |
sglang | python/sglang/srt/parser/code_completion_parser.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... | 139 | 4,042 |
sglang | python/sglang/srt/parser/reasoning_parser.py | .py | import inspect
import re
from typing import Dict, List, Optional, Tuple, Type
from sglang.srt.entrypoints.openai.encoding_dsv4 import dsml_token as dsv4_dsml_token
from sglang.srt.entrypoints.openai.encoding_dsv4 import eos_token as dsv4_eos_token
from sglang.srt.entrypoints.openai.encoding_dsv4 import (
thinking_... | 1,994 | 80,072 |
sglang | python/sglang/srt/parser/conversation.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,238 | 45,713 |
sglang | python/sglang/srt/parser/template_detection.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... | 782 | 28,914 |
sglang | python/sglang/srt/kv_canary/expected_inputs.py | .py | from __future__ import annotations
from dataclasses import dataclass
import torch
@dataclass(frozen=True, slots=True, kw_only=True)
class ExpectedInputs:
tokens: torch.Tensor
positions: torch.Tensor
@classmethod
def allocate(cls, *, capacity: int, device: torch.device) -> ExpectedInputs:
re... | 25 | 689 |
sglang | python/sglang/srt/kv_canary/state.py | .py | from __future__ import annotations
from dataclasses import dataclass
from typing import Optional
import torch
from sglang.kernels.ops.kv_canary.consts import VIOLATION_FIELDS
from sglang.srt.kv_canary.config import CanaryConfig
@dataclass(frozen=True, slots=True, kw_only=True)
class ViolationLog:
"""Global vio... | 136 | 6,745 |
sglang | python/sglang/srt/kv_canary/endpoint.py | .py | from __future__ import annotations
from dataclasses import dataclass
from typing import Optional
import torch
from sglang.kernels.ops.kv_canary.consts import (
RealKvHashMode,
)
from sglang.kernels.ops.kv_canary.verify import (
CanaryLaunchTag,
RealKvSource,
VerifyOrWriteContext,
VerifyPlan,
... | 221 | 7,269 |
sglang | python/sglang/srt/kv_canary/capacities.py | .py | from __future__ import annotations
import math
from dataclasses import dataclass
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from sglang.srt.server_args import ServerArgs
@dataclass(frozen=True, slots=True, kw_only=True)
class CanaryLaunchCapacities:
"""Pre-allocation sizes for the per-forward tensor... | 118 | 4,866 |
sglang | python/sglang/srt/kv_canary/plan_input.py | .py | from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
import torch
if TYPE_CHECKING:
from sglang.srt.model_executor.forward_batch_info import ForwardBatch
@dataclass(frozen=True, slots=True, kw_only=True)
class PlanInput:
"""Pre-staged input to launch_canary_... | 141 | 6,566 |
sglang | python/sglang/srt/kv_canary/radix_cache_walker.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING, Any
import torch
from sglang.srt.mem_cache.radix_cache import RadixCache
from sglang.srt.mem_cache.swa_radix_cache import SWARadixCache
from sglang.srt.mem_cache.unified_cache.unified_tree_core_interface import (
RadixCacheWalkResult,
)
from sg... | 153 | 4,712 |
sglang | python/sglang/srt/kv_canary/buffer_group.py | .py | from __future__ import annotations
from dataclasses import dataclass
from enum import IntEnum
from typing import Optional
import torch
from sglang.kernels.ops.kv_canary.verify import RealKvSource
class PoolKind(IntEnum):
"""Which attention regime a canary group belongs to.
- ``FULL`` covers ``[0, K_req)``... | 68 | 3,009 |
sglang | python/sglang/srt/kv_canary/req_to_expected_token_ids_manager.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING, Optional
import torch
from sglang.kernels.ops.kv_canary.scatter_req_token_ids import (
launch_scatter_req_token_ids_kernel,
)
from sglang.srt.utils.common import flatten_arrays_to_int64_tensor
if TYPE_CHECKING:
from sglang.srt.managers.sch... | 85 | 3,103 |
sglang | python/sglang/srt/kv_canary/api.py | .py | from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any, Callable, Optional
import torch
from sglang.srt.kv_canary.capacities import CanaryLaunchCapacities
from sglang.srt.kv_canary.config import CanaryConfig, CanaryMode
from sglang.srt.kv_canary.perturb.config import PerturbConfig
fr... | 132 | 5,473 |
sglang | python/sglang/srt/kv_canary/config.py | .py | from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
from typing import TYPE_CHECKING
from sglang.kernels.ops.kv_canary.consts import (
RealKvHashMode,
)
from sglang.srt.environ import envs
if TYPE_CHECKING:
from sglang.srt.server_args import ServerArgs
class CanaryMod... | 81 | 3,884 |
sglang | python/sglang/srt/kv_canary/sweep_plan_builder.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING, Optional
import torch
from sglang.kernels.ops.kv_canary.verify import VerifyPlan
from sglang.srt.kv_canary.radix_cache_walker import walk_radix_cache_for_canary
if TYPE_CHECKING:
from sglang.srt.mem_cache.base_prefix_cache import BasePrefixCac... | 75 | 2,713 |
sglang | python/sglang/srt/kv_canary/single_forward_manager/manager.py | .py | from __future__ import annotations
from dataclasses import dataclass
from enum import IntEnum
from typing import TYPE_CHECKING, Optional
import torch
from sglang.kernels.ops.kv_canary.verify import CanaryLaunchTag, VerifyPlan
from sglang.kernels.ops.kv_canary.write import WritePlan
from sglang.srt.kv_canary.buffer_g... | 326 | 12,678 |
sglang | python/sglang/srt/kv_canary/single_forward_manager/data.py | .py | from __future__ import annotations
from dataclasses import dataclass
import torch
@dataclass(frozen=True, slots=True, kw_only=True)
class PostOpsInsideGraphOutputBuffer:
verify_plan_enable: torch.Tensor
kernel_run_counters: torch.Tensor
slot_run_counters: torch.Tensor
violation_write_index: torch.Te... | 61 | 2,094 |
sglang | python/sglang/srt/kv_canary/perturb/utils.py | .py | from __future__ import annotations
import logging
import random
from collections.abc import Callable
from typing import TYPE_CHECKING, Optional
import torch
from sglang.kernels.ops.kv_canary.verify import RealKvSource
from sglang.srt.kv_canary.buffer_group import CanaryBufferGroup, PoolKind
from sglang.srt.kv_canary... | 202 | 6,397 |
sglang | python/sglang/srt/kv_canary/perturb/manager.py | .py | from __future__ import annotations
from collections.abc import Callable
from typing import TYPE_CHECKING, Optional
from sglang.srt.kv_canary.buffer_group import CanaryBufferGroup
from sglang.srt.kv_canary.perturb import (
real_kv_post_forward,
real_kv_unused_cache,
real_kv_used,
req_to_token,
)
from s... | 108 | 3,871 |
sglang | python/sglang/srt/kv_canary/perturb/real_kv_post_forward.py | .py | """Pick a random real-KV source byte derived from out_cache_loc and flip it
in-place AFTER the TAIL kernel has captured its canary hash.
The slot id is taken from maybe_inaccurate_forward_batch.out_cache_loc and used
only as a lookup into the target group's real-KV source buffer; the actual flip
happens inside that bu... | 79 | 2,546 |
sglang | python/sglang/srt/kv_canary/perturb/slot_picker.py | .py | from __future__ import annotations
import random
from dataclasses import dataclass
from typing import TYPE_CHECKING, Optional
import torch
if TYPE_CHECKING:
from sglang.srt.mem_cache.memory_pool import ReqToTokenPool
from sglang.srt.model_executor.forward_batch_info import ForwardBatch
@dataclass(frozen=Tr... | 101 | 3,488 |
sglang | python/sglang/srt/kv_canary/perturb/real_kv_unused_cache.py | .py | """Flip the first byte of a radix-cached but currently-unused (orphan) slot.
Detection should come from sweep (per-forward verify won't even look at this
slot). Designed to surface bugs where cached KV is silently corrupted and
sleeps until much later when a prefix happens to match.
"""
from __future__ import annotat... | 163 | 4,853 |
sglang | python/sglang/srt/kv_canary/perturb/next_token_swap.py | .py | """Swap two requests' sampled next tokens at the sampler exit.
KV path is untouched, so kv_canary KV-side fail_reasons stay silent. The
token-oracle input check downstream MUST report fail_reason=write_token — this
validates that the input-check link is genuinely active.
"""
from __future__ import annotations
import... | 84 | 2,065 |
sglang | python/sglang/srt/kv_canary/perturb/req_to_token.py | .py | """Flip the req_to_token pointer of a currently-active req.
The hook picks a random (req_pool_idx, position, value) from active reqs,
filtering out entries whose value is 0 (so slot 0 is excluded), and overwrites
req_to_token[req_pool_idx, position] with another active req's slot id.
KV bytes are not touched.
"""
fro... | 76 | 2,569 |
sglang | python/sglang/srt/kv_canary/perturb/config.py | .py | from __future__ import annotations
from dataclasses import dataclass
from enum import IntEnum
from sglang.srt.environ import envs
from sglang.srt.kv_canary.buffer_group import PoolKind
class TargetGroupKind(IntEnum):
FULL = PoolKind.FULL.value
SWA = PoolKind.SWA.value
def __str__(self) -> str:
... | 95 | 3,090 |
sglang | python/sglang/srt/kv_canary/perturb/real_kv_used.py | .py | """Flip the first byte of a slot currently being used by an active req.
Detection should come from per-forward verify (HEAD/TAIL kernel), NOT from
sweep. Designed to surface CUDA-graph-idle-class bugs where production reads
a slot whose KV byte was silently overwritten.
"""
from __future__ import annotations
import ... | 135 | 4,064 |
sglang | python/sglang/srt/kv_canary/runner/enable_warner.py | .py | from __future__ import annotations
import logging
from typing import Optional
import torch
from sglang.srt.kv_canary.runner.future_tensor import DelayedDeviceHostHandler
logger = logging.getLogger(__name__)
class CanaryEnableWarner:
def __init__(
self, *, verify_capacity: int, d2h_stream: Optional[tor... | 36 | 1,163 |
sglang | python/sglang/srt/kv_canary/runner/health_checker.py | .py | from __future__ import annotations
import logging
from collections.abc import Callable
from typing import Optional
import torch
from sglang.kernels.ops.kv_canary.verify import CanaryLaunchTag
from sglang.srt.kv_canary.config import CanaryConfig
from sglang.srt.kv_canary.runner.future_tensor import DelayedDeviceHostH... | 82 | 3,070 |
sglang | python/sglang/srt/kv_canary/runner/swa_divergence.py | .py | from __future__ import annotations
import json
import logging
import re
from dataclasses import asdict, dataclass
from typing import TYPE_CHECKING, Any, Optional
import torch
from sglang.kernels.ops.kv_canary.verify import VerifyPlan
from sglang.srt.kv_canary.buffer_group import CanaryBufferGroup, PoolKind
from sgla... | 210 | 7,913 |
sglang | python/sglang/srt/kv_canary/runner/future_tensor.py | .py | from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import Any, Optional, Union
import torch
_PayloadDict = dict[str, Any]
_TensorOrDict = Union[torch.Tensor, _PayloadDict]
_DUMMY_DICT_KEY = "__dummy_key__"
@dataclass(slots=True, kw_only=Tru... | 125 | 4,193 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.