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/aot/tests/speculative/test_eagle_utils.py
.py
import sys import pytest import torch import torch.nn.functional as F from sgl_kernel import verify_tree_greedy def test_verify_tree_greedy(): candidates = torch.tensor( [ [0, 1, 2, 3, 4, 5], [7, 8, 9, 10, 11, 12], ], dtype=torch.int64, device="cuda", )...
90
2,410
sglang
python/sglang/kernels/aot/tests/speculative/test_ngram_utils.py
.py
import sys import pytest import torch import torch.nn.functional as F from sgl_kernel import reconstruct_indices_from_tree_mask def test_reconstruct_indices_from_tree_mask(): bs = 1 num_branch_token = 4 seq_lens = torch.tensor([12], device="cuda", dtype=torch.int64) retrive_index = torch.full( ...
79
1,968
sglang
python/sglang/kernels/aot/tests/speculative/test_speculative_sampling.py
.py
import sys import pytest import torch import torch.nn.functional as F from sgl_kernel import tree_speculative_sampling_target_only test_cases = [ ( 1, 1, [3, -1, -1, 4, 5, 18, 11, -1, -1, -1, 12, 18], [[0, 3, 4, 5], [6, 10, 11, -1]], [3, 2], ), ( 0, # thres...
132
4,085
sglang
python/sglang/kernels/aot/tests/spatial/test_greenctx_stream.py
.py
import sys import pytest import torch import torch.nn.functional as F from sgl_kernel import create_greenctx_stream_by_value, get_sm_available def test_green_ctx(): A = torch.randn(5120, 5120).cuda() B = torch.randn(5120, 5120).cuda() C = torch.matmul(A, B) sm_counts = get_sm_available(0) stream_...
28
801
sglang
python/sglang/kernels/aot/benchmark/bench_sum_scale.py
.py
import os import torch import triton import triton.language as tl from sgl_kernel import moe_sum_reduce as moe_sum_reduce_cuda from triton.testing import do_bench from sglang.utils import is_in_ci IS_CI = is_in_ci() @triton.jit def _moe_sum_reduce_kernel( input_ptr, input_stride_0, input_stride_1, ...
250
7,904
sglang
python/sglang/kernels/aot/benchmark/bench_dsv4_norm_rope.py
.py
"""Benchmark for DeepSeek-V4 fused norm + RoPE kernels.""" import itertools import sgl_kernel import torch import triton import triton.testing try: from sglang.utils import is_in_ci IS_CI = is_in_ci() except ImportError: IS_CI = False batch_sizes = [1] if IS_CI else [1, 4, 16, 64, 256] num_heads_list =...
76
2,153
sglang
python/sglang/kernels/aot/benchmark/bench_fp4_gemm.py
.py
import argparse import csv import logging from functools import partial from typing import List, Tuple import torch import triton from flashinfer import fp4_quantize, mm_fp4 from flashinfer.autotuner import autotune from flashinfer.jit.core import logger as flashinfer_logger from flashinfer.testing import bench_gpu_ti...
463
13,132
sglang
python/sglang/kernels/aot/benchmark/bench_moe_topk_softmax.py
.py
import itertools import os import pytest import torch import triton from sgl_kernel import topk_softmax from sglang.utils import is_in_ci # Optional vLLM import try: from vllm import _custom_ops as vllm_custom_ops VLLM_AVAILABLE = True except ImportError: vllm_custom_ops = None VLLM_AVAILABLE = Fals...
221
6,463
sglang
python/sglang/kernels/aot/benchmark/bench_fp8_gemm_swap_ab.py
.py
"""Targeted benchmark for the SM90 FP8 swap-AB dispatch path. Sweeps small batch sizes (M = 1..128) across N/K shapes that exercise each dispatch bucket in `fp8_gemm_sm90_dispatch.cuh`. Output style matches `bench_fp8_gemm.py`: `triton.testing.perf_report` + GB/s table per (N, K). Compare against `main` by: 1. Run ...
133
4,133
sglang
python/sglang/kernels/aot/benchmark/bench_per_tensor_quant_fp8.py
.py
import itertools import math import os from typing import Any, Dict, List, Optional, Tuple import numpy as np import torch import triton import triton.testing from sglang.kernels.ops.quantization.per_tensor_quant_fp8 import ( per_tensor_quant_fp8, ) from sglang.utils import is_in_ci # Optional imports try: f...
137
3,816
sglang
python/sglang/kernels/aot/benchmark/bench_int8_gemm.py
.py
import argparse import copy import itertools import os import torch import triton from sgl_kernel import int8_scaled_mm from sglang.utils import is_in_ci # Optional vLLM import try: from vllm._custom_ops import cutlass_scaled_mm as vllm_scaled_mm VLLM_AVAILABLE = True except ImportError: vllm_scaled_mm ...
184
5,131
sglang
python/sglang/kernels/aot/benchmark/bench_amd_deterministic_allreduce.py
.py
""" Benchmark latency comparison between different all-reduce implementations. Compares: - NCCL all-reduce (may be non-deterministic) - Reduce-scatter + all-gather (RS+AG, deterministic but slower) - Deterministic 1-stage kernel (forces fixed accumulation order, deterministic) Note: The "deterministic kernel" is NOT ...
690
29,516
sglang
python/sglang/kernels/aot/benchmark/bench_moe_topk_sigmoid.py
.py
import itertools import os import pytest import torch import triton from sgl_kernel import topk_sigmoid from sglang.utils import is_in_ci # Optional MUSA import try: from sglang.srt.utils import is_musa if is_musa(): from sglang.srt.hardware_backend.musa.kernels.topk import ( topk_sigmoi...
243
6,938
sglang
python/sglang/kernels/aot/benchmark/bench_per_token_group_quant_8bit.py
.py
import itertools import os import torch import triton from sgl_kernel.test_utils import create_per_token_group_quant_test_data from sglang.kernels.ops.quantization.fp8_kernel import ( per_token_group_quant_8bit as triton_per_token_group_quant_8bit, ) from sglang.kernels.ops.quantization.fp8_kernel import ( sg...
242
7,277
sglang
python/sglang/kernels/aot/benchmark/bench_moe_ep_post_reorder.py
.py
import torch import triton from sglang.kernels.ops.moe.ep_moe_kernels import post_reorder_triton_kernel from sglang.utils import is_in_ci IS_CI = is_in_ci() # CI environment uses simplified parameters if IS_CI: batch_sizes = [64, 128] # Only test 2 values in CI else: batch_sizes = [64, 128, 256, 512, 640, 7...
86
2,481
sglang
python/sglang/kernels/aot/benchmark/bench_activation.py
.py
# Benchmarks SGLang kernels versus vLLM across # (kernel, dtype, batch_size, seq_len, dim) and prints speed-up. import argparse import itertools import os import re from typing import List, Tuple import sgl_kernel import torch import torch.nn.functional as F import triton import triton.testing from sgl_kernel import g...
210
6,890
sglang
python/sglang/kernels/aot/benchmark/bench_fp8_blockwise_group_gemm.py
.py
import argparse import random from dataclasses import dataclass from typing import List, Tuple import deep_gemm import torch from sgl_kernel import fp8_blockwise_scaled_grouped_mm from sglang.utils import is_in_ci IS_CI = is_in_ci() def get_m_alignment_for_contiguous_layout(): return 128 def ceil_div(x: int,...
341
11,549
sglang
python/sglang/kernels/aot/benchmark/bench_es_fp8_blockwise_grouped_gemm.py
.py
import argparse import random from dataclasses import dataclass from typing import List, Tuple import numpy as np import torch from sgl_kernel import ( es_fp8_blockwise_scaled_grouped_mm, fp8_blockwise_scaled_grouped_mm, ) random.seed(28) def ceil_div(x: int, y: int) -> int: return (x + y - 1) // y de...
371
11,631
sglang
python/sglang/kernels/aot/benchmark/bench_rotary_embedding.py
.py
import itertools import os import torch import triton from sgl_kernel.testing.rotary_embedding import ( FlashInferRotaryEmbedding, FusedSetKVBufferArg, MHATokenToKVPool, RotaryEmbedding, create_inputs, ) from sglang.srt.utils.bench_utils import bench_kineto from sglang.utils import is_in_ci IS_CI...
109
2,800
sglang
python/sglang/kernels/aot/benchmark/bench_awq_dequant.py
.py
import itertools import os from typing import List, Tuple import torch import triton import triton.testing from sgl_kernel import awq_dequantize from sglang.utils import is_in_ci # Optional vLLM import try: from vllm import _custom_ops as ops VLLM_AVAILABLE = True except ImportError: ops = None VLLM...
152
4,432
sglang
python/sglang/kernels/aot/benchmark/bench_mrope.py
.py
# Adapted from vLLM benchmark_mrope.py # This script benchmarks the mrope kernel (mainly for Qwen2VL and Qwen2.5VL models). # It generates test data, runs benchmarks, and saves results to a CSV file. # # The CSV file (named with current date/time) contains these columns: # model_name, tp_size, num_tokens, num_heads, n...
251
8,031
sglang
python/sglang/kernels/aot/benchmark/bench_top_k_top_p_sampling.py
.py
import itertools import os import flashinfer.sampling import sgl_kernel import torch import triton import triton.testing from sglang.utils import is_in_ci IS_CI = is_in_ci() def torch_top_k_top_p_joint_sampling_from_probs( normalized_prob, top_k, top_p, eps=1e-4 ): """Reference PyTorch implementation of jo...
147
4,667
sglang
python/sglang/kernels/aot/benchmark/bench_cutlass_mla.py
.py
import argparse import copy import itertools import os import torch import triton from sgl_kernel import cutlass_mla_decode, cutlass_mla_get_workspace_size from sglang.srt.utils import get_device_capability from sglang.utils import is_in_ci IS_CI = is_in_ci() # CI environment uses simplified parameters if IS_CI: ...
176
5,184
sglang
python/sglang/kernels/aot/benchmark/bench_rmsnorm.py
.py
# Benchmarks SGLang RMSNorm kernels versus vLLM and FlashInfer across # (batch_size, seq_len, hidden_size) and prints speed-up. import argparse import itertools import os import re from typing import List, Optional, Tuple, Union import sgl_kernel import torch import torch.nn as nn import triton import triton.testing f...
396
12,192
sglang
python/sglang/kernels/aot/benchmark/bench_fp8_gemm.py
.py
import argparse import copy import itertools import os from typing import Optional, Tuple import torch import triton from sgl_kernel import fp8_scaled_mm as sgl_scaled_mm from sglang.kernels.ops.quantization.per_tensor_quant_fp8 import per_tensor_quant_fp8 from sglang.utils import is_in_ci # Optional vLLM import try...
247
7,255
sglang
python/sglang/kernels/aot/benchmark/bench_moe_align_block_size.py
.py
import argparse import itertools import os import torch import triton import triton.language as tl from sgl_kernel import moe_align_block_size as sgl_moe_align_block_size from sglang.utils import is_in_ci try: from vllm import _custom_ops as ops VLLM_AVAILABLE = True except ImportError: ops = None V...
444
13,708
sglang
python/sglang/kernels/ops/__init__.py
.py
"""Public operator groups for the ``sglang.kernels`` namespace. Each submodule corresponds to one operator group from RFC #29630. Importing a group registers its :class:`~sglang.kernels.spec.KernelSpec` metadata and exposes thin, lazily-dispatched wrapper callables. Importing this package eagerly imports every group ...
46
1,149
sglang
python/sglang/kernels/ops/speculative/ngram_embedding.py
.py
from __future__ import annotations from typing import TYPE_CHECKING from sglang.kernel_api_logging import debug_kernel_api from sglang.kernels.jit.utils import cache_once, load_jit if TYPE_CHECKING: import torch from tvm_ffi.module import Module @cache_once def _jit_ngram_embedding_module() -> Module: ...
166
4,642
sglang
python/sglang/kernels/ops/speculative/fused_kv_materialize.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...
458
17,056
sglang
python/sglang/kernels/ops/speculative/eagle.py
.py
import torch import triton import triton.language as tl from sglang.srt.utils import is_cpu, next_power_of_2 _is_cpu = is_cpu() if _is_cpu: from sgl_kernel import fill_accept_out_cache_loc_cpu, fill_bonus_tokens_cpu @triton.jit def fill_bonus_tokens( accept_tokens, accept_lens, bonus_tokens_ptr, ...
92
2,351
sglang
python/sglang/kernels/ops/speculative/__init__.py
.py
"""Speculative-decoding kernels (Triton). The Triton kernels migrated here live in this package (``sglang.kernels.ops.speculative.<module>``); import them from there. Their ``KernelSpec`` metadata is registered below for inventory (backend = Triton). """ from sglang.kernels.registry import register_kernel from sglang...
37
1,331
sglang
python/sglang/kernels/ops/speculative/ngram_corpus.py
.py
from __future__ import annotations from collections.abc import Iterable, Sequence from typing import Dict, List, Tuple import numpy as np import torch import tvm_ffi from sglang.kernels.jit.utils import cache_once, load_jit _MATCH_TYPE_MAP = {"BFS": 0, "PROB": 1} def _to_csr(batch_tokens: List[List[int]]) -> Tupl...
141
5,026
sglang
python/sglang/kernels/ops/speculative/ragged_verify_kernels.py
.py
from __future__ import annotations import msgspec import torch import triton import triton.language as tl class PaddedToBucket: @classmethod def execute( cls, *, verify_lens: torch.Tensor, graph_num_tokens: int, bs: int, padded_bs: int, ) -> torch.Tensor: ...
200
5,703
sglang
python/sglang/kernels/ops/speculative/multi_layer_eagle.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...
797
26,944
sglang
python/sglang/kernels/ops/speculative/dflash.py
.py
import torch import triton import triton.language as tl @triton.jit def _dflash_accept_bonus_contig_kernel( candidates_ptr, target_top1_ptr, accept_lens_out_ptr, commit_lens_out_ptr, bonus_ids_out_ptr, out_tokens_ptr, prefix_lens_ptr, new_seq_lens_out_ptr, candidates_row_stride, ...
247
8,042
sglang
python/sglang/kernels/ops/speculative/cache_locs.py
.py
from __future__ import annotations import torch import triton import triton.language as tl from sglang.srt.utils import ( is_cpu, is_cuda, is_hip, is_musa, is_npu, is_xpu, next_power_of_2, ) _is_cpu = is_cpu() _is_cuda = is_cuda() _is_hip = is_hip() _is_npu = is_npu() _is_musa = is_musa()...
491
15,261
sglang
python/sglang/kernels/ops/speculative/reject_sampling.py
.py
import triton import triton.language as tl @triton.jit def speculative_sampling_classic_kernel( # Pointers Predicts, AcceptIndex, AcceptTokenNum, Candidates, RetriveIndex, UniformSamples, UniformSamplesFinal, TargetProbs, DraftProbs, # Strides stride_cand_b, stride_...
209
6,349
sglang
python/sglang/kernels/ops/speculative/gather_spec_extras.py
.py
from __future__ import annotations from typing import Optional import torch import triton import triton.language as tl @triton.jit def _gather_rows_kernel( idx_ptr, s0, d0, n0, s1, d1, n1, s2, d2, n2, s3, d3, n3, HAS3: tl.constexpr, BLOCK: tl.constexpr, ):...
118
3,790
sglang
python/sglang/kernels/ops/speculative/topk1.py
.py
from __future__ import annotations import torch import triton import triton.language as tl _DRAFT_TOPK1_BLOCK = 8192 @triton.jit def _draft_topk1_partial_argmax_kernel( logits, partial_vals, partial_indices, logits_row_stride, vocab_size: tl.constexpr, num_splits: tl.constexpr, BLOCK: tl...
151
4,881
sglang
python/sglang/kernels/ops/speculative/spec_tree.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...
282
10,723
sglang
python/sglang/kernels/ops/speculative/dspark/dspark_schedule.py
.py
from __future__ import annotations from typing import TYPE_CHECKING import torch import triton import triton.language as tl from sglang.kernels.ops.speculative.dspark.dispatch import ( inputs_on_cuda, ) if TYPE_CHECKING: from sglang.srt.speculative.dspark_components.dspark_planner import ( DSparkSch...
261
7,836
sglang
python/sglang/kernels/ops/speculative/dspark/dspark_draft_model.py
.py
from __future__ import annotations from typing import Optional import msgspec import torch import torch.nn.functional as F import triton import triton.language as tl from sglang.kernels.ops.speculative.dspark.dispatch import inputs_on_cuda _BLOCK_V = 1024 _IDX_SENTINEL = tl.constexpr(2147483647) class SampleStepT...
448
14,288
sglang
python/sglang/kernels/ops/speculative/dspark/dspark_accept.py
.py
from __future__ import annotations from typing import Optional import msgspec import torch import triton import triton.language as tl from sglang.kernels.ops.speculative.dspark.dispatch import inputs_on_cuda from sglang.kernels.ops.speculative.reject_sampling import ( chain_speculative_sampling_triton, ) from sg...
865
26,608
sglang
python/sglang/kernels/ops/speculative/dspark/dispatch.py
.py
from __future__ import annotations import torch 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 inputs take the torch reference implementation (triton is CUDA-only, and CPU-side call...
15
583
sglang
python/sglang/kernels/ops/speculative/dspark/fused_kv_write.py
.py
from typing import Optional import torch import triton import triton.language as tl @triton.jit def _fused_kv_norm_rope_write_kernel( kv_ptr, meta_ptr, knw_ptr, cos_sin_ptr, pos_ptr, loc_ptr, commit_lens_ptr, locs_row_width, KV: tl.constexpr, D: tl.constexpr, NH: tl.conste...
127
4,130
sglang
python/sglang/kernels/ops/speculative/dspark/dspark_verify_window.py
.py
from __future__ import annotations import msgspec import torch import triton import triton.language as tl from sglang.kernels.ops.speculative.cache_locs import assign_extend_cache_locs_func from sglang.kernels.ops.speculative.dspark.dispatch import inputs_on_cuda from sglang.srt.managers.schedule_batch import Schedul...
908
27,198
sglang
python/sglang/kernels/ops/speculative/dspark/dspark_attn_metadata.py
.py
from __future__ import annotations from typing import Tuple import msgspec import torch import triton import triton.language as tl from sglang.kernels.ops.speculative.dspark.dispatch import inputs_on_cuda from sglang.srt.utils import ceil_align class DsparkWindowGather(msgspec.Struct, frozen=True): num_q: int ...
492
15,426
sglang
python/sglang/kernels/ops/activation/__init__.py
.py
"""Fused gated-activation kernels (``act(x[:h]) * x[h:]``). Each operator is a :class:`~sglang.kernels.fused_op.BaseFusedOp` with a pure-``torch`` reference (``forward_native``) plus AOT (``sgl_kernel``) and JIT CUDA backends behind one ``(input, out)`` signature. The JIT backend additionally accepts ``expert_ids`` / ...
333
10,949
sglang
python/sglang/kernels/ops/activation/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, ) from sglang.srt.utils.custom_op import register_custom_op if TYPE_C...
230
7,363
sglang
python/sglang/kernels/ops/activation/softcap.py
.py
import torch import triton import triton.language as tl from triton.language.extra import libdevice softcap_out_autotune = triton.autotune( configs=[ triton.Config(kwargs={"BLOCK_SIZE": 128}, num_warps=4), triton.Config(kwargs={"BLOCK_SIZE": 128}, num_warps=8), triton.Config(kwargs={"BLOCK_...
121
3,880
sglang
python/sglang/kernels/ops/mm/__init__.py
.py
"""Multimodal kernels.""" __all__ = ["process"]
4
49
sglang
python/sglang/kernels/ops/mm/process/__init__.py
.py
"""Multimodal input-processing kernels.""" from sglang.kernels.ops.mm.process.image import normalize_and_patchify __all__ = ["normalize_and_patchify"]
6
153
sglang
python/sglang/kernels/ops/mm/process/image.py
.py
import torch import torch.nn.functional as F import triton import triton.language as tl _MAX_TRITON_ELEMENTS = 2**31 - 1 @triton.jit def _normalize_and_patchify_kernel( input_ptr, scale_ptr, bias_ptr, output_ptr, channels: tl.constexpr, input_height, input_width, grid_height, grid...
125
3,687
sglang
python/sglang/kernels/ops/kvcache/triton_store_cache.py
.py
from typing import Literal 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, ) _FP8_DTYPE = torch.float8_e4m3fnuz i...
261
7,844
sglang
python/sglang/kernels/ops/kvcache/hisparse.py
.py
from __future__ import annotations import functools from typing import TYPE_CHECKING import torch from sglang.kernels.jit.utils import load_jit, make_cpp_args if TYPE_CHECKING: from tvm_ffi.module import Module @functools.cache def _jit_sparse_module( item_size_bytes: int, block_size: int, num_top...
330
9,339
sglang
python/sglang/kernels/ops/kvcache/mla_buffer.py
.py
from __future__ import annotations import torch import triton import triton.language as tl from sglang.kernels.jit.utils import is_arch_support_pdl from sglang.srt.runtime_context import get_parallel @triton.jit def set_mla_kv_buffer_kernel( kv_buffer_ptr, cache_k_nope_ptr, cache_k_rope_ptr, loc_ptr...
387
11,578
sglang
python/sglang/kernels/ops/kvcache/aiter_unified_attention.py
.py
import triton import triton.language as tl @triton.jit def scatter_ragged_to_page_table_kernel( kv_flat_ptr, kv_indptr_ptr, dest_ptr, dest_stride, sw_page_table_ptr, swa_slot_mapping_ptr, PAGE_SIZE: tl.constexpr, BLOCK_SIZE: tl.constexpr, HAS_SWA: tl.constexpr, ): """Scatter ra...
98
2,789
sglang
python/sglang/kernels/ops/kvcache/trtllm_mha_page_table.py
.py
"""Device-side page-table builder for the trtllm_mha attention backend. trtllm_mha builds its block (page) table from the global ``req_to_token`` pool. Doing it with a host-max PyTorch gather forces a ``seq_lens.max().item()`` D2H sync (the CPU must know the page-table width before launching). This kernel instead deri...
139
5,714
sglang
python/sglang/kernels/ops/kvcache/set_mla_kv_buffer.py
.py
"""JIT TMA bulk-store path for ``set_mla_kv_buffer``. Each warp scatter-writes one item's (nope, rope) row via a single ``cp.async.bulk.global.shared::cta`` store. Requires SM90+ (Hopper or later) for the TMA bulk-store hardware. The host-side wrapper in ``sglang.srt.mem_cache.utils`` falls back to a Triton kernel for...
118
4,013
sglang
python/sglang/kernels/ops/kvcache/cache_ops.py
.py
import torch import triton import triton.language as tl @triton.jit def concat_and_cast_mha_k_kernel( k_ptr, k_nope_ptr, k_rope_ptr, head_cnt: tl.constexpr, k_stride0: tl.constexpr, k_stride1: tl.constexpr, nope_stride0: tl.constexpr, nope_stride1: tl.constexpr, rope_stride0: tl.co...
796
30,948
sglang
python/sglang/kernels/ops/kvcache/__init__.py
.py
"""KV-cache write/transfer kernels. This group wraps the Triton ``reshape_and_cache`` launcher, whose implementation now lives in this package (``sglang.kernels.ops.kvcache.cache_ops``) after being migrated out of ``sglang.srt.layers.attention.triton_ops`` (RFC #29630). """ from __future__ import annotations from ty...
89
3,056
sglang
python/sglang/kernels/ops/kvcache/kvcache.py
.py
from __future__ import annotations import logging 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.custom_op import register_custom_op if TYPE_CHECKING: from tvm_ffi.module impor...
111
3,840
sglang
python/sglang/kernels/ops/kvcache/kv_indices.py
.py
import triton import triton.language as tl _FLASHMLA_CREATE_KV_BLOCK_SIZE = 4096 FLASHMLA_CREATE_KV_BLOCK_SIZE_TRITON = tl.constexpr(_FLASHMLA_CREATE_KV_BLOCK_SIZE) @triton.jit def create_flashinfer_kv_indices_triton( req_to_token_ptr, # [max_batch, max_context_len] req_pool_indices_ptr, page_kernel_len...
167
6,003
sglang
python/sglang/kernels/ops/kvcache/rope_cache.py
.py
import torch import triton import triton.language as tl @triton.jit def _get_gptj_rotated_x( x, x_rotated_mask, BLOCK_D: tl.constexpr, BLOCK_D_HALF: tl.constexpr, ): # GPT-J rotary layout: # Pair adjacent dimensions and apply: # [x0, x1, x2, x3] -> [-x1, x0, -x3, x2] # Apply sign inve...
737
25,651
sglang
python/sglang/kernels/ops/kvcache/hicache.py
.py
from __future__ import annotations import logging from typing import TYPE_CHECKING 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: import torch from tvm_ffi.module import Module DEFAULT_BLOCK_QUOTA = 2 @cache...
351
10,855
sglang
python/sglang/kernels/ops/kvcache/zero_pages.py
.py
"""Zero whole page envelopes of the unified pool by physical page id. The pool is viewed as int64 words (the MLA page envelope is always 8-byte-aligned: entry bytes per layer = kv_cache_dim * itemsize, a multiple of 8), one wide element per lane; grid = (num_pages, page word blocks). """ from __future__ import annota...
49
1,480
sglang
python/sglang/kernels/ops/kvcache/minimax_store_kv_index.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 @cache_once def _jit_module(head_bytes: int) -> Modu...
80
2,331
sglang
python/sglang/kernels/ops/kvcache/trtllm_mha_graph_metadata.py
.py
"""Fused CUDA-graph metadata update for the TRTLLM MHA backend. `TRTLLMHAAttnBackend._apply_cuda_graph_metadata` used to rebuild the page table(s) and seqlen buffers with ~25 small aten ops per graph replay (index gathers, floor_divide, cumsum, dtype casts, copies). On some CPUs that is ~0.7-1.0 ms of pure host dispat...
207
8,421
sglang
python/sglang/kernels/ops/kvcache/cache_move.py
.py
import torch import triton import triton.language as tl from sglang.srt.utils import is_cpu _is_cpu = is_cpu() if _is_cpu: from sgl_kernel import copy_all_layer_kv_cache_cpu @triton.jit def set_kv_buffer_prefix_valid_tiled( src_k_ptr, src_v_ptr, dst_k_ptr, dst_v_ptr, loc_2d_ptr, commit_...
307
10,403
sglang
python/sglang/kernels/ops/kvcache/fused_fp8_qkv_kv_cache.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 @cache_once def _jit_fused_fp8_qkv_kv_cache_module(d...
71
2,036
sglang
python/sglang/kernels/ops/embeddings/__init__.py
.py
"""Embedding kernels.""" from sglang.kernels.registry import register_kernel from sglang.kernels.spec import KernelBackend, KernelSpec register_kernel( KernelSpec( op="embeddings.vocab_parallel_embedding", backend=KernelBackend.TRITON, target=( "sglang.kernels.ops.embeddings.vo...
18
417
sglang
python/sglang/kernels/ops/embeddings/vocab_parallel_embedding.py
.py
"""Fused Triton vocabulary-parallel embedding lookup.""" import torch import triton import triton.language as tl @triton.jit def _vocab_parallel_embedding_kernel( input_ptr, weight_ptr, out_ptr, # The scalar params are tl.constexpr on purpose: it lets the compiler fold # the vocab-window comparis...
97
2,965
sglang
python/sglang/kernels/ops/mamba/transfer_mamba.py
.py
"""JIT-compiled Mamba KV cache transfer kernel. Provides ``transfer_kv_mamba_pf_lf`` (load: page_first -> layer_first) and ``transfer_kv_mamba_lf_pf`` (backup: layer_first -> page_first). Uses the shared ``load_jit`` + ``cache_once`` infrastructure from ``sglang.kernels.jit.utils`` — the same mechanism used by ``hica...
84
2,131
sglang
python/sglang/kernels/ops/mamba/__init__.py
.py
"""State-space / Mamba kernels (causal conv1d).""" 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 FormatSignature, KernelBackend, KernelSpec if TYPE_CHECK...
104
2,904
sglang
python/sglang/kernels/ops/mamba/causal_conv1d_triton.py
.py
# SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Copyright (c) 2024, Tri Dao. # Adapted from https://github.com/Dao-AILab/causal-conv1d/blob/main/causal_conv1d/causal_conv1d_interface.py # and https://github.com/vllm-project/vllm/blob/main/vllm/model_executor/...
1,208
48,091
sglang
python/sglang/kernels/ops/mamba/mamba_state_scatter_triton.py
.py
""" Fused Triton kernel for Mamba state scatter operations. This kernel replaces the expensive advanced indexing operations in `update_mamba_state_after_mtp_verify` with a single fused gather-scatter kernel, avoiding multiple `index_elementwise_kernel` launches. """ import torch import triton import triton.language a...
890
31,220
sglang
python/sglang/kernels/ops/mamba/mamba_state_indices_triton.py
.py
"""Fused replay-prep state-indices kernel for the mamba cuda-graph path. ``MambaAttnBackendBase._replay_metadata`` refreshes the captured per-bs ``state_indices_list`` buffer before every cuda-graph replay. The reference form is a chain of dispatched aten ops whose host cost shows up in the bs=1 MTP inter-phase seam: ...
76
2,904
sglang
python/sglang/kernels/ops/mamba/inkling_sconv.py
.py
"""CUDA-JIT implementations of the Inkling short-convolution kernels. Their signatures match the Triton entrypoints so model layers can select either backend without adapting arguments. """ from __future__ import annotations from typing import TYPE_CHECKING import torch from sglang.kernels.jit.utils import cache_o...
240
7,677
sglang
python/sglang/kernels/ops/mamba/triton_ops/ssd_state_passing.py
.py
# Adapted from: https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/layers/mamba/ops/ssd_state_passing.py # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Copyright (c) 2024, Tri Dao, Albert Gu. # Adapted from https://github.com/state-spaces/m...
265
10,060
sglang
python/sglang/kernels/ops/mamba/triton_ops/ssd_chunk_scan.py
.py
# Adapted from: https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/layers/mamba/ops/ssd_chunk_scan.py # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Copyright (c) 2024, Tri Dao, Albert Gu. # Adapted from https://github.com/state-spaces/mamb...
563
18,405
sglang
python/sglang/kernels/ops/mamba/triton_ops/ssd_combined.py
.py
# Adapted from: https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/layers/mamba/ops/ssd_combined.py # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Copyright (c) 2024, Tri Dao, Albert Gu. # Adapted from https://github.com/state-spaces/mamba/...
276
9,323
sglang
python/sglang/kernels/ops/mamba/triton_ops/__init__.py
.py
from .mamba_ssm import PAD_SLOT_ID from .ssd_combined import mamba_chunk_scan_combined from .ssu_dispatch import ( initialize_mamba_selective_state_update_backend, selective_state_update, ) __all__ = [ "PAD_SLOT_ID", "selective_state_update", "mamba_chunk_scan_combined", "initialize_mamba_selec...
14
350
sglang
python/sglang/kernels/ops/mamba/triton_ops/ssd_chunk_state.py
.py
# Adapted from: https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/layers/mamba/ops/ssd_chunk_state.py # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Copyright (c) 2024, Tri Dao, Albert Gu. # Adapted from https://github.com/state-spaces/mam...
647
20,854
sglang
python/sglang/kernels/ops/mamba/triton_ops/ssu_dispatch.py
.py
from __future__ import annotations import logging from abc import ABC, abstractmethod from typing import TYPE_CHECKING import torch if TYPE_CHECKING: from sglang.srt.server_args import ServerArgs logger = logging.getLogger(__name__) class MambaSSUBackend(ABC): @property @abstractmethod def name(se...
306
9,971
sglang
python/sglang/kernels/ops/mamba/triton_ops/ssd_bmm.py
.py
# Adapted from: https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/layers/mamba/ops/ssd_bmm.py # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Copyright (c) 2024, Tri Dao, Albert Gu. # Adapted from https://github.com/state-spaces/mamba/blob/...
215
6,821
sglang
python/sglang/kernels/ops/mamba/triton_ops/mamba_ssm.py
.py
# Adapted from: https://github.com/vllm-project/vllm/tree/main/vllm/model_executor/layers/mamba/ops/mamba_ssm.py # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project # Copyright (c) 2024, Tri Dao, Albert Gu. # Adapted from https://github.com/state-spaces/mamba/blo...
569
18,579
sglang
python/sglang/kernels/ops/elementwise/add3.py
.py
"""CUDA JIT elementwise 3-way add: out = bf16(bf16(a + b) + c).""" 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_CHECKING...
70
2,004
sglang
python/sglang/kernels/ops/elementwise/__init__.py
.py
"""Generic elementwise / fused-pointwise kernels. Home for cross-cutting pointwise kernels that do not belong to a single functional group: the fused-pointwise Triton collection (``elementwise``: sigmoid-mul, gated-activation and fused-rmsnorm variants shared across models) and the ``add_constant`` JIT reference kerne...
12
470
sglang
python/sglang/kernels/ops/elementwise/add_constant.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_add_constant_module(constant: int) -> Module: args = make_cpp_args(constant) ...
29
691
sglang
python/sglang/kernels/ops/elementwise/elementwise.py
.py
import torch import triton import triton.language as tl from sglang.kernels.jit.utils import is_arch_support_pdl from sglang.srt.utils import is_hip _is_hip = is_hip() rmsnorm_autotune = triton.autotune( configs=[ triton.Config(kwargs={"BLOCK_SIZE": 1024}, num_warps=4, num_stages=1), triton.Conf...
548
17,571
sglang
python/sglang/kernels/ops/diffusion/modulate_scale_shift.py
.py
"""Fused adaLN modulate: ``x * (1 + scale) + shift`` in one CUDA kernel. Numerical contract: the kernel reproduces each eager op's fp32-opmath/round-to-storage-dtype boundary (fp16/bf16), so its output is bit-exact vs the eager chain (``torch.equal``) and needs no quality gate. """ from __future__ import annotations ...
131
4,029
sglang
python/sglang/kernels/ops/diffusion/residual_gate_add.py
.py
from __future__ import annotations import logging from typing import TYPE_CHECKING import torch from sglang.kernels.jit.utils import cache_once, load_jit, make_cpp_args from sglang.srt.utils.custom_op import register_custom_op if TYPE_CHECKING: from tvm_ffi.module import Module _SUPPORTED_DTYPES = (torch.floa...
137
4,215
sglang
python/sglang/kernels/ops/diffusion/timestep_embedding.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, make_cpp_args if TYPE_CHECKING: from tvm_ffi.module import Module @cache_once def _jit_timestep_embedding_module(dt...
54
1,374
sglang
python/sglang/kernels/ops/diffusion/fused_ln_modulate.py
.py
"""LayerNorm + adaLN modulate folded into one affine LN call. ``layer_norm(x, weight=(1 + scale), bias=shift)`` replaces the affine-free LayerNorm + modulate pair: one kernel and one HBM pass per site instead of two. ``1 + scale`` keeps the eager rounding of the [1, D] modulation row, but scale/shift then apply in fp...
82
2,551
sglang
python/sglang/kernels/ops/diffusion/bitexact_gate.py
.py
"""Shared first-sight verification for bit-exact diffusion fast paths.""" from __future__ import annotations import logging from collections.abc import Callable from typing import Any, TypeVar import torch T = TypeVar("T") EqualFn = Callable[[Any, Any], bool] DiagnosticHintFn = Callable[[], str | None] def flashi...
178
6,462
sglang
python/sglang/kernels/ops/diffusion/__init__.py
.py
"""Registered diffusion-model kernels and their public wrappers. Hot paths import concrete implementations from submodules. The package-level wrappers remain available for backward compatibility. """ from __future__ import annotations from typing import TYPE_CHECKING from sglang.kernels.registry import register_ker...
123
3,622
sglang
python/sglang/kernels/ops/diffusion/usp_relayout.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 from sglang.srt.utils.custom_op import register_custom_op if TYPE_CHECKING: from tvm_ffi.module import Module _SUPPORTED_DTYPES = (torch.float16, torch.bflo...
86
2,599
sglang
python/sglang/kernels/ops/diffusion/ltx2_rmsnorm_modulate.py
.py
"""Weightless RMSNorm + adaLN modulate folded into one kernel for LTX-2. ``rms_norm(x) * (1 + scale) + shift`` at the LTX-2 transformer-block adaLN sites is otherwise an aten ``F.rms_norm`` plus a separate ``mul``/``add`` modulate (one reduction kernel plus several pointwise passes per site). This folds the whole chai...
81
2,945
sglang
python/sglang/kernels/ops/diffusion/quality_gate.py
.py
"""Shared module-site protocol for request-scoped diffusion fast paths.""" from __future__ import annotations import logging from collections.abc import Callable, Iterator from typing import Any from torch import nn RejectReason = Callable[[nn.Module], str | None] class QualityGatedFusion: """Track and toggle...
83
2,732
sglang
python/sglang/kernels/ops/diffusion/ltx2_qknorm_split_rope.py
.py
from __future__ import annotations from typing import TYPE_CHECKING 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_ltx2_qknorm_split_rope_module() -> Modul...
206
4,809