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/diffusion/causal_conv3d_cat_pad.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...
141
3,809
sglang
python/sglang/kernels/ops/diffusion/qknorm_rope.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...
237
6,548
sglang
python/sglang/kernels/ops/diffusion/fused_gate_rmsnorm.py
.py
"""Quality-gated fused RMSNorm modulate/gate sites. Adaln-style DiT blocks (Ideogram 4) spend four elementwise chains per block on modulate/gate around each RMSNorm: ``RMSNorm(x) * scale`` before attention/FFN and ``x + tanh(gate) * RMSNorm(out)`` after. Shared BF16-native Triton kernels (:mod:`sglang.kernels.ops.diff...
123
4,648
sglang
python/sglang/kernels/ops/diffusion/fused_linear_gelu.py
.py
"""Fused linear + tanh-GELU via the cublasLt GELU epilogue, gated by quality. Many diffusion DiT FeedForwards compute ``gelu(linear(x), approximate="tanh")`` as a standalone up-projection GEMM followed by a separate, bandwidth-bound GELU kernel over the ``[tokens, 4*dim]`` MLP intermediate. ``torch._addmm_activation``...
181
7,850
sglang
python/sglang/kernels/ops/diffusion/norm_scale_shift_native.py
.py
from __future__ import annotations from typing import TYPE_CHECKING import torch from sglang.kernels.jit.utils import cache_once, load_jit if TYPE_CHECKING: from tvm_ffi.module import Module _HIDDEN = 3072 _ALIGN = 32 def _aligned(t: torch.Tensor) -> bool: return t.data_ptr() % _ALIGN == 0 def _blackw...
131
3,279
sglang
python/sglang/kernels/ops/diffusion/hunyuan_qknorm.py
.py
# SPDX-License-Identifier: Apache-2.0 from __future__ import annotations import logging from functools import cache import torch import torch.nn as nn from sglang.kernels.ops.diffusion.quality_gate import QualityGatedFusion logger = logging.getLogger(__name__) _FUSION = QualityGatedFusion( name="HunyuanVideo ...
100
2,490
sglang
python/sglang/kernels/ops/diffusion/group_norm_silu.py
.py
import torch from torch import nn def apply_group_norm_silu( x: torch.Tensor, norm: nn.Module, activation: nn.Module, ) -> torch.Tensor: if ( x.is_cuda and not torch.is_grad_enabled() and not x.requires_grad and isinstance(norm, nn.GroupNorm) and isinstance(acti...
36
841
sglang
python/sglang/kernels/ops/diffusion/sparse_linear_attn_kernels.py
.py
"""Sparse linear-attention block-map and fwd kernels, migrated from ``sglang.multimodal_gen.runtime.layers.attention.backends.sparse_linear_attn`` (RFC #29630, Phase 2.5). """ import torch import triton import triton.language as tl def get_block_map(q, k, topk_ratio, BLKQ=64, BLKK=64): arg_k = k - torch.mean( ...
131
3,860
sglang
python/sglang/kernels/ops/diffusion/flydsl/fused_residual_norm.py
.py
"""FlyDSL fused normalization kernels for AMD ROCm (gfx950). Provides two fused kernels: - flydsl_fused_residual_norm_scale_shift: residual_add + gate_mul + RMSNorm/LayerNorm + scale·shift - flydsl_norm_scale_shift: RMSNorm/LayerNorm + scale·shift Both kernels use register-cache optimization: Phas...
903
32,659
sglang
python/sglang/kernels/ops/diffusion/triton/silu_mul_bitexact.py
.py
# SPDX-License-Identifier: Apache-2.0 """Bit-exact fused ``silu(a) * b`` over two same-shape tensors. For SwiGLU MLPs whose gate/up projections are separate GEMMs (so the concatenated-input ``silu_and_mul`` kernels don't apply without an extra full-width ``cat`` pass), this fuses the eager pair ``s = F.silu(a)`` ...
128
3,984
sglang
python/sglang/kernels/ops/diffusion/triton/npu_fallback.py
.py
import torch import torch_npu NPU_ROTARY_MUL_MAX_NUM_HEADS = 1000 NPU_ROTARY_MUL_MAX_HEAD_SIZE = 896 # TODO: remove this when triton ascend bug is fixed def fuse_scale_shift_native( x: torch.Tensor, scale: torch.Tensor, shift: torch.Tensor, block_l: int = 128, block_c: int = 128, ): return x ...
51
1,424
sglang
python/sglang/kernels/ops/diffusion/triton/ulysses_qkv.py
.py
# SPDX-License-Identifier: Apache-2.0 import torch import triton import triton.language as tl @triton.jit def _pack_qkv_destination_major_kernel( output_ptr, q_ptr, k_ptr, v_ptr, total_elements, rows, local_heads, head_size, stride_q_row, stride_q_head, stride_k_row, s...
123
3,667
sglang
python/sglang/kernels/ops/diffusion/triton/norm.py
.py
from typing import Optional, Tuple import torch import triton # type: ignore import triton.language as tl # type: ignore from torch import Tensor from sglang.multimodal_gen.runtime.platforms import current_platform from sglang.srt.utils.custom_op import register_custom_op # RMSNorm-fp32 def maybe_contiguous_lastd...
661
19,918
sglang
python/sglang/kernels/ops/diffusion/triton/mps_fallback.py
.py
"""MPS (Apple Silicon) fallbacks for Triton diffusion kernels. Triton is not available on macOS / Metal, so these pure-PyTorch (and optionally MLX-accelerated) implementations replace the Triton kernels at import time when ``current_platform.is_mps()`` is True. MLX acceleration (opt-in via ``SGLANG_USE_MLX=1``): ...
123
4,137
sglang
python/sglang/kernels/ops/diffusion/triton/causal_conv3d_pad.py
.py
from __future__ import annotations import torch import triton # type: ignore import triton.language as tl # type: ignore @triton.jit def _fused_cat_pad_5d_kernel( x_ptr, cache_ptr, out_ptr, total, channels, t_size, h_size, w_size, cache_t, out_t, out_h, out_w, pa...
123
3,115
sglang
python/sglang/kernels/ops/diffusion/triton/scale_shift.py
.py
import torch import triton # type: ignore import triton.language as tl # type: ignore from sglang.kernels.ops.diffusion.triton.numerics import mul_rn_f32 from sglang.multimodal_gen.runtime.platforms import current_platform @triton.jit def _fused_scaled_residual_add_exact_kernel( output_ptr, residual_ptr, ...
752
23,522
sglang
python/sglang/kernels/ops/diffusion/triton/wan_temb_table_slices.py
.py
# SPDX-License-Identifier: Apache-2.0 """Fused, contiguous adaLN slices for Wan2.2-TI2V per-token modulation. The eager chain per block is ``(scale_shift_table.unsqueeze(0) + temb.float()).chunk(6, dim=2)`` which materializes the full ``(B, S, 6, D)`` tensor in fp32 (a widening copy plus an add over ~8 GB at 704...
100
3,447
sglang
python/sglang/kernels/ops/diffusion/triton/numerics.py
.py
# SPDX-License-Identifier: Apache-2.0 """Numerical primitives shared by bit-exact diffusion Triton kernels.""" import triton # type: ignore import triton.language as tl # type: ignore _FLT_MIN = tl.constexpr(1.1754943508222875e-38) @triton.jit def round_bf16_to_fp32(value): """RNE-round fp32 to bf16 precision...
73
1,797
sglang
python/sglang/kernels/ops/diffusion/triton/sana_wm_gdn_chunkwise.py
.py
# Copyright 2024 NVIDIA CORPORATION & AFFILIATES # # 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 a...
1,740
60,207
sglang
python/sglang/kernels/ops/diffusion/triton/sana_wm_gdn.py
.py
# Copyright 2024 NVIDIA CORPORATION & AFFILIATES # # 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 a...
242
7,969
sglang
python/sglang/kernels/ops/diffusion/triton/hunyuan_qkv_pack.py
.py
# SPDX-License-Identifier: Apache-2.0 import torch import triton import triton.language as tl @triton.autotune( configs=[ triton.Config({"BLOCK_HEADS": 1, "BLOCK_HALF": 64}, num_warps=2), triton.Config({"BLOCK_HEADS": 2, "BLOCK_HALF": 64}, num_warps=4), triton.Config({"BLOCK_HEADS": 4, "B...
215
7,497
sglang
python/sglang/kernels/ops/diffusion/triton/ltx2_rotary.py
.py
import torch import triton import triton.language as tl @triton.jit def _ltx2_split_rotary_kernel( out_ptr, x_ptr, cos_ptr, sin_ptr, seq_len: tl.constexpr, num_heads: tl.constexpr, head_dim: tl.constexpr, half_dim: tl.constexpr, stride_cos_b: tl.constexpr, stride_cos_h: tl.cons...
103
3,258
sglang
python/sglang/kernels/ops/diffusion/triton/wan_causal_cache.py
.py
# SPDX-License-Identifier: Apache-2.0 """Bit-exact data-movement kernels for the Wan causal VAE. Both kernels only move values (plus zero fill / one same-order addition), so their outputs are bitwise identical to the aten op chains they replace: - :func:`cat_pad_channels_last_3d` builds a causal Conv3d input directly...
384
11,232
sglang
python/sglang/kernels/ops/diffusion/triton/indexed_modulation.py
.py
# SPDX-License-Identifier: Apache-2.0 import torch import triton import triton.language as tl from sglang.kernels.ops.diffusion.triton.numerics import round_bf16_to_fp32 @triton.jit def _indexed_scale_shift_bf16_kernel( output_ptr, x_ptr, shift_ptr, scale_ptr, indices_ptr, hidden_size, s...
158
3,664
sglang
python/sglang/kernels/ops/diffusion/triton/layernorm_modulate.py
.py
# SPDX-License-Identifier: Apache-2.0 """Fused LayerNorm + adaLN modulate Triton kernels for bf16 activations. Two fusions, each replacing an eager multi-kernel chain with a single launch while reproducing the eager results bit for bit (``torch.equal``), so callers need no quality gate: - ``fused_layernorm_modulate``...
489
16,817
sglang
python/sglang/kernels/ops/diffusion/triton/native_bf16_rmsnorm.py
.py
# SPDX-License-Identifier: Apache-2.0 """BF16-native RMSNorm fusions shared by diffusion transformer models.""" from __future__ import annotations import torch import triton # type: ignore import triton.language as tl # type: ignore MAX_HIDDEN_SIZE = 8192 @triton.jit def _tanh(x): return 2.0 / (1.0 + tl.exp(...
209
6,037
sglang
python/sglang/kernels/ops/diffusion/triton/rmsnorm_onepass.py
.py
import torch import triton # type: ignore import triton.language as tl # type: ignore from sglang.kernel_api_logging import debug_kernel_api from sglang.multimodal_gen.runtime.platforms import current_platform from sglang.srt.utils.custom_op import register_custom_op # Adapted from https://github.com/ModelTC/Light...
84
2,582
sglang
python/sglang/kernels/ops/diffusion/triton/torch_fallback.py
.py
"""Pytorch native based fallbacks for Triton diffusion kernels. Triton is not available on some platforms, so these pure-PyTorch implementations replace the Triton kernels """ from typing import Optional import torch from torch import Tensor def fuse_scale_shift_kernel_native( x: torch.Tensor, scale: torc...
147
4,277
sglang
python/sglang/kernels/ops/diffusion/triton/varlen_pack_pad.py
.py
"""Fused Triton pack/scatter kernels for the varlen mask path. Used by ``USPAttention.forward`` masked branch to gather Q/K/V at valid positions and scatter the FA output back to the dense ``[B, S, H, D]`` layout. """ from __future__ import annotations import torch import triton # type: ignore import triton.languag...
192
6,412
sglang
python/sglang/kernels/ops/diffusion/triton/rmsnorm_scale_shift_bitexact.py
.py
# SPDX-License-Identifier: Apache-2.0 """Bit-exact fused RMSNorm + adaLN scale/shift (optionally with a preceding residual-gate add) for bf16 activations. Replaces the eager ERNIE-Image adaLN chain ``norm(x) * (1 + scale) + shift`` (4 kernels) ``res = residual + gate * update`` before the n...
312
10,763
sglang
python/sglang/kernels/ops/diffusion/triton/rope_rotate_half_bitexact.py
.py
# SPDX-License-Identifier: Apache-2.0 """Bit-exact fused rotate-half RoPE for bf16 ``(B, S, H, D)`` activations. Replaces the eager ERNIE-Image per-projection chain ``cos/sin -> chunk -> cat(-x2, x1) -> two muls + add -> cat(tail)`` (~7 kernels per q/k, including two full-width concats) with one Triton kernel, r...
155
5,042
sglang
python/sglang/kernels/ops/diffusion/triton/group_norm_silu.py
.py
import math import torch import torch.nn.functional as F import triton # type: ignore import triton.language as tl # type: ignore from sglang.srt.utils.custom_op import register_custom_op _SUPPORTED_DTYPES = {torch.float16, torch.bfloat16, torch.float32} _LARGE_GROUP_THRESHOLD = 1 << 18 _BLOCK_SIZE = 4096 _BLOCKS_...
413
12,347
sglang
python/sglang/kernels/ops/diffusion/triton/rotary.py
.py
import torch import triton # type: ignore import triton.language as tl # type: ignore from sglang.multimodal_gen.runtime.platforms import current_platform @triton.autotune( configs=[ triton.Config({"BLOCK_HEADS": 1, "BLOCK_HS_HALF": 32}, num_warps=2), triton.Config({"BLOCK_HEADS": 2, "BLOCK_HS_...
142
4,404
sglang
python/sglang/kernels/ops/diffusion/triton/group_norm_silu_twopass.py
.py
# SPDX-License-Identifier: Apache-2.0 """Channels-last two-pass GroupNorm(+SiLU) Triton kernels. Relationship to ``group_norm_silu.py`` (``triton_group_norm_silu``): that kernel serves the general NCHW-contiguous case (any channels-per-group, any ndim, always applies SiLU) and keeps backing ``apply_group_norm_silu`` f...
241
8,131
sglang
python/sglang/kernels/ops/diffusion/triton/zimage_native_norm.py
.py
# SPDX-License-Identifier: Apache-2.0 """Z-Image-specific bit-exact per-head RMSNorm kernel.""" from __future__ import annotations import torch import triton # type: ignore import triton.language as tl # type: ignore from sglang.kernels.jit.utils import get_jit_cuda_arch @triton.jit def _qk_rmsnorm_native_kernel...
180
7,031
sglang
python/sglang/kernels/ops/diffusion/triton/wan_rmsnorm_silu.py
.py
# SPDX-License-Identifier: Apache-2.0 """Channels-last-3d Wan VAE RMSNorm(+SiLU) Triton kernel. Fuses the Wan VAE ``WanRMS_norm -> SiLU`` chain (``SiLU(F.normalize(x, dim=1) * scale * gamma + bias)`` on channel-first 5D activations) into one kernel for ``channels_last_3d`` tensors: one program reduces one (b, t, h, w)...
198
6,010
sglang
python/sglang/kernels/ops/diffusion/triton/ltx2_ada_values.py
.py
# Adapted from NVlabs/Sana sol-engine LTX2 Ada-value fusion. # # SPDX-License-Identifier: Apache-2.0 import torch import triton import triton.language as tl @triton.jit def _ltx2_ada_values9_kernel( temb_ptr, table_ptr, out0_ptr, out1_ptr, out2_ptr, out3_ptr, out4_ptr, out5_ptr, o...
187
5,737
sglang
python/sglang/kernels/ops/diffusion/render/__init__.py
.py
from __future__ import annotations import os import shutil import sys from pathlib import Path from typing import Any, Sequence import torch from sglang.multimodal_gen.runtime.utils.logging_utils import init_logger logger = init_logger(__name__) def _get_build_directory(name: str) -> Path: try: from t...
131
3,738
sglang
python/sglang/kernels/ops/diffusion/render/mesh_processor/__init__.py
.py
# SPDX-License-Identifier: Apache-2.0 """ Mesh processor C++ extension for texture inpainting. This module provides JIT-compiled C++ mesh processing for fast texture inpainting. Adapted from Hunyuan3D-2: https://github.com/Tencent/Hunyuan3D-2 """ from __future__ import annotations import os from typing import Tuple ...
65
1,805
sglang
python/sglang/kernels/ops/diffusion/render/hunyuan3d_rasterizer/__init__.py
.py
# SPDX-License-Identifier: Apache-2.0 """ Custom CUDA rasterizer for Hunyuan3D texture generation. This module provides JIT-compiled CUDA rasterization for fast mesh rendering. Adapted from Hunyuan3D-2: https://github.com/Tencent/Hunyuan3D-2 """ from __future__ import annotations import os from typing import Tuple ...
96
2,685
sglang
python/sglang/kernels/ops/diffusion/cutedsl/utils.py
.py
from typing import Optional import cutlass import cutlass.cute as cute import torch WARP_SIZE = 32 TORCH_TO_CUTE_DTYPE = { torch.float16: cutlass.Float16, torch.bfloat16: cutlass.BFloat16, torch.float32: cutlass.Float32, } def to_cute_arg( t, *, assume_aligned: Optional[int] = 32, use_3...
53
1,451
sglang
python/sglang/kernels/ops/diffusion/cutedsl/scale_residual_norm_scale_shift.py
.py
from typing import Optional, Tuple, Union import cuda.bindings.driver as cuda import cutlass import cutlass.cute as cute import torch from sglang.kernels.ops.diffusion.cutedsl.common.norm_fusion import ( apply_norm_cta, broadcast_tensor_for_bsfd, tensor_slice_for_bsfd, ) from sglang.kernels.ops.diffusion....
414
15,293
sglang
python/sglang/kernels/ops/diffusion/cutedsl/common/norm_fusion.py
.py
from typing import Optional, Tuple, Union import cutlass import cutlass.cute as cute import torch from einops import rearrange from sglang.kernels.ops.diffusion.cutedsl.common.reduce import ( cta_reduce_sum, warp_reduce_sum, ) @cute.jit def apply_norm_cta( norm_type: cutlass.Constexpr, num_warps: cu...
202
7,141
sglang
python/sglang/kernels/ops/diffusion/cutedsl/common/reduce.py
.py
import math import cutlass import cutlass.cute as cute @cute.jit def warp_reduce_sum(val: cute.Numeric, reduce_size: int = 32) -> cute.Numeric: iters = int(math.log2(reduce_size)) for i in range(iters): val = val + cute.arch.shuffle_sync_down(val, offset=1 << (iters - i - 1)) return val @cute.j...
34
921
sglang
python/sglang/kernels/ops/layernorm/norm.py
.py
from __future__ import annotations import logging 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, is_arch_support_pdl, load_jit, make_cpp_args, ) if TYPE_CHECKING: from tvm_ffi.modul...
180
5,158
sglang
python/sglang/kernels/ops/layernorm/mhc_head.py
.py
"""Fused triton kernel for the DSV4 hc_head LM-head mixer. Reference torch implementation (deepseek_v4.py DeepseekV4Model.hc_head): shape, dtype = x.size(), x.dtype x = x.flatten(1).float() rsqrt = torch.rsqrt(x.square().mean(-1, keepdim=True) + norm_eps) mixes = F.linear(x, hc_fn) * rsqrt pre = t...
152
4,867
sglang
python/sglang/kernels/ops/layernorm/fused_eh_norm.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 def is_supported_fused_eh_norm_hidden_size(hidden_size: int) -...
68
2,107
sglang
python/sglang/kernels/ops/layernorm/__init__.py
.py
"""Layer-normalization kernels. Each operator is a :class:`~sglang.kernels.fused_op.BaseFusedOp` with a pure-``torch`` reference (``forward_native``) plus optimized per-device backends, all behind one signature. The public module-level functions are thin wrappers over module-level instances; auto-selection follows the...
540
17,445
sglang
python/sglang/kernels/ops/layernorm/mhc.py
.py
import functools import importlib import logging import math import threading from typing import Tuple import torch from sglang.kernels.jit.utils import is_arch_support_pdl from sglang.srt.distributed.device_communicators.pynccl_allocator import ( use_symmetric_memory, ) from sglang.srt.distributed.parallel_state...
1,619
58,235
sglang
python/sglang/kernels/ops/layernorm/gemma4_fused_ops.py
.py
"""Fused triton kernels for Gemma4 decoder layer operations. Fuses standard RMSNorm + residual-add (+ optional scalar multiply) into a single kernel pass to reduce kernel launch overhead. """ from typing import Optional import torch import triton import triton.language as tl @triton.jit def _gemma_rmsnorm_residual...
541
15,974
sglang
python/sglang/kernels/ops/layernorm/minimax_m3_rmsnorm.py
.py
# SPDX-License-Identifier: Apache-2.0 """Fused Gemma RMSNorm Triton kernels for MiniMax-M3 on AMD ROCm. Gemma RMSNorm = ``normalize(x) * (1 + weight)``, computed in a single fp32 pass. On ROCm with AITER, ``GemmaRMSNorm.forward_hip`` otherwise falls back to a ~8-op PyTorch sequence: ``sgl_kernel``'s Gemma kernels are ...
149
3,993
sglang
python/sglang/kernels/ops/layernorm/rmsnorm_hf.py
.py
"""RMSNorm with HF LlamaRMSNorm semantics (cast to dtype before weight multiply).""" 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: fr...
80
2,701
sglang
python/sglang/kernels/ops/lplb/torch_solver.py
.py
"""IPM LP Solver entry point — dispatches to the fused JIT CUDA kernel. Solves: min c^T x subject to Ax = b, x >= 0 using a barrier (interior point) method with 5 iterations. The fused kernel lives in ``cuda_solver`` (CUDA C++ via ``load_jit``, backed by header-only cuBLASDx + a hand-written block Cholesky). This m...
193
7,127
sglang
python/sglang/kernels/ops/lplb/shmem_budget.py
.py
"""Shared-memory budget accounting for the fused IPM kernel. Fused layout (fp32), one block per LP, all state in shared memory:: A NC * NV constraint matrix (resident) c NV cost vector (resident) x NV IPM state (resident) ata ...
153
4,536
sglang
python/sglang/kernels/ops/lplb/cuda_solver.py
.py
"""JIT-compiled CUDA Interior Point Method LP solver. Replaces the Numba/nvmath-python implementation in ``cublasdx_solver.py``. The kernel is a single-block fused IPM defined in ``csrc/lplb/ipm.cuh`` and compiled per ``(NC, NV, BLOCK_DIM, SM_VER, NUM_ITERS)`` tuple via sglang's ``tvm-ffi`` ``load_jit``. Per-call CPU...
325
11,860
sglang
python/sglang/kernels/ops/lplb/cublasdx_solver.py
.py
"""Backwards-compatible shim. The Numba/nvmath-python fused IPM that used to live here has been replaced by a CUDA C++ kernel JIT-compiled via sglang's ``load_jit`` infrastructure. The new implementation lives in ``cuda_solver``. This module re-exports the public API so any external import keeps working. """ from sgl...
15
440
sglang
python/sglang/kernels/ops/quantization/per_tensor_quant_fp8.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 @cache_once def per_tensor_quant_fp8_module(is...
78
2,422
sglang
python/sglang/kernels/ops/quantization/int8_kernel.py
.py
import functools import json import logging import os from typing import Any, Dict, List, Optional, Tuple import torch import triton import triton.language as tl from triton.language.extra import libdevice from sglang.srt.utils import get_device_name, is_cuda, is_hip _is_cuda = is_cuda() _is_hip = is_hip() if _is_cu...
427
12,893
sglang
python/sglang/kernels/ops/quantization/per_token_group_quant_8bit_v2.py
.py
"""DEPRECATED: superseded by ``sglang.kernels.ops.quantization.per_token_group_quant`` (the default CUDA path). No sglang runtime code may call this kernel; it is kept only as the perf baseline for the per_token_group_quant benchmarks and its own bit-parity tests, and will be deleted once those move to torch references...
137
4,715
sglang
python/sglang/kernels/ops/quantization/per_token_group_quant.py
.py
from __future__ import annotations from typing import TYPE_CHECKING, Optional, 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_c...
224
7,506
sglang
python/sglang/kernels/ops/quantization/gptq_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...
118
3,145
sglang
python/sglang/kernels/ops/quantization/gptq_marlin_repack.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 if TYPE_CHECKING: from tvm_ffi.module import Module # Constants matching device::marlin:: in marlin.cuh _TILE_SIZE = ...
46
1,108
sglang
python/sglang/kernels/ops/quantization/__init__.py
.py
"""Quantization kernels (per-token / per-token-group FP8 & INT8).""" 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, Format...
210
6,813
sglang
python/sglang/kernels/ops/quantization/mxfp8_amd_gfx95.py
.py
# SPDX-License-Identifier: Apache-2.0 """Native MXFP8 (1x32 block, E8M0 scale) ops for AMD CDNA4 (gfx950). * per-token MXFP8 activation quant (single fused Triton pass) * dense GEMM via Triton ``tl.dot_scaled`` (consumes FP8 E4M3 weights + E8M0 block scales directly, no dequant-to-BF16), lowering to the CDNA4 ...
334
11,756
sglang
python/sglang/kernels/ops/quantization/hadamard.py
.py
from __future__ import annotations from typing import TYPE_CHECKING, Callable import torch from sglang.kernels.jit.utils import KERNEL_PATH, 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 @cache_once def _jit_ha...
91
2,966
sglang
python/sglang/kernels/ops/quantization/mxfp8_interleave_sf.py
.py
"""Triton kernel for writing MXFP8 scale factors in interleaved layout. When page_size=128 and sf_vec_size=32, FA4 expects scale factors in the BlockScaledBasicChunk atom layout: [num_pages, nheads, 32, 4, 4]. The interleave mapping for a token at page offset `t` (0-127), head `h`, scale index `s` (0-3) is: outp...
104
3,619
sglang
python/sglang/kernels/ops/quantization/minimax_quant_ue8m0.py
.py
from __future__ import annotations from typing import TYPE_CHECKING, Tuple 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(group_size: int) -> Module:...
106
3,868
sglang
python/sglang/kernels/ops/quantization/nvfp4_gemm_swiglu_nvfp4_quant.py
.py
# Copyright (c) 2026 LightSeek Foundation # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish...
3,016
120,786
sglang
python/sglang/kernels/ops/quantization/mxfp8_quant.py
.py
"""MXFP8 quantization helpers for Inkling attention.""" from __future__ import annotations from typing import NamedTuple import torch import triton import triton.language as tl MXFP8_BLOCK_SIZE = 32 class MXFP8Tensor(NamedTuple): data: torch.Tensor scale: torch.Tensor @triton.jit def _mxfp8_quant_kernel...
370
11,436
sglang
python/sglang/kernels/ops/quantization/awq_dequantize.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_awq_dequantize_module(dtype: torch.dtype) -> Module: args = make_cpp_args(dtype...
39
964
sglang
python/sglang/kernels/ops/quantization/fp8_kernel.py
.py
# Copyright 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 writing, so...
2,267
71,146
sglang
python/sglang/kernels/ops/quantization/awq_marlin_repack.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 if TYPE_CHECKING: from tvm_ffi.module import Module @cache_once def _jit_awq_marlin_repack_module() -> Module: r...
60
1,517
sglang
python/sglang/kernels/ops/quantization/per_token_quant_fp8.py
.py
from __future__ import annotations from typing import TYPE_CHECKING import torch from sglang.kernels.jit.utils import ( cache_once, get_jit_cuda_arch, load_jit, make_cpp_args, ) from sglang.srt.utils.custom_op import register_custom_op if TYPE_CHECKING: from tvm_ffi.module import Module @cache...
51
1,476
sglang
python/sglang/kernels/ops/quantization/fp8_quantize.py
.py
# Copyright (c) 2026 LightSeek Foundation # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish...
161
5,269
sglang
python/sglang/kernels/ops/quantization/fp8_utils.py
.py
from __future__ import annotations from typing import Optional, Tuple import torch import triton.language as tl from sglang.kernels.jit.utils import ( get_jit_cuda_arch, is_hip_runtime, is_musa_runtime, ) def cuda_capability_uses_fp8_e4b15(cuda_capability: Tuple[int, int]) -> bool: """Triton names ...
51
1,467
sglang
python/sglang/kernels/ops/quantization/awq_triton.py
.py
# Adapted from https://github.com/vllm-project/vllm/blob/main/vllm/model_executor/layers/quantization/awq_triton.py # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project import torch import triton import triton.language as tl AWQ_TRITON_SUPPORTED_GROUP_SIZES = [-1...
369
12,658
sglang
python/sglang/kernels/ops/quantization/dsv32/__init__.py
.py
"""DSA only.""" from .elementwise import ( fused_k_indexer_norm_rope, fused_k_indexer_norm_rope_store, ) __all__ = [ "fused_k_indexer_norm_rope", "fused_k_indexer_norm_rope_store", ]
12
201
sglang
python/sglang/kernels/ops/quantization/dsv32/elementwise.py
.py
"""DSA only. Indexer K kernels (JIT).""" import torch from sglang.kernels.jit.utils import ( cache_once, is_arch_support_pdl, load_jit, make_cpp_args, ) _CUDA_FILE = "deepseek_v32/indexer_k.cuh" @cache_once def _jit_k_indexer_norm_rope_module(dtype: torch.dtype): args = make_cpp_args(dtype, is_...
91
2,419
sglang
python/sglang/kernels/ops/grammar/token_filter_ops.py
.py
# 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://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, so...
176
4,990
sglang
python/sglang/kernels/ops/grammar/__init__.py
.py
"""Constrained-decoding / grammar kernels (Triton). The Triton kernels migrated here live in this package (``sglang.kernels.ops.grammar.<module>``); import them from there. Their ``KernelSpec`` metadata is registered below for inventory (backend = Triton). """ from sglang.kernels.registry import register_kernel from ...
27
825
sglang
python/sglang/kernels/ops/grammar/bitmask_ops.py
.py
# Adapt from # https://github.com/mlc-ai/xgrammar/blob/v0.1.17/python/xgrammar/kernels/apply_token_bitmask_inplace_triton.py from typing import List, Optional, Union import torch import triton import triton.language as tl from sglang.srt.utils import get_device_core_count @triton.jit def apply_token_bitmask_inplac...
142
4,614
sglang
python/sglang/kernels/ops/moe/pack_topk_ids.py
.py
"""Pack ``(topk_id, topk_weight)`` pairs into one int32 per entry. Migrated from ``sglang.srt.layers.quantization.mxfp4_flashinfer_trtllm_moe`` (RFC #29630, Phase 2.5). Used by the FlashInfer TRT-LLM routed-MoE path, which consumes routing ids and bf16 weights packed as ``(id << 16) | weight_bits``. """ import torch ...
100
2,962
sglang
python/sglang/kernels/ops/moe/moe_permute_prepare.py
.py
from __future__ import annotations from typing import TYPE_CHECKING, Tuple 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_moe_permute_prepare_module() -> M...
78
1,992
sglang
python/sglang/kernels/ops/moe/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.moe.moe_align import ( moe_align_block_size as jit_moe_align_block_size, ) @triton.jit def _fused_virtual_topk_ids_kernel( topk_ids_ptr, token...
789
25,936
sglang
python/sglang/kernels/ops/moe/mxfp8_moe_amd_gfx95.py
.py
"""Native MXFP8 (1x32 block, E8M0 scale) MoE for AMD CDNA4 (gfx950). Replaces the prior SGLang MXFP8 MoE family (dense / hybrid / packed / grouped_gemm1 / grouped_gemm12 / compact / fused_act) with a single grouped ``tl.dot_scaled`` kernel. Instead of an explicit ``argsort`` + ``index_select`` gather, a materialized i...
437
13,580
sglang
python/sglang/kernels/ops/moe/moe_fused_mul_sum.py
.py
import torch import triton import triton.language as tl from torch._subclasses.fake_tensor import FakeTensor from sglang.srt.utils import get_device_capability @triton.jit def moe_fused_mul_sum_kernel( inputs_ptr, topk_weights_ptr, outputs_ptr, top_ids_ptr, expert_map_ptr, num_tokens, str...
219
6,532
sglang
python/sglang/kernels/ops/moe/moe_align.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_moe_align_module(dtype: torch.dtype) -> Module: args = make_cpp_args(dtype) ...
47
1,118
sglang
python/sglang/kernels/ops/moe/inkling_moe.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.common import is_sm121 DEFAULT_BLOCK_SIZE = 4096 BLOCK_SIZE_M = 128 @triton.jit(do_not_specialize=["M"]) def silu_and_mul_interleaved_kernel( gateup_out_ptr, # type: ignore # ...
1,020
35,731
sglang
python/sglang/kernels/ops/moe/moe_lora_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_moe_align_module(dtype: torch.dtype) -> Module: args = make_cpp_args(...
75
1,977
sglang
python/sglang/kernels/ops/moe/minimax_m3_swiglu.py
.py
# SPDX-License-Identifier: Apache-2.0 """Fused SwiGLU-OAI (split layout) Triton kernel for MiniMax-M3 on AMD ROCm. SwiGLU-OAI on a ``[*, 2I]`` split-layout tensor (gate = first half, up = second half): ``gate * sigmoid(alpha * gate) * (up + beta)`` with optional clamp, computed in fp32. Used by the dense MLP / shared ...
202
6,283
sglang
python/sglang/kernels/ops/moe/inkling_gate_topk_renorm.py
.py
"""Shape-specialized Inkling MoE gate top-k + renorm JIT kernels. Three families, all specialized for the Inkling gate layout (logits ``[tokens, 258]`` fp32 = 256 routed + 2 shared experts, top-6 selection by ``sigmoid(logit) + bias``, logsigmoid renorm over selected ++ shared): - ``inkling_gate_topk_renorm`` --...
326
12,054
sglang
python/sglang/kernels/ops/moe/moe_topk_sum.py
.py
"""CUDA JIT top-k expert-output sum: out[M, K] = in[M, topk, K].sum(dim=1).""" 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.modul...
38
911
sglang
python/sglang/kernels/ops/moe/moe_align_single_token.py
.py
"""CUDA JIT single-warp moe_align_block_size for M == 1 decode batches.""" from __future__ import annotations from typing import TYPE_CHECKING, Tuple 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.mo...
50
1,513
sglang
python/sglang/kernels/ops/moe/__init__.py
.py
"""Mixture-of-Experts routing / bookkeeping 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, ...
189
5,814
sglang
python/sglang/kernels/ops/moe/router.py
.py
from typing import Optional import torch import triton import triton.language as tl from sglang.srt.utils import is_hip _is_hip = is_hip() @triton.jit def fused_moe_router_cudacore_kernel( input_ptr, # input (bs, hidden_dim) moe_router_weight_ptr, # input (num_experts, hidden_dim) topk_weights_ptr, ...
388
12,418
sglang
python/sglang/kernels/ops/moe/ep_moe_kernels.py
.py
import logging from typing import Optional, Tuple import torch import triton from sglang.srt.environ import envs from sglang.srt.utils import ceil_div, is_cuda, is_musa logger = logging.getLogger(__name__) _is_cuda = is_cuda() _is_musa = is_musa() if _is_cuda or _is_musa: from sglang.kernels.ops.quantization....
2,075
66,982
sglang
python/sglang/kernels/ops/moe/moe_topk_sigmoid.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 from sglang.srt.utils.custom_op import register_custom_op if TYPE_CHECKING: from tvm_ffi.module import Module @cache_once def _jit_moe_topk_sigmoi...
106
3,398
sglang
python/sglang/kernels/ops/moe/rocm_moe_utils.py
.py
# Adapted from https://github.com/vllm-project/vllm/blob/v0.9.1rc2/vllm/model_executor/layers/fused_moe/rocm_aiter_fused_moe.py # SPDX-License-Identifier: Apache-2.0 # SPDX-FileCopyrightText: Copyright contributors to the vLLM project from enum import IntEnum from typing import Optional import torch import triton impo...
330
9,848
sglang
python/sglang/kernels/ops/moe/moe_finalize_fuse_shared.py
.py
from __future__ import annotations from typing import Optional import torch from sglang.kernels.jit.utils import cache_once, load_jit @cache_once def _jit_module(): return load_jit( "moe_finalize_fuse_shared", cuda_files=["moe/moe_finalize_fuse_shared.cu"], extra_dependencies=["cutlass"...
61
1,682
sglang
python/sglang/kernels/ops/moe/gate_topk.py
.py
import torch import triton import triton.language as tl @triton.jit def get_topmask_and_fullmask(x): tl.static_assert( x.dtype.is_int_unsigned(), "floating-point value must be passed as bits" ) tm: tl.constexpr = 1 << (-1 + x.dtype.primitive_bitwidth) fm: tl.constexpr = (1 << x.dtype.primitive...
170
5,697