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/kernels/ops/attention/linear/seg_la.py | .py | # -*- coding: utf-8 -*-
"""
Copyright (c) Ant Financial Service Group and its affiliates.
"""
# Copied from https://code.alipay.com/pia/PainlessInferenceAcceleration/blob/v0.0.6/flood/flood/ops/seg_la.py
from dataclasses import dataclass
from typing import Optional
import torch
import triton
import triton.language a... | 946 | 26,839 |
sglang | python/sglang/kernels/ops/attention/linear/kda_ptx_prefill/__init__.py | .py | # SPDX-License-Identifier: Apache-2.0
"""Hand-written PTX/tcgen05 KDA chunked-prefill kernel (GB300 / sm_103a).
Vendored from the upstream ``kda_prefill`` artifact (commit 33583615): the CUDA
source in ``kernels/jit/csrc/attention/kda_prefill.cu`` plus the FLA-signature
``chunk_kda_fwd`` wrapper below, which is a drop... | 208 | 7,939 |
sglang | python/sglang/kernels/ops/attention/linear/kda_blackwell/kernel_h.py | .py | # SPDX-License-Identifier: Apache-2.0
# KDA (Kimi Delta Attention) SM100 chunk recurrent-state kernel.
#
# Idea is adopted from GDN blackwell kernel. KDA differs from GDN only in the
# decay gate, which is PER-CHANNEL (one decay per key-dim k) instead of a single
# scalar per head. The hard cross-token part of the per-... | 720 | 30,328 |
sglang | python/sglang/kernels/ops/attention/linear/kda_blackwell/prologue.py | .py | # SPDX-License-Identifier: Apache-2.0
# Fused Triton prologue for the KDA Blackwell pipeline.
#
# In ONE pass per (chunk, head) it computes the per-chunk cumsum g_cu and the five
# pre-scaled key/query tensors the cutedsl kernels consume, replacing ~30 separate
# PyTorch elementwise ops + copies:
#
# g_cu = cums... | 103 | 3,426 |
sglang | python/sglang/kernels/ops/attention/linear/kda_blackwell/__init__.py | .py | # SPDX-License-Identifier: Apache-2.0
# KDA (Kimi Delta Attention) SM100/Blackwell CuteDSL prefill pipeline.
#
# Mirrors gdn_blackwell but for KDA's PER-CHANNEL decay gate. A fused Triton
# prologue computes the per-chunk cumsum g_cu and five pre-scaled key/query
# tensors; three cutedsl kernels then run the chunked ga... | 260 | 10,208 |
sglang | python/sglang/kernels/ops/attention/linear/kda_blackwell/kernel_kkt_inv_uw.py | .py | # SPDX-License-Identifier: Apache-2.0
# KDA (Kimi Delta Attention) SM100 KKT-inverse + U/W kernel.
#
# Adapted from gdn_blackwell/kernel_kkt_inv_uw.py. KDA's decay is PER-CHANNEL, so
# (as with kernel_h/o) the gate is folded OUTSIDE this kernel into pre-scaled keys:
#
# kL [c,d] = k[c,d] * exp(g_cu[c,d] - g_cu_last[d... | 742 | 31,529 |
sglang | python/sglang/kernels/ops/attention/linear/kda_blackwell/kernel_o.py | .py | # SPDX-License-Identifier: Apache-2.0
# KDA (Kimi Delta Attention) SM100 output kernel.
#
# Adapted from gdn_blackwell/kernel_o.py. KDA's decay is PER-CHANNEL, so the
# decay cannot be applied as a post-MMA scalar Gamma. Instead all gate + scale
# factors are folded OUTSIDE this kernel into three pre-scaled tensors:
#
... | 585 | 23,727 |
sglang | python/sglang/kernels/ops/attention/linear/kda_nvidia_prefill/fuse_k4_only_persistent.py | .py | # Vendored from the NVIDIA KDA_prefill package (benchmark/ Blackwell path)
# for the Kimi-K3 chunked prefill forward. Local deltas: fla.* imports
# re-pointed to sglang's vendored fla subset, flat sibling imports made
# package-relative, RCP_LN2 inlined.
# ruff: noqa -- vendored kernel library, minimal local deltas
""... | 1,296 | 50,380 |
sglang | python/sglang/kernels/ops/attention/linear/kda_nvidia_prefill/chunk_fwd.py | .py | # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES.
# SPDX-License-Identifier: Apache-2.0
# Vendored from the NVIDIA KDA_prefill package (benchmark/ Blackwell path)
# for the Kimi-K3 chunked prefill forward. Local deltas: fla.* imports
# re-pointed to sglang's vendored fla subset, flat sibling... | 1,147 | 42,599 |
sglang | python/sglang/kernels/ops/attention/linear/kda_nvidia_prefill/fuse_kernel123_persistent.py | .py | # Vendored from the NVIDIA KDA_prefill package (benchmark/ Blackwell path)
# for the Kimi-K3 chunked prefill forward. Local deltas: fla.* imports
# re-pointed to sglang's vendored fla subset, flat sibling imports made
# package-relative, RCP_LN2 inlined.
# ruff: noqa -- vendored kernel library, minimal local deltas
""... | 1,705 | 77,116 |
sglang | python/sglang/kernels/ops/attention/linear/kda_nvidia_prefill/Akk_inverse_lower_triangle_bf16.py | .py | # Vendored from the NVIDIA KDA_prefill package (benchmark/ Blackwell path)
# for the Kimi-K3 chunked prefill forward. Local deltas: fla.* imports
# re-pointed to sglang's vendored fla subset, flat sibling imports made
# package-relative, RCP_LN2 inlined.
# ruff: noqa -- vendored kernel library, minimal local deltas
""... | 1,009 | 34,382 |
sglang | python/sglang/kernels/ops/attention/linear/gdn_blackwell/kernel_h.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/4868b542c9dfd166662eecc4bb8be3a36a3feaa2/vllm/model_executor/layers/mamba/ops/gdn_chunk_cutedsl/kernel_h.py
from functools import cache
import cutlass
impo... | 773 | 31,667 |
sglang | python/sglang/kernels/ops/attention/linear/gdn_blackwell/__init__.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/4868b542c9dfd166662eecc4bb8be3a36a3feaa2/vllm/model_executor/layers/mamba/ops/gdn_chunk_cutedsl/__init__.py
from functools import cache
import cutlass
imp... | 269 | 8,743 |
sglang | python/sglang/kernels/ops/attention/linear/gdn_blackwell/kernel_kkt_inv_uw.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/4868b542c9dfd166662eecc4bb8be3a36a3feaa2/vllm/model_executor/layers/mamba/ops/gdn_chunk_cutedsl/kernel_kkt_inv_uw.py
from functools import cache
import cut... | 824 | 34,293 |
sglang | python/sglang/kernels/ops/attention/linear/gdn_blackwell/kernel_o.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/4868b542c9dfd166662eecc4bb8be3a36a3feaa2/vllm/model_executor/layers/mamba/ops/gdn_chunk_cutedsl/kernel_o.py
from functools import cache
import cutlass
impo... | 632 | 24,716 |
sglang | python/sglang/kernels/ops/attention/helion/__init__.py | .py | """Helion attention kernels."""
# K3 exposes 12 local value heads at TP=8. Lower value-head counts share the
# same small-head decode regime.
KDA_SMALL_VALUE_HEAD_THRESHOLD = 12
| 6 | 179 |
sglang | python/sglang/kernels/ops/attention/helion/kda_prefill.py | .py | """Helion kernels for SGLang's Kimi Delta Attention prefill path.
The public :func:`chunk_kda` entry point in this module is intended to match
``sglang.kernels.ops.attention.fla.kda.chunk_kda``. KDA uses 64-token chunks
and keeps the cumulative per-key decay in base-2 logarithm space.
"""
from __future__ import anno... | 1,400 | 43,239 |
sglang | python/sglang/kernels/ops/attention/helion/kda_decode.py | .py | """Helion implementation of SGLang's packed KDA decode contract."""
from __future__ import annotations
import helion
import helion.language as hl
import torch
from sglang.kernels.ops.attention.helion import KDA_SMALL_VALUE_HEAD_THRESHOLD
# SGLang initializes torch.distributed, but this kernel has no collectives.
_I... | 385 | 12,603 |
sglang | python/sglang/kernels/ops/attention/helion/kda_replayssm.py | .py | """Helion ReplaySSM decode for Kimi Delta Attention.
The public :func:`helion_fused_recurrent_kda_replayssm_decode` mirrors
``fused_recurrent_linear_replayssm_decode(..., is_kda=True)`` from
``sglang.kernels.ops.attention.fla.fused_recurrent_linear_replayssm``. That
Triton kernel is gate-generic (GDN scalar gate / KD... | 781 | 26,619 |
sglang | python/sglang/kernels/ops/attention/fa4_sm120/runtime.py | .py | # Copyright (c) 2025, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao.
"""Host-side policy and launch state for the SM120 forward kernel.
The generic FA4 interface owns argument normalization, compilation, and
architecture dispatch. This module owns the SM120-specific decisions that
must... | 1,629 | 55,918 |
sglang | python/sglang/kernels/ops/attention/fa4_sm120/scheduler.py | .py | # Copyright (c) 2026, SGLang Team.
"""Schedulers owned by the SGLang SM120 FA4 implementation."""
from dataclasses import dataclass
from typing import Tuple
import cutlass
import cutlass.cute as cute
from cutlass import Int32
from quack.cute_dsl_utils import ParamsBase
from sglang.kernels.ops.attention.flash_attn.cu... | 151 | 5,094 |
sglang | python/sglang/kernels/ops/attention/fa4_sm120/policy.py | .py | # Copyright (c) 2026, SGLang Team.
"""Pure workload qualification shared by the SM120 FA4 host and kernel."""
from typing import Optional
LOW_HD_DECODE_SHAPES = frozenset({(64, 64), (128, 128)})
LOW_HD_DECODE_TILE_N = 64
LOW_HD_DECODE_MIN_VISIBLE_K = 256
LOW_HD_DECODE_SHORT_VISIBLE_K = 512
LOW_HD_DECODE_MAX_SPLITS = ... | 91 | 2,919 |
sglang | python/sglang/kernels/ops/attention/fa4_sm120/paged_kv.py | .py | import math
from dataclasses import dataclass
from typing import Type
import cutlass
import cutlass.cute as cute
from cutlass import Int32, const_expr
from cutlass.cute import FastDivmodDivisor
from cutlass.cute.nvgpu import cpasync
from quack.cute_dsl_utils import ParamsBase
from sglang.kernels.ops.attention.flash_a... | 217 | 7,970 |
sglang | python/sglang/kernels/ops/attention/fa4_sm120/dispatch.py | .py | # Copyright (c) 2026, SGLang Team.
"""Lightweight dispatch bridge for SGLang-owned SM120 FA4 kernels.
The vendored FA4 interface dispatches through this module so the SM120
implementation and its launch state remain outside ``flash_attn/cute``.
"""
from functools import lru_cache
@lru_cache(maxsize=None)
def get_fo... | 59 | 1,989 |
sglang | python/sglang/kernels/ops/attention/fa4_sm120/flash_fwd_decode.py | .py | # Copyright (c) 2026, SGLang Team.
"""End-to-end transposed SM120 paged-decode specialization.
This path keeps the packed query axis on the N=8 dimension of warp MMA:
scores.T = K @ Q.T # (64, 8)
output.T = V.T @ P.T # (256, 8)
The dataflow is isolated from the general SM120 kernel because its pa... | 712 | 27,106 |
sglang | python/sglang/kernels/ops/attention/fa4_sm120/flash_fwd.py | .py | # Copyright (c) 2025, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao.
# SM120 (Blackwell GeForce / DGX Spark) forward pass.
import math
import operator
from functools import lru_cache, partial
from types import SimpleNamespace
from typing import Callable, Optional
import cuda.bindings.... | 4,553 | 170,836 |
sglang | python/sglang/kernels/ops/attention/fla/l2norm.py | .py | # Adapt from https://github.com/fla-org/flash-linear-attention/blob/main/fla/modules/l2norm.py
# -*- coding: utf-8 -*-
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
from typing import Optional
import torch
import torch.nn as nn
import triton
import triton.language as tl
from sglang.kernels.ops.attention.fla.util... | 148 | 3,720 |
sglang | python/sglang/kernels/ops/attention/fla/fused_recurrent_linear_replayssm.py | .py | # Buffered output-only linear-attention decode (ReplaySSM Part A), ported to
# SGLang. Covers BOTH gate granularities with one kernel:
# * GDN (``IS_KDA=False``): per-head SCALAR gate ``alpha = exp(g)``.
# * KDA (``IS_KDA=True``): per-K-channel gate ``alpha[k] = exp(g[k])`` —
# the state decays column-wise, ... | 629 | 27,441 |
sglang | python/sglang/kernels/ops/attention/fla/chunk_o.py | .py | # Adapted from https://github.com/fla-org/flash-linear-attention/blob/main/fla/ops/common/chunk_o.py
# -*- coding: utf-8 -*-
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
from typing import Optional
import torch
import triton
import triton.language as tl
from sglang.kernels.ops.attention.fla.index import prepare... | 175 | 4,904 |
sglang | python/sglang/kernels/ops/attention/fla/utils.py | .py | # Adapt from https://github.com/fla-org/flash-linear-attention/blob/main/fla/utils.py
# -*- coding: utf-8 -*-
import contextlib
import functools
import inspect
import logging
import os
import sys
from enum import Enum
from functools import lru_cache
from typing import Any, Callable, Dict, Literal, Optional, Tuple
imp... | 340 | 10,666 |
sglang | python/sglang/kernels/ops/attention/fla/chunk.py | .py | # Adapted from https://github.com/fla-org/flash-linear-attention/blob/main/fla/ops/gated_delta_rule/chunk.py
# -*- coding: utf-8 -*-
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
from typing import Optional
import torch
from einops import rearrange
from sglang.kernels.ops.attention.fla.chunk_delta_h import chunk... | 263 | 9,330 |
sglang | python/sglang/kernels/ops/attention/fla/index.py | .py | # Adapt from https://github.com/fla-org/flash-linear-attention/blob/main/fla/ops/utils/index.py
# -*- coding: utf-8 -*-
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
import torch
import triton
from sglang.kernels.ops.attention.fla.utils import tensor_cache
@tensor_cache
def prepare_lens(cu_seqlens: torch.LongTe... | 36 | 990 |
sglang | python/sglang/kernels/ops/attention/fla/chunk_intra_token_parallel.py | .py | # Adapted from flash-linear-attention project.
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
# Token-parallel implementation of KDA intra chunk kernel
import torch
import triton
import triton.language as tl
from sglang.kernels.ops.attention.fla.op import exp2
from sglang.kernels.ops.attention.fla.utils import aut... | 198 | 5,333 |
sglang | python/sglang/kernels/ops/attention/fla/chunk_fwd.py | .py | # Adapted from https://github.com/fla-org/flash-linear-attention/blob/main/fla/ops/gated_delta_rule/chunk_fwd.py
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
import torch
import triton
import triton.language as tl
from sglang.kernels.ops.attention.fla.index import prepare_chunk_indices
from sglang.kernels.ops.at... | 417 | 15,932 |
sglang | python/sglang/kernels/ops/attention/fla/fused_norm_gate.py | .py | # Adapt from https://github.com/fla-org/flash-linear-attention/blob/main/fla/modules/fused_norm_gate.py
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
import torch
import torch.nn as nn
import triton
import triton.language as tl
from sglang.srt.utils import (
cdiv,
cpu_has_amx_support,
is_cpu,
is_... | 397 | 12,337 |
sglang | python/sglang/kernels/ops/attention/fla/layernorm_gated.py | .py | # Adapt from https://github.com/fla-org/flash-linear-attention/blob/main/fla/modules/layernorm_gated.py
# Copyright (c) 2024, Tri Dao.
# Based on the Triton LayerNorm tutorial: https://triton-lang.org/main/getting-started/tutorials/05-layer-norm.html
# For the backward pass, we keep weight_grad and bias_grad in registe... | 484 | 15,241 |
sglang | python/sglang/kernels/ops/attention/fla/chunk_intra.py | .py | # Adapted from flash-linear-attention project.
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
import torch
import triton
import triton.language as tl
from sglang.kernels.ops.attention.fla.chunk_intra_token_parallel import (
chunk_kda_fwd_intra_token_parallel,
)
from sglang.kernels.ops.attention.fla.index impor... | 1,054 | 40,508 |
sglang | python/sglang/kernels/ops/attention/fla/cumsum.py | .py | # Adapt from https://github.com/fla-org/flash-linear-attention/blob/main/fla/ops/utils/cumsum.py
# -*- coding: utf-8 -*-
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
from typing import Optional
import torch
import triton
import triton.language as tl
from sglang.kernels.ops.attention.fla.index import prepare_chu... | 295 | 8,522 |
sglang | python/sglang/kernels/ops/attention/fla/gdn_replayssm_spec_decode.py | .py | # SPDX-License-Identifier: Apache-2.0
"""ReplaySSM speculative-decode verify kernel for GDN (Gated DeltaNet).
Ported from the vLLM ReplaySSM reference implementation
(github.com/Johnny-Liou/ReplaySSM, commit ``3c85112``,
``vllm/model_executor/layers/fla/ops/gdn_replayssm_spec_decode.py``) and the Dao
AI Lab ReplaySSM ... | 1,023 | 38,165 |
sglang | python/sglang/kernels/ops/attention/fla/fused_sigmoid_gating_recurrent.py | .py | from typing import Optional
import torch
import triton
import triton.language as tl
@triton.jit(do_not_specialize=["T"])
def fused_sigmoid_gating_delta_rule_update_kernel(
A_log,
a,
dt_bias,
softplus_beta,
softplus_threshold,
lower_bound,
q,
k,
v,
b,
o,
h0_source,
... | 507 | 18,895 |
sglang | python/sglang/kernels/ops/attention/fla/bench_gdn_replayssm_fold.py | .py | """Microbenchmark for ``commit_gdn_replayssm_fold_all_layers`` (defaults match
Qwen3.5-397B at TP4). The kernel is bound by the mandatory checkpoint
read+write (``bs * layers * HV * K * V * 4 B * 2``), so the reported GB/s
approximates achieved HBM bandwidth.
Run: ``python -m sglang.kernels.ops.attention.fla.bench_gdn... | 128 | 4,264 |
sglang | python/sglang/kernels/ops/attention/fla/kda_replayssm_spec_decode.py | .py | # SPDX-License-Identifier: Apache-2.0
"""ReplaySSM speculative-decode state commit for KDA (Kimi Delta Attention).
KDA keeps its own recurrent verify kernel for the per-step OUTPUT (unchanged),
so — unlike the GDN spec kernel (gdn_replayssm_spec_decode.py) — this module does
NOT reconstruct the verify output. It only ... | 387 | 15,027 |
sglang | python/sglang/kernels/ops/attention/fla/chunk_delta_h.py | .py | # Adapted from https://github.com/fla-org/flash-linear-attention/blob/main/fla/ops/common/chunk_delta_h.py
# -*- coding: utf-8 -*-
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
import os
from typing import Optional, Tuple
import torch
import triton
import triton.language as tl
from sglang.kernels.ops.attention.f... | 387 | 14,309 |
sglang | python/sglang/kernels/ops/attention/fla/fused_gdn_gating.py | .py | from typing import Tuple
import torch
import triton
import triton.language as tl
# g = -self.A_log.float().exp() * F.softplus(a.float() + self.dt_bias)
# beta_output = b.sigmoid()
@triton.jit
def fused_gdn_gating_kernel(
g,
beta_output,
A_log,
a,
b,
dt_bias,
seq_len,
stride_a,
str... | 76 | 2,147 |
sglang | python/sglang/kernels/ops/attention/fla/wy_fast.py | .py | # Adapt from https://github.com/fla-org/flash-linear-attention/blob/main/fla/ops/gated_delta_rule/wy_fast.py
# -*- coding: utf-8 -*-
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
from typing import Optional, Tuple
import torch
import triton
import triton.language as tl
from sglang.kernels.ops.attention.fla.index... | 157 | 4,308 |
sglang | python/sglang/kernels/ops/attention/fla/op.py | .py | # Adapt from https://github.com/fla-org/flash-linear-attention/blob/main/fla/ops/utils/op.py
# -*- coding: utf-8 -*-
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
import os
import triton
import triton.language as tl
import triton.language.extra.libdevice as tldevice
from sglang.kernels.ops.attention.fla.utils im... | 67 | 1,696 |
sglang | python/sglang/kernels/ops/attention/fla/gdn_replayssm_spec_fold.py | .py | # SPDX-License-Identifier: Apache-2.0
"""GDN ReplaySSM fold-every-commit: replay the ring-written raw inputs of the
accepted draft prefix into the fp32 checkpoint on commit (replaces the
per-draft ``intermediate_ssm`` snapshots).
The fold is a BITWISE CLONE of ``fused_sigmoid_gating_delta_rule_update_kernel``'s
GDN br... | 262 | 9,469 |
sglang | python/sglang/kernels/ops/attention/fla/fused_recurrent.py | .py | # Adapt from https://github.com/fla-org/flash-linear-attention/blob/main/fla/ops/gated_delta_rule/fused_recurrent.py
# -*- coding: utf-8 -*-
# Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
from typing import Optional, Tuple
import torch
import triton
import triton.language as tl
from sglang.kernels.ops.attention.f... | 1,262 | 44,566 |
sglang | python/sglang/kernels/ops/attention/fla/kda.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/0384aa7150c4c9778efca041ffd1beb3ad2bd694/vllm/model_executor/layers/fla/ops/kda.py
# This file contains code copied from the flash-linear-attention project.... | 1,238 | 36,154 |
sglang | python/sglang/kernels/ops/attention/dsa/paged_mqa_logits.py | .py | # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
from collections.abc import Callable
import torch
def _restore_row_stride(logits: torch.Tensor) -> torch.Tensor:
"""Undo PyTorch's DLPack st... | 185 | 6,282 |
sglang | python/sglang/kernels/ops/attention/dsa/tilelang_kernel.py | .py | import functools
from functools import lru_cache
from typing import Any, Optional, Tuple
import tilelang
import tilelang.language as T
import torch
from sglang.kernels.ops.quantization.fp8_kernel import is_fp8_fnuz
from sglang.srt.utils import is_gfx95_supported, is_hip
tilelang.set_log_level("WARNING")
# Workaroun... | 2,577 | 107,156 |
sglang | python/sglang/kernels/ops/attention/dsa/cp_split.py | .py | """Round-robin CP q-sequence split kernel for DSA prefill.
Migrated from ``sglang.srt.layers.attention.dsa.utils`` (RFC #29630, Phase 2.5).
"""
import triton
import triton.language as tl
@triton.jit
def dsa_cp_round_robin_split_q_seqs_kernel(
in_seqs_ptr,
out_seqs_ptr,
bs_idx_ptr,
tokens: tl.constex... | 30 | 780 |
sglang | python/sglang/kernels/ops/attention/dsa/cutedsl_paged_mqa_logits.py | .py | # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""CuTe DSL FP8 Paged MQA Logits runner and custom op.
Ported from TensorRT-LLM https://github.com/NVIDIA/TensorRT-LLM/pull/13219
Provides ``torch.ops.sglang.cute_dsl_fp8_paged_mqa_l... | 476 | 16,411 |
sglang | python/sglang/kernels/ops/attention/dsa/__init__.py | .py | """DeepSeek DSA kernels (RFC #29630, Phase 2.5)."""
# --- merged from sglang.kernels.ops.attention.dsa (RFC #29630 Phase 4) ---
from .paged_mqa_logits import (
aiter_paged_mqa_logits,
cutedsl_paged_mqa_logits,
deepgemm_paged_mqa_logits_native,
deepgemm_paged_mqa_logits_split,
)
def pick_dsl_expand(*a... | 34 | 944 |
sglang | python/sglang/kernels/ops/attention/dsa/index_buf_accessor.py | .py | from typing import TYPE_CHECKING
import torch
import triton
import triton.language as tl
from sglang.kernels.ops.quantization.fp8_kernel import is_fp8_fnuz
from sglang.srt.layers.attention.dsa.utils import (
INDEXER_K_CACHE_PRESHUFFLE_TILE,
aiter_can_use_preshuffle_paged_mqa,
)
from sglang.srt.utils import ge... | 714 | 23,365 |
sglang | python/sglang/kernels/ops/attention/dsa/quant_k_cache.py | .py | import torch
import triton
import triton.language as tl
def quantize_k_cache(cache_k):
return _quantize_k_cache_fast_wrapped(cache_k)
def quantize_k_cache_separate(
k_nope: torch.Tensor,
k_rope: torch.Tensor,
tile_size: int = 128,
):
"""
Quantize k_nope and k_rope separately without concat, ... | 450 | 15,944 |
sglang | python/sglang/kernels/ops/attention/dsa/dequant_k_cache.py | .py | from typing import Optional
import torch
import triton
import triton.language as tl
def dequantize_k_cache(quant_k_cache):
return _dequantize_k_cache_fast_wrapped(quant_k_cache)
def _dequantize_k_cache_ref(
quant_k_cache: torch.Tensor, # (num_blocks, block_size, 1, bytes_per_token)
dv: int = 512,
... | 657 | 22,349 |
sglang | python/sglang/kernels/ops/attention/dsa/triton_kernel.py | .py | from typing import Optional, Tuple
import torch
import triton
import triton.language as tl
# Triton implementation
@triton.jit
def _act_quant_kernel(
X_ptr,
Y_ptr,
S_ptr,
M,
N,
group_size: tl.constexpr,
round_scale: tl.constexpr,
BLOCK_M: tl.constexpr,
BLOCK_N: tl.constexpr,
):
... | 197 | 5,682 |
sglang | python/sglang/kernels/ops/attention/dsa/transform_index.py | .py | from itertools import accumulate
from typing import List, Optional
import torch
import triton
import triton.language as tl
def transform_index_page_table_prefill(**kwargs):
return transform_index_page_table_prefill_fast(**kwargs)
def transform_index_page_table_decode(**kwargs):
return transform_index_page_... | 270 | 8,779 |
sglang | python/sglang/kernels/ops/attention/dsa/triton_sparse_mla.py | .py | """Triton sparse-MLA forward for the DSA fp8 prefill path.
A per-query flash-attention kernel over the indexer-selected topk KV. On
gfx950 this is ~1.6x faster than the TileLang partial+combine kernel for the
prefill regime (n_groups=1): the attention tile is tiny (M=16 heads = one
16x16 MFMA), so a small-warp per-pro... | 161 | 5,197 |
sglang | python/sglang/kernels/ops/kv_canary/write.py | .py | from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
import torch
from sglang.kernels.jit.utils import cache_once, load_jit
from sglang.kernels.ops.kv_canary import consts
from sglang.kernels.ops.kv_canary.verify import (
VerifyOrWriteContext,
_assert_contiguo... | 262 | 13,551 |
sglang | python/sglang/kernels/ops/kv_canary/verify_ref.py | .py | from __future__ import annotations
import torch
from sglang.kernels.ops.kv_canary import consts
from sglang.kernels.ops.kv_canary.consts import splitmix64, splitmix64_mix3
from sglang.kernels.ops.kv_canary.verify import (
RealKvSource,
VerifyOrWriteContext,
VerifyPlan,
)
_U64_MASK: int = (1 << 64) - 1
_I... | 248 | 9,066 |
sglang | python/sglang/kernels/ops/kv_canary/scatter_req_token_ids.py | .py | from __future__ import annotations
import torch
import triton
import triton.language as tl
_SCATTER_TOKEN_BLOCK: int = 256
# Upper bound on bs+1 the kernel can scan per program. Owner-req lookup uses an
# outer-product tile of shape ``[TOKEN_BLOCK, BATCH_BLOCK]``; keep this small so
# the tile stays in registers (256... | 194 | 7,198 |
sglang | python/sglang/kernels/ops/kv_canary/verify.py | .py | from __future__ import annotations
from dataclasses import dataclass
from enum import IntEnum
from typing import TYPE_CHECKING, Final
import torch
from sglang.kernels.jit.utils import cache_once, load_jit, make_cpp_args
from sglang.kernels.ops.kv_canary import consts
if TYPE_CHECKING:
from tvm_ffi.module import... | 403 | 19,924 |
sglang | python/sglang/kernels/ops/kv_canary/consts.py | .py | from __future__ import annotations
from enum import IntEnum, IntFlag
from typing import Final
CANARY_CHAIN_ANCHOR: Final[int] = 0xC0FFEE1234567890
# Mirrors SGLang's ReqToTokenPool contract: req_pool_idx 0 is the CUDA-graph padding row, while real
# request rows start at 1.
REQ_POOL_IDX_PADDING: Final[int] = 0
# Mi... | 72 | 2,219 |
sglang | python/sglang/kernels/ops/kv_canary/plan_ref.py | .py | from __future__ import annotations
from typing import Optional
import torch
from sglang.kernels.ops.kv_canary.consts import REQ_POOL_IDX_PADDING
from sglang.kernels.ops.kv_canary.verify import VerifyPlan
from sglang.kernels.ops.kv_canary.write import WritePlan
def launch_canary_plan_kernels_torch_reference(
*,... | 318 | 11,235 |
sglang | python/sglang/kernels/ops/kv_canary/write_ref.py | .py | from __future__ import annotations
import torch
from sglang.kernels.ops.kv_canary import consts
from sglang.kernels.ops.kv_canary.verify import (
VerifyOrWriteContext,
)
from sglang.kernels.ops.kv_canary.verify_ref import (
_compute_real_kv_hash_scalar,
_to_signed_int64,
compute_slot_hash,
splitmi... | 214 | 8,665 |
sglang | python/sglang/kernels/ops/kv_canary/plan/entries_kernel.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING, Optional
import torch
from sglang.kernels.jit.utils import cache_once, load_jit, make_cpp_args
if TYPE_CHECKING:
from tvm_ffi.module import Module
@cache_once
def _jit_plan_entries_module(
has_swa_lut: bool, has_verify_expected_token_poo... | 72 | 2,337 |
sglang | python/sglang/kernels/ops/kv_canary/plan/utils.py | .py | from __future__ import annotations
from typing import Optional
import torch
import triton
import triton.language as tl
def _resolve_swa_lut(
lut: Optional[torch.Tensor], device: torch.device
) -> tuple[torch.Tensor, int, bool]:
"""Return the (tensor, length, has_lut) triple to launch the plan kernel with.
... | 98 | 3,441 |
sglang | python/sglang/kernels/ops/kv_canary/plan/api.py | .py | from __future__ import annotations
from typing import Optional
import torch
from sglang.kernels.ops.kv_canary.plan.entries_kernel import (
launch_plan_entries_kernel,
)
from sglang.kernels.ops.kv_canary.plan.offsets_kernel import (
_PLAN_BS_BLOCK_SIZE,
launch_plan_offsets_kernel,
)
from sglang.kernels.op... | 166 | 9,747 |
sglang | python/sglang/kernels/ops/kv_canary/plan/offsets_kernel.py | .py | from __future__ import annotations
from typing import Optional
import torch
import triton
import triton.language as tl
from sglang.kernels.ops.kv_canary.consts import (
REQ_POOL_IDX_PADDING,
TOKEN_TO_KV_SLOT_PADDING,
)
from sglang.kernels.ops.kv_canary.plan.utils import (
_compute_window_start,
_requ... | 442 | 15,555 |
sglang | docs/scripts/gen_redirects.py | .py | #!/usr/bin/env python3
"""Generate Mintlify docs.json redirects from old Sphinx paths to new Mintlify paths."""
from __future__ import annotations
import json
import os
from pathlib import Path
REPO = Path(__file__).resolve().parent.parent.parent
OLD_DOCS = REPO / "docs"
NEW_DOCS = REPO / "docs" / "docs"
# Director... | 228 | 11,285 |
sglang | docs/scripts/update_lmsys_sglang_blogs.py | .py | #!/usr/bin/env python3
"""Sync SGLang-related LMSYS blog cards into index.mdx."""
from __future__ import annotations
import json
import os
import re
import urllib.request
from dataclasses import dataclass
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
INDEX_PATH = ROOT / "index.mdx"
START_MARKE... | 287 | 9,340 |
sglang | scripts/export_deepseek_nextn.py | .py | """
Export NextN layer for DeepSeek-V3/R1 model. The exported model can be used for speculative decoding.
Usage:
python3 export_deepseek_nextn.py --input-dir /path/to/DeepSeek-V3 --output-dir /path/to/DeepSeek-V3-NextN
"""
import argparse
import json
import os
import shutil
from safetensors import safe_open
from saf... | 116 | 3,981 |
sglang | scripts/update_pr_whl_index.py | .py | #!/usr/bin/env python3
"""
Update the wheel index for PR SGLang releases.
This script generates a single PyPI-compatible index.html file at pr/index.html
containing all PR builds, ordered by PR number and commit count (newest first).
Similar to update_nightly_whl_index.py but for PR builds.
"""
import argparse
impor... | 184 | 5,916 |
sglang | scripts/convert_otel_2_perfetto.py | .py | import argparse
import bisect
import json
import time
from collections import defaultdict
from pathlib import Path
from typing import Any, Dict, Iterable, List, Tuple
parser = argparse.ArgumentParser(
description="Convert SGLang OTEL trace files to Perfetto format.",
formatter_class=argparse.ArgumentDefaultsHe... | 469 | 15,191 |
sglang | scripts/update_kernel_whl_index.py | .py | # Reference: https://github.com/flashinfer-ai/flashinfer/blob/v0.2.0/scripts/update_whl_index.py
import argparse
import hashlib
import pathlib
import re
# All the CUDA versions that the wheels will cover
SUPPORTED_CUDA_VERSIONS = ["129", "130"]
DEFAULT_CUDA_VERSION = "130"
def check_wheel_cuda_version(path_name, ta... | 95 | 3,818 |
sglang | scripts/update_deepgemm_whl_index.py | .py | # Generates a PEP 503 simple index for sgl-deep-gemm wheels under
# sgl-whl/cu<version>/sgl-deep-gemm/index.html. Mirrors the layout used by
# update_kernel_whl_index.py so consumers can `pip install
# sgl-deep-gemm --extra-index-url https://...whl/cu129`.
import argparse
import hashlib
import pathlib
import re
SUPPO... | 46 | 1,539 |
sglang | scripts/update_nightly_whl_index.py | .py | #!/usr/bin/env python3
"""
Update the wheel index for nightly SGLang releases.
This script generates a PyPI-compatible index.html file at cu{version}/sglang/index.html
containing all historical nightly builds, ordered by commit count (newest first).
The CUDA version is specified via the --cuda-version argument.
Refe... | 204 | 7,044 |
sglang | scripts/update_deepep_whl_index.py | .py | """Update the PEP 503 indexes for sgl-deep-ep release wheels."""
import argparse
import hashlib
import pathlib
import re
SUPPORTED_CUDA_VERSIONS = ("129", "130")
WHEEL_PATTERN = re.compile(
r"^sgl_deep_ep-(?P<version>[0-9][^-]*)-[^-]+-[^-]+-[^-]+\.whl$"
)
ANCHOR_PATTERN = re.compile(r'^<a href="[^"]+">(?P<filenam... | 83 | 2,935 |
sglang | scripts/sort_testcases_alphabetically.py | .py | """
Sort the test case by name alphabetically for run_suite.py
"""
from dataclasses import dataclass
@dataclass
class TestFile:
name: str
estimated_time: float = 60
suites = {}
if __name__ == "__main__":
for key in suites:
cases = suites[key]
names = [x.name for x in cases]
na... | 28 | 571 |
sglang | scripts/code_sync/utils.py | .py | """
Shared constants and helpers for code-sync scripts.
"""
import os
import re
import subprocess
from typing import Optional
# --- Configuration Begin ---
# List of folders and files to copy to / from the OSS repo.
# Changes outside these paths will be ignored.
FOLDER_NAMES = [
"3rdparty",
"assets",
"ben... | 136 | 3,920 |
sglang | scripts/code_sync/check_commits.py | .py | """
List commits in the private repo that need to be synced to the OSS repo.
NOTE:
1. This script resolves the git root automatically and can be run anywhere
inside the repo.
This script will:
1. Find the most recent sync commit (message starts with
"[Automated PR] Copy OSS code from commit").
2. Scan commits a... | 484 | 15,063 |
sglang | scripts/code_sync/copy_from_oss.py | .py | """
Sync code from OSS repo to the local repo and open a PR if changes exist.
NOTE:
1. You need to execute this script in the git root folder.
2. A GH_TOKEN environment variable is required to create the pull request.
- see also https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-... | 274 | 9,020 |
sglang | scripts/code_sync/copy_to_oss.py | .py | """
Sync a specific commit from the local private repo to the OSS upstream and open a PR.
NOTE:
1. You need to execute this script in the git root folder.
2. A GH_TOKEN environment variable is required to create the pull request.
- see also https://docs.github.com/en/authentication/keeping-your-account-and-data-secu... | 592 | 20,344 |
sglang | scripts/playground/reference_hf.py | .py | """
Usage: python3 scripts/playground/reference_hf.py --model-path MODEL_PATH --model-type {text,vlm} [--max-new-tokens NUM] [--dtype DTYPE]
--model-path MODEL_PATH: Path to model (default: TinyLlama/TinyLlama-1.1B-Chat-v0.4)
--model-type {text,vlm}: Model type, text or vlm (default: text)
--max-new-tokens NUM: M... | 198 | 6,268 |
sglang | scripts/playground/bench_speculative.py | .py | """
Usage:
# single GPU
python3 bench_speculative.py --model-path meta-llama/Llama-2-7b-chat-hf --speculative-draft-model-path lmsys/sglang-EAGLE-llama2-chat-7B
# multiple GPU
python3 bench_speculative.py --model-path deepseek-ai/DeepSeek-V3 --speculative-draft-model-path lmsys/DeepSeek-V3-NextN --tp-size 8 --trust-re... | 320 | 11,913 |
sglang | scripts/playground/load_tokenizer.py | .py | import argparse
import code
from sglang.srt.utils.hf_transformers_utils import get_tokenizer
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--name", type=str, default="meta-llama/Meta-Llama-3-8B-Instruct"
)
args = parser.parse_args()
t = get_tokenizer(... | 15 | 365 |
sglang | scripts/playground/replay_request_dump.py | .py | """
Usage:
# replay from a folder
python3 replay_request_dump.py --file-number 100 --parallel 512 --input-folder /data/lianmin/sglang_request_dump/engine-34xd1/
# replay from a single file
python3 replay_request_dump.py --parallel 512 --input-file /data/sglang_crash_dump/crash_dump_2025-06-04_20-13-18.pkl
"""
import ... | 182 | 5,725 |
sglang | scripts/playground/long_context_example.py | .py | from urllib.request import urlopen
from openai import OpenAI
test_cases = {
"64k": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2.5-1M/test-data/64k.txt",
"200k": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2.5-1M/test-data/200k.txt",
"600k": "https://qianwen-res.oss-cn-beijing.aliyuncs.c... | 37 | 1,365 |
sglang | scripts/playground/disaggregation/cli-logprob.py | .py | prompt = "The capital of france is "
import json
import requests
response = requests.post(
"http://0.0.0.0:8000/generate",
json={
"text": prompt,
"sampling_params": {"temperature": 0},
"return_logprob": True,
"return_input_logprob": True,
"logprob_start_len": 0,
},... | 23 | 508 |
sglang | scripts/playground/disaggregation/cli.py | .py | import json
import requests
prompt = """
According to CNBC's Faber, the investors present on the call interpreted this statement as an indication of an upcoming funding round. While speculative, Faber believes the funding round could be as large as $25 billion, and bestow a valuation of between $150 billion and $200 ... | 30 | 1,910 |
sglang | scripts/playground/disaggregation/cli-so.py | .py | import json
import requests
port = 8000
json_schema = json.dumps(
{
"type": "object",
"properties": {
"name": {"type": "string", "pattern": "^[\\w]+$"},
"population": {"type": "integer"},
},
"required": ["name", "population"],
}
)
# JSON
response = req... | 35 | 1,069 |
sglang | scripts/playground/router/test_tree.py | .py | import random
import string
import time
import unittest
from typing import Dict, List, Tuple
from tree import MultiTenantRadixTree
class TestMultiTenantRadixTree(unittest.TestCase):
def setUp(self):
self.tree = MultiTenantRadixTree()
def test_insert_exact_match(self):
"""Test 1: Basic insert... | 208 | 7,736 |
sglang | scripts/playground/router/tree.py | .py | import time
from collections import defaultdict
from typing import Dict
class Node:
def __init__(self):
self.children: Dict[str, Node] = dict()
# We choose to use text because most of the use cases are text-to-text,
# so we can save the tokenizing overhead.
self.text: str = ""
... | 278 | 10,235 |
sglang | scripts/playground/lora/lora_vllm_play.py | .py | from vllm import LLM, SamplingParams
from vllm.lora.request import LoRARequest
MODEL = "mistralai/Mistral-7B-Instruct-v0.3"
ADAPTER = "/home/ying/test_lora"
prompt = """
### Instruction:
Write a poem about the transformers Python library.
Mention the word "large language models" in that poem.
### Response:
The Transfo... | 31 | 704 |
sglang | scripts/playground/lora/analyzer.py | .py | import glob
import json
import os
import re
import sys
from tqdm import tqdm
sys.path.append("../../")
from fix_corrupted_json import clean_json_file
dirpath = "/Users/ying"
output_file_prefix = "analyzed_log"
time = {}
tot_time = {}
size = {}
os.system(f"rm {output_file_prefix}*")
for dirname in glob.glob(os.pat... | 78 | 2,348 |
sglang | scripts/playground/lora/lora_hf_play.py | .py | import torch
from peft import PeftModel
from transformers import LlamaForCausalLM, LlamaTokenizer
MODEL = "mistralai/Mistral-7B-Instruct-v0.3"
# ADAPTER = "winddude/wizardLM-LlaMA-LoRA-7B"
ADAPTER = "/home/ying/test_lora"
HF_TOKEN = "..."
prompt = """
### Instruction:
Write a poem about the transformers Python libra... | 63 | 1,520 |
sglang | scripts/ci_monitor/ci_auto_bisect.py | .py | #!/usr/bin/env python3
"""
SGLang CI Auto Bisect
Fetches recent Nvidia scheduled PR Test runs, identifies consistently failing
tests, and calls Claude to classify each as regression/flaky/hardware/environment.
Self-contained: does its own lightweight GitHub API analysis instead of running
the full ci_failures_analysi... | 1,312 | 45,216 |
sglang | scripts/ci_monitor/ci_failures_analysis.py | .py | """
SGLang CI Consecutive Failures Analyzer
Monitors GitHub Actions workflows for consecutive test failures and runner issues.
Detects failure streaks, tracks job health, identifies problematic runners, and generates alerts.
Features:
- Analyzes all jobs in PR Test workflow (excluding administrative jobs)
- Tracks co... | 2,752 | 125,333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.