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/hardware_backend/musa/layers/utils/cp_utils.py | .py | from typing import TYPE_CHECKING, Callable
import torch
if TYPE_CHECKING:
from sglang.srt.hardware_backend.musa.attention.flashattention_backend import (
MusaFlashAttentionBackend,
)
from sglang.srt.model_executor.forward_batch_info import ForwardBatch
def musa_cp_attn_forward_extend(
musa_f... | 58 | 1,908 |
sglang | python/sglang/srt/hardware_backend/musa/utils/patch_torch.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... | 64 | 2,493 |
sglang | python/sglang/srt/hardware_backend/musa/kernels/topk.py | .py | from typing import (
Optional,
)
import torch
import triton
import triton.language as tl
@triton.jit
def tanh(x):
# Tanh is just a scaled sigmoid
return 2 * tl.sigmoid(2 * x) - 1
@triton.autotune(
configs=[
triton.Config({}, num_warps=1, num_stages=1),
triton.Config({}, num_warps=1,... | 301 | 9,259 |
sglang | python/sglang/srt/hardware_backend/musa/attention/__init__.py | .py | from .flashattention_backend import MusaFlashAttentionBackend
__all__ = ["MusaFlashAttentionBackend"]
| 4 | 103 |
sglang | python/sglang/srt/hardware_backend/musa/attention/flashattention_backend.py | .py | from __future__ import annotations
import threading
from typing import TYPE_CHECKING, Optional, Tuple, Union
import torch
from flash_attn_interface import flash_attn_varlen_func
from flash_attn_interface import flash_attn_with_kvcache as mate_flash_attn_with_kvcache
from flash_attn_interface import get_scheduler_meta... | 952 | 40,308 |
sglang | python/sglang/srt/hardware_backend/mlx/model_runner_stub.py | .py | """Lightweight ModelRunner stub for MLX on Apple Silicon.
Skips PyTorch weight loading. Creates only the CPU-side bookkeeping
(req_to_token_pool, token_to_kv_pool_allocator) the scheduler needs.
"""
import logging
from typing import Tuple
import torch
from sglang.srt.configs.hybrid_arch import mambaish_config
from... | 328 | 13,723 |
sglang | python/sglang/srt/hardware_backend/mlx/sampling.py | .py | """MLX-native in-graph sampling for the MLX backend.
Token selection (temperature / top-k / top-p / min-p / per-request seed)
built entirely from ``mx`` ops, so it lives inside the same lazy graph as
the forward pass. That is what lets sampling coexist with the overlap
scheduler: ``decode_batch_start_chained`` feeds ... | 415 | 15,306 |
sglang | python/sglang/srt/hardware_backend/mlx/profiler.py | .py | from __future__ import annotations
import gzip
import json
import logging
import os
import shutil
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, Optional
import torch
from sglang.srt.managers.io_struct import ProfileReqOutput
from sglang.srt.utils.tensor_brid... | 262 | 7,771 |
sglang | python/sglang/srt/hardware_backend/mlx/scheduler_mixin.py | .py | """MLX overlap scheduling mixin for the SGLang scheduler.
Provides ``event_loop_overlap_mlx``, which pipelines MLX forward
passes by keeping two in-flight lazy graphs queued on the GPU while
the scheduler runs its CPU-side bookkeeping on the tokens of the
older one. The lazy-graph primitives live in
``hardware_backen... | 281 | 12,996 |
sglang | python/sglang/srt/hardware_backend/mlx/parent_watchdog.py | .py | """Parent-death watchdog for MLX workers on Apple Silicon.
macOS has no ``PR_SET_PDEATHSIG`` equivalent, so the kernel will not signal a
worker process when its parent dies; the worker would be reparented to PID 1
and leak (holding GPU/host memory and ports). This module emulates PDEATHSIG
with a daemon thread that wa... | 61 | 2,240 |
sglang | python/sglang/srt/hardware_backend/mlx/model_runner.py | .py | """MLX model runner for Apple Silicon.
Slot allocation and radix-trie prefix matching are handled by the
scheduler (``TokenToKVPoolAllocator`` / ``RadixCache``). This runner
reads cached attention KV from ``MlxAttentionKVPool``, restores any
native auxiliary layer state, runs the forward pass, and writes the new
cach... | 1,706 | 70,290 |
sglang | python/sglang/srt/hardware_backend/mlx/tp_worker.py | .py | """MLX-specific TpModelWorker subclass for Apple Silicon.
Routes forward passes through the MLX model runner, bypassing PyTorch
MPS. A lightweight stub provides scheduler bookkeeping; the actual
attention KV data lives in MlxAttentionKVPool.
The worker also exposes an async (lazy-eval) surface used by the MLX
overla... | 671 | 27,975 |
sglang | python/sglang/srt/hardware_backend/mlx/aot.py | .py | """AOT kernel selection and decode-context helpers for the MLX backend."""
from __future__ import annotations
import logging
from dataclasses import dataclass, field
from typing import Any, Callable, Optional
import mlx.core as mx
from sglang.srt.environ import envs
logger = logging.getLogger(__name__)
def _load... | 255 | 8,273 |
sglang | python/sglang/srt/hardware_backend/mlx/remote_code_gate.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... | 127 | 5,416 |
sglang | python/sglang/srt/hardware_backend/mlx/kv_cache/layout.py | .py | """Model cache layout helpers for the MLX backend."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Sequence
@dataclass(frozen=True)
class MlxModelCacheLayout:
"""Map model layers to MLX cache storage components.
Full-attention layers store softmax-atte... | 142 | 5,261 |
sglang | python/sglang/srt/hardware_backend/mlx/kv_cache/attention_wrapper.py | .py | """Batched decode attention wrapper for MLX backend."""
from __future__ import annotations
import threading
from dataclasses import dataclass, field
from typing import Any, Optional
import mlx.core as mx
import mlx.nn as nn
from sglang.srt.hardware_backend.mlx.aot import (
MlxAOTKernelContext,
MlxAOTKernelS... | 399 | 15,826 |
sglang | python/sglang/srt/hardware_backend/mlx/kv_cache/auxiliary_state.py | .py | """MLX auxiliary-state snapshots for unified radix cache.
Hybrid MLX models may include non-softmax-attention layers whose native
``mlx-lm`` cache state cannot be reconstructed from the attention KV pool.
The global scheduler exposes that state through its existing MAMBA component
contract, so this MLX adapter keeps t... | 417 | 15,893 |
sglang | python/sglang/srt/hardware_backend/mlx/kv_cache/attention_kv_cache.py | .py | """Attention KV cache adapters for the MLX backend."""
from __future__ import annotations
from typing import TYPE_CHECKING
import mlx.core as mx
from mlx_lm.models.base import create_causal_mask
if TYPE_CHECKING:
from sglang.srt.hardware_backend.mlx.kv_cache.attention_kv_pool import (
MlxAttentionKVPool... | 360 | 13,711 |
sglang | python/sglang/srt/hardware_backend/mlx/kv_cache/model_patching.py | .py | """Model introspection and attention patching."""
import logging
from typing import Any
import mlx.nn as nn
from sglang.srt.hardware_backend.mlx.kv_cache.attention_contract import (
get_container_window_size,
get_layer_window_sizes,
is_attention_module,
)
from sglang.srt.hardware_backend.mlx.kv_cache.att... | 84 | 3,147 |
sglang | python/sglang/srt/hardware_backend/mlx/kv_cache/__init__.py | .py | """Cache components for the MLX backend."""
from sglang.srt.hardware_backend.mlx.kv_cache.attention_contract import (
get_attention_scale,
get_container_window_size,
get_head_dim,
get_layer_window_sizes,
get_num_heads,
get_num_kv_heads,
is_attention_module,
uses_sliding_window_attention... | 70 | 1,956 |
sglang | python/sglang/srt/hardware_backend/mlx/kv_cache/attention_kv_pool.py | .py | """Flat attention KV pool for the MLX backend.
Each layer buffer has shape ``(pool_size, n_kv_heads, head_dim)``.
The pool stores full-attention layers only and stays intentionally
uniform: every stored layer must share the same KV shape and
full-context KV semantics. Sliding-window layers keep window-bounded
per-req... | 87 | 3,171 |
sglang | python/sglang/srt/hardware_backend/mlx/kv_cache/attention_contract.py | .py | """Attention helpers based on duck typing for the MLX backend."""
from __future__ import annotations
from typing import Any, Iterable
# ``rope`` and a softmax scale are required by MLXAttentionWrapper. Keeping
# them in the contract also prevents recurrent mixers such as DeltaNet from
# being mistaken for softmax at... | 108 | 3,922 |
sglang | python/sglang/srt/hardware_backend/mlx/moe/fused_swiglu.py | .py | """Path B fusion for SwitchGLU: gate gather_qmv with silu(gate) * x_up epilogue.
Why this exists
---------------
The existing `FusedSwitchUpGate` (fused_switch_glu.py) concatenates up_proj
and gate_proj weights along the output dim and runs one gather_qmm. That saves
one kernel launch per layer but doubles the matmul'... | 574 | 24,195 |
sglang | python/sglang/srt/hardware_backend/mlx/models/muse_glimmer_mlx.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... | 741 | 31,879 |
sglang | python/sglang/srt/hardware_backend/npu/utils.py | .py | import functools
import logging
import sys
from enum import IntEnum
from typing import TYPE_CHECKING, Callable
import torch
from sglang.srt.environ import envs
from sglang.srt.utils import get_npu_memory_capacity, is_npu
if TYPE_CHECKING:
from sglang.srt.server_args import ServerArgs
logger = logging.getLogger(... | 369 | 11,665 |
sglang | python/sglang/srt/hardware_backend/npu/memory_pool_npu.py | .py | from typing import TYPE_CHECKING, Optional
import torch
from sglang.srt.constants import GPU_MEMORY_TYPE_KV_CACHE
from sglang.srt.environ import envs
from sglang.srt.mem_cache.memory_pool import (
MHATokenToKOnlyPool,
MHATokenToKVPool,
MiniMaxSparseKVPool,
MLATokenToKVPool,
get_tensor_size_bytes,
... | 790 | 29,996 |
sglang | python/sglang/srt/hardware_backend/npu/cmo.py | .py | import torch
cmo_stream = None
share_stream = None
def get_cmo_stream():
"""
Cache Management Operation(CMO).
Launch a new stream to prefetch the weight of matmul when running other
AIV or communication kernels, aiming to overlap the memory access time.
"""
global cmo_stream
return cmo_st... | 84 | 2,119 |
sglang | python/sglang/srt/hardware_backend/npu/allocator_npu.py | .py | from typing import TYPE_CHECKING
import torch
from sglang.srt.mem_cache.allocator import (
PagedTokenToKVPoolAllocator,
alloc_extend_naive,
)
from sglang.srt.utils import get_num_new_pages, next_power_of_2
if TYPE_CHECKING:
from sglang.srt.mem_cache.memory_pool import KVCache
class NPUPagedTokenToKVPoo... | 156 | 4,903 |
sglang | python/sglang/srt/hardware_backend/npu/batch_invariant_ops/npu_batch_invariant_ops.py | .py | # Adapted from https://github.com/thinking-machines-lab/batch_invariant_ops/blob/main/batch_invariant_ops/batch_invariant_ops.py
import batch_invariant_ops # noqa: F401
import torch
import torch_npu
def npu_mm_batch_invariant(a, b):
return torch.ops.batch_invariant_ops.npu_mm_batch_invariant(a, b)
def npu_mat... | 63 | 1,953 |
sglang | python/sglang/srt/hardware_backend/npu/dsv4/dsv4_req_to_token_pool.py | .py | """DSV4-NPU per-request mapping pool.
Subclass of ``ReqToTokenPool`` that adds five auxiliary per-request tables
needed by the DSV4 attention backend:
* ``req_to_token_swa`` — slot ids in the SWA full-pool view
* ``req_to_token_c4`` — slot ids in the c4 compressed-KV pool
* ``req_to_token_c128`` ... | 170 | 7,077 |
sglang | python/sglang/srt/hardware_backend/npu/dsv4/dsv4_rope.py | .py | """NPU interleaved RoPE cos/sin cache for DeepSeek-V4 on Ascend.
One Dsv4NpuRoPE per freqs_cis (singleton by id). Tables are built once at
init and registered as buffers on the shared rotary_emb, so model.to() moves
them and a captured aclgraph sees stable tensors; decode only does index_select.
mscale: cos/sin store... | 182 | 7,338 |
sglang | python/sglang/srt/hardware_backend/npu/dsv4/dsv4_common_hooks.py | .py | """Helpers used by mem_cache/common.py to wire DSV4-NPU per-req tables.
mem_cache/common.py runs platform-agnostic alloc flow. When the model is
DSV4 on NPU, ``alloc_paged_token_slots_{extend,decode}`` already stashed the
:class:`DSV4OutCacheLoc` the allocator returned onto
``batch.out_cache_loc_dsv4``. After each ``a... | 581 | 19,878 |
sglang | python/sglang/srt/hardware_backend/npu/dsv4/dsv4_allocator.py | .py | """DSV4-NPU SWA + c4/c128 paged allocator.
Subclasses :class:`SWATokenToKVPoolAllocator` and adds paged allocation for the
c4/c128 compressed-KV pools and their tail-only compress-state pools, alongside
the parent's full + SWA pools.
Per ``alloc_extend`` / ``alloc_decode``:
1. super() allocates the full + SWA slots... | 792 | 30,306 |
sglang | python/sglang/srt/hardware_backend/npu/dsv4/dsv4_memory_pool.py | .py | """NPU-only KV pool variant for DeepSeek-V4.
Subclasses :class:`DeepSeekV4TokenToKVPool` to swap the ring-buffered
:class:`CompressStatePool` for the paged :class:`NPUCompressStatePool` that
the on-NPU fused compressor kernel (``torch.ops.custom.compressor`` with
``cache_mode=1``) requires. Atlas A3 rejects ``cache_mo... | 670 | 28,278 |
sglang | python/sglang/srt/hardware_backend/npu/quantization/gptq_kernels.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING, Optional
import torch
if TYPE_CHECKING:
from sglang.srt.layers.quantization.base_config import QuantizationConfig
import logging
logger = logging.getLogger(__name__)
def unpack_from_int32(
weight: torch.Tensor,
num_bits: int,
pa... | 319 | 12,140 |
sglang | python/sglang/srt/hardware_backend/npu/quantization/online_moe_methods.py | .py | """Online (config-driven) quantized FusedMoE methods for Ascend NPU.
These are the ``--quantization <scheme>`` entry points: the checkpoint holds
BF16/FP16 expert weights and the per-gmm kernels quantize them at load time.
Offline (msmodelslim) checkpoints go through the ModelSlim schemes instead and
reuse the same ke... | 66 | 3,052 |
sglang | python/sglang/srt/hardware_backend/npu/quantization/linear_method_npu.py | .py | import logging
from typing import TYPE_CHECKING, Optional
import torch
from torch.nn.parameter import Parameter
from sglang.srt.hardware_backend.npu.utils import NPUACLFormat, npu_format_cast
from sglang.srt.layers.quantization.base_config import LinearMethodBase
if TYPE_CHECKING:
from sglang.srt.layers.quantiza... | 895 | 38,396 |
sglang | python/sglang/srt/hardware_backend/npu/quantization/moe_methods.py | .py | from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple
import numpy as np
import torch
from torch.nn.parameter import Parameter
from sglang.srt.environ import envs
from sglang.srt.hardware_backend.npu.utils import npu_format_cast
from sglang.srt.layers.quantization.base_config import FusedMoEMethodBase
if TYPE... | 953 | 36,009 |
sglang | python/sglang/srt/hardware_backend/npu/quantization/awq_kernels.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING, Optional
import torch
import torch.nn.functional as F
import torch_npu
from sglang.srt.hardware_backend.npu.quantization.moe_methods import (
NPUWNA16Int4MoEMethod,
)
from sglang.srt.layers.quantization.utils import replace_parameter
if TYPE_C... | 259 | 11,355 |
sglang | python/sglang/srt/hardware_backend/npu/moe/quant.py | .py | """
Quantization kernel wrappers for NPU MoE.
Each class quantises hidden states and returns a (quantized_tensor, scale) tuple.
For static quantization the scale is ``None``.
"""
from abc import ABC, abstractmethod
from typing import Optional, Tuple
import torch
class BaseHiddenStatesQuant(ABC):
"""Abstract ba... | 84 | 2,735 |
sglang | python/sglang/srt/hardware_backend/npu/moe/init_routing.py | .py | """
NPU MoE init routing components.
Prepare token routing before expert computation. Two API versions are provided:
- v1: legacy routing using ``npu_moe_init_routing``.
- v2: improved routing using ``npu_moe_init_routing_v2``.
"""
from abc import ABC, abstractmethod
from typing import Optional, Tuple
import torch
... | 150 | 5,055 |
sglang | python/sglang/srt/hardware_backend/npu/moe/finalize_routing.py | .py | """
NPU MoE finalize routing components.
These classes reassemble expert outputs into the original token order
after the expert computation. A generic TP‑all‑gather wrapper is provided
to transparently gather the hidden dimension when needed (e.g. GGUF with
full weights).
"""
from abc import ABC, abstractmethod
impo... | 100 | 3,157 |
sglang | python/sglang/srt/hardware_backend/npu/moe/activation.py | .py | from abc import ABC, abstractmethod
from typing import Any, Optional, Tuple
import torch
import torch.nn.functional as F
from sglang.srt.distributed.communication_op import (
tensor_model_parallel_all_gather,
)
from sglang.srt.layers.activation import GeluAndMul
from sglang.srt.runtime_context import get_parallel... | 247 | 8,764 |
sglang | python/sglang/srt/hardware_backend/npu/moe/topk.py | .py | from typing import TYPE_CHECKING, Optional
import torch
from sgl_kernel_npu.norm.l1_norm import l1_norm
from sglang.srt.eplb.expert_distribution import get_global_expert_distribution_recorder
from sglang.srt.eplb.expert_location_dispatch import topk_ids_logical_to_physical
from sglang.srt.layers.moe.topk import (
... | 133 | 5,087 |
sglang | python/sglang/srt/hardware_backend/npu/moe/matmul.py | .py | from abc import ABC, abstractmethod
from typing import Tuple
import torch
class BaseMatmul(ABC):
@abstractmethod
def forward(
self,
layer: torch.nn.Module,
weight_prefix: str,
hidden_states: torch.Tensor,
expert_tokens: torch.Tensor,
output_dtype: torch.dtype,
... | 90 | 3,053 |
sglang | python/sglang/srt/hardware_backend/npu/moe/fuseep.py | .py | """Ascend FuseEP fused dispatch+GEMM+combine forward path.
Follows the mega_moe shape: a free-function bypass invoked from
``FusedMoE.forward`` when ``--moe-a2a-backend ascend_fuseep`` is set, plus a
weight-postprocess helper that NPU quant_methods call from their
``process_weights_after_loading`` when the same backen... | 179 | 6,676 |
sglang | python/sglang/srt/hardware_backend/npu/modules/qwen_vl_processor.py | .py | import torch
import torchvision.transforms.v2.functional as tvF
from transformers.image_processing_utils import BatchFeature
from transformers.image_transforms import group_images_by_shape, reorder_images
from transformers.image_utils import (
ChannelDimension,
PILImageResampling,
SizeDict,
get_image_si... | 305 | 11,232 |
sglang | python/sglang/srt/hardware_backend/npu/modules/deepseek_v2_attention_mla_npu.py | .py | import re
from typing import TYPE_CHECKING
import torch
import torch_npu
from sgl_kernel_npu.norm.fused_split_qk_norm import fused_split_qk_norm
from sglang.srt.environ import envs
from sglang.srt.hardware_backend.npu.attention.mla_preprocess import (
NPUFusedMLAPreprocess,
is_fia_nz,
is_mla_preprocess_en... | 616 | 20,670 |
sglang | python/sglang/srt/hardware_backend/npu/modules/minimax_m3_processor.py | .py | """NPU patch for MiniMax M3 VL image and video preprocessing.
The MiniMax M3 VL image processor (MiniMaxM3VLImageProcessor) and video
processor (MiniMaxM3VLVideoProcessor) create 10-dimensional tensors during
patch extraction, which exceeds Ascend NPU's 8-dimension limit.
This patch restructures the computation using... | 302 | 10,665 |
sglang | python/sglang/srt/hardware_backend/npu/modules/glm46v_processor.py | .py | """NPU patch for GLM-4.6V image and video preprocessing.
The GLM-4.6V image processor (Glm46VImageProcessorFast) and video processor
(Glm46VVideoProcessor) create 10-dimensional tensors during patch extraction,
which exceeds Ascend NPU's 8-dimension limit.
This patch restructures the computation to stay within 8 dime... | 286 | 10,742 |
sglang | python/sglang/srt/hardware_backend/npu/attention/ascend_backend.py | .py | from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, List, Optional
import torch
import torch_npu
from sgl_kernel_npu.attention.sinks_attention import (
attention_sinks_prefill_triton,
attention_sinks_triton,
)
from sglang.srt.configs.model_config import Atte... | 3,001 | 126,617 |
sglang | python/sglang/srt/hardware_backend/npu/attention/ascend_torch_native_backend.py | .py | from __future__ import annotations
import math
from typing import Optional
import torch
from torch.nn.functional import scaled_dot_product_attention
class AscendTorchNativeAttnBackend:
def __init__(self):
pass
def scaled_dot_product_attention_with_softcapping(
self,
query,
k... | 337 | 13,601 |
sglang | python/sglang/srt/hardware_backend/npu/attention/mla_preprocess.py | .py | import re
from functools import lru_cache
from typing import TYPE_CHECKING, Optional
import torch
import torch.nn.functional as F
from sglang.srt.hardware_backend.npu.utils import npu_format_cast
from sglang.srt.model_executor.forward_context import (
get_attn_backend,
get_token_to_kv_pool,
)
from sglang.srt.... | 494 | 18,942 |
sglang | python/sglang/srt/hardware_backend/npu/attention/ascend_dsv4_backend.py | .py | from __future__ import annotations
import logging
import math
from types import SimpleNamespace
from typing import TYPE_CHECKING, Optional
import torch
import torch.nn.functional as F
from sglang.srt.hardware_backend.npu.attention.ascend_backend import AscendAttnBackend
from sglang.srt.layers.attention.dsv4.compress... | 2,180 | 91,133 |
sglang | python/sglang/srt/hardware_backend/npu/attention/ascend_kda_backend.py | .py | import math
from typing import Optional
import torch
from sgl_kernel_npu.fla.kda_chunk_delta_h import (
chunk_gated_delta_rule_fwd_h_npu,
)
from sgl_kernel_npu.fla.kda_gate import fused_kda_gate_npu
from sgl_kernel_npu.fla.kda_prefill import (
chunk_gla_fwd_o_gk_npu,
recompute_w_u_fwd_npu,
)
from sgl_kerne... | 635 | 23,914 |
sglang | python/sglang/srt/hardware_backend/npu/attention/ascend_gdn_backend.py | .py | from typing import Optional, Tuple, Union
import torch
from sgl_kernel_npu.fla.fused_gdn_gating import (
fused_gdn_gating_kernel_without_sigmoid,
fused_gdn_gating_npu,
)
from sglang.srt.hardware_backend.npu.attention.ascend_hybrid_linear_attn_backend import (
AscendMambaAttnBackendBase,
)
from sglang.srt.... | 385 | 14,815 |
sglang | python/sglang/srt/hardware_backend/npu/attention/ascend_hybrid_linear_attn_backend.py | .py | import logging
from typing import Optional, Union
import torch
from sgl_kernel_npu.mamba.mamba_state_update_triton import (
conv_state_rollback,
move_intermediate_cache,
)
from sglang.srt.layers.attention.base_attn_backend import AttentionBackend
from sglang.srt.layers.attention.hybrid_linear_attn_backend imp... | 323 | 13,051 |
sglang | python/sglang/srt/hardware_backend/npu/graph_runner/vit_npu_graph_runner.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... | 232 | 8,233 |
sglang | python/sglang/srt/hardware_backend/npu/graph_runner/eagle_draft_npu_graph_runner.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... | 106 | 4,187 |
sglang | python/sglang/srt/hardware_backend/npu/graph_runner/npu_graph_runner.py | .py | # Copyright 2023-2024 SGLang Team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | 285 | 10,361 |
sglang | python/sglang/srt/hardware_backend/npu/graph_runner/eagle_draft_extend_npu_graph_runner.py | .py | # Copyright 2024-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... | 51 | 1,858 |
sglang | python/sglang/srt/hardware_backend/npu/graph_runner/npu_cudagraph_backend.py | .py | """NPUCudaGraphBackend — Ascend NPU full-graph capture (torch.npu.NPUGraph).
Mirrors FullCudaGraphBackend with two differences:
- Captures via torch.npu.graph(...) into torch.npu.NPUGraph.
- replay_with_input_update(shape_key, seq_lens, attr_name) rebinds
the recorded graph's input bindings for variable seq_le... | 183 | 6,142 |
sglang | python/sglang/srt/hardware_backend/npu/graph_runner/multi_layer_eagle_draft_extend_npu_graph_runner.py | .py | # Copyright 2024-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... | 55 | 1,918 |
sglang | python/sglang/srt/platforms/device_mixin.py | .py | """
Shared device abstraction for SGLang platforms.
DeviceMixin provides the common device identity queries and operations
shared between the SRT (LLM inference) and Multimodal (diffusion)
platform hierarchies. Concrete per-device mixins (e.g. MyDeviceMixin)
implement the abstract operations; subsystem-specific platf... | 268 | 9,066 |
sglang | python/sglang/srt/platforms/cpu.py | .py | """CPU device operations for the SRT platform layer."""
import gc
import platform as _platform
from functools import cached_property
from typing import Optional
import psutil
import torch
from sglang.srt.platforms.device_mixin import (
CpuArchEnum,
DeviceCapability,
DeviceMixin,
PlatformEnum,
)
from ... | 134 | 5,602 |
sglang | python/sglang/srt/platforms/rocm.py | .py | """ROCm device operations for the SRT platform layer.
PyTorch exposes ROCm through the same ``torch.cuda.*`` API surface as CUDA
(HIP is a binary shim, and ``torch.device("rocm")`` does not exist). So
``RocmDeviceMixin`` inherits all device ops from ``CudaDeviceMixin`` and
only overrides identity (``_enum``, ``device_... | 32 | 1,351 |
sglang | python/sglang/srt/platforms/__init__.py | .py | """
SGLang Platform Discovery and Lazy Initialization.
Provides `current_platform` as a module-level lazy singleton. On first access,
it discovers platform plugins via entry_points and instantiates the appropriate
SRTPlatform subclass.
Usage:
from sglang.srt.platforms import current_platform
print(current_pla... | 174 | 6,410 |
sglang | python/sglang/srt/platforms/xpu.py | .py | """XPU device operations for the SRT platform layer."""
import logging
from typing import Optional
import torch
from sglang.srt.platforms.device_mixin import (
DeviceCapability,
DeviceMixin,
PlatformEnum,
)
from sglang.srt.platforms.interface import SRTPlatform
logger = logging.getLogger(__name__)
cla... | 105 | 3,367 |
sglang | python/sglang/srt/platforms/interface.py | .py | """
SGLang SRT Hardware Platform Abstraction.
Defines SRTPlatform — the base class for SRT (LLM inference) platform
backends. SRTPlatform inherits DeviceMixin for shared device operations
and adds SRT-specific subsystem factory methods, capability flags, and
configuration lifecycle hooks.
Out-of-tree platforms regis... | 143 | 5,145 |
sglang | python/sglang/srt/platforms/cuda.py | .py | """CUDA device operations for the SRT platform layer."""
from typing import Optional
import torch
from sglang.srt.platforms.device_mixin import (
DeviceCapability,
DeviceMixin,
PlatformEnum,
)
from sglang.srt.platforms.interface import SRTPlatform
class CudaDeviceMixin(DeviceMixin):
"""CUDA impleme... | 81 | 2,418 |
sglang | python/sglang/srt/weight_cache/ipc_loader.py | .py | # SPDX-License-Identifier: Apache-2.0
"""IPC Model Loader — loads model weights from a Weight Cache Daemon via CUDA IPC.
Zero-copy mode: param.data points directly to IPC-mapped GPU memory. Only 1x GPU
memory needed — engine and daemon share the same physical GPU memory via CUDA IPC.
Engine depends on daemon staying a... | 564 | 23,971 |
sglang | python/sglang/srt/weight_cache/protocol.py | .py | # SPDX-License-Identifier: Apache-2.0
"""Protocol definitions for the weight cache daemon.
Defines CacheConfig for validation and socket message protocol helpers.
"""
import hashlib
import json
import logging
import os
import pickle
import signal
import struct
from typing import Any, Dict, Optional
import msgspec
f... | 381 | 14,117 |
sglang | python/sglang/srt/weight_cache/daemon.py | .py | # SPDX-License-Identifier: Apache-2.0
"""Weight Cache Daemon — a persistent process that holds post-quantized,
TP-sharded model weights in GPU memory and serves them via CUDA IPC handles.
Each GPU runs one daemon process for its TP rank. The daemon:
1. Loads model weights from disk (full pipeline: disk → TP shard → qu... | 945 | 36,884 |
sglang | python/sglang/srt/eplb/lplb_solver.py | .py | """
LPLBSolver — Linear-Programming Load Balancer for Expert Parallelism.
Encapsulates LP matrix construction (offline, at init/rebalance) and
per-batch solving (online, per MoE layer forward pass).
Design for DP-attention:
Each EP rank counts its local tokens, then all ranks participate in an
all-reduce to o... | 286 | 11,812 |
sglang | python/sglang/srt/eplb/eplb_manager.py | .py | from __future__ import annotations
import logging
import time
from typing import TYPE_CHECKING, Any, Callable, List
import torch.cuda
import torch.distributed as dist
from torch import nn
from sglang.srt.elastic_ep.elastic_ep import ElasticEPStateManager
from sglang.srt.environ import envs
from sglang.srt.eplb.exper... | 359 | 13,585 |
sglang | python/sglang/srt/eplb/expert_location_updater.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... | 636 | 24,261 |
sglang | python/sglang/srt/eplb/expert_distribution.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,090 | 38,281 |
sglang | python/sglang/srt/eplb/expert_location.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... | 819 | 30,308 |
sglang | python/sglang/srt/eplb/expert_location_dispatch.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... | 175 | 7,017 |
sglang | python/sglang/srt/eplb/eplb_simulator/reader.py | .py | from collections import defaultdict
from pathlib import Path
import torch
from tqdm import tqdm
from sglang.srt.eplb.expert_distribution import (
_convert_global_physical_count_to_logical_count,
)
convert_global_physical_count_to_logical_count = (
_convert_global_physical_count_to_logical_count
)
def read_... | 52 | 1,828 |
sglang | python/sglang/srt/eplb/eplb_algorithms/deepseek_vec.py | .py | # This file is copied from https://github.com/deepseek-ai/EPLB/blob/main/eplb.py since that one is not a pypi package
from typing import Optional, Tuple
import torch
def pack_groups(tokens_per_group: torch.Tensor, num_nodes: int) -> torch.Tensor:
num_layers, num_groups = tokens_per_group.shape
assert num_gro... | 277 | 10,654 |
sglang | python/sglang/srt/eplb/eplb_algorithms/__init__.py | .py | from enum import Enum, auto
from typing import Optional
import torch
from sglang.srt.eplb.eplb_algorithms import deepseek, deepseek_vec, elasticity_aware
class EplbAlgorithm(Enum):
deepseek = auto()
deepseek_hierarchical = auto()
deepseek_vec = auto()
deepseek_vec_hierarchical = auto()
elasticit... | 88 | 2,901 |
sglang | python/sglang/srt/eplb/eplb_algorithms/elasticity_aware.py | .py | from typing import Tuple
import torch
from sglang.srt.eplb.eplb_algorithms.deepseek import rebalance_experts_hierarchical
def rebalance_experts(
weight: torch.Tensor,
num_replicas: int,
num_groups: int,
num_nodes: int,
num_gpus: int,
enable_hierarchical: bool,
active_ranks: torch.Tensor,... | 88 | 3,230 |
sglang | python/sglang/srt/eplb/eplb_algorithms/deepseek.py | .py | # This file is copied from https://github.com/deepseek-ai/EPLB/blob/main/eplb.py since that one is not a pypi package
from typing import Tuple
import torch
def balanced_packing(
weight: torch.Tensor, num_packs: int
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Pack n weighted objects to m packs, such that ... | 225 | 8,508 |
sglang | python/sglang/srt/session/streaming_session.py | .py | from __future__ import annotations
import copy
import logging
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Dict, Optional
import torch
from sglang.srt.mem_cache.base_prefix_cache import (
BasePrefixCache,
DecLockRefParams,
DecLockRefResult,
EvictParams,
EvictRes... | 647 | 25,203 |
sglang | python/sglang/srt/session/session_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 writing, s... | 488 | 20,010 |
sglang | python/sglang/srt/utils/nvtx_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... | 120 | 4,439 |
sglang | python/sglang/srt/utils/runai_utils.py | .py | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adapted from https://github.com/vllm-project/vllm/blob/v0.6.4.post1/vllm/model_executor/model_loader/runai_utils.py
import hashlib
import logging
import os
from pathlib import Path
from sglang.srt.environ impo... | 133 | 4,489 |
sglang | python/sglang/srt/utils/numa_utils.py | .py | import ctypes
import glob
import logging
import math
import multiprocessing
import os
import random
import shutil
import subprocess
import time
from contextlib import contextmanager
from pathlib import Path
from typing import Optional
import torch
from sglang.srt.environ import envs
from sglang.srt.server_args import... | 472 | 19,231 |
sglang | python/sglang/srt/utils/request_logger.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... | 317 | 11,561 |
sglang | python/sglang/srt/utils/video_decoder.py | .py | """Unified video decoder: torchcodec preferred, decord as fallback."""
import logging
import os
import numpy as np
logger = logging.getLogger(__name__)
try:
from torchcodec.decoders import VideoDecoder
_BACKEND = "torchcodec"
except (ImportError, RuntimeError):
_BACKEND = "decord"
_cuda_backend_enabl... | 188 | 6,512 |
sglang | python/sglang/srt/utils/weight_checker.py | .py | import hashlib
import logging
import time
from typing import Any, Callable, Dict, Iterable, NamedTuple, Optional, Set
import torch
import torch.distributed as dist
from pydantic import BaseModel, ConfigDict
from sglang.srt.managers.mm_utils import tensor_hash
from sglang.srt.utils.weight_checker_comparator import (
... | 303 | 9,906 |
sglang | python/sglang/srt/utils/poll_based_barrier.py | .py | import torch
from sglang.srt.distributed import get_world_group
class PollBasedBarrier:
def __init__(self, noop: bool = False):
self._noop = noop
self._local_arrived = False
def local_arrive(self):
assert not self._local_arrived
self._local_arrived = True
def poll_global... | 32 | 937 |
sglang | python/sglang/srt/utils/triton_load_watch.py | .py | """Detect Triton kernel device-loads after the engine starts serving.
Triton loads each kernel specialization's cubin onto the GPU at its first
launch (``CompiledKernel._init_handles`` -> ``cuModuleLoadData``). That load
needs free device memory *outside* the torch caching allocator. Engines size
their pools to leave ... | 122 | 4,251 |
sglang | python/sglang/srt/utils/slow_rank_detector.py | .py | import logging
from typing import Any, Dict, List
import torch
import torch.distributed as dist
import triton
logger = logging.getLogger(__name__)
def execute():
if dist.get_rank() == 0:
logger.info(f"[slow_rank_detector] Start benchmarking...")
local_metrics = {
bench_name: _compute_local_... | 72 | 2,052 |
sglang | python/sglang/srt/utils/field_validators.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... | 82 | 2,793 |
sglang | python/sglang/srt/utils/patch_torch.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,191 |
sglang | python/sglang/srt/utils/patch_tokenizer.py | .py | import logging
from sglang.srt.environ import envs
logger = logging.getLogger(__name__)
def patch_tokenizer(tokenizer):
if not envs.SGLANG_PATCH_TOKENIZER.get():
return tokenizer
if _is_kimi_tiktoken_tokenizer(tokenizer):
logger.info(
f"Applying special tokens cache patch for Ki... | 128 | 4,508 |
sglang | python/sglang/srt/utils/multi_stream_utils.py | .py | # Adapted from trtllm.
from typing import Any, Callable, Optional
import torch
from sglang.srt.runtime_context import get_forward
def set_do_multi_stream(enable: bool):
get_forward().set("multi_stream", enable)
def do_multi_stream() -> bool:
return get_forward().multi_stream
def with_multi_stream(enabl... | 61 | 1,729 |
sglang | python/sglang/srt/utils/watchdog.py | .py | from __future__ import annotations
import logging
import os
import signal
import sys
import threading
import time
from contextlib import contextmanager
from multiprocessing import Process
from typing import Callable, List, Optional
import psutil
from sglang.srt.utils.cudacore_pyspy_dump_utils import pyspy_dump_sched... | 224 | 7,018 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.