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/rope.py
.py
from __future__ import annotations from dataclasses import dataclass from typing import TYPE_CHECKING, Optional import torch from sglang.kernels.jit.utils import ( cache_once, is_arch_support_pdl, load_jit, make_cpp_args, ) from sglang.srt.utils.custom_op import register_custom_op if TYPE_CHECKING: ...
226
7,405
sglang
python/sglang/kernels/ops/attention/rotary_triton.py
.py
"""Triton JIT kernels for multimodal rotary positional embeddings.""" from __future__ import annotations from typing import List import torch import triton import triton.language as tl @triton.jit def _triton_mrope_forward_fused( q_ptr, k_ptr, cos_sin_cache_ptr, positions_ptr, q_stride, k_s...
273
9,907
sglang
python/sglang/kernels/ops/attention/dsv4_attn_metadata_kernels.py
.py
from __future__ import annotations from typing import Optional import msgspec import torch import triton import triton.language as tl def _inputs_on_cuda(*args, **kwargs) -> bool: """Route kernel dispatch by input placement: the first tensor argument decides. CUDA inputs take the fused triton kernel; CPU in...
527
17,258
sglang
python/sglang/kernels/ops/attention/rocm_mla_decode_rope.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...
440
13,857
sglang
python/sglang/kernels/ops/attention/cutedsl_gdn.py
.py
"""CuTe DSL Fused Sigmoid Gating Delta Rule Kernel for GDN Decode.""" import logging from typing import Dict, Optional, Tuple import cuda.bindings.driver as cuda import cutlass import cutlass.cute as cute import torch from cutlass.cute.nvgpu import cpasync from cutlass.cute.runtime import from_dlpack logger = loggin...
1,495
56,512
sglang
python/sglang/kernels/ops/attention/flash_attention.py
.py
from typing import Optional, Union import torch from .flash_attention_v3 import flash_attn_varlen_func as fa3_flash_attn_varlen_func from .flash_attention_v3 import flash_attn_with_kvcache as fa3_flash_attn_with_kvcache def flash_attn_with_kvcache( q, k_cache, v_cache, k=None, v=None, qv=Non...
329
12,837
sglang
python/sglang/kernels/ops/attention/deepseek_v4_rope.py
.py
import logging import math from functools import lru_cache from typing import Optional import torch import triton import triton.language as tl logger = logging.getLogger(__name__) # This module is imported during model-registry discovery. Keep it free of # TileLang imports so discovery does not load TileLang's nativ...
652
19,510
sglang
python/sglang/kernels/ops/attention/pad.py
.py
import torch import triton import triton.language as tl @triton.jit def pad_sequence_with_mask_kernel( input_ptr, # (total_tokens, hidden) offsets_ptr, # (B,) lengths_ptr, # (B,) output_ptr, # (B, max_len, hidden) mask_ptr, # (B, max_len) max_len, hidden_dim, BLOCK_M: tl.constexpr...
391
11,356
sglang
python/sglang/kernels/ops/attention/concat_mla.py
.py
from __future__ import annotations from typing import TYPE_CHECKING import torch from sglang.kernels.jit.utils import ( cache_once, is_arch_support_pdl, load_jit, make_cpp_args, ) if TYPE_CHECKING: from tvm_ffi.module import Module @cache_once def _jit_concat_mla_k_module() -> Module: retu...
73
2,127
sglang
python/sglang/kernels/ops/attention/fused_qknorm_rope.py
.py
from __future__ import annotations import logging from typing import TYPE_CHECKING, Optional import torch from sglang.kernels.jit.utils import cache_once, load_jit from sglang.srt.utils.custom_op import register_custom_op if TYPE_CHECKING: from tvm_ffi.module import Module @cache_once def _jit_fused_qknorm_ro...
191
5,902
sglang
python/sglang/kernels/ops/attention/fixup_zero_kv.py
.py
from __future__ import annotations from typing import TYPE_CHECKING 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_fixup_module(dtype: torch.dtype) -> Module: args = make_cpp_args(dtype) ret...
45
1,369
sglang
python/sglang/kernels/ops/attention/verify_mla.py
.py
""" Grouped-head split-KV attention for speculative *verify* (topk==1). Following the pattern of ``python/sglang/kernels/ops/attention/verify_splitkv.py``. Grid is ``(bs, n_head_blocks, split)``; each program handles ``BLOCK_H`` query heads x ALL ``L_EXT`` draft queries. It supports absorbed MLA and ordinary MHA/GQA w...
742
22,917
sglang
python/sglang/kernels/ops/attention/kda_packed_decode.py
.py
"""CUDA KDA packed-decode kernel (batched decode fast path). Row-streaming port of the triton fused_recurrent_kda_packed_decode_kernel: the triton kernel keeps a [BV, K] fp32 state tile in one warp's registers and tops out at ~5 TB/s; this kernel streams the state one 512B row at a time and reaches the in-place read+w...
121
3,751
sglang
python/sglang/kernels/ops/attention/pa_page_table.py
.py
"""Paged-attention page-table builder, migrated from ``sglang.srt.layers.attention.flashattention_backend`` (RFC #29630, Phase 2.5). """ from typing import Optional import torch import triton import triton.language as tl @triton.jit def _build_pa_page_table_kernel( req_to_token_ptr, req_pool_indices_ptr, ...
99
3,070
sglang
python/sglang/kernels/ops/attention/fused_store_index_cache.py
.py
""" This module provides JIT-compiled CUDA kernels for fusing multiple tensor copy operations into single kernel launches, reducing kernel launch overhead and improving CUDA graph replay performance. The kernels are compiled on-demand using TVM FFI and cached for subsequent use. """ from __future__ import annotations...
106
3,335
sglang
python/sglang/kernels/ops/attention/flash_attention_v4_sm120.py
.py
# Copyright (c) 2026, SGLang Team. """SGLang-facing FlashAttention-4 APIs specialized for SM12x.""" from __future__ import annotations import os from dataclasses import dataclass from typing import Callable, Optional, Tuple, Union import torch from sglang.kernel_api_logging import debug_kernel_api from sglang.kerne...
340
11,394
sglang
python/sglang/kernels/ops/attention/extend_attention.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,411
46,767
sglang
python/sglang/kernels/ops/attention/fused_qk_norm_rope_store.py
.py
"""Fused Q per-head RMSNorm + KV RMSNorm + RoPE + FP8 nope quant + paged SWA store. Single Triton kernel replacing the 2-kernel path: 1. fused_reduce_qk_norm_rope_swa_write (norm + RoPE) 2. store_cache -> fused_store_cache (FP8 quant + paged scatter) Grid: (cdiv(M, BLOCK_SIZE_M), num_local_heads + 1). pid_h < n...
411
14,011
sglang
python/sglang/kernels/ops/attention/mrope.py
.py
"""Interleaved M-RoPE Triton kernel, migrated from ``sglang.srt.layers.rotary_embedding.mrope`` (RFC #29630, Phase 2.5). """ import torch import triton import triton.language as tl @triton.jit def apply_interleaved_rope_kernel( x_ptr, out_ptr, S: tl.constexpr, D: tl.constexpr, stride_x_m, str...
90
2,312
sglang
python/sglang/kernels/ops/attention/inkling_rel_proj.py
.py
"""CUDA-JIT latency-lean rel_logits projection for SMALL token counts, with the optional log-scaling tau prescale folded in registers. See csrc/tml/inkling_rel_proj.cuh; cuBLAS keeps everything above the measured small-t band (an earlier bandwidth-oriented custom kernel lost to it at every size).""" from __future__ im...
54
1,674
sglang
python/sglang/kernels/ops/attention/score_mod.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...
57
2,290
sglang
python/sglang/kernels/ops/attention/position.py
.py
import torch import triton import triton.language as tl def compute_position_triton( extend_prefix_lens: torch.Tensor, extend_seq_lens: torch.Tensor, extend_seq_lens_sum ): """Compute positions. It is a fused version of `compute_position_torch`.""" batch_size = extend_seq_lens.shape[0] has_prefix = ex...
60
1,654
sglang
python/sglang/kernels/ops/attention/minimax_m3_qk_norm_rope.py
.py
# SPDX-License-Identifier: Apache-2.0 """Fused MiniMax-M3 per-head Gemma Q/K RMSNorm + partial RoPE for ROCm.""" from typing import Tuple import torch import triton import triton.language as tl @triton.jit def _qk_gemma_rmsnorm_rope_kernel( q_ptr, k_ptr, q_out_ptr, k_out_ptr, q_weight_ptr, k...
660
19,604
sglang
python/sglang/kernels/ops/attention/kda_fused_decode.py
.py
"""Fully fused KDA decode step (Kimi K3 batched decode fast path). One kernel replaces the three-kernel decode chain ``causal_conv1d_update -> kda_packed_decode -> rms_norm_gated``: it reads the raw (pre-conv) qkv slice straight out of the fused projection GEMM output, does the causal conv1d update (conv state shifted...
167
5,751
sglang
python/sglang/kernels/ops/attention/clamp_position.py
.py
from __future__ import annotations from typing import TYPE_CHECKING 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_clamp_position_module(dtype: torch.dtype) -> Module: """Compile and cache the J...
36
956
sglang
python/sglang/kernels/ops/attention/log_scaling_tau.py
.py
import torch import triton import triton.language as tl @triton.jit def _apply_log_scaling_tau_kernel( x_ptr, tau_ptr, # [rows] fp32 (flattened per-row scale) out_ptr, # [rows, inner] contiguous, same dtype as x x_row_stride, inner, total, BLOCK: tl.constexpr, ): pid = tl.program_id(...
71
2,441
sglang
python/sglang/kernels/ops/attention/triton_gdn_fused_proj.py
.py
from __future__ import annotations import torch import triton import triton.language as tl from sglang.srt.utils import get_bool_env_var, is_hip _is_hip = is_hip() _use_aiter = get_bool_env_var("SGLANG_USE_AITER") and _is_hip # ============================================================================= # Fused ke...
429
13,134
sglang
python/sglang/kernels/ops/attention/qprep_bf16_fp8_sm90.py
.py
"""JIT-compiled SM90 (Hopper) kernel for the Q8KV8 born-fp8 q-prep. Fuses the per-head absorbed-q bmm (q_nope [T, H, K] bf16 x w_kc [H, K, N] bf16, fp32 accumulate), the nope/rope concat, and the bf16 -> fp8_e4m3 cast into one hand-written WGMMA kernel. CUDA replacement for the Triton ``absorbed_bmm_concat_cast_q_fp8...
134
4,975
sglang
python/sglang/kernels/ops/attention/minimax_sparse/prefill/flash_with_topk_idx.py
.py
# Copyright 2025 XunhaoLai. All rights reserved. from typing import Optional import torch import triton import triton.language as tl from ..common.utils import ( _bitonic_merge, _sort_ids_ascending, check_sparse_kv_fp8, get_cu_seqblocks, robust_allocator, sparse_out_dtype, unit_scale, ) ...
604
21,609
sglang
python/sglang/kernels/ops/attention/minimax_sparse/prefill/topk_sparse.py
.py
# Copyright 2025 XunhaoLai. All rights reserved. from typing import Optional import torch import triton import triton.language as tl from ..common.utils import ( check_sparse_kv_fp8, get_cu_seqblocks, robust_allocator, sparse_out_dtype, unit_scale, ) @triton.heuristics( { "BLOCK_SIZ...
382
13,455
sglang
python/sglang/kernels/ops/attention/minimax_sparse/decode/flash_with_topk_idx.py
.py
# Copyright 2025 XunhaoLai. All rights reserved. from typing import Optional import torch import triton import triton.language as tl from sglang.srt.environ import envs from ..common.utils import ( _bitonic_merge, _sort_ids_ascending, check_sparse_kv_fp8, robust_allocator, sparse_out_dtype, ...
1,110
38,782
sglang
python/sglang/kernels/ops/attention/minimax_sparse/decode/topk_sparse.py
.py
# Copyright 2025 XunhaoLai. All rights reserved. from typing import Optional import torch import triton import triton.language as tl from ..common.utils import ( check_sparse_kv_fp8, robust_allocator, sparse_out_dtype, unit_scale, ) @triton.heuristics( { "BLOCK_SIZE_H": lambda args: max...
440
15,991
sglang
python/sglang/kernels/ops/attention/minimax_sparse/common/utils.py
.py
# Copyright 2025 XunhaoLai. All rights reserved. import functools from collections import deque from typing import Any, Callable, List, Optional, Tuple import torch import triton import triton.language as tl _tma_keep_alive_buf = deque(maxlen=200) # The paged main K/V cache may be fp8 (unit-scaled) under --kv-cache...
319
12,201
sglang
python/sglang/kernels/ops/attention/minimax_sparse/common/index.py
.py
import torch def topk_index_reduce(tensor: torch.Tensor, dim: int) -> torch.Tensor: """ Reduces a specific dimension by computing the union of all top-k indices along that dimension. The resulting tensor will have the 'dim' removed, and the last dimension expanded. Example: Input: [10, num_h...
68
2,551
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/pipeline.py
.py
# Copyright (c) 2025, Tri Dao. from dataclasses import dataclass from typing import Optional import cutlass.cute as cute from cutlass import Boolean, Int32, const_expr from cutlass.cutlass_dsl import dsl_user_op, if_generate from cutlass.pipeline import NamedBarrier as NamedBarrierOg from cutlass.pipeline import Pipe...
413
14,687
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/cute_dsl_ptxas.py
.py
""" System ptxas replacement for CUTLASS DSL. Environment variables: CUTE_DSL_PTXAS_PATH - Path to ptxas (e.g., /usr/local/cuda/bin/ptxas) CUTE_DSL_PTXAS_VERBOSE - Set to 1 for verbose output """ import ctypes import os import re import subprocess import sys from pathlib import Path import cutlass CUTE_DS...
160
5,246
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/batch_invariance.py
.py
"""Process-wide so it need not thread through the autograd entry points. Set before the first kernel compile; it keys the forward compile cache. """ from __future__ import annotations _batch_invariant = False def set_batch_invariant(enabled: bool) -> None: global _batch_invariant _batch_invariant = bool(ena...
17
390
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/tile_scheduler.py
.py
# Copyright (c) 2025, Tri Dao, Siyu Wang, Shengbin Di, Yuxi Chi, Johnsonms, Linfeng Zheng, Haoyan Huang, Lanbo Li, Yun Zhong, Man Yuan, Minmin Sun, Yong Li, Wei Lin. from dataclasses import dataclass from enum import IntEnum, auto from typing import Optional, Protocol, Tuple, runtime_checkable try: from typing im...
1,714
66,695
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/utils.py
.py
# Copyright (c) 2025, Tri Dao. import hashlib import inspect import math import os from functools import partial from typing import Callable, NamedTuple, Optional, Tuple, Type, overload import cutlass import cutlass.cute as cute import quack.activation from cutlass import Float32, Int32, const_expr from cutlass._mlir...
1,165
39,132
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/topk_gather_kv.py
.py
import math import operator from dataclasses import dataclass from typing import Optional, Type import cutlass import cutlass.cute as cute import cutlass.pipeline as pipeline from cutlass import Boolean, Int32, Uint32, const_expr from cutlass.cute.nvgpu import cpasync from quack.cute_dsl_utils import ParamsBase from ...
290
10,688
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/flash_fwd_mla_sm100.py
.py
# Copyright (c) 2026, Colfax International. import math import time from functools import partial from typing import Callable, Optional import cuda.bindings.driver as cuda import cutlass import cutlass.cute as cute import cutlass.pipeline as pipeline import cutlass.utils.blackwell_helpers as sm100_utils import torch ...
3,911
161,698
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/softmax.py
.py
# Copyright (c) 2025, Tri Dao. import math import operator from dataclasses import dataclass from typing import Tuple import cutlass import cutlass.cute as cute from cutlass import Boolean, Float32 from quack import layout_utils from quack.cute_dsl_utils import ParamsBase import sglang.kernels.ops.attention.flash_at...
760
30,069
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/block_info.py
.py
# Copyright (c) 2025, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao. from dataclasses import dataclass from typing import Optional, Tuple import cutlass import cutlass.cute as cute from cutlass import Int32, const_expr from sglang.kernels.ops.attention.flash_attn.cute.seqlen_info impo...
213
8,853
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/seqlen_info.py
.py
from dataclasses import dataclass from typing import Optional import cutlass import cutlass.cute as cute from cutlass import Int32, const_expr from quack import copy_utils """ This consolidates all the info related to sequence length. This is so that we can do all the gmem reads once at the beginning of each tile, ra...
332
12,153
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/mask.py
.py
# Copyright (c) 2025, Tri Dao. import enum from dataclasses import dataclass from typing import Callable, Optional, Tuple, TypeAlias import cutlass import cutlass.cute as cute from cutlass import Float32, Int32, Uint32, const_expr from cutlass.cutlass_dsl import min as dsl_min from quack import layout_utils import s...
1,847
80,140
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/__init__.py
.py
"""Flash Attention CUTE (CUDA Template Engine) implementation.""" from importlib.metadata import PackageNotFoundError, version try: __version__ = version("fa4") except PackageNotFoundError: __version__ = "0.0.0" from .interface import ( flash_attn_func, flash_attn_varlen_func, ) __all__ = [ "fla...
19
367
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/flash_fwd_combine.py
.py
# Copyright (c) 2025, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao. # A reimplementation of https://github.com/Dao-AILab/flash-attention/blob/main/hopper/flash_fwd_combine_kernel.h # from Cutlass C++ to Cute-DSL. import math from functools import partial from typing import Optional, Ty...
770
32,992
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/paged_kv.py
.py
import math from dataclasses import dataclass from typing import Optional, 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.attenti...
394
14,844
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/testing.py
.py
import math from contextlib import nullcontext from functools import wraps from typing import Optional import torch import torch.nn.functional as F from einops import rearrange, repeat from torch._guards import active_fake_mode from torch._subclasses.fake_tensor import FakeTensorMode class IndexFirstAxis(torch.autog...
581
20,234
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/block_sparsity.py
.py
""" Block-sparsity utilities for FlexAttention """ from typing import Callable, NamedTuple, Tuple import cutlass.cute as cute import torch from sglang.kernels.ops.attention.flash_attn.cute.cute_dsl_utils import ( get_broadcast_dims, to_cute_tensor, ) def ceildiv(a: int, b: int) -> int: return (a + b - ...
723
26,834
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/pack_gqa.py
.py
# Copyright (c) 2025, Tri Dao. from dataclasses import dataclass from typing import Tuple, Union import cutlass import cutlass.cute as cute from cutlass.cute.nvgpu import cpasync from quack import layout_utils import sglang.kernels.ops.attention.flash_attn.cute.utils as utils def pack_gqa_layout(T, qhead_per_kvhea...
301
12,171
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/cu_blocks_kernels.py
.py
from typing import Callable import cuda.bindings.driver as cuda import cutlass import cutlass.cute as cute from cutlass import Int32, const_expr class CuSeqlensToBlocksKernel: """Single-CTA prep for block-packed shear scheduling: computes the cumulative per-batch group-block counts and the block -> batch ind...
124
4,073
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/fast_math.py
.py
# Copyright (c) 2025, Tri Dao. import cutlass import cutlass.cute as cute from cutlass import Int32 @cute.jit def clz(x: Int32) -> Int32: # for i in cutlass.range_constexpr(32): # if (1 << (31 - i)) & x: # return Int32(i) # return Int32(32) # Early exit is not supported yet res = ...
22
492
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/shearing_bias.py
.py
# Copyright (c) 2026, Colfax International. import math from functools import partial from typing import Callable, Optional import cuda.bindings.driver as cuda import cutlass import cutlass.cute as cute from cutlass import Float32, Int32, const_expr from sglang.kernels.ops.attention.flash_attn.cute.block_info import...
583
24,414
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/blackwell_helpers.py
.py
# Copyright (c) 2025, Tri Dao. from typing import Optional, Tuple import cutlass import cutlass.cute as cute from cutlass import Boolean, Int32, const_expr from cutlass._mlir.dialects import llvm from cutlass.cute.nvgpu import tcgen05 import sglang.kernels.ops.attention.flash_attn.cute.mma_sm100_desc as sm100_desc ...
1,225
52,490
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/flash_fwd_sm100.py
.py
# Copyright (c) 2025, Tri Dao. # Copyright (c) 2026, Colfax International. (modifications) # Supported features: # - BF16 & FP16 dtype # - noncausal & causal attention # - MHA, GQA, MQA # - hdim 64, 96, 128, (192, 128). # - varlen # - sliding window # - split-kv # # Colfax modifications: # - relative bias # - MXFP8 dt...
5,611
251,136
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/fa_logging.py
.py
# Copyright (c) 2025, Tri Dao. """Unified FlashAttention logging controlled by a single ``FA_LOG_LEVEL`` env var. Host-side messages go through Python ``logging`` (logger name ``flash_attn``). A default ``StreamHandler`` is attached automatically when ``FA_LOG_LEVEL >= 1`` so that standalone scripts get output withou...
98
2,915
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/cache_utils.py
.py
# Manage Ahead-of-Time (AOT) compiled kernels import ctypes import fcntl import hashlib import os import pickle import sys import tempfile import time from functools import lru_cache from getpass import getuser from pathlib import Path from typing import Hashable, TypeAlias import cutlass import cutlass.cute as cute i...
290
10,074
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/cute_dsl_utils.py
.py
# Copyright (c) 2025, Tri Dao. from functools import lru_cache from typing import Tuple import torch try: from triton.tools.disasm import extract except ImportError: extract = None import cutlass import cutlass.cute as cute from cutlass.cute.runtime import from_dlpack from cutlass.cutlass_dsl import Numeric...
177
5,830
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/ampere_helpers.py
.py
# Copyright (c) 2025, Tri Dao. from typing import Callable, Optional, Type import cutlass import cutlass.cute as cute def get_smem_layout_atom( dtype: Type[cutlass.Numeric], k_dim: int ) -> cute.ComposedLayout: dtype_byte = cutlass.const_expr(dtype.width // 8) bytes_per_row = cutlass.const_expr(k_dim * d...
123
4,008
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/flash_fwd_sm90.py
.py
# Copyright (c) 2025, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao. # SM90 (Hopper) forward pass for flash attention, extracted from flash_fwd.py. from functools import partial from types import SimpleNamespace from typing import Callable, Literal, Optional import cuda.bindings.drive...
2,137
89,491
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/sm100_hd256_2cta_fmha_forward.py
.py
# Copyright (c) 2025, Siyu Wang, Shengbin Di, Yuxi Chi, Johnsonms, Linfeng Zheng, Haoyan Huang, Lanbo Li, Yun Zhong, Man Yuan, Minmin Sun, Yong Li, Wei Lin. import math from typing import Optional, Tuple import cuda.bindings.driver as cuda import cutlass import cutlass.cute as cute import cutlass.cute.nvgpu.tcgen05 a...
2,075
95,894
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/block_sparse_utils.py
.py
""" Block-sparse runtime utilities for CUTE DSL kernels. This module contains runtime execution functions for block-sparse attention kernels. These utilities are used by CUTE DSL kernels to produce and consume block-sparse loads. """ import math from functools import partial from typing import Callable, Optional, Tup...
1,635
59,575
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/interface.py
.py
# Copyright (c) 2025, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao. import math import os from dataclasses import dataclass from functools import lru_cache from typing import Callable, Optional, Tuple import cutlass import cutlass.cute as cute import torch from cutlass import Float32,...
2,589
97,698
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/named_barrier.py
.py
# Copyright (c) 2025, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao. import enum class NamedBarrierFwd(enum.IntEnum): Epilogue = enum.auto() # starts from 1 as barrier 0 is reserved for sync_threads() WarpSchedulerWG1 = enum.auto() WarpSchedulerWG2 = enum.auto() Warp...
59
1,651
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/flash_fwd.py
.py
# Copyright (c) 2025, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao. # A reimplementation of # https://github.com/Dao-AILab/flash-attention/blob/main/hopper/flash_fwd_kernel_sm80.h # and https://github.com/Dao-AILab/flash-attention/blob/main/hopper/flash_fwd_kernel_sm90.h # from Cutlass...
1,539
60,920
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/mma_sm100_desc.py
.py
# Copyright (c) 2025, Tri Dao. # Ported Cutlass code from C++ to Python: # https://github.com/NVIDIA/cutlass/blob/main/include/cute/arch/mma_sm100_desc.hpp # https://github.com/NVIDIA/cutlass/blob/main/include/cute/atom/mma_traits_sm100.hpp from enum import IntEnum import cutlass import cutlass.cute as cute # ------...
320
11,157
sglang
python/sglang/kernels/ops/attention/flash_attn/cute/copy_utils.py
.py
# Copyright (c) 2025, Wentao Guo, Ted Zadouri, Tri Dao. import math from typing import Callable, Optional, Type import cutlass import cutlass.cute as cute import cutlass.pipeline import cutlass.utils.blackwell_helpers as sm100_utils from cutlass import Float32, Int32, const_expr from cutlass._mlir.dialects import llv...
403
12,823
sglang
python/sglang/kernels/ops/attention/dsv4/sparse_prefill_kernels.py
.py
"""SWA token-id build and topk+SWA index combine kernels for DSV4 sparse prefill. Migrated from ``sglang.srt.layers.attention.dsv4.sparse_prefill_utils`` (RFC #29630, Phase 2.5). """ import triton import triton.language as tl @triton.jit def _build_swa_token_ids_kernel( out_ptr, swa_first_pos_ptr, swa_g...
111
3,975
sglang
python/sglang/kernels/ops/attention/dsv4/moe.py
.py
from typing import Optional, Tuple import torch from sglang.kernels.jit.utils import ( cache_once, is_arch_support_pdl, is_hip_runtime, load_jit, make_cpp_args, ) from sglang.srt.utils import is_xpu from .utils import make_name _is_xpu = is_xpu() @cache_once def _jit_mask_topk_module(): re...
238
6,360
sglang
python/sglang/kernels/ops/attention/dsv4/online_c128_mtp.py
.py
from __future__ import annotations from dataclasses import dataclass from typing import TYPE_CHECKING, Any, List, Optional import torch from sglang.kernels.jit.utils import cache_once, load_jit, make_cpp_args from sglang.kernels.ops.attention.dsv4.utils import make_name from sglang.srt.environ import envs if TYPE_C...
278
9,183
sglang
python/sglang/kernels/ops/attention/dsv4/rms_normalize_hip.py
.py
"""RMS-normalize kernel used by the HIP DSV4 compressor. Migrated from ``sglang.srt.layers.attention.dsv4.compress_hip`` (RFC #29630, Phase 2.5). """ import torch import triton import triton.language as tl @triton.jit def _rms_normalize_kernel( x_ptr, weight_ptr, eps, stride_row, dim, BLOCK_...
53
1,290
sglang
python/sglang/kernels/ops/attention/dsv4/utils.py
.py
def make_name(name: str) -> str: return f"dpsk_v4_{name}"
3
62
sglang
python/sglang/kernels/ops/attention/dsv4/compress_old.py
.py
from __future__ import annotations from typing import TYPE_CHECKING, Literal, NamedTuple, Optional, Union import torch from sglang.kernels.jit.utils import ( cache_once, is_arch_support_pdl, load_jit, make_cpp_args, ) from sglang.srt.environ import envs from .utils import make_name if TYPE_CHECKING...
309
9,484
sglang
python/sglang/kernels/ops/attention/dsv4/fused_compress_triton.py
.py
"""HIP fused compressor kernels using the NV/main metadata contract. The public wrappers mirror ``compress_forward``: decode: indices, seq_lens, extra_data prefill: indices, compress_plan, write_plan, extra_data Prefill plans are the upstream 16-byte ``PrefillPlan`` structs stored as ``uint8[:, 16]``. The wrappers...
1,117
35,918
sglang
python/sglang/kernels/ops/attention/dsv4/compress.py
.py
from __future__ import annotations from typing import TYPE_CHECKING, Literal, NamedTuple, Optional, Union import torch from sglang.kernels.jit.utils import ( cache_once, is_arch_support_pdl, load_jit, make_cpp_args, ) from sglang.srt.layers.attention.dsa.utils import ( INDEXER_K_CACHE_PRESHUFFLE_...
462
14,597
sglang
python/sglang/kernels/ops/attention/dsv4/gemm.py
.py
import functools import importlib.util from typing import Optional import torch from sglang.srt.environ import envs from sglang.srt.utils import get_bool_env_var, is_hip _is_hip = is_hip() _use_aiter = get_bool_env_var("SGLANG_USE_AITER") and _is_hip if _use_aiter: from aiter.tuned_gemm import tgemm _linear_bf...
170
5,656
sglang
python/sglang/kernels/ops/attention/dsv4/__init__.py
.py
"""DeepSeek-V4 attention kernels (RFC #29630, Phase 2.5).""" # --- merged from sglang.kernels.ops.attention.dsv4 (RFC #29630 Phase 4) --- from .attn import ( fused_store_cache, get_paged_mqa_logits_metadata, triton_create_paged_compress_data, ) from .c128_cleanup import clear_unaccepted_c128_draft_states f...
67
1,967
sglang
python/sglang/kernels/ops/attention/dsv4/fp4_indexer.py
.py
from __future__ import annotations import torch import triton import triton.language as tl @triton.jit def _select_group_value(group, v0, v1, v2, v3): return tl.where( group == 0, v0, tl.where(group == 1, v1, tl.where(group == 2, v2, v3)), ) @triton.jit def _ceil_ue8m0_exp(x): b...
164
4,638
sglang
python/sglang/kernels/ops/attention/dsv4/c128_cleanup.py
.py
import torch import triton import triton.language as tl @triton.jit def _clear_unaccepted_c128_draft_states_kernel( state, req_pool_indices, seq_lens, accept_lens, ring_size: tl.constexpr, half: tl.constexpr, num_draft_tokens: tl.constexpr, BLOCK_D: tl.constexpr, ): bid = tl.progra...
59
1,500
sglang
python/sglang/kernels/ops/attention/dsv4/index_buf_accessor.py
.py
from __future__ import annotations from dataclasses import dataclass from typing import Any import torch import triton import triton.language as tl from sglang.kernels.ops.quantization.fp8_kernel import is_fp8_fnuz fp8_dtype = torch.float8_e4m3fnuz if is_fp8_fnuz() else torch.float8_e4m3fn @dataclass class NopeFp...
258
8,091
sglang
python/sglang/kernels/ops/attention/dsv4/topk.py
.py
from __future__ import annotations from typing import Optional import torch from sglang.kernels.jit.utils import ( cache_once, is_arch_support_pdl, is_hip_runtime, load_jit, make_cpp_args, ) from .utils import make_name @cache_once def _jit_topk_v1_module(): # topk (<= 1024) is a runtime a...
119
4,055
sglang
python/sglang/kernels/ops/attention/dsv4/quant_k_cache.py
.py
import torch import triton import triton.language as tl from sglang.kernels.ops.attention.dsv4.index_buf_accessor import NopeFp8RopeBf16Pack from sglang.kernels.ops.quantization.fp8_kernel import is_fp8_fnuz fp8_dtype = torch.float8_e4m3fnuz if is_fp8_fnuz() else torch.float8_e4m3fn @triton.jit def _quant_k_cache_f...
121
3,666
sglang
python/sglang/kernels/ops/attention/dsv4/fp8_wo_a.py
.py
from __future__ import annotations from typing import TYPE_CHECKING, Tuple import torch from sglang.kernel_api_logging import debug_kernel_api from sglang.kernels.jit.utils import ( cache_once, is_arch_support_pdl, load_jit, make_cpp_args, ) from sglang.srt.utils.custom_op import register_custom_op ...
94
2,961
sglang
python/sglang/kernels/ops/attention/dsv4/dequant_k_cache.py
.py
from typing import Optional import torch import triton import triton.language as tl from sglang.kernels.ops.quantization.fp8_kernel import is_fp8_fnuz fp8_dtype = torch.float8_e4m3fnuz if is_fp8_fnuz() else torch.float8_e4m3fn # v4 KV cache layout (see dsv4.index_buf_accessor._set_k_and_s_triton_kernel): # per-to...
227
7,985
sglang
python/sglang/kernels/ops/attention/dsv4/elementwise.py
.py
from typing import Optional, Tuple import torch from sglang.kernels.jit.utils import ( cache_once, is_arch_support_pdl, load_jit, make_cpp_args, ) from sglang.srt.utils import is_hip, is_xpu from .utils import make_name _is_hip = is_hip() _is_xpu = is_xpu() if _is_xpu: from sgl_kernel import fu...
289
8,856
sglang
python/sglang/kernels/ops/attention/dsv4/attn.py
.py
from typing import Literal, Tuple import torch import triton import triton.language as tl from sglang.kernels.jit.utils import ( cache_once, is_arch_support_pdl, is_hip_runtime, load_jit, make_cpp_args, ) from .utils import make_name @cache_once def _jit_metadata_module(): return load_jit( ...
216
6,641
sglang
python/sglang/kernels/ops/attention/dsv4/metadata_kernel.py
.py
from typing import Optional, Tuple import torch import triton import triton.language as tl @triton.jit(do_not_specialize=["bs", "num_write_tokens", "c128_cur_max_seq_len"]) def _init_compressed_attn_metadata_kernel( seq_lens_ptr, positions_ptr, raw_out_loc_ptr, page_table_ptr, c4_out_loc_ptr, ...
218
6,883
sglang
python/sglang/kernels/ops/attention/dsv4/unified_kv_kernels/runtime.py
.py
"""Runtime glue for the unified_kv backend. Builds unified_kv-style flat ``kv_indices`` / ``kv_indptr`` from SGLang's already-computed DSV4 metadata, scatters SWA K into the bf16 ``unified_kv`` ring, and dispatches the vendored paged decode/prefill kernels. unified_kv[L] layout (page_size 1, bf16, row-major): - row...
492
17,054
sglang
python/sglang/kernels/ops/attention/dsv4/unified_kv_kernels/paged_decode.py
.py
# SPDX-License-Identifier: MIT # Copyright (C) 2024-2026, Advanced Micro Devices, Inc. All rights reserved. # The following kernel is imported from ATOM. # Source: atom/model_ops/v4_kernels/paged_decode.py """Sparse decode attention over a unified KV pool with per-token paged indices. Designed for V4 decode + CUDAGr...
890
33,975
sglang
python/sglang/kernels/ops/attention/dsv4/unified_kv_kernels/paged_decode_indices.py
.py
# SPDX-License-Identifier: MIT # Copyright (C) 2024-2026, Advanced Micro Devices, Inc. All rights reserved. # The following kernel is imported from ATOM. # Source: atom/model_ops/v4_kernels/paged_decode_indices.py """V4 paged-decode index scatter — single Triton kernel writes SWA window- prefix paged offsets into the...
191
8,745
sglang
python/sglang/kernels/ops/attention/dsv4/unified_kv_kernels/env_gate.py
.py
from __future__ import annotations import functools from sglang.srt.environ import envs from sglang.srt.utils import is_hip @functools.lru_cache(maxsize=1) def is_unified_kv_triton() -> bool: # unified_kv_triton is only implemented on HIP (ROCm) return is_hip() and envs.SGLANG_HACK_FLASHMLA_BACKEND.get() ==...
13
341
sglang
python/sglang/kernels/ops/attention/dsv4/unified_kv_kernels/paged_prefill.py
.py
# SPDX-License-Identifier: MIT # Copyright (C) 2024-2026, Advanced Micro Devices, Inc. All rights reserved. # The following kernel is imported from ATOM. # Source: atom/model_ops/v4_kernels/paged_prefill.py """Sparse prefill attention with two KV sources: paged `unified_kv` (history) and per-fwd flat `kv` (current ch...
360
12,532
sglang
python/sglang/kernels/ops/attention/cute_utils/cvt.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/cute_utils/cvt.py from cutlass import Constexpr, Float32, Uint32, cute from cutlass._mlir import ir from cutla...
147
4,592
sglang
python/sglang/kernels/ops/attention/cute_utils/__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/cute_utils/__init__.py from cutlass import BFloat16, Float32, Int64, Uint32, cute from cutlass._mlir import ir...
136
4,184
sglang
python/sglang/kernels/ops/attention/cute_utils/_tcgen05.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/cute_utils/_tcgen05.py # this module is named _tcgen05 to avoid name collision with cute.nvgpu.tcgen05 import...
221
6,285
sglang
python/sglang/kernels/ops/attention/nsa_triton_decode/triton_mla_kernels_decode_fused.py
.py
""" Fused Gather+Dequant+Attention Kernel for DSV4 (d_qk=512) This module implements a fused kernel that combines: 1. Gather: Load KV from sparse indices 2. Dequant: FP8 to BF16 dequantization 3. Attention: Compute attention scores and output Supports: - DSV4 (d_qk=512): 7 tiles of 64, uint8 scales - All configs: wit...
3,060
105,006
sglang
python/sglang/kernels/ops/attention/nsa_triton_decode/__init__.py
.py
""" Triton-based sparse attention decode kernels for DeepSeek V4. This package provides an alternative to the tilelang implementation, controlled by the environment variable SGLANG_HACK_FLASHMLA_BACKEND=triton. """ from typing import Optional, Tuple import torch from sglang.kernels.ops.attention.nsa_triton_decode.t...
99
3,117
sglang
python/sglang/kernels/ops/attention/nsa_triton_decode/triton_mla_kernels_decode_optimized.py
.py
""" Optimized Triton MLA Decode Kernels for DeepSeek V4. This module provides optimized sparse attention decode. Key optimizations: 1. Fused gather+dequant+attention kernels (eliminates intermediate buffers) 2. Split-K for better GPU parallelism on small batches 3. Proper dispatch: no-splitk for large batches, split-...
163
5,271
sglang
python/sglang/kernels/ops/attention/linear/lightning_attn.py
.py
# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/model_executor/layers/mamba/linear_attn.py # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import torch import triton import triton.language as tl from einops import rearrange @triton.jit def...
768
22,016