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/moe/deepep_waterfill_kernels.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... | 323 | 11,273 |
sglang | python/sglang/kernels/ops/moe/fused_moe_lora_kernel.py | .py | # Temporarily adapted from https://github.com/vllm-project/vllm/blob/main/vllm/lora/ops/triton_ops/fused_moe_lora_op.py, will optimize in future refactor
import torch
import triton
import triton.language as tl
from sglang.srt.distributed import (
tensor_model_parallel_all_gather,
tensor_model_parallel_all_red... | 702 | 20,980 |
sglang | python/sglang/kernels/ops/moe/moe_align_small_numel.py | .py | """Single-launch moe_align for tiny batches with many experts.
The CUDA small-batch align kernel is gated to ``num_experts <= 64`` (its shared
memory grows as O(threads x experts)), so bs=1 decode on a MoE with a wider
expert dimension always paid the generic two-kernel (align + count_and_sort)
path. This kernel cover... | 148 | 6,133 |
sglang | python/sglang/kernels/ops/moe/fused_moe_triton_kernels.py | .py | from __future__ import annotations
import functools
from collections import OrderedDict
from typing import Any, Dict, List, Optional
import torch
import triton
import triton.language as tl
from sglang.kernels.ops.quantization.fp8_kernel import (
per_token_group_quant_fp8,
scaled_fp8_quant,
sglang_per_tok... | 1,560 | 54,775 |
sglang | python/sglang/kernels/ops/moe/moe_route_radix.py | .py | """Native-CUDA radix-select router for K3 routing (all batch sizes).
Keys and activations stay in registers (224 threads, 4 experts each), the
split-bin search runs on warp scans instead of cub, rounds exit early when the
top-k separates on a byte boundary, and the (biased desc, id asc) output sort
is optional. Consum... | 99 | 3,299 |
sglang | python/sglang/kernels/ops/moe/sigmoid_gate_topk_renorm.py | .py | """Fused MoE gate: sigmoid + bias + top-k selection + logsigmoid renorm.
sel = sigmoid(logits)[:, :N] + bias # selection score (bias optional)
idx = topk(sel, k) # top-k routed experts
w = logsigmoid_norm(logits[idx] ++ shared) * route_scale * global_scale
The renorm ru... | 253 | 9,013 |
sglang | python/sglang/kernels/ops/moe/moe_route_quant_fused.py | .py | """Fused K3 MoE-front prep: radix routing + trtllm id pack + mxfp8 quant.
One launch replaces the three tiny kernels between the K3 fused-front GEMM and
the trtllm-gen routed-MoE op at decode batch sizes (route_radix -> triton
(id<<16|bf16(w)) pack -> per_token_group_quant, ~7.5us busy + 2 extra launches
per MoE layer... | 126 | 4,365 |
sglang | python/sglang/kernels/ops/moe/triton_sigmoid_gate_mul.py | .py | """Fused sigmoid-gate-multiply Triton kernels.
Two variants:
- ``sigmoid_gate_mul``: element-wise ``x * sigmoid(gate)`` when x and gate
have identical shapes.
- ``sigmoid_gate_mul_broadcast``: broadcast ``x * sigmoid(gate)`` when gate
is ``(N, 1)`` and x is ``(N, D)``.
"""
from __future__ import annotations
impo... | 88 | 2,402 |
sglang | python/sglang/kernels/ops/moe/moe_fused_gate.py | .py | from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Tuple
import torch
import triton
import triton.language as tl
from sglang.kernel_api_logging import debug_kernel_api
from sglang.kernels.jit.utils import cache_once, is_arch_support_pdl, load_jit
from sglang.kernels.ops.moe import mo... | 376 | 14,839 |
sglang | python/sglang/kernels/ops/moe/moe_front.py | .py | """K3 MoE front: merged gate + routed_expert_down_proj GEMM, and the fp32 router.
The unfused MoE front -- the path every EP-a2a / WideEP deployment takes -- runs
three ops over the same `hidden_states [T, 7168]`:
router_logits = gate(hidden_states) # [896, 7168] 12.85 MB
topk_output = ... | 236 | 8,519 |
sglang | python/sglang/kernels/ops/moe/triton_hash_topk.py | .py | """HIP fallback for ``hash_topk``: ``csrc/deepseek_v4/hash_topk.cuh`` uses
CUDA-only primitives, so on ROCm we dispatch to this Triton implementation.
"""
from __future__ import annotations
from typing import Tuple
import torch
import triton
import triton.language as tl
@triton.jit
def _hash_topk_triton_kernel(
... | 100 | 2,970 |
sglang | python/sglang/kernels/ops/moe/moe_wna16_marlin.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING, Optional
import torch
from sglang.kernel_api_logging import debug_kernel_api
from sglang.kernels.jit.utils import cache_once, load_jit, make_cpp_args
if TYPE_CHECKING:
from sgl_kernel.scalar_type import ScalarType
from tvm_ffi.module impor... | 177 | 4,897 |
sglang | python/sglang/kernels/ops/moe/fill_padded_rows.py | .py | """Fused padded-row fill for MoE top-k outputs.
Migrated from ``sglang.srt.layers.moe.topk`` (RFC #29630, Phase 2.5), where two
near-identical copies had accumulated; this keeps the later, runtime-winning
copy (explicit raises instead of asserts).
"""
import torch
import triton
import triton.language as tl
@triton.... | 79 | 2,869 |
sglang | python/sglang/kernels/ops/moe/trtllm_lora_temp/virtual_experts.py | .py | """
LoRA Virtual Experts Triton Ops.
"""
import functools
from typing import Any
import torch
import triton
import triton.language as tl
from sglang.kernels.ops.gemm.trtllm_lora_temp.kernel_utils import (
get_pdl_launch_metadata,
)
from sglang.kernels.ops.moe.moe_align import (
moe_align_block_size as jit_mo... | 1,167 | 42,623 |
sglang | python/sglang/kernels/ops/moe/trtllm_lora_temp/jit.py | .py | from pathlib import Path
def _data_dir() -> Path:
return Path(__file__).resolve().parent / "data"
def gen_sgl_trtllm_gen_fused_moe_sm100_module():
import flashinfer
from flashinfer.artifacts import ArtifactPath, CheckSumHash
from flashinfer.jit import env as jit_env
from flashinfer.jit.core impo... | 109 | 4,425 |
sglang | python/sglang/kernels/ops/moe/trtllm_lora_temp/__init__.py | .py | """Experimental TRT-LLM LoRA kernel variants (gated by ``SGLANG_EXPERIMENTAL_LORA_OPTI`` / ``lora_envs``).
Migrated from ``sglang.srt.lora.trtllm_lora_temp.triton_ops`` (RFC #29630)."""
# --- merged from sglang.kernels.ops.moe.trtllm_lora_temp (RFC #29630 Phase 4) ---
from sglang.kernels.ops.moe.trtllm_lora_temp.core... | 25 | 929 |
sglang | python/sglang/kernels/ops/moe/trtllm_lora_temp/kimi_k2_moe_fused_gate.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING, Tuple
import torch
from sglang.kernels.jit.utils import cache_once, load_jit
if TYPE_CHECKING:
from tvm_ffi.module import Module
@cache_once
def _jit_kimi_k2_moe_fused_gate_module() -> Module:
return load_jit(
"kimi_k2_moe_fused_... | 71 | 2,240 |
sglang | python/sglang/kernels/ops/moe/trtllm_lora_temp/topk_pack.py | .py | """Fused pack for the trtllm routed-MoE topk format.
The trtllm routed MoE consumes top-k routing as a single int32 per (token, slot):
``PackedScoreIdx`` = ``(expert_id << 16) | bf16_weight_bits`` (little-endian: low 16
bits = bf16 weight, high 16 bits = int16 expert id).
The torch reference builds this with a cluste... | 52 | 2,102 |
sglang | python/sglang/kernels/ops/moe/trtllm_lora_temp/moe_lora_merged_align.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_module(dtype: torch.dtype) -> Module:
args = make_cpp_args(dtype)
... | 136 | 5,443 |
sglang | python/sglang/kernels/ops/moe/trtllm_lora_temp/topk_softmax_pack.py | .py | """Fused top-k gating softmax with routed-pack output (JIT).
JIT port of sgl-kernel's AOT ``topk_softmax`` power-of-2 fast path
(``topkGatingSoftmax``) extended with a third output: the FlashInfer routed-MoE
packed format ``(topk_id << 16) | bf16_bits(topk_weight)`` computed in the
kernel epilogue after renormalizatio... | 91 | 3,112 |
sglang | python/sglang/kernels/ops/moe/trtllm_lora_temp/core.py | .py | import functools
from typing import List, Optional, Union
import torch
from sglang.srt.lora.trtllm_lora_temp.environ import lora_envs
@functools.cache
def get_sgl_trtllm_moe_sm100_module():
import flashinfer.fused_moe.core as fi_core
from sglang.kernels.ops.moe.trtllm_lora_temp.jit import (
gen_sgl... | 515 | 16,506 |
sglang | python/sglang/kernels/ops/kimi_k3/moe.py | .py | from __future__ import annotations
import torch
from sglang.kernels.jit.utils import (
cache_once,
is_arch_support_pdl,
load_jit,
make_cpp_args,
)
def _make_name(*args):
return "kimi_k3_" + "_".join(str(a) for a in args)
@cache_once
def _jit_situ_mul_quant_varlen_module(
quant_group_size: ... | 62 | 1,359 |
sglang | python/sglang/kernels/ops/kimi_k3/gemm_ag.py | .py | """K3 column-parallel up_proj + multicast all-gather + add3 (bf16, TP8).
One entry point over ``csrc/kimi_k3/comm/gemm_ag.cuh``: for the latent MoE
up_proj ([M, 3584] x [3584, 7168]) at small decode M, every rank computes
only its 896-column slice of the replicated GEMM (the C++ side slices the
full weight itself), mu... | 89 | 2,780 |
sglang | python/sglang/kernels/ops/kimi_k3/sp_collective.py | .py | """K3 SP-MoE bf16 reduce-scatter and all-gather over MNNVL push memory."""
from __future__ import annotations
import json
import os
from typing import TYPE_CHECKING, NamedTuple, Optional
import torch
from sglang.kernels.jit.utils import (
cache_once,
is_arch_support_pdl,
load_jit,
make_cpp_args,
)
f... | 339 | 8,696 |
sglang | python/sglang/kernels/ops/kimi_k3/__init__.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from sglang.srt.utils import is_npu
if TYPE_CHECKING:
import torch
_is_npu = is_npu()
_K3_N_GEMM_DISPATCH_MAP = {
(144, 7168): 16,
(896, 7168): 8,
}
_K3_K_GEMM_DISPATCH_MAP = {
(1536, 128): 12,
}
def situ_and_mul(
i... | 87 | 1,841 |
sglang | python/sglang/kernels/ops/kimi_k3/activation.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING, Optional
import torch
from sglang.kernels.jit.utils import (
cache_once,
get_jit_cuda_arch,
is_arch_support_pdl,
is_hip_runtime,
load_jit,
make_cpp_args,
)
if TYPE_CHECKING:
from tvm_ffi.module import Module
def _make... | 90 | 2,733 |
sglang | python/sglang/kernels/ops/kimi_k3/attn_res_hip.py | .py | """Triton attention-residual aggregation for Kimi-K3 on ROCm.
The HIP counterpart of attn_res.py: same aggregation point (score the bank rows
against the current prefix, softmax, weighted sum, output RMSNorm), one launch,
but built for a GPU with no TMA and no tcgen05. See _agg_kernel for why the
shape differs so much... | 213 | 8,138 |
sglang | python/sglang/kernels/ops/kimi_k3/mla_output_gate.py | .py | """CUDA JIT K3 MLA output gate: out = x * sigmoid(gate) in one kernel."""
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,
)
from sglang.srt.utils import is_npu
if TYPE_C... | 55 | 1,465 |
sglang | python/sglang/kernels/ops/kimi_k3/kda_decode_mtp.py | .py | """CuTe DSL device kernel KDA conv-MTP.
conv enabled, no bias, optional fused gated RMSNorm, lower_bound gate, Q/K
L2 norm, beta sigmoid, ILP=2, W=4. Recurrent-state tiles are cp.async'd into
NUM_STATE_STAGES smem stages. Phase 2 walks the V // TILE_V state tiles in
passes of TILES_PER_PASS: a multi-token verify keeps... | 1,136 | 47,938 |
sglang | python/sglang/kernels/ops/kimi_k3/attn_res.py | .py | """CUDA JIT wrapper for the Kimi-K3 SM100 attention-residual kernel."""
from __future__ import annotations
from typing import TYPE_CHECKING
import torch
from sglang.kernels.jit.utils import (
cache_once,
load_jit,
make_cpp_args,
override_jit_cuda_arch,
)
from sglang.srt.utils.custom_op import regist... | 302 | 9,305 |
sglang | python/sglang/kernels/ops/kimi_k3/all_reduce.py | .py | """K3 MNNVL fused all-reduce (bf16): zero-copy AR and AR+RMSNorm.
Four entry points over ``csrc/kimi_k3/comm/ar_fusion.cuh``, spanning two
algorithm families x two epilogues:
============ ========================= ==================================
res (+ optional residual) norm (fused RMSNorm on the... | 381 | 11,464 |
sglang | python/sglang/kernels/ops/kimi_k3/gemm_ar.py | .py | """K3 fused o_proj GEMM + all-reduce for decode (bf16, TP row-parallel).
One entry point over ``csrc/kimi_k3/comm/gemm_ar.cuh``: a single kernel per
rank computes the local ``x_r [M, K] @ W_r [7168, K]^T`` partial AND the
cross-rank sum — the epilogue pushes finished tiles straight into a
peer-mapped P2P comm region, ... | 217 | 7,207 |
sglang | python/sglang/kernels/ops/sampling/renorm_triton.py | .py | """ROCm-compatible top-k / top-p probability renormalization fallbacks."""
from __future__ import annotations
from typing import Union
import torch
import triton
import triton.language as tl
_BLOCK_SIZE = 1024
@triton.jit
def _mask_and_partial_sum_kernel(
probs_ptr,
pivots_ptr,
out_ptr,
partial_su... | 173 | 5,943 |
sglang | python/sglang/kernels/ops/sampling/top_p_renorm_triton.py | .py | """ROCm-compatible top-p probability renormalization fallback."""
from __future__ import annotations
from typing import Union
import torch
import triton
import triton.language as tl
_BLOCK_SIZE = 1024
@triton.jit
def _mask_and_partial_sum_kernel(
probs_ptr,
pivots_ptr,
out_ptr,
partial_sums_ptr,
... | 128 | 4,109 |
sglang | python/sglang/kernels/ops/sampling/__init__.py | .py | """Sampling kernels (top-k / top-p probability renormalization)."""
from __future__ import annotations
from typing import TYPE_CHECKING, Union
from sglang.kernels.registry import register_kernel
from sglang.kernels.selector import get_kernel
from sglang.kernels.spec import FormatSignature, KernelBackend, KernelSpec
... | 63 | 1,932 |
sglang | python/sglang/kernels/ops/sampling/murmur_hash.py | .py | import torch
import triton
import triton.language as tl
@triton.jit
def rotl32(x, r: tl.constexpr) -> tl.uint32:
"""
rotate left 32-bit integer x by r bits
e.g. x = 01110001, r = 2 -> 11000101
"""
x = x.to(tl.uint64)
return ((x << r) | (x >> (32 - r))) & 0xFFFFFFFF
@triton.jit
def fmix32(h: ... | 122 | 3,150 |
sglang | python/sglang/kernels/ops/memory/allocator.py | .py | import triton
import triton.language as tl
# free_page_ptr aliases self.free_pages, which the paged allocator re-slices
# after every allocation (self.free_pages = self.free_pages[num_new_pages:]).
# Slicing only advances data_ptr() by num_new_pages * 8 bytes, so the pointer
# flips between 16-byte-aligned and unalig... | 136 | 5,091 |
sglang | python/sglang/kernels/ops/memory/gpu_tensor_hash.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... | 186 | 5,118 |
sglang | python/sglang/kernels/ops/memory/virtual_slot.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... | 97 | 3,500 |
sglang | python/sglang/kernels/ops/memory/__init__.py | .py | """Memory / KV-slot allocation kernels (Triton).
The Triton kernels migrated here live in this package
(``sglang.kernels.ops.memory.<module>``); import them from there. Their
``KernelSpec`` metadata is registered below for inventory (backend = Triton).
"""
from sglang.kernels.registry import register_kernel
from sgla... | 48 | 1,398 |
sglang | python/sglang/kernels/ops/memory/memcpy_triton.py | .py | """Offset/size-driven device memcpy kernel, migrated from
``sglang.srt.layers.dp_attention`` (RFC #29630, Phase 2.5).
"""
import functools
import triton
import triton.language as tl
@triton.jit
def memcpy_triton_kernel(
dst_ptr,
src_ptr,
offset_ptr,
sz_ptr,
offset_src: tl.constexpr,
chunk_si... | 50 | 1,448 |
sglang | python/sglang/kernels/ops/memory/common.py | .py | from __future__ import annotations
import torch
import triton
import triton.language as tl
@triton.jit
def write_req_to_token_pool_triton(
req_to_token_ptr, # [max_batch, max_context_len]
req_pool_indices,
prefix_tensors,
pre_lens,
seq_lens,
extend_lens,
out_cache_loc,
req_to_token_p... | 164 | 5,137 |
sglang | python/sglang/kernels/ops/communication/__init__.py | .py | """Collective-communication kernels (custom all-reduce, ...).
Reserved group in the ``sglang.kernels`` namespace (RFC #29630). No thin
wrappers are exposed here: the collective ops (custom all-reduce and friends)
are stateful — they manage workspaces / IPC handles and are driven through a
``CustomAllreduce``-style obj... | 13 | 605 |
sglang | python/sglang/kernels/ops/communication/mp.py | .py | """Multi-process / multi-GPU launching utilities (torchrun-based).
Shared `multigpu_launch` helper that both `sglang.test.kernels.utils` and
`sglang.kernels.jit.benchmark.utils` build their domain-specific entry points on
top of (`multigpu_pytest_main`, `multigpu_bench_main`).
When a script that calls one of those wr... | 219 | 7,680 |
sglang | python/sglang/kernels/ops/communication/inkling_ar_scattered_sconv.py | .py | """Fused all-reduce and scattered short-convolution for Inkling.
The kernel reduces a per-rank hidden-channel slice, applies causal convolution,
and updates the convolution and prefix caches in one launch.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
import torch
from sglang.kernels.jit.... | 350 | 10,713 |
sglang | python/sglang/kernels/ops/communication/inkling_ar_fused.py | .py | """Fused all-reduce, decode short-convolution, and RMSNorm for Inkling.
The small-batch decode kernel processes one token per block.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
import torch
from sglang.kernels.jit.utils import cache_once, empty_sentinel, load_jit, make_cpp_args
if TYPE... | 223 | 7,098 |
sglang | python/sglang/kernels/ops/communication/all_reduce.py | .py | from __future__ import annotations
import enum
from typing import TYPE_CHECKING, List, Tuple, Union
import torch
import tvm_ffi
from tvm_ffi import Module
from sglang.kernel_api_logging import debug_kernel_api
from sglang.kernels.jit.utils import (
cache_once,
is_arch_support_pdl,
lazy_register_class,
... | 200 | 6,039 |
sglang | python/sglang/kernels/ops/communication/inkling_all_reduce.py | .py | """CUDA-JIT all-reduce kernels for Inkling symmetric-memory buffers.
The producer writes its local shard into the symmetric buffer, and the reduced
result remains there so callers do not need staging or copy-out kernels.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
import torch
from sgla... | 358 | 12,565 |
sglang | python/sglang/kernels/ops/gemm/sgemm_lora_b.py | .py | import torch
import triton
import triton.language as tl
from sglang.kernels.ops.gemm.kernel_utils import _resolve_token_positions
from sglang.srt.lora.utils import LoRABatchInfo
@triton.jit
def _sgemm_lora_b_kernel(
# Pointers to matrices
x,
weights,
output,
# Matrix dimensions
N, # output_d... | 189 | 5,572 |
sglang | python/sglang/kernels/ops/gemm/fp8_blockwise_gemm.py | .py | from __future__ import annotations
from typing import TYPE_CHECKING
import torch
from sglang.kernel_api_logging import debug_kernel_api
from sglang.kernels.jit.utils import cache_once, load_jit
from sglang.srt.utils.common import is_sm120_supported
from sglang.srt.utils.custom_op import register_custom_op
if TYPE_C... | 84 | 2,396 |
sglang | python/sglang/kernels/ops/gemm/chunked_sgmv_shrink.py | .py | import torch
import triton
import triton.language as tl
from sglang.kernels.ops.gemm.lora_tuning_config import get_lora_shrink_config
from sglang.srt.lora.utils import LoRABatchInfo
from sglang.srt.utils import cached_triton_kernel
@cached_triton_kernel(
lambda _, kwargs: (kwargs["K"], kwargs["NUM_SLICES"], kwar... | 197 | 6,217 |
sglang | python/sglang/kernels/ops/gemm/kv_b_lora_absorbed.py | .py | """Triton kernels for absorbed-MLA ``kv_b_proj`` LoRA correction.
The absorbed-MLA path bypasses ``kv_b_proj.forward()`` and folds the K/V
sides as plain BMMs ``q_nope @ w_kc`` and ``attn_output @ w_vc``. When a
LoRA adapter is active on ``kv_b_proj`` we add the LoRA delta to
``q_nope_out`` / ``attn_bmm_output`` manu... | 854 | 26,260 |
sglang | python/sglang/kernels/ops/gemm/dsv3_fused_a_gemm.py | .py | """
JIT kernel for DeepSeek V3 fused QKV-A GEMM (min-latency).
Runtime-compiled CUDA C++ kernel for SM90+ (Hopper) GPUs.
Shapes: hd_in a multiple of 256, hd_out a multiple of 16, num_tokens 1-16, bfloat16.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
import torch
from sglang.ke... | 91 | 2,658 |
sglang | python/sglang/kernels/ops/gemm/kernel_utils.py | .py | import triton
import triton.language as tl
@triton.jit
def _resolve_token_positions(
sorted_token_ids, seg_start, s_offset, seg_len, SORTED_BY_ADAPTER: tl.constexpr
):
"""Map logical segment offsets to physical token positions.
When SORTED_BY_ADAPTER is True, segments are grouped by adapter and
sorte... | 20 | 659 |
sglang | python/sglang/kernels/ops/gemm/gate_up_lora_b.py | .py | import torch
import triton
import triton.language as tl
from sglang.kernels.ops.gemm.kernel_utils import _resolve_token_positions
from sglang.srt.lora.utils import LoRABatchInfo
@triton.jit
def _gate_up_lora_b_kernel(
# Pointers to matrices
x,
weights,
output,
# Parameters of size
K, # K = R... | 205 | 6,220 |
sglang | python/sglang/kernels/ops/gemm/chunked_sgmv_expand.py | .py | from typing import Optional
import torch
import triton
import triton.language as tl
from sglang.kernels.ops.gemm.lora_tuning_config import get_lora_expand_config
from sglang.srt.lora.utils import LoRABatchInfo
from sglang.srt.utils import cached_triton_kernel
@cached_triton_kernel(
lambda _, kwargs: (kwargs["NU... | 239 | 7,797 |
sglang | python/sglang/kernels/ops/gemm/__init__.py | .py | """GEMM and fused-GEMM kernels."""
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
from sglang.kernels.registry import register_kernel
from sglang.kernels.selector import get_kernel
from sglang.kernels.spec import (
CapabilityRequirement,
FormatSignature,
KernelBackend,
... | 164 | 5,320 |
sglang | python/sglang/kernels/ops/gemm/dsv3_router_gemm.py | .py | """
JIT kernel for DeepSeek V3 router GEMM.
Runtime-compiled CUDA C++ kernel for SM90+ (Hopper) GPUs.
Supports num_experts in {256, 384}, hidden_dim a multiple of 1024, num_tokens 1-16.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
import torch
from sglang.kernel_api_logging imp... | 93 | 2,580 |
sglang | python/sglang/kernels/ops/gemm/chunked_embedding_lora_a.py | .py | import torch
import triton
import triton.language as tl
from sglang.srt.lora.utils import LoRABatchInfo
@triton.jit(do_not_specialize=["num_segments"])
def _chunked_embedding_lora_a_kernel(
# Pointers to tensors
input_ids,
weights,
output,
# Dimensions
vocab_size,
rank,
num_loras,
... | 143 | 4,211 |
sglang | python/sglang/kernels/ops/gemm/embedding_lora_a.py | .py | import torch
import triton
import triton.language as tl
from sglang.srt.lora.utils import LoRABatchInfo
@triton.jit
def _embedding_lora_a_kernel(
# Pointers to tensors
input_ids,
weights,
output,
extra_embeddings,
# Dimensions
vocab_size,
rank,
num_loras,
# Strides
w_strid... | 187 | 5,345 |
sglang | python/sglang/kernels/ops/gemm/sgemm_lora_a.py | .py | import torch
import triton
import triton.language as tl
from sglang.kernels.ops.gemm.kernel_utils import _resolve_token_positions
from sglang.srt.lora.utils import LoRABatchInfo
@triton.jit
def _sgemm_lora_a_kernel(
# Pointers to matrices
x,
weights,
output,
# Matrix dimensions
N, # stack_nu... | 183 | 5,521 |
sglang | python/sglang/kernels/ops/gemm/cutedsl_bf16_gemm.py | .py | # Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved.
# Copyright (c) 2026 by FlashInfer team.
# Copyright 2026 SGLang Team
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http... | 1,496 | 63,439 |
sglang | python/sglang/kernels/ops/gemm/cutedsl_dsv3_fused_a_gemm.py | .py | # Copyright (c) 2019-2024, NVIDIA CORPORATION. All rights reserved.
# 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/L... | 385 | 13,377 |
sglang | python/sglang/kernels/ops/gemm/qkv_lora_b.py | .py | import torch
import triton
import triton.language as tl
from sglang.kernels.ops.gemm.kernel_utils import _resolve_token_positions
from sglang.srt.lora.utils import LoRABatchInfo
@triton.jit
def _qkv_lora_b_kernel(
# Pointers to matrices
x,
weights,
output,
# Parameters of size
K, # K = R
... | 217 | 6,940 |
sglang | python/sglang/kernels/ops/gemm/fused_a_gemm.py | .py | """Unified entry point for the DeepSeek-V3 fused QKV-A GEMM.
Dispatches to one of two interchangeable implementations via ``backend``:
- ``"jit"``: runtime-compiled CUDA C++ (``sglang.kernels.ops.gemm.dsv3_fused_a_gemm``).
- ``"cutedsl"``: CuTe DSL (``sglang.kernels.ops.gemm.cutedsl_dsv3_fused_a_gemm``).
- ``"auto"``... | 78 | 2,361 |
sglang | python/sglang/kernels/ops/gemm/lora_tuning_config.py | .py | """
Configuration loader for auto-tuned LoRA CSGMV kernel block sizes.
Follows the same pattern as fused_moe_triton_config.py:
- Offline tuning script writes JSON files keyed by chunk_size (BLOCK_M)
- At server startup, the config loader reads the best block sizes for each kernel
- Kernels use these instead of hardcod... | 202 | 6,890 |
sglang | python/sglang/kernels/ops/gemm/tiny_gemm.py | .py | from __future__ import annotations
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,
)
if TYPE_CHECKING:
from tvm_ffi.module import Module
_MAX_M_DEFAULT: int = 16
@cache_once
def _jit_tiny_... | 145 | 4,775 |
sglang | python/sglang/kernels/ops/gemm/trtllm_lora_temp/sgemm_lora_b.py | .py | import torch
import triton
import triton.language as tl
from sglang.kernels.ops.gemm.trtllm_lora_temp.gate_up_lora_b import (
_CUBLAS_MIN_S_RANK,
)
from sglang.kernels.ops.gemm.trtllm_lora_temp.kernel_utils import (
_resolve_token_positions,
get_pdl_launch_metadata,
)
from sglang.srt.lora.trtllm_lora_temp.... | 312 | 9,442 |
sglang | python/sglang/kernels/ops/gemm/trtllm_lora_temp/kv_b_lora_absorbed.py | .py | """Triton kernels for absorbed-MLA ``kv_b_proj`` LoRA correction.
The absorbed-MLA path bypasses ``kv_b_proj.forward()`` and folds the K/V
sides as plain BMMs ``q_nope @ w_kc`` and ``attn_output @ w_vc``. When a
LoRA adapter is active on ``kv_b_proj`` we add the LoRA delta to
``q_nope_out`` / ``attn_bmm_output`` manu... | 966 | 30,475 |
sglang | python/sglang/kernels/ops/gemm/trtllm_lora_temp/kernel_utils.py | .py | import triton
import triton.language as tl
from sglang.kernels.jit.utils import is_arch_support_pdl
def get_pdl_launch_metadata() -> tuple[bool, dict]:
"""Return (ENABLE_PDL constexpr value, extra launch kwargs) for LoRA kernels.
``launch_pdl`` is NVIDIA-only Triton launch metadata; the HIP backend
reje... | 32 | 1,117 |
sglang | python/sglang/kernels/ops/gemm/trtllm_lora_temp/gate_up_lora_b.py | .py | import torch
import triton
import triton.language as tl
from sglang.kernels.ops.gemm.trtllm_lora_temp.kernel_utils import (
_resolve_token_positions,
get_pdl_launch_metadata,
)
from sglang.srt.lora.trtllm_lora_temp.environ import lora_envs
from sglang.srt.lora.utils import LoRABatchInfo
# Minimum total_tokens... | 268 | 8,537 |
sglang | python/sglang/kernels/ops/gemm/trtllm_lora_temp/__init__.py | .py | """Experimental TRT-LLM LoRA kernel variants (gated by ``SGLANG_EXPERIMENTAL_LORA_OPTI`` / ``lora_envs``).
Migrated from ``sglang.srt.lora.trtllm_lora_temp.triton_ops`` (RFC #29630)."""
| 4 | 187 |
sglang | python/sglang/kernels/ops/gemm/trtllm_lora_temp/sgemm_lora_a.py | .py | import functools
import torch
import triton
import triton.language as tl
from sglang.kernels.ops.gemm.trtllm_lora_temp.kernel_utils import (
_resolve_token_positions,
get_pdl_launch_metadata,
)
from sglang.srt.lora.trtllm_lora_temp.environ import lora_envs
from sglang.srt.lora.utils import LoRABatchInfo
@tr... | 337 | 10,918 |
sglang | python/sglang/kernels/ops/gemm/trtllm_lora_temp/qkv_lora_b.py | .py | from typing import Optional
import torch
import triton
import triton.language as tl
from sglang.kernels.ops.gemm.trtllm_lora_temp.kernel_utils import (
_resolve_token_positions,
get_pdl_launch_metadata,
)
from sglang.srt.lora.trtllm_lora_temp.environ import lora_envs
from sglang.srt.lora.utils import LoRABatc... | 297 | 10,267 |
sglang | python/sglang/kernels/ops/attention/flash_attention_v4.py | .py | from __future__ import annotations
import os
from typing import Callable, Optional, Tuple, Union
import torch
import torch.nn.functional as F
from sglang.kernel_api_logging import debug_kernel_api
try:
if os.environ.get("SGLANG_INKLING_FA4_USE_PIP") == "1":
# A/B debug escape hatch: route through the pi... | 310 | 10,880 |
sglang | python/sglang/kernels/ops/attention/inkling_attn_prologue.py | .py | """Fused target-verify attention prologue: {k/v sconv + save_windows + qk-norm
+ KV-cache store} in one kernel (csrc/tml/inkling_attn_prologue_fused.cuh)."""
from __future__ import annotations
from typing import TYPE_CHECKING
import torch
from sglang.kernels.jit.utils import (
cache_once,
empty_sentinel,
... | 401 | 13,579 |
sglang | python/sglang/kernels/ops/attention/dcp_kernels.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... | 667 | 21,521 |
sglang | python/sglang/kernels/ops/attention/mla_kv_pack_quantize_fp8.py | .py | """Fused ``cat(k_nope, broadcast(k_pe)) + FP8 quantize`` for K and ``FP8 quantize`` for V.
Dispatches between two Triton kernels per batch size; see ``_pick_kernel``.
"""
from __future__ import annotations
from typing import Optional, Tuple
import torch
import triton
import triton.language as tl
from sglang.kernel... | 296 | 9,297 |
sglang | python/sglang/kernels/ops/attention/verify_splitkv.py | .py | """Split-KV (flash-decode) attention for EAGLE speculative *verify*.
Only valid when speculative ``topk == 1`` (the EAGLE tree reduces to a pure
causal chain); the caller gates on that. ``topk > 1`` trees fall back to
``extend_attention_fwd``.
On the Triton backend, EAGLE target-verify runs through the prefill
``exte... | 858 | 29,097 |
sglang | python/sglang/kernels/ops/attention/vision_rope.py | .py | """Fused interleaved complex RoPE for vision attention Q/K tensors."""
from __future__ import annotations
from typing import Tuple
import torch
import triton
import triton.language as tl
PreparedInplaceComplexRoPE = Tuple[torch.Tensor, torch.Tensor]
@triton.jit(do_not_specialize=["n_pairs"])
def _fused_qk_complex... | 218 | 6,883 |
sglang | python/sglang/kernels/ops/attention/flash_attention_v3.py | .py | import logging
import os
from typing import Optional, Union
import torch
from sglang.kernel_api_logging import debug_kernel_api
from sglang.kernels.jit.utils import cache_once
from sglang.srt.environ import envs
from sglang.srt.utils import get_device_capability, is_musa
logger = logging.getLogger(__name__)
SGL_FA3... | 281 | 8,853 |
sglang | python/sglang/kernels/ops/attention/cutedsl_fp8_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 kernel for Blackwell (SM100).
Architecture:
- 384 threads: 256 math (2 WGs) + 128 specialized (2 TMA + 2 UMMA)
- 1 TMA per KV block [128, 128], ... | 1,818 | 83,046 |
sglang | python/sglang/kernels/ops/attention/merge_state.py | .py | from typing import Optional, Tuple
import torch
import triton
import triton.language as tl
@triton.jit
def merge_state_kernel(
output, # [NUM_TOKENS, NUM_HEADS, HEAD_SIZE] v_merged
output_lse, # [NUM_TOKENS, NUM_HEADS] s_merged
prefix_output, # [NUM_TOKENS, NUM_HEADS, HEAD_SIZE] v_a
prefix_lse, #... | 97 | 2,877 |
sglang | python/sglang/kernels/ops/attention/utils.py | .py | import torch
import triton
import triton.language as tl
from sglang.kernels.jit.utils import is_arch_support_pdl
from sglang.kernels.ops.attention.pad import (
pad_sequence_with_mask as pad_sequence_with_mask,
)
from sglang.kernels.ops.attention.pad import (
pad_sequence_with_mask_kernel as pad_sequence_with_m... | 477 | 16,679 |
sglang | python/sglang/kernels/ops/attention/decode_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,045 | 30,615 |
sglang | python/sglang/kernels/ops/attention/fused_metadata_copy.py | .py | """
Fused metadata copy kernel for DSA backend CUDA graph replay.
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 cac... | 317 | 12,754 |
sglang | python/sglang/kernels/ops/attention/minimax_qknorm_rope.py | .py | """Fused per-head Gemma-RMSNorm + partial NeoX RoPE for MiniMax-M3 attention.
In-place over a fused QKV tensor: normalizes + rotates one or more groups of
heads (each group = a contiguous head run sharing one norm weight, all getting
RoPE), leaving every other head (V, index-V) untouched. Consumes the model's
own ``co... | 171 | 4,988 |
sglang | python/sglang/kernels/ops/attention/flash_mla_sm120_triton.py | .py | """SM120-optimized Triton FlashMLA sparse decode kernel — Tiled V2.
Replaces V1's serial token loop with a tiled vectorized approach:
1. BLOCK_T tokens loaded simultaneously via 2D gather (vs 1-at-a-time)
2. All BLOCK_T QK scores computed at once via vectorized mul-reduce
3. V accumulation via vectorized weighte... | 371 | 13,324 |
sglang | python/sglang/kernels/ops/attention/minimax_decode_topk.py | .py | """Block top-k over per-row block scores for the MiniMax-M3 sparse decode indexer.
Drop-in replacement for the 2-stage split-K Triton topk
(``_topk_index_partial_kernel`` + ``_topk_index_merge_kernel``): given the
decode score tensor ``[num_heads, batch, max_seqblock]`` it produces
``topk_idx`` ``[num_heads, batch, to... | 137 | 5,006 |
sglang | python/sglang/kernels/ops/attention/metadata.py | .py | from typing import TYPE_CHECKING, Optional
import torch
import triton
import triton.language as tl
if TYPE_CHECKING:
from sglang.srt.mem_cache.swa_memory_pool import SWAKVPool
@triton.jit
def get_num_kv_splits_triton(
num_kv_splits_ptr,
seq_lens_ptr,
num_seq,
num_group,
num_head,
num_kv_... | 733 | 25,498 |
sglang | python/sglang/kernels/ops/attention/cutedsl_gdn_mtp_ring.py | .py | # Vendored from flashinfer 0.6.15.post1 (flashinfer/gdn_kernels/gdn_decode_bf16_state.py,
# Apache-2.0) to add the ReplaySSM fused ring-write to the GDN MTP verify kernels.
# Covers only the BF16-STATE (SM100) variant; the fp32-state SM90 entry in
# flashinfer/gdn_decode.py is untouched -- fold verify on fp32 states fa... | 4,128 | 186,539 |
sglang | python/sglang/kernels/ops/attention/cutedsl_kda.py | .py | """CuTe DSL Fused Sigmoid Gating Delta Rule Kernel for KDA Decode.
This version uses production / Triton-compatible VK state layout:
state.shape == (pool_size, HV, V, K)
The kernel still computes on a logical (K, V) matrix in shared memory. Global
state loads/stores therefore explicitly map:
global(V, K) <-> ... | 1,563 | 58,287 |
sglang | python/sglang/kernels/ops/attention/set_mla_kv_concat_q.py | .py | """Fused MLA decode prepare tail: paged-KV scatter + absorbed-q concat.
One launch replacing the back-to-back ``set_mla_kv_buffer`` +
``concat_mla_absorb_q`` pair on the trtllm-mla decode graph path. Both
workloads are launch-bound data movement at decode batch sizes; the fusion
saves a kernel launch per MLA layer and... | 319 | 10,843 |
sglang | python/sglang/kernels/ops/attention/sparse_mla_q8kv8_prefill_sm90.py | .py | """JIT-compiled Q8KV8 sparse prefill attention kernel for SM90 (Hopper/H200).
Uses native FP8 GMMA instructions via CUTLASS/CUTE for MLA attention
with FP8 quantized Q and KV tensors.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Optional
import torch
from sglang.kernel_api_logging impor... | 399 | 11,486 |
sglang | python/sglang/kernels/ops/attention/flash_mla_sm120.py | .py | """SM120 FlashMLA sparse decode implementation.
On SM120 (Blackwell Desktop / RTX PRO 6000) the flash_mla CUDA kernel
is not available, so this module provides alternative implementations:
- A fused Triton kernel (default, ``SGLANG_SM120_TRITON_FLASHMLA=1``)
- A pure-PyTorch fallback (``SGLANG_SM120_TRITON_FLASHMLA=0... | 641 | 21,486 |
sglang | python/sglang/kernels/ops/attention/fused_qk_rmsnorm_rope_gate.py | .py | """Fused Q/K GemmaRMSNorm + NeoX RoPE + gate deinterleave (Triton).
Single kernel launch fusing per-head GemmaRMSNorm, partial NeoX RoPE,
and gate deinterleave for Qwen3.5's interleaved Q+Gate layout.
2D grid (T, num_q_heads + num_kv_heads) — each program handles one
(token, head) pair. Q programs also copy the gate ... | 202 | 6,594 |
sglang | python/sglang/kernels/ops/attention/__init__.py | .py | """Attention compute kernels (Triton): decode / extend / prefill / metadata.
The Triton kernels migrated here live in this package
(``sglang.kernels.ops.attention.<module>``); import them from there. Their
``KernelSpec`` metadata is registered below for inventory (backend = Triton).
KV-cache index/write kernels went t... | 151 | 5,557 |
sglang | python/sglang/kernels/ops/attention/inkling_row_scale.py | .py | """CUDA-JIT vectorized per-row scale (the apply_log_scaling_tau contract):
``out[row, :] = bf16(fp32(x[row, :]) * tau[row])``. See
csrc/tml/inkling_row_scale.cuh; the scalar triton kernel remains the fallback
for non-bf16 / unaligned inputs."""
from __future__ import annotations
from typing import TYPE_CHECKING
impo... | 60 | 1,944 |
sglang | python/sglang/kernels/ops/attention/prefill_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... | 220 | 6,362 |
sglang | python/sglang/kernels/ops/attention/dsa_metadata.py | .py | from typing import Optional
import torch
import triton
import triton.language as tl
@triton.jit(
do_not_specialize=[
"page_table_stride_0",
"real_page_table_stride_0",
"max_len",
]
)
def _fused_dsa_decode_metadata_kernel(
seq_lens,
req_pool_indices,
req_to_token,
cache... | 720 | 24,081 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.