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/layers/attention/nsa_backend.py | .py | # [Deprecated] nsa_backend.py is a thin re-export shim for backward compatibility.
# Use dsa_backend.py instead. This file will be removed in a future release.
import warnings
warnings.warn(
"sglang.srt.layers.attention.nsa_backend is deprecated; "
"use sglang.srt.layers.attention.dsa_backend instead.",
De... | 24 | 772 |
sglang | python/sglang/srt/layers/attention/hybrid_attn_backend.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING, Optional
import torch
from sglang.srt.layers.attention.base_attn_backend import AttentionBackend
from sglang.srt.layers.attention.dsa.dsa_indexer_metadata import BaseIndexerMetadata
from sglang.srt.layers.radix_attention import RadixAttention
from ... | 245 | 9,582 |
sglang | python/sglang/srt/layers/attention/flashinfer_backend.py | .py | from __future__ import annotations
from sglang.srt.runtime_context import get_parallel
"""
Support different attention backends.
Now there are two backends: FlashInfer and Triton.
FlashInfer is faster and Triton is easier to customize.
Each backend supports two operators: extend (i.e. prefill with cached prefix) and ... | 2,431 | 100,765 |
sglang | python/sglang/srt/layers/attention/flashinfer_mla_backend.py | .py | from __future__ import annotations
from sglang.srt.runtime_context import get_disagg, get_exec, get_parallel, get_schedule
"""
Support attention backend for flashinfer MLA.
The flashinfer_mla_disable_ragged flag controls whether to use ragged prefill wrapper and defaults to be false.
When it's set to false, all wrapp... | 1,303 | 50,519 |
sglang | python/sglang/srt/layers/attention/wave_backend.py | .py | from __future__ import annotations
import logging
from dataclasses import dataclass
from typing import TYPE_CHECKING, Optional
import torch
import triton
from sglang.kernels.ops.attention.metadata import get_num_kv_splits_triton
from sglang.kernels.ops.kvcache.kv_indices import (
create_flashinfer_kv_indices_tri... | 565 | 20,637 |
sglang | python/sglang/srt/layers/attention/minimax_sparse_backend.py | .py | from __future__ import annotations
import logging
import os
from types import SimpleNamespace
from typing import TYPE_CHECKING, Optional, Tuple
import torch
from sglang.srt.configs.model_config import (
get_minimax_sparse_attention_config,
get_minimax_sparse_disable_value_layer_ids,
get_minimax_sparse_la... | 1,730 | 68,678 |
sglang | python/sglang/srt/layers/attention/tokenspeed_mla_backend.py | .py | # Copyright (c) 2026 LightSeek Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish... | 681 | 25,315 |
sglang | python/sglang/srt/layers/attention/verify_mask.py | .py | from __future__ import annotations
from typing import Optional
import msgspec
import torch
from sglang.srt.speculative.eagle_utils import TreeMaskMode, default_tree_mask_mode
def tree_mask_numel(
mode: TreeMaskMode, bs: int, num_draft_tokens: int, max_context_len: int
) -> int:
"""Cells the tree kernel wri... | 82 | 2,747 |
sglang | python/sglang/srt/layers/attention/tbo_backend.py | .py | from __future__ import annotations
from types import SimpleNamespace
from typing import TYPE_CHECKING, Callable, List, Optional
from sglang.srt.batch_overlap import two_batch_overlap
from sglang.srt.layers.attention.base_attn_backend import AttentionBackend
if TYPE_CHECKING:
from sglang.srt.layers.attention.veri... | 254 | 10,538 |
sglang | python/sglang/srt/layers/attention/vision_utils.py | .py | """Utility functions for vision attention layers."""
import torch
from sglang.srt.runtime_context import get_parallel
def update_vit_attn_dummy_heads_config(config):
"""Update HF config to ensure vision attention num_attention_heads is divisible by tp_size"""
tp_size = get_parallel().attn_tp_size
num_he... | 66 | 2,762 |
sglang | python/sglang/srt/layers/attention/trtllm_mla_backend.py | .py | """
Support attention backend for TRTLLM MLA kernels from flashinfer.
"""
from __future__ import annotations
import logging
import math
from dataclasses import dataclass
from typing import TYPE_CHECKING, Optional, Union
import torch
import triton
from sglang.kernels.ops.attention.fixup_zero_kv import fixup_zero_kv_... | 1,583 | 65,259 |
sglang | python/sglang/srt/layers/attention/flashmla_backend.py | .py | """
Support attention backend for FlashMLA.
"""
from __future__ import annotations
import logging
from dataclasses import dataclass
from typing import TYPE_CHECKING, Callable, Optional, Tuple, Union
import torch
import triton
from sgl_kernel.flash_mla import flash_mla_with_kvcache, get_mla_metadata
from sglang.kern... | 652 | 26,138 |
sglang | python/sglang/srt/layers/attention/hip_flash_mla.py | .py | from typing import Any, Optional
import torch
from sglang.kernels.ops.quantization.fp8_kernel import is_fp8_fnuz
from sglang.srt.environ import envs
from sglang.srt.utils import is_hip
FP8_DTYPE = torch.float8_e4m3fnuz if is_fp8_fnuz() else torch.float8_e4m3fn
def flash_mla_with_kvcache_entrypoint(backend: str, **... | 204 | 6,666 |
sglang | python/sglang/srt/layers/attention/deepseek_v4_backend_hip_radix.py | .py | from __future__ import annotations
import enum
import functools
import logging
from dataclasses import dataclass, field
from typing import (
TYPE_CHECKING,
Dict,
List,
Literal,
Optional,
Tuple,
TypeVar,
Union,
)
import torch
import torch.nn.functional as F
from sglang.kernels.ops.atte... | 1,869 | 76,441 |
sglang | python/sglang/srt/layers/attention/hpc_ops_backend.py | .py | from __future__ import annotations
"""
Attention backend powered by HPC-Ops (https://github.com/Tencent/hpc-ops),
a production-grade operator library for LLM inference developed by the
Tencent Hunyuan AI Infra team.
The backend wraps the paged MHA kernels ``attention_with_kvcache_prefill_bf16``
(extend) and ``attenti... | 701 | 28,126 |
sglang | python/sglang/srt/layers/attention/cutedsl_mla_backend.py | .py | """
Attention backend for the flashinfer cute-dsl MLA decode kernels with decode
context parallelism (DCP).
Subclasses :class:`TRTLLMMLABackend` (``backend="cute-dsl"``) to reuse its MLA
data preparation, workspace, and prefill plumbing. The flashinfer cute-dsl
monolithic MLA decode kernel natively accepts cyclic DCP ... | 486 | 18,916 |
sglang | python/sglang/srt/layers/attention/vision.py | .py | from __future__ import annotations
import dataclasses
import functools
import math
import warnings
from functools import lru_cache, partial
from typing import Any, Callable, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops import rearrange
from sglang.kernels.ops.layerno... | 1,497 | 51,018 |
sglang | python/sglang/srt/layers/attention/dual_chunk_flashattention_backend.py | .py | # SPDX-License-Identifier: Apache-2.0
"""Attention layer with Dual chunk flash attention and sparse attention."""
import functools
import logging
import math
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple
import torch
import torch.nn.functional as F
from sgl_kerne... | 1,712 | 68,697 |
sglang | python/sglang/srt/layers/attention/attention_registry.py | .py | import logging
import warnings
from typing import TYPE_CHECKING
from sglang.srt.configs.hybrid_arch import (
hybrid_gdn_config,
hybrid_lightning_config,
kimi_linear_config,
mamba2_config,
mambaish_config,
)
from sglang.srt.configs.linear_attn_model_registry import (
get_linear_attn_config,
... | 497 | 18,606 |
sglang | python/sglang/srt/layers/attention/torch_native_backend.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING, Optional
import torch
from torch.nn.functional import scaled_dot_product_attention
from sglang.srt.layers.attention.base_attn_backend import AttentionBackend
from sglang.srt.layers.radix_attention import AttentionType
from sglang.srt.mem_cache.memo... | 402 | 15,008 |
sglang | python/sglang/srt/layers/attention/base_attn_backend.py | .py | from __future__ import annotations
from abc import ABC
from enum import Enum, auto
from typing import TYPE_CHECKING, Optional
import torch
from sglang.kernel_api_logging import debug_kernel_api
from sglang.srt.utils.common import is_npu
if TYPE_CHECKING:
from sglang.srt.layers.attention.dsa.dsa_indexer_metadata... | 310 | 11,396 |
sglang | python/sglang/srt/layers/attention/flashattention_backend.py | .py | from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING, Optional
import numpy as np
import torch
from sglang.kernels.ops.attention.metadata import (
draft_extend_set_metadata,
normal_decode_set_metadata,
prepare_swa_spec_page_table_triton,
)
from sglang.kern... | 3,645 | 170,665 |
sglang | python/sglang/srt/layers/attention/mamba/mamba.py | .py | import logging
from typing import Callable, List, Optional, Tuple
import torch
import torch.nn as nn
from sglang.kernels.ops.mamba.triton_ops import (
mamba_chunk_scan_combined,
selective_state_update,
)
from sglang.srt.configs.mamba_utils import (
Mamba2CacheParams,
extra_groups_for_head_shards,
)
fr... | 769 | 30,892 |
sglang | python/sglang/srt/layers/attention/mamba/mamba2_metadata.py | .py | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# 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
#
# h... | 318 | 14,207 |
sglang | python/sglang/srt/layers/attention/mamba/causal_conv1d.py | .py | # Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/model_executor/layers/mamba/ops/causal_conv1d.py
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Copyright (c) 2024, Tri Dao.
# Adapted from https://github.com/Dao-AILab/causal-conv1d/blob/ma... | 188 | 6,680 |
sglang | python/sglang/srt/layers/attention/mamba/mixer2_rms_norm_gated.py | .py | from typing import Union
import torch
from sglang.kernels.fused_op import BaseFusedOp
from sglang.kernels.ops.attention.fla.layernorm_gated import rms_norm_gated
from sglang.srt.distributed.communication_op import (
tensor_model_parallel_all_gather,
tensor_model_parallel_all_reduce,
)
from sglang.srt.layers.d... | 136 | 5,355 |
sglang | python/sglang/srt/layers/attention/dsv4/indexer.py | .py | from __future__ import annotations
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
Optional,
Tuple,
TypeAlias,
Union,
)
import torch
import torch.nn as nn
import torch.nn.functional as F
from sglang.kernels.ops.attention.dsv4 import (
fused_q_indexer_rope_hadama... | 978 | 34,802 |
sglang | python/sglang/srt/layers/attention/dsv4/compressor.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING, List, Literal, NamedTuple, Optional, Union
import torch
import torch.nn as nn
from sglang.kernels.fused_op import BaseFusedOp
from sglang.kernels.ops.attention.dsa.triton_kernel import act_quant
from sglang.kernels.ops.attention.dsv4 import (
l... | 481 | 17,715 |
sglang | python/sglang/srt/layers/attention/dsv4/metadata.py | .py | from __future__ import annotations
import warnings
from dataclasses import dataclass, field, fields
from typing import TYPE_CHECKING, Any, List, Optional
import torch
from sglang.srt.environ import envs
from sglang.srt.utils import is_hip, is_xpu
if TYPE_CHECKING:
pass
"""
Some comments on the common terms us... | 202 | 6,741 |
sglang | python/sglang/srt/layers/attention/dsv4/compressor_v2.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING, List, Literal, Optional, TypeAlias, Union, cast
import torch
from sglang.kernels.jit.utils import is_hip_runtime
from sglang.kernels.ops.attention.dsv4 import (
CompressorDecodePlan,
CompressorPrefillPlan,
compress_forward,
compress... | 528 | 20,600 |
sglang | python/sglang/srt/layers/attention/dsv4/compress_hip.py | .py | from __future__ import annotations
import os
from functools import cached_property
from typing import TYPE_CHECKING, Any
import torch
import torch.nn as nn
from sglang.kernels.ops.attention.deepseek_v4_rope import (
apply_rotary_emb_triton,
fused_norm_rope_inplace_triton,
fused_softmax_pool_triton,
)
fro... | 524 | 20,804 |
sglang | python/sglang/srt/layers/attention/dsv4/sparse_prefill_utils.py | .py | """Per-query sparse-index combiner for the FlashMLA sparse prefill path.
Adapts vllm's ``combine_topk_swa_indices`` to sglang's flat-workspace layout.
Reference:
https://github.com/vllm-project/vllm/blob/124fac10cb0ea83aee2ffeabac0b413d6b759b26/vllm/models/deepseek_v4/common/ops/cache_utils.py#L476
For each
query tok... | 516 | 21,903 |
sglang | python/sglang/srt/layers/attention/nsa/tilelang_kernel.py | .py | # [Deprecated] Re-export shim for backward compatibility. Use dsa.tilelang_kernel instead.
import warnings
warnings.warn(
"sglang.srt.layers.attention.nsa.tilelang_kernel is deprecated; "
"use sglang.kernels.ops.attention.dsa.tilelang_kernel instead.",
DeprecationWarning,
stacklevel=2,
)
from sglang.ke... | 11 | 389 |
sglang | python/sglang/srt/layers/attention/nsa/utils.py | .py | # [Deprecated] Re-export shim for backward compatibility. Use dsa.utils instead.
import warnings
warnings.warn(
"sglang.srt.layers.attention.nsa.utils is deprecated; "
"use sglang.srt.layers.attention.dsa.utils instead.",
DeprecationWarning,
stacklevel=2,
)
from sglang.srt.layers.attention.dsa.utils im... | 11 | 347 |
sglang | python/sglang/srt/layers/attention/nsa/nsa_backend_mtp_precompute.py | .py | # [Deprecated] Re-export shim for backward compatibility. Use dsa.dsa_backend_mtp_precompute instead.
import warnings
warnings.warn(
"sglang.srt.layers.attention.nsa.nsa_backend_mtp_precompute is deprecated; "
"use sglang.srt.layers.attention.dsa.dsa_backend_mtp_precompute instead.",
DeprecationWarning,
... | 11 | 431 |
sglang | python/sglang/srt/layers/attention/nsa/__init__.py | .py | # [Deprecated] attention/nsa/ is a thin re-export shim for backward compatibility.
# Use attention/dsa/ instead. This directory will be removed in a future release.
import warnings
warnings.warn(
"sglang.srt.layers.attention.nsa is deprecated; "
"use sglang.srt.layers.attention.dsa instead.",
DeprecationWa... | 12 | 413 |
sglang | python/sglang/srt/layers/attention/nsa/index_buf_accessor.py | .py | # [Deprecated] Re-export shim for backward compatibility. Use dsa.index_buf_accessor instead.
import warnings
warnings.warn(
"sglang.srt.layers.attention.nsa.index_buf_accessor is deprecated; "
"use sglang.kernels.ops.attention.dsa.index_buf_accessor instead.",
DeprecationWarning,
stacklevel=2,
)
from ... | 11 | 401 |
sglang | python/sglang/srt/layers/attention/nsa/quant_k_cache.py | .py | # [Deprecated] Re-export shim for backward compatibility. Use dsa.quant_k_cache instead.
import warnings
warnings.warn(
"sglang.srt.layers.attention.nsa.quant_k_cache is deprecated; "
"use sglang.kernels.ops.attention.dsa.quant_k_cache instead.",
DeprecationWarning,
stacklevel=2,
)
from sglang.kernels.... | 11 | 381 |
sglang | python/sglang/srt/layers/attention/nsa/dequant_k_cache.py | .py | # [Deprecated] Re-export shim for backward compatibility. Use dsa.dequant_k_cache instead.
import warnings
warnings.warn(
"sglang.srt.layers.attention.nsa.dequant_k_cache is deprecated; "
"use sglang.kernels.ops.attention.dsa.dequant_k_cache instead.",
DeprecationWarning,
stacklevel=2,
)
from sglang.ke... | 11 | 389 |
sglang | python/sglang/srt/layers/attention/nsa/triton_kernel.py | .py | # [Deprecated] Re-export shim for backward compatibility. Use dsa.triton_kernel instead.
import warnings
warnings.warn(
"sglang.srt.layers.attention.nsa.triton_kernel is deprecated; "
"use sglang.kernels.ops.attention.dsa.triton_kernel instead.",
DeprecationWarning,
stacklevel=2,
)
from sglang.kernels.... | 11 | 381 |
sglang | python/sglang/srt/layers/attention/nsa/transform_index.py | .py | # [Deprecated] Re-export shim for backward compatibility. Use dsa.transform_index instead.
import warnings
warnings.warn(
"sglang.srt.layers.attention.nsa.transform_index is deprecated; "
"use sglang.kernels.ops.attention.dsa.transform_index instead.",
DeprecationWarning,
stacklevel=2,
)
from sglang.ke... | 11 | 389 |
sglang | python/sglang/srt/layers/attention/nsa/nsa_indexer.py | .py | # [Deprecated] Re-export shim for backward compatibility. Use dsa.dsa_indexer instead.
import warnings
warnings.warn(
"sglang.srt.layers.attention.nsa.nsa_indexer is deprecated; "
"use sglang.srt.layers.attention.dsa.dsa_indexer instead.",
DeprecationWarning,
stacklevel=2,
)
from sglang.srt.layers.atte... | 11 | 371 |
sglang | python/sglang/srt/layers/attention/linear/gdn_backend.py | .py | from typing import Optional, Tuple, Union
import torch
from sglang.kernels.ops.attention.fla.fused_gdn_gating import fused_gdn_gating
from sglang.kernels.ops.mamba.causal_conv1d_triton import (
causal_conv1d_fn,
causal_conv1d_update,
)
from sglang.srt.configs.hybrid_arch import hybrid_gdn_config
from sglang.s... | 897 | 36,304 |
sglang | python/sglang/srt/layers/attention/linear/short_conv_backend.py | .py | # Copyright 2023-2026 SGLang Team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | 232 | 10,872 |
sglang | python/sglang/srt/layers/attention/linear/utils.py | .py | from __future__ import annotations
from enum import Enum
from typing import TYPE_CHECKING, Optional
import msgspec
from sglang.srt.runtime_context import get_exec
from sglang.srt.utils.common import rank0_log
if TYPE_CHECKING:
from sglang.srt.server_args import ServerArgs
class LinearAttnKernelBackend(Enum):
... | 137 | 4,463 |
sglang | python/sglang/srt/layers/attention/linear/lightning_backend.py | .py | import logging
import math
import torch
from sglang.kernels.ops.attention.linear.lightning_attn import (
BailingLinearKernel,
linear_decode_forward_triton,
)
from sglang.kernels.ops.attention.linear.seg_la import SegLaMeta, seg_la_fwd
from sglang.srt.layers.attention.hybrid_linear_attn_backend import MambaAtt... | 471 | 17,861 |
sglang | python/sglang/srt/layers/attention/linear/kda_backend.py | .py | import importlib.util
from typing import Optional, Tuple, Union
import torch
from sglang.kernels.ops.attention import kda_fused_decode
from sglang.kernels.ops.mamba.causal_conv1d_triton import (
causal_conv1d_fn,
causal_conv1d_update,
)
from sglang.srt.layers.attention.hybrid_linear_attn_backend import MambaA... | 1,064 | 43,767 |
sglang | python/sglang/srt/layers/attention/linear/linear_metadata.py | .py | from dataclasses import dataclass
import torch
from sglang.srt.layers.attention.mamba.mamba2_metadata import ForwardMetadata
from sglang.srt.model_executor.forward_batch_info import ForwardBatch
@dataclass(kw_only=True)
class BailingLinearMetadata(ForwardMetadata):
num_prefills: int
num_prefill_tokens: int
... | 71 | 2,541 |
sglang | python/sglang/srt/layers/attention/linear/inkling_sconv_backend.py | .py | # Copyright 2023-2026 SGLang Team
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... | 609 | 27,326 |
sglang | python/sglang/srt/layers/attention/linear/kernels/kda_flashkda.py | .py | from typing import Optional
import torch
from sglang.srt.layers.attention.linear.kernels.kernel_backend import (
LinearAttnKernelBase,
)
# FlashKDA chunk size. Sequences shorter than this fall back to Triton.
_FLASHKDA_CHUNK_SIZE = 64
# FlashKDA's max sequence length, Batches whose longest sequence exceeds this... | 267 | 9,407 |
sglang | python/sglang/srt/layers/attention/linear/kernels/kda_flashinfer.py | .py | """FlashInfer KDA decode/verify wrapper.
Wraps ``flashinfer.kda_decode.recurrent_kda`` (SM100 / Blackwell). FlashInfer has
no KDA prefill kernel, so ``extend`` stays on Triton / CuTe DSL.
Contract with the Triton KDA reference:
- raw per-K gate ``a`` is activated in-kernel as
``-exp(A_log) * softplus(a + dt_bia... | 338 | 14,617 |
sglang | python/sglang/srt/layers/attention/linear/kernels/kda_cutedsl.py | .py | import logging
from typing import Optional
import torch
from sglang.kernels.ops.attention.cutedsl_kda import (
cutedsl_fused_sigmoid_gating_kda_update,
)
from sglang.srt.layers.attention.linear.kernels.kernel_backend import (
LinearAttnKernelBase,
)
logger = logging.getLogger(__name__)
def _is_blackwell() ... | 169 | 6,132 |
sglang | python/sglang/srt/layers/attention/linear/kernels/kda_ptx.py | .py | # SPDX-License-Identifier: Apache-2.0
"""PTX/tcgen05 KDA chunked-prefill backend (``--linear-attn-prefill-backend ptx_kda``).
Wraps the vendored hand-CUDA ``kda_ptx_prefill`` kernel (GB300 / sm_103a) through
its FLA-compatible ``chunk_kda_fwd`` interface. The kernel selects a fused
long-sequence route or a two-launch ... | 348 | 13,151 |
sglang | python/sglang/srt/layers/attention/linear/kernels/kda_triton.py | .py | from typing import Optional
import torch
from sglang.srt.layers.attention.linear.kernels.kernel_backend import (
LinearAttnKernelBase,
)
from sglang.srt.utils import is_cpu, is_npu
if not is_cpu():
from sglang.kernels.ops.attention.fla.fused_recurrent import (
fused_recurrent_kda_packed_decode,
)... | 245 | 8,845 |
sglang | python/sglang/srt/layers/attention/linear/kernels/kda_helion.py | .py | """Helion backend for Kimi Delta Attention."""
from __future__ import annotations
import torch
from sglang.srt.layers.attention.linear.kernels.kda_triton import TritonKDAKernel
from sglang.srt.layers.attention.linear.kernels.kernel_backend import (
LinearAttnKernelBase,
)
class HelionKDAKernel(LinearAttnKernel... | 192 | 6,284 |
sglang | python/sglang/srt/layers/attention/linear/kernels/kda_nvidia.py | .py | # SPDX-License-Identifier: Apache-2.0
"""NVIDIA split KDA prefill backend (K1-K4 CuTe/Triton/cuTile pipeline).
Wraps the vendored ``kda_nvidia_prefill`` package through its FLA-compatible
``chunk_kda_fwd`` interface. SGLang owns the boundary conversion from its
V-major ``[B,H,V,K]`` cache to the vendor's K-major ``[B,... | 496 | 17,741 |
sglang | python/sglang/srt/layers/attention/linear/kernels/gdn_triton.py | .py | import torch
from sglang.srt.layers.attention.linear.kernels.kernel_backend import (
LinearAttnKernelBase,
)
from sglang.srt.utils import is_cpu, is_npu, is_xpu
if not is_cpu():
from sglang.kernels.ops.attention.fla.chunk import chunk_gated_delta_rule
from sglang.kernels.ops.attention.fla.fused_recurrent ... | 242 | 8,261 |
sglang | python/sglang/srt/layers/attention/linear/kernels/kernel_backend.py | .py | from abc import ABC, abstractmethod
import torch
class LinearAttnKernelBase(ABC):
"""Abstract base class for linear attention kernel implementations.
Each concrete implementation wraps a specific kernel (Triton, CuTe DSL, etc.)
and provides decode/extend/target_verify methods with a unified interface.
... | 65 | 1,611 |
sglang | python/sglang/srt/layers/attention/linear/kernels/gdn_cutedsl.py | .py | """CuTe DSL kernels for GDN (Gated Delta Network) linear attention.
Decode path uses the existing ``cutedsl_fused_sigmoid_gating_delta_rule_update``
(works on SM90+).
Prefill (extend) path uses the ported vLLM SM100 chunkwise kernel
(``chunk_gated_delta_rule_cutedsl``). Requires SM100+ and ``head_k_dim == 128``.
"""
... | 175 | 5,930 |
sglang | python/sglang/srt/layers/attention/linear/kernels/gdn_flashinfer.py | .py | """FlashInfer-based kernels for GDN (Gated Delta Network) linear attention.
Both SM90 and SM100 use the same pool layout: [pool, HV, V, K] (K-last).
SM90 (Hopper): full support — decode, prefill, MTP. State dtype: fp32.
SM100 (Blackwell): full support — decode, prefill, MTP.
Requires flashinfer >= 0.6.14.
"""
from... | 437 | 16,109 |
sglang | python/sglang/srt/layers/attention/wave_ops/decode_attention.py | .py | """
Memory-efficient attention for decoding.
It supports page size = 1.
"""
import functools
import logging
from wave_lang.kernel.lang.global_symbols import *
from wave_lang.kernel.wave.compile import WaveCompileOptions, wave_compile
from wave_lang.kernel.wave.constraints import GenericDot, MMAOperand, MMAType
from w... | 185 | 4,732 |
sglang | python/sglang/srt/layers/attention/wave_ops/prefill_attention.py | .py | """
Memory-efficient attention for prefill.
It support page size = 1.
"""
import math
import os
from wave_lang.kernel.lang.global_symbols import *
from wave_lang.kernel.wave.compile import WaveCompileOptions, wave_compile
from wave_lang.kernel.wave.constraints import MMAType
from wave_lang.kernel.wave.templates.atten... | 80 | 2,342 |
sglang | python/sglang/srt/layers/attention/wave_ops/extend_attention.py | .py | """
Memory-efficient attention for prefill.
It support page size = 1.
"""
import functools
import os
import torch
from wave_lang.kernel.lang.global_symbols import *
from wave_lang.kernel.wave.compile import WaveCompileOptions, wave_compile
from wave_lang.kernel.wave.constraints import MMAType
from wave_lang.kernel.wa... | 148 | 3,877 |
sglang | python/sglang/srt/layers/attention/dsa/dsa_npu_indexer.py | .py | from __future__ import annotations
import torch
from sglang.srt.environ import envs
from sglang.srt.layers.communicator import ScatterMode
from sglang.srt.layers.dp_attention import attn_tp_all_gather_into_tensor
from sglang.srt.layers.utils.cp_utils import cp_all_gather_rerange_output
from sglang.srt.model_executor.... | 370 | 15,591 |
sglang | python/sglang/srt/layers/attention/dsa/utils.py | .py | from functools import lru_cache
from typing import TYPE_CHECKING, List, Tuple, Union
import torch
import triton
from sglang.srt.environ import envs
from sglang.srt.layers.dp_attention import DpPaddingMode
from sglang.srt.model_executor.runner_backend_utils.breakable_cuda_graph import (
is_in_breakable_cuda_graph,... | 365 | 14,120 |
sglang | python/sglang/srt/layers/attention/dsa/dsa_indexer.py | .py | from __future__ import annotations
import contextlib
import logging
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
import torch
from einops import rearrange
from sglang.kernels.fused_op import BaseFusedOp
from sglang.kernels.ops.attention.fused_store_index_cache import (
can_use_dsa_fu... | 1,836 | 71,862 |
sglang | python/sglang/srt/layers/attention/dsa/paged_mqa_logits_backend.py | .py | from __future__ import annotations
from enum import Enum
from sglang.srt.utils import is_hip, is_sm100_supported
class DSAPagedMQALogitsBackend(Enum):
DEEPGEMM = "deepgemm"
CUTEDSL = "cutedsl"
AITER = "aiter"
def is_deepgemm(self) -> bool:
return self == DSAPagedMQALogitsBackend.DEEPGEMM
... | 43 | 1,442 |
sglang | python/sglang/srt/layers/attention/dsa/dsa_backend_mtp_precompute.py | .py | """Multi-step precompute utilities for Native Sparse Attention backend.
This module provides optimization utilities for multi-step speculative decoding
by precomputing shared metadata once and copying it to multiple backend instances.
"""
from __future__ import annotations
from dataclasses import dataclass
from typi... | 384 | 14,382 |
sglang | python/sglang/srt/layers/attention/dsa/dsa_topk_backend.py | .py | from __future__ import annotations
from enum import Enum, IntEnum, auto
from typing import Callable, Dict, List, Optional, Tuple
import torch
from sglang.srt.environ import envs
_FLASHINFER_TIE_BREAK_VALUES = {
"small": 1,
"large": 2,
}
class TopkTransformMethod(IntEnum):
# Transform topk indices to i... | 377 | 15,580 |
sglang | python/sglang/srt/layers/attention/dsa/dsa_indexer_metadata.py | .py | from __future__ import annotations
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import TYPE_CHECKING, List, Optional, Tuple
import torch
from sglang.srt.layers.attention.dsa.dsa_backend_mtp_precompute import (
compute_cu_seqlens,
)
from sglang.srt.layers.attention.dsa.dsa_top... | 169 | 5,619 |
sglang | python/sglang/srt/layers/attention/dsa/dsa_prefill_cuda_graph.py | .py | from __future__ import annotations
import torch
from sglang.srt.compilation.compilation_config import register_split_op
from sglang.srt.model_executor.forward_context import get_attn_backend
from sglang.srt.model_executor.runner_backend_utils.breakable_cuda_graph import (
eager_on_graph,
)
from sglang.srt.model_e... | 192 | 6,673 |
sglang | python/sglang/srt/layers/attention/minimax_sparse_ops/minimax_sparse.py | .py | # Copyright 2025 XunhaoLai. All rights reserved.
import logging
from typing import Callable, List, Optional, Tuple
import torch
from sglang.kernels.ops.attention.minimax_sparse.common.index import topk_index_reduce
from sglang.kernels.ops.attention.minimax_sparse.common.utils import get_cu_seqblocks
from sglang.kern... | 330 | 12,646 |
sglang | python/sglang/srt/layers/attention/minimax_sparse_ops/msa.py | .py | # MSA (fmha_sm100) drop-in for the MiniMax-M3 main sparse-attention step.
#
# Replaces only step 3 of MiniMax sparse prefill/decode. The lightning indexer
# (steps 1-2) is unchanged and still produces `topk_idx`.
# NVIDIA Blackwell (SM100/sm_103) only; callers gate on `msa_available()`.
#
# Dtypes: bf16 end-to-end, or ... | 459 | 18,963 |
sglang | python/sglang/srt/layers/attention/minimax_sparse_ops/tests/test_msa_fp8_parity.py | .py | """Parity tests for MSA (fmha_sm100) all-fp8 sparse attention (fp8 attn-GEMM mode).
No upstream fp8 test exists for fmha_sm100's cutlass sparse-decode path, so
this is the reference check: MSA fp8 vs the Triton fp8 sparse kernels on the
same quantized tensors, plus fp8-vs-bf16 error bounds and CUDA-graph
capture/repla... | 287 | 9,735 |
sglang | python/sglang/srt/layers/attention/minimax_sparse_ops/tests/test_fp8_attn_gemm.py | .py | """Unit tests for fp8 (fp8 attn-GEMM mode) support in the M3 sparse Triton kernels.
Strategy: quantize random bf16 tensors to fp8_e4m3fn, then compare the fp8
kernel run against the SAME kernel run in bf16 on the *dequantized* tensors.
Both runs see numerically identical Q/K values, so the QK GEMMs match closely
and t... | 456 | 15,247 |
sglang | python/sglang/srt/layers/attention/minimax_sparse_ops/tests/test_sparse_gqa.py | .py | """Unit tests for flash_decode_with_gqa_share_sparse (sparse GQA attention).
Tests the Triton sparse GQA kernel against a PyTorch reference that computes
attention only on the topk blocks via standard softmax, covering GQA ratios,
sink tokens, paged KV (randperm), variable seq_lens, and edge cases.
"""
import sys
im... | 363 | 10,900 |
sglang | python/sglang/srt/layers/attention/minimax_sparse_ops/tests/test_flash_with_topk_idx.py | .py | import sys
import pytest
import torch
from sglang.kernels.ops.attention.minimax_sparse.decode.flash_with_topk_idx import (
flash_decode_with_topk_idx,
)
from sglang.srt.environ import envs
DEVICE = "cuda"
RTOL_VS_REF = 5e-3
ATOL_VS_REF = 5e-3
# ------------------------------------------------------------------... | 481 | 14,421 |
sglang | python/sglang/srt/layers/attention/minimax_sparse_ops/naive/flash_with_topk_idx.py | .py | # Copyright 2025 XunhaoLai. All rights reserved.
from typing import Optional
import torch
from einops import einsum, rearrange
def naive_flash_decode_with_topk_idx(
q: torch.Tensor, # [batch_size, num_heads, head_dim]
sink: Optional[torch.Tensor], # [num_heads, head_dim]
kv_cache: torch.Tensor, # [ma... | 85 | 3,445 |
sglang | python/sglang/srt/layers/attention/minimax_sparse_ops/naive/topk_sparse.py | .py | # Copyright 2025 XunhaoLai. All rights reserved.
from typing import Optional
import torch
def naive_flash_decode_with_gqa_share_sparse(
q: torch.Tensor, # [batch_size, num_q_heads, head_dim]
sink: Optional[torch.Tensor], # [num_q_heads, head_dim]
kv_cache: torch.Tensor, # [max_slots, 2, max_len, num_... | 89 | 3,568 |
sglang | python/sglang/srt/weight_sync/utils.py | .py | from typing import Optional
import torch
import torch.distributed as dist
from torch.distributed.device_mesh import DeviceMesh
from torch.distributed.tensor import DTensor
from sglang.srt.entrypoints.engine import Engine
from sglang.srt.managers.io_struct import UpdateWeightsFromTensorReqInput
from sglang.srt.model_e... | 122 | 4,190 |
sglang | python/sglang/srt/weight_sync/tensor_bucket.py | .py | from dataclasses import dataclass
from typing import List, Tuple
import torch
@dataclass
class FlattenedTensorMetadata:
"""Metadata for a tensor in a flattened bucket"""
name: str
shape: torch.Size
dtype: torch.dtype
start_idx: int
end_idx: int
numel: int
class FlattenedTensorBucket:
... | 108 | 3,749 |
sglang | python/sglang/srt/debug_utils/tensor_dump_forward_hook.py | .py | """
This file provides a function `register_forward_hook_for_model` that registers a forward hook on every operator of the model.
After registration, during model inference, all tensors generated throughout the forward pass will be recorded.
Usage:
Specify the output directory for dumping tensors using the argument `-... | 165 | 6,923 |
sglang | python/sglang/srt/debug_utils/text_comparator.py | .py | import argparse
import hashlib
import json
from pathlib import Path
import polars as pl
_DESCRIPTION = """Compare and find differences to benchmark outputs.
Supported inputs:
* The samples jsonl from `lm_eval --log_samples --output_path FOLDER_NAME`
* The output from `gsm8k/bench_sglang.py --raw-result-file FILE_NAM... | 235 | 7,370 |
sglang | python/sglang/srt/debug_utils/log_parser.py | .py | _PATTERN_DECODE = (
r"(\(\w+ pid=(?P<pid>\d+)(?:,\s*ip=(?P<ip>[\d\.]+))?\))?\s*"
r"\[(?P<time>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})"
r"(?:\s+DP(?P<dp_rank>\d+))?"
r"(?:\s+TP(?P<tp_rank>\d+))?"
r"(?:\s+EP(?P<ep_rank>\d+))?"
r"(?:\s+PP(?P<pp_rank>\d+))?"
r"\]\s+"
r"Decode batch( \[\d+\])?,\... | 47 | 1,524 |
sglang | python/sglang/srt/debug_utils/cuda_coredump.py | .py | """CUDA coredump helpers.
When SGLANG_CUDA_COREDUMP=1, this module injects CUDA coredump environment
variables into the current process so that GPU exceptions (e.g. illegal
memory access) produce lightweight coredump files for post-mortem analysis
with cuda-gdb.
The injection happens at module import time via _inject... | 113 | 3,935 |
sglang | python/sglang/srt/debug_utils/dumper.py | .py | import enum
import functools
import json
import os
import random
import re
import socket
import threading
import time
import traceback
from abc import ABC, abstractmethod
from collections.abc import Callable
from contextlib import contextmanager
from copy import deepcopy
from dataclasses import asdict, dataclass, field... | 2,029 | 70,122 |
sglang | python/sglang/srt/debug_utils/pr_fix_toggle.py | .py | """Reverse-apply historical PR fixes for regression-style tests."""
from __future__ import annotations
from typing import Dict
from sglang.srt.debug_utils.source_patcher import apply_patches_from_config
from sglang.srt.environ import envs
_PR_REVERT_YAML_25015 = """
patches:
- target: sglang.srt.speculative.eagle... | 134 | 4,205 |
sglang | python/sglang/srt/debug_utils/dump_loader.py | .py | import functools
import os
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable, Dict, Optional, Tuple
import polars as pl
import torch
LOAD_FAILED: object = object()
def parse_meta_from_filename(path: Path) -> Dict[str, Any]:
stem = Path(path).stem
result: Dict[str, A... | 184 | 5,467 |
sglang | python/sglang/srt/debug_utils/model_truncator.py | .py | # This file also references Slime :: fp8_cast_bf16.py
import json
import os
import re
from argparse import ArgumentParser
from pathlib import Path
from typing import Dict
import torch
from huggingface_hub import snapshot_download
from safetensors.torch import load_file, save_file
def main(args):
dir_input = Path... | 113 | 3,718 |
sglang | python/sglang/srt/debug_utils/dump_comparator.py | .py | """Simplified dump comparator — a self-contained single-file script for comparing
two dump directories tensor-by-tensor.
For advanced features (unshard, token alignment, per-dimension annotations), see the
full ``comparator/`` package: ``python -m sglang.srt.debug_utils.comparator``.
"""
import argparse
import functo... | 298 | 9,585 |
sglang | python/sglang/srt/debug_utils/source_patcher/types.py | .py | import types
from collections.abc import Callable
from typing import Any
from pydantic import BaseModel, ConfigDict, model_validator
class PatchApplicationError(Exception):
"""match text not found or not unique in source."""
class _StrictBase(BaseModel):
model_config = ConfigDict(extra="forbid")
class Ed... | 64 | 1,737 |
sglang | python/sglang/srt/debug_utils/source_patcher/source_editor.py | .py | from sglang.srt.debug_utils.source_patcher.types import EditSpec, PatchApplicationError
def apply_edits(*, source: str, edits: list[EditSpec]) -> str:
"""Apply a sequence of match/replacement edits to source text.
Each edit is applied sequentially so later edits see the result of earlier ones.
"""
re... | 145 | 5,107 |
sglang | python/sglang/srt/debug_utils/source_patcher/__init__.py | .py | from sglang.srt.debug_utils.source_patcher.code_patcher import (
CodePatcher,
apply_patches_from_config,
patch_function,
)
from sglang.srt.debug_utils.source_patcher.types import (
EditSpec,
PatchApplicationError,
PatchConfig,
PatchSpec,
PatchState,
)
| 13 | 284 |
sglang | python/sglang/srt/debug_utils/source_patcher/code_patcher.py | .py | import __future__
import importlib
import inspect
import textwrap
import types
from collections.abc import Callable
from typing import Any, Optional
import yaml
from sglang.srt.debug_utils.source_patcher.source_editor import apply_edits
from sglang.srt.debug_utils.source_patcher.types import (
EditSpec,
Patc... | 196 | 6,091 |
sglang | python/sglang/srt/debug_utils/comparator/output_types.py | .py | from __future__ import annotations
from abc import abstractmethod
from typing import TYPE_CHECKING, Annotated, Any, Literal, Optional, Union
from pydantic import ConfigDict, Discriminator, Field, TypeAdapter, model_validator
from rich.console import Group, RenderableType
from rich.markup import escape
from sglang.sr... | 325 | 9,437 |
sglang | python/sglang/srt/debug_utils/comparator/display.py | .py | from __future__ import annotations
from collections import defaultdict
from io import StringIO
from pathlib import Path
from typing import Any, Optional
import polars as pl
from sglang.srt.debug_utils.comparator.output_types import (
InputIdsRecord,
RankInfoRecord,
)
from sglang.srt.debug_utils.comparator.re... | 145 | 4,489 |
sglang | python/sglang/srt/debug_utils/comparator/utils.py | .py | from __future__ import annotations
import functools
import re
from pathlib import Path
from typing import TYPE_CHECKING, Callable, Generic, Optional, Tuple, TypeVar
import torch
from pydantic import BaseModel, ConfigDict
_T = TypeVar("_T")
_U = TypeVar("_U")
def _check_equal_lengths(**named_lists: list) -> None:
... | 166 | 4,829 |
sglang | python/sglang/srt/debug_utils/comparator/__main__.py | .py | from sglang.srt.debug_utils.comparator.entrypoint import main
if __name__ == "__main__":
main()
| 5 | 101 |
sglang | python/sglang/srt/debug_utils/comparator/__init__.py | .py | from sglang.srt.debug_utils.comparator.aligner.entrypoint.traced_types import ( # noqa: F401
TracedAlignerPlan,
)
from sglang.srt.debug_utils.comparator.aligner.entrypoint.types import ( # noqa: F401
AlignerPlan,
)
from sglang.srt.debug_utils.comparator.output_types import ComparisonTensorRecord
ComparisonTe... | 10 | 347 |
sglang | python/sglang/srt/debug_utils/comparator/dp_utils.py | .py | """DP filtering: keep only the non-empty dp_rank items."""
from __future__ import annotations
from collections import defaultdict
from typing import Optional
import torch
from sglang.srt.debug_utils.comparator.dims_spec import ParallelAxis
from sglang.srt.debug_utils.dump_loader import ValueWithMeta
_PARALLEL_INFO... | 101 | 2,975 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.