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/test/kv_canary/runner_test_base.py | .py | from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import patch
import torch
from sglang.kernels.ops.kv_canary.consts import RealKvHashMode
from sglang.kernels.ops.kv_canary.verify import CanaryLaunchTag
from sglang.srt.kv_canary import endpoint as endpoint_module
from sglang.srt... | 121 | 4,104 |
sglang | python/sglang/test/kv_canary/fixtures.py | .py | from __future__ import annotations
from dataclasses import dataclass
from types import SimpleNamespace
from typing import List, Optional
import torch
from sglang.kernels.ops.kv_canary import consts
from sglang.kernels.ops.kv_canary.verify import CANARY_SLOT_BYTES, RealKvSource
from sglang.srt.kv_canary.buffer_group ... | 292 | 9,402 |
sglang | python/sglang/test/kv_canary/consts.py | .py | from __future__ import annotations
from typing import Final
# SWA e2e pool sizing for 8 reqs Γ ~7K prompt + 2K decode, SWA window 1024.
# FULL pool = max-total-tokens; must fit 8 Γ (7000 + 2048) = 72_384 to avoid preempt.
# SWA pool = max-total-tokens Γ ratio;
# β₯ 8 Γ 1024 = 8192 (else deadlock β in-flight footp... | 53 | 1,461 |
sglang | python/sglang/test/kv_canary/violation_assert_mixin.py | .py | from __future__ import annotations
import time
from typing import Literal, Optional
from sglang.srt.kv_canary.perturb.config import TargetGroupKind
from sglang.test.kv_canary.violation_log_utils import (
assert_no_violation_in_log,
find_violation_in_log,
)
_Side = Optional[Literal["prefill", "decode"]]
cla... | 146 | 4,800 |
sglang | python/sglang/test/kv_canary/mode_config.py | .py | from __future__ import annotations
from dataclasses import dataclass
from typing import Optional
@dataclass(frozen=True, slots=True, kw_only=True)
class _ModeConfig:
model_path: str
json_model_override_args: Optional[str] = None
_MODE_CONFIGS: dict[str, _ModeConfig] = {
"mha": _ModeConfig(
mode... | 24 | 514 |
sglang | python/sglang/test/kv_canary/pd_fixture.py | .py | from __future__ import annotations
import uuid
from typing import ClassVar, Literal, Optional
from sglang.srt.kv_canary.config import CanaryMode
from sglang.test.kv_canary.mode_config import _MODE_CONFIGS, _ModeConfig
from sglang.test.kv_canary.utils import build_canary_server_args, post_parallel_generate
from sglang... | 100 | 3,831 |
sglang | python/sglang/kernels/fused_op.py | .py | """Unified multi-backend / multi-platform operator contract (RFC #29630, #26426).
:class:`BaseFusedOp` is the single operator abstraction of the unified
``sglang.kernels`` namespace: one logical operator, implemented once, with
multiple interchangeable implementations behind a single ``forward()``. It
subsumes the for... | 680 | 27,857 |
sglang | python/sglang/kernels/__init__.py | .py | """Unified public kernel namespace for SGLang (RFC #29630).
SGLang runtime code and tests should import callable kernels from
``sglang.kernels.ops.<group>``, e.g.::
from sglang.kernels.ops.layernorm import rmsnorm
from sglang.kernels.ops.activation import silu_and_mul
from sglang.kernels.ops.kvcache impor... | 77 | 2,618 |
sglang | python/sglang/kernels/registry.py | .py | """In-memory registry of :class:`KernelSpec` entries.
The registry is the single inventory of "which operators have which backend
implementations". It is populated at import time by the ``sglang.kernels.ops.*``
group packages, using only metadata (import path strings) β registering a spec
never imports ``torch`` or a ... | 79 | 2,808 |
sglang | python/sglang/kernels/spec.py | .py | """Lightweight metadata for the unified ``sglang.kernels`` namespace.
This module defines small, dependency-free descriptors used to *inventory*
kernel implementations and drive a simple, heuristic dispatch. It intentionally
does not import ``torch``, ``sgl_kernel`` or ``sglang.kernels.jit`` at module
import time so t... | 264 | 10,153 |
sglang | python/sglang/kernels/selector.py | .py | """Device-aware fixed-path kernel resolution over the :data:`registry`.
There is no priority *ranking* or preference heuristic. Resolution of an op's
call path is deterministic:
- an op with a single registered backend resolves to it directly;
- an op with several registered backends is filtered by the detected platf... | 104 | 3,722 |
sglang | python/sglang/kernels/jit/__main__.py | .py | import argparse
import logging
import os
import re
import shutil
import subprocess
from tvm_ffi.libinfo import find_dlpack_include_path, find_include_path
from sglang.kernels.jit.utils import get_jit_cuda_arch
from sglang.kernels.jit.utils.arch import get_default_target_flags, make_jit_cuda_arch
from sglang.kernels.j... | 121 | 3,903 |
sglang | python/sglang/kernels/jit/__init__.py | .py | """Internal JIT home under ``sglang.kernels`` (RFC #29630).
Mirrors the legacy ``sglang.kernels.jit`` tree; shared build/runtime
infrastructure lives in :mod:`sglang.kernels.jit.utils`. csrc / include /
operators migrate here in later phases.
"""
| 7 | 248 |
sglang | python/sglang/kernels/jit/csrc/fast-hadamard-transform/code_gen.py | .py | from pathlib import Path
import numpy as np
# From https://en.wikipedia.org/wiki/Paley_construction (construction II for q = 5)
had_12_paley = """
+-++++++++++
--+-+-+-+-+-
+++-++----++
+---+--+-++-
+++++-++----
+-+---+--+-+
++--+++-++--
+--++---+--+
++----+++-++
+--+-++---+-
++++----+++-
+-+--+-++---
"""
# From ht... | 198 | 5,024 |
sglang | python/sglang/kernels/jit/benchmark/utils.py | .py | """Common utilities for jit_kernel benchmark files."""
from typing import Callable, List, Optional, Sequence, Tuple
import torch
import triton.testing
from sglang.kernels.ops.communication.mp import multigpu_launch
from sglang.utils import is_in_ci
def multigpu_bench_main(
name: str,
file: str,
num_gpu... | 109 | 3,383 |
sglang | python/sglang/kernels/jit/benchmark/marker.py | .py | import contextlib
import inspect
import itertools
import math
import os
from typing import (
Any,
Callable,
ContextManager,
Dict,
Generic,
Iterable,
List,
Literal,
NamedTuple,
Optional,
Tuple,
TypeAlias,
TypeVar,
)
import torch
from sglang.kernels.jit.utils import c... | 558 | 21,126 |
sglang | python/sglang/kernels/jit/benchmark/kv_canary/utils.py | .py | from __future__ import annotations
from dataclasses import dataclass
from typing import Callable
import torch
from sglang.kernels.ops.kv_canary.verify import CANARY_SLOT_BYTES, RealKvSource
BS_AXIS: list[int] = [1, 4, 32, 128, 256, 1024]
PREFIX_AXIS: list[int] = [0, 128, 1024, 4096, 10240, 16384]
EXTEND_LEN_AXIS: l... | 405 | 12,050 |
sglang | python/sglang/kernels/jit/utils/__init__.py | .py | """Public interface of sglang.kernels.jit.utils."""
from sglang.kernels.jit.utils.arch import (
get_jit_cuda_arch,
is_arch_support_pdl,
override_jit_cuda_arch,
)
from sglang.kernels.jit.utils.common import (
cache_once,
empty_sentinel,
get_ci_test_range,
is_hip_runtime,
is_musa_runtime,... | 34 | 776 |
sglang | python/sglang/kernels/jit/utils/deps.py | .py | """Header-only dependency registration (flashinfer, cutlass, mathdx, ...)."""
from __future__ import annotations
import importlib.util
import os
import pathlib
from typing import Callable, Dict, List, Optional
def _find_package_root(package: str) -> Optional[pathlib.Path]:
spec = importlib.util.find_spec(packag... | 142 | 4,713 |
sglang | python/sglang/kernels/jit/utils/arch.py | .py | """CUDA/ROCm architecture detection and default compile target flags."""
from __future__ import annotations
import logging
import os
import re
import shutil
import subprocess
from contextlib import contextmanager
from dataclasses import dataclass
from typing import List
import torch
from sglang.kernels.jit.utils.co... | 182 | 5,967 |
sglang | python/sglang/kernels/jit/utils/common.py | .py | """Shared helpers: caching decorator, CI test gating, and runtime detection."""
from __future__ import annotations
import functools
from typing import Any, Callable, Dict, List, TypeVar
import torch
from sglang.srt.environ import envs
from sglang.utils import is_in_ci
F = TypeVar("F", bound=Callable[..., Any])
T =... | 89 | 2,662 |
sglang | python/sglang/kernels/jit/utils/compile/ninja.py | .py | """Generating and running the ``build.ninja`` for one JIT module.
Owning this file is what makes the cache key exact. Every compiler, flag,
include path and link argument is written here, so the key can be taken over the
generated text itself instead of over an approximation of what a dependency
would have chosen.
Tw... | 229 | 8,080 |
sglang | python/sglang/kernels/jit/utils/compile/__init__.py | .py | """JIT compilation: source layout, ninja generation, the build cache, load_jit.
The package owns the whole path from a ``load_jit`` call to a loaded module,
including the ``build.ninja`` it compiles through β only tvm-ffi's headers,
its shared library, and ``tvm_ffi.load_module`` are consumed from outside.
Modules, i... | 45 | 1,390 |
sglang | python/sglang/kernels/jit/utils/compile/toolchain.py | .py | """The toolchain a JIT build runs on: compilers, tvm-ffi's headers, base flags.
sglang generates its own ``build.ninja`` rather than going through
``tvm_ffi.cpp.load_inline``, so the flags tvm-ffi used to supply implicitly have
to be stated here. That is the point: every flag that reaches the compiler is
now visible i... | 169 | 5,778 |
sglang | python/sglang/kernels/jit/utils/compile/spec.py | .py | """One fully-resolved JIT build, described in one place.
``BuildSpec`` is the hand-off between the halves of ``load_jit``: the cache has
to see *every* input that could change the output in order to key it, and the
ninja generator has to feed those same inputs to the compiler.
Anything added here that affects the gen... | 135 | 4,450 |
sglang | python/sglang/kernels/jit/utils/compile/paths.py | .py | """Where the in-tree JIT sources live, and the compile defaults applied to them.
Kept in its own module so that both the build cache and the loader can depend
on it without depending on each other.
"""
from __future__ import annotations
import importlib.util
import pathlib
from typing import List
from sglang.kernel... | 33 | 965 |
sglang | python/sglang/kernels/jit/utils/compile/cpp_args.py | .py | """Rendering Python values as C++ template arguments."""
from __future__ import annotations
from typing import TypeAlias, Union
import torch
CPP_TEMPLATE_TYPE: TypeAlias = Union[int, float, str, bool, torch.dtype]
class CPPArgList(list):
def __str__(self) -> str:
return ", ".join(self)
CPP_DTYPE_MAP... | 51 | 1,481 |
sglang | python/sglang/kernels/jit/utils/compile/loader.py | .py | """``load_jit``: resolve a request, reuse a cached build, or make one."""
from __future__ import annotations
import contextlib
import fcntl
import logging
import os
import pathlib
import shutil
import uuid
from typing import TYPE_CHECKING, List, Tuple
import torch
from sglang.kernels.jit.utils.arch import get_defau... | 201 | 8,325 |
sglang | python/sglang/kernels/jit/utils/compile/cache.py | .py | """Content-addressed JIT build cache: key derivation, layout, publication.
The cache answers one question on every ``load_jit``: *is there an already-built
``.so`` that is guaranteed to be identical to what a build right now would
produce?* It does so with two keys, because the full answer is not computable
before the... | 523 | 19,352 |
sglang | python/sglang/kernels/aot/setup_rocm.py | .py | # Copyright 2025 SGLang Team. All Rights Reserved.
#
# 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 ... | 130 | 4,096 |
sglang | python/sglang/kernels/aot/analyze_whl_kernel_sizes.py | .py | import argparse
import json
import os
import shutil
import subprocess
import sys
import tempfile
import zipfile
from pathlib import Path
def extract_whl(whl_file, extract_dir):
with zipfile.ZipFile(whl_file, "r") as zip_ref:
zip_ref.extractall(extract_dir)
def find_binary_files(extract_dir):
binary_... | 222 | 6,924 |
sglang | python/sglang/kernels/aot/setup_metal.py | .py | # Copyright 2026 SGLang Team. All Rights Reserved.
#
# 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 ... | 299 | 9,622 |
sglang | python/sglang/kernels/aot/setup_musa.py | .py | # Copyright 2025 SGLang Team. All Rights Reserved.
#
# 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 ... | 235 | 7,378 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/mamba.py | .py | from typing import Optional
import torch
# mamba
def causal_conv1d_fwd(
x: torch.Tensor,
weight: torch.Tensor,
bias_: Optional[torch.Tensor],
conv_states: Optional[torch.Tensor],
query_start_loc: Optional[torch.Tensor],
cache_indices: Optional[torch.Tensor],
has_initial_state: Optional[to... | 123 | 2,601 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/cutlass_moe.py | .py | import torch
def get_cutlass_w4a8_moe_mm_data(
topk_ids: torch.Tensor,
expert_offsets: torch.Tensor,
problem_sizes1: torch.Tensor,
problem_sizes2: torch.Tensor,
input_permutation: torch.Tensor,
output_permutation: torch.Tensor,
num_experts: int,
n: int,
k: int,
):
"""
Prepa... | 113 | 3,997 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/top_k.py | .py | from typing import Optional
import torch
def fast_topk(values, topk, dim):
if topk == 1:
# Use max along the specified dimension to get both value and index
return torch.max(values, dim=dim, keepdim=True)
else:
# Use topk for efficiency with larger k values
# TODO: implement f... | 150 | 6,292 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/moe.py | .py | from typing import Optional
import torch
def moe_align_block_size(
topk_ids,
num_experts,
block_size,
sorted_token_ids,
experts_ids,
num_tokens_post_pad,
cumsum_buffer,
pad_sorted_token_ids=False,
ignore_invalid_expert=False,
):
torch.ops.sgl_kernel.moe_align_block_size.defaul... | 227 | 5,087 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/scalar_type.py | .py | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
import functools
import struct
from dataclasses import dataclass
from enum import Enum
from typing import Optional, Union
_SCALAR_TYPES_ID_MAP = {}
# Mirrors enum in `core/scalar_type.hpp`
class NanRepr(Enum):... | 353 | 12,383 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/musa.py | .py | from typing import Optional, Union
import torch
from sgl_kernel.utils import _to_tensor_scalar_tuple
def musa_batched_rotary_embedding_contiguous(
positions: torch.Tensor,
query: torch.Tensor,
key: torch.Tensor,
head_size: int,
cos_sin_cache: torch.Tensor,
is_neox: bool,
rot_dim: int,
... | 354 | 10,015 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/expert_specialization.py | .py | import torch
def es_fp8_blockwise_scaled_grouped_mm(
output,
a,
b,
scales_a,
scales_b,
stride_a,
stride_b,
stride_d,
problem_sizes,
expert_offsets,
workspace,
):
torch.ops.sgl_kernel.es_fp8_blockwise_scaled_grouped_mm.default(
output,
a,
b,
... | 51 | 1,118 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/utils.py | .py | # Copyright 2025 SGLang Team. All Rights Reserved.
#
# 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 ... | 67 | 1,984 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/grammar.py | .py | from typing import List, Optional, Union
import torch
def apply_token_bitmask_inplace_cuda(
logits: torch.Tensor,
bitmask: torch.Tensor,
indices: Optional[Union[List[int], torch.Tensor]] = None,
) -> None:
if isinstance(indices, list):
indices = torch.tensor(indices, dtype=torch.int32, device... | 16 | 492 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/spatial.py | .py | import torch
from torch.cuda.streams import ExternalStream
try:
from . import spatial_ops # triggers TORCH extension registration
except Exception as _e:
_spatial_import_error = _e
else:
_spatial_import_error = None
_IMPORT_ERROR = ImportError(
"Failed to load sgl_kernel.spatial_ops extension. Ensure... | 64 | 1,808 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/metal.py | .py | """Python entry points for the sgl_kernel Metal extension."""
from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING
if TYPE_CHECKING:
import mlx.core as mx
_METALLIB_NAME = "sgl_metal_kernels.metallib"
try:
from . import _metal
_metallib_path = Path(_metal.__file... | 113 | 3,994 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/load_utils.py | .py | import ctypes
import glob
import importlib.util
import logging
import os
import shutil
from pathlib import Path
from typing import List
import torch
logger = logging.getLogger(__name__)
def _get_compute_capability():
"""Get the compute capability of the current GPU."""
if not torch.cuda.is_available():
... | 248 | 9,358 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/attention.py | .py | from typing import Optional, Tuple
import torch
def merge_state_v2(
v_a: torch.Tensor,
s_a: torch.Tensor,
v_b: torch.Tensor,
s_b: torch.Tensor,
v_merged: Optional[torch.Tensor] = None,
s_merged: Optional[torch.Tensor] = None,
) -> Tuple[torch.Tensor, torch.Tensor]:
s_a = s_a.to(torch.floa... | 114 | 3,726 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/sampling.py | .py | from typing import Optional, Union
import torch
from sgl_kernel.utils import _to_tensor_scalar_tuple
try:
import flashinfer.sampling as _flashinfer_sampling
_has_flashinfer = True
except ImportError:
_has_flashinfer = False
def _top_k_renorm_probs_internal(
probs: torch.Tensor,
maybe_top_k_arr:... | 116 | 3,937 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/gemm.py | .py | from typing import Optional
import torch
def awq_dequantize(
qweight: torch.Tensor, scales: torch.Tensor, qzeros: torch.Tensor
) -> torch.ByteTensor:
return torch.ops.sgl_kernel.awq_dequantize.default(qweight, scales, qzeros)
def int8_scaled_mm(mat_a, mat_b, scales_a, scales_b, out_dtype, bias=None):
r... | 112 | 3,018 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/flash_attn.py | .py | from functools import lru_cache
from typing import Optional, Union
import torch
from sgl_kernel.debug_utils import maybe_wrap_debug_kernel
try:
from sgl_kernel import flash_ops
except:
raise ImportError(
"Can not import FA3 in sgl_kernel. Please check your installation."
)
@lru_cache(maxsize=1)
... | 425 | 16,160 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/__init__.py | .py | import platform
import sys
from sgl_kernel.version import __version__ # noqa: F401
# On macOS only the Metal extension is shipped; skip CUDA op loading and
# re-exports so those symbols are not exposed on Apple Silicon.
if sys.platform == "darwin" and platform.machine() == "arm64":
from sgl_kernel.metal import *... | 233 | 7,240 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/speculative.py | .py | from typing import Optional
import torch
def tree_speculative_sampling_target_only(
predicts: torch.Tensor, # mutable
accept_index: torch.Tensor, # mutable
accept_token_num: torch.Tensor, # mutable
candidates: torch.Tensor,
retrive_index: torch.Tensor,
retrive_next_token: torch.Tensor,
... | 309 | 7,676 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/debug_utils.py | .py | import os
from typing import Any, Callable, TypeVar, cast, overload
F = TypeVar("F", bound=Callable[..., Any])
def _wrap_debug_kernel(func: F, op_name: str | None = None) -> F:
try:
if int(os.environ.get("SGLANG_KERNEL_API_LOGLEVEL", "0")) == 0:
return func
except Exception:
retur... | 46 | 1,137 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/kvcacheio.py | .py | import os
from typing import List, Optional
import torch
def is_hip() -> bool:
return torch.version.hip is not None
_is_hip = is_hip()
def _default_mla_block_quota() -> int:
"""CU (block) quota for the MLA page_first KV gather kernel.
Defaults to 16 on ROCm / 2 on CUDA. Override with the
SGLANG_... | 357 | 8,414 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/elementwise.py | .py | from typing import Optional
import torch
from sgl_kernel.utils import is_arch_support_pdl
try:
import flashinfer.norm as _flashinfer_norm
_has_flashinfer = True
except ImportError:
_has_flashinfer = False
_FLASHINFER_NORM_SUPPORTED_DTYPES = {torch.float16, torch.bfloat16}
def _rmsnorm_internal(
in... | 441 | 13,848 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/flash_mla.py | .py | import dataclasses
from typing import Optional, Tuple
import torch
try:
from sgl_kernel import flashmla_ops # triggers TORCH extension registration
except Exception as _e:
_flashmla_import_error = _e
else:
_flashmla_import_error = None
_IMPORT_ERROR = ImportError(
"Failed to load sgl_kernel.flashmla... | 343 | 12,551 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/allreduce.py | .py | from typing import List, Optional, Tuple
import torch
if torch.version.hip is not None:
# ROCM custom allreduce
def init_custom_ar(
meta: torch.Tensor,
rank_data: torch.Tensor,
handles: List[str],
offsets: List[int],
rank: int,
full_nvlink: bool,
) -> int:
... | 131 | 4,381 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/sparse_flash_attn.py | .py | from typing import List, Optional, Tuple, Union
import torch
import torch.nn as nn
def maybe_contiguous(x):
return x.contiguous() if x is not None and x.stride(-1) != 1 else x
# Sparse attention utils
def convert_vertical_slash_indexes(
q_seqlens: torch.Tensor, # [BATCH, ]
kv_seqlens: torch.Tensor, #... | 294 | 10,410 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/test_utils.py | .py | import torch
def create_per_token_group_quant_test_data(num_tokens, hidden_dim, num_ranks, flags):
device = torch.device("cuda")
dtype = torch.bfloat16
seed = num_tokens * 10000 + hidden_dim
gen_cpu = torch.Generator(device="cpu")
gen_cpu.manual_seed(seed)
gen_cuda = torch.Generator(device="c... | 126 | 4,110 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/memory.py | .py | import torch
def weak_ref_tensor(tensor):
return (
torch.ops.sgl_kernel.weak_ref_tensor(tensor)
if isinstance(tensor, torch.Tensor)
else tensor
)
| 10 | 180 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/testing/rotary_embedding.py | .py | from dataclasses import dataclass
from typing import Optional, Tuple, Union
import torch
from sglang.kernels.ops.attention.rope import (
FusedSetKVBufferArg as _JitFusedSetKVBufferArg,
)
from sglang.kernels.ops.attention.rope import (
apply_rope_with_cos_sin_cache_inplace as _jit_apply_rope_with_cos_sin_cache... | 274 | 8,596 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/quantization/__init__.py | .py | from .gguf import (
ggml_dequantize,
ggml_moe_a8,
ggml_moe_a8_vec,
ggml_moe_get_block_size,
ggml_mul_mat_a8,
ggml_mul_mat_vec_a8,
)
| 9 | 156 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/quantization/gguf.py | .py | import torch
def ggml_dequantize(
weight: torch.Tensor, quant_type: int, M: int, N: int, dtype: torch.dtype
):
assert M > 0 and N > 0, "GGUF weight Input shape must be of positive dimensions"
return torch.ops.sgl_kernel.ggml_dequantize.default(weight, quant_type, M, N, dtype)
def ggml_mul_mat_vec_a8(
... | 63 | 1,593 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/infllm_v2/attention.py | .py | """InfLLM-V2 sparse FlashAttention public API.
Ported (drop-in) from ``3rdparty/infllmv2_cuda_impl/infllm_v2/infllmv2_sparse_attention.py``.
The CUDA backend now lives in the standalone ``infllm_ops`` extension.
"""
import torch
from sgl_kernel.infllm_v2._loader import load_infllm_ops
def maybe_contiguous(x):
r... | 83 | 1,934 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/infllm_v2/__init__.py | .py | from sgl_kernel.infllm_v2.attention import infllmv2_attn_stage1
from sgl_kernel.infllm_v2.max_pooling import max_pooling_1d_varlen
__all__ = [
"infllmv2_attn_stage1",
"max_pooling_1d_varlen",
]
| 8 | 203 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/infllm_v2/max_pooling.py | .py | import torch
def max_pooling_1d_varlen(
input: torch.Tensor, # num_heads x total_q x max_k
cu_seqlens_q: torch.Tensor, # batch_size + 1
cu_seqlens_k: torch.Tensor, # batch_size + 1
cache_lens: torch.Tensor, # batch_size
max_seqlen_q: int,
max_context_len: int,
local_blocks: int,
in... | 62 | 1,707 |
sglang | python/sglang/kernels/aot/python/sgl_kernel/infllm_v2/_loader.py | .py | """Robust loader for the standalone ``infllm_ops`` pybind extension.
The InfLLM-V2 FlashAttention backend is built as its own module ``infllm_ops``
(installed into the ``sgl_kernel`` package directory). Under editable installs
the compiled ``.so`` may live in ``site-packages/sgl_kernel`` while the imported
``sgl_kerne... | 99 | 2,959 |
sglang | python/sglang/kernels/aot/tests/test_flash_attn_sparse.py | .py | import math
import sys
from typing import List, Optional
import pytest
import torch
from einops import rearrange, repeat
from sgl_kernel.sparse_flash_attn import (
convert_vertical_slash_indexes,
convert_vertical_slash_indexes_mergehead,
sparse_attn_func,
)
from test_flash_attention import construct_local_... | 490 | 17,523 |
sglang | python/sglang/kernels/aot/tests/test_torch_defaults_reset.py | .py | import sys
import pytest
import torch
def test_change_torch_defaults():
torch.set_default_device("cpu:0")
torch.set_default_dtype(torch.float16)
def test_check_torch_defaults():
assert torch.get_default_device() == torch.device("cpu")
assert torch.get_default_dtype() == torch.float32
if __name__ ... | 19 | 373 |
sglang | python/sglang/kernels/aot/tests/utils.py | .py | import torch
def is_sm10x():
return torch.cuda.get_device_capability() >= (10, 0)
def is_hopper():
return torch.cuda.get_device_capability() == (9, 0)
| 10 | 163 |
sglang | python/sglang/kernels/aot/tests/test_apply_token_bitmask_inplace.py | .py | import sys
import pytest
import torch
from sgl_kernel import apply_token_bitmask_inplace_cuda
def test_apply_token_bitmask_inplace_kernel():
neginf = float("-inf")
bool_mask = torch.tensor([0, 1, 0, 1, 0, 1, 0, 1, 0, 1], dtype=torch.bool)
logits = torch.tensor(
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0,... | 26 | 791 |
sglang | python/sglang/kernels/aot/tests/test_flash_attention.py | .py | # Adapted from https://github.com/Dao-AILab/flash-attention/blob/main/hopper/test_flash_attn.py
import itertools
import math
import sys
from typing import Optional
import pytest
import torch
import torch.nn.functional as F
from einops import rearrange, repeat
apply_rotary_emb = None
def is_hopper():
# Only Hop... | 1,420 | 54,588 |
sglang | python/sglang/kernels/aot/tests/test_cutlass_mla.py | .py | import sys
import pytest
import torch
import torch.nn.functional as F
from sgl_kernel import cutlass_mla_decode, cutlass_mla_get_workspace_size
from torch import Tensor
# Disable tests on SM103 until the accuracy issues are fixed.
if torch.cuda.get_device_capability() != (10, 0):
pytest.skip(
reason="Cutl... | 107 | 3,513 |
sglang | python/sglang/kernels/aot/tests/test_fp8_blockwise_moe.py | .py | import random
import sys
from typing import Tuple
import pytest
import torch
from sgl_kernel import fp8_blockwise_scaled_grouped_mm
def cdiv(a: int, b: int) -> int:
return -(a // -b)
def scale_shape(shape, group_shape):
return tuple(cdiv(shape[i], group_shape[i]) for i in range(len(group_shape)))
def to_... | 223 | 7,640 |
sglang | python/sglang/kernels/aot/tests/test_flashmla.py | .py | import math
import random
import sys
from typing import Optional, Tuple
import pytest
import torch
import triton
from sgl_kernel.flash_mla import (
flash_mla_sparse_fwd,
flash_mla_with_kvcache,
get_mla_metadata,
)
# ================ prefill usage ================ #
S_Q_PREFILL = [1, 62]
KV_TOPK_PREFILL = ... | 664 | 23,691 |
sglang | python/sglang/kernels/aot/tests/test_per_token_group_quant_8bit.py | .py | import itertools
import sys
import pytest
import torch
from sgl_kernel.test_utils import (
assert_all_close_or_tiny_diff,
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.kernel... | 184 | 5,385 |
sglang | python/sglang/kernels/aot/tests/test_infllm_v2_attention.py | .py | """Equivalence tests for the migrated InfLLM-V2 FlashAttention API.
These compare the ``sgl_kernel.infllm_v2`` implementations against the original
``infllm_v2`` package (3rdparty/infllmv2_cuda_impl). Both call the same CUDA
kernels, so outputs are expected to match closely. The whole module is skipped
if the referenc... | 62 | 2,074 |
sglang | python/sglang/kernels/aot/tests/test_es_mxfp8_blockscaled_moe.py | .py | import random
import sys
import pytest
import torch
from sgl_kernel import (
es_sm100_mxfp8_blockscaled_grouped_mm,
es_sm100_mxfp8_blockscaled_grouped_quant,
)
random.seed(42)
torch.manual_seed(42)
torch.cuda.manual_seed(42)
torch.cuda.manual_seed_all(42)
def align(val: int, alignment: int = 128) -> int:
... | 157 | 4,833 |
sglang | python/sglang/kernels/aot/tests/test_kvcacheio.py | .py | import sys
import pytest
import torch
from sgl_kernel.kvcacheio import (
transfer_embedding_ranges_direct,
transfer_kv_all_layer,
transfer_kv_all_layer_direct_lf_pf,
transfer_kv_all_layer_lf_ph,
transfer_kv_all_layer_mla,
transfer_kv_direct,
transfer_kv_per_layer,
transfer_kv_per_layer_... | 776 | 28,154 |
sglang | python/sglang/kernels/aot/tests/test_fused_qk_norm_rope.py | .py | import pytest
import torch
from sgl_kernel import fused_qk_norm_rope as sgl_fused_qk_norm_rope
from sglang.srt.layers.layernorm import RMSNorm
from sglang.srt.layers.rotary_embedding import get_rope
from sglang.srt.server_args import (
ServerArgs,
get_global_server_args,
set_global_server_args_for_schedule... | 236 | 7,002 |
sglang | python/sglang/kernels/aot/tests/test_gguf.py | .py | # SPDX-License-Identifier: Apache-2.0
import random
import sys
from pathlib import Path
import numpy as np
import pytest
import torch
from gguf import GGMLQuantizationType, GGUFReader, ReaderTensor, dequantize
from huggingface_hub import snapshot_download
from sgl_kernel import (
ggml_dequantize,
ggml_moe_a8,... | 168 | 5,536 |
sglang | python/sglang/kernels/aot/tests/test_gptq_kernel.py | .py | import sys
import pytest
import torch
from sgl_kernel import gptq_gemm
from sglang.srt.layers.quantization.utils import pack_cols, pack_rows
def torch_dequantize(q_weight, q_zeros, scales, g_idx, use_shuffle, bit, K, N):
assert bit == 4, "Reference dequantization only supports 4-bit"
group_size = K // scale... | 134 | 4,181 |
sglang | python/sglang/kernels/aot/tests/test_causal_conv1d.py | .py | # SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
# Adapted from https://github.com/vllm-project/vllm/blob/main/tests/kernels/mamba/test_causal_conv1d.py
import sys
from typing import Optional
import torch
from sgl_kernel import causal_conv1d_fwd
from sgl_kernel... | 493 | 17,900 |
sglang | python/sglang/kernels/aot/tests/test_topk.py | .py | import sys
from typing import Any, Optional
import pytest
import torch
from sgl_kernel import (
fast_topk_transform_fused,
fast_topk_transform_ragged_fused,
fast_topk_v2,
)
def _ref_torch_impl(
score: torch.Tensor,
seq_len: int,
topk: int,
row_starts: Optional[torch.Tensor] = None,
) -> t... | 254 | 8,273 |
sglang | python/sglang/kernels/aot/tests/test_int8_gemm.py | .py | import sys
import pytest
import torch
from sgl_kernel import int8_scaled_mm
from utils import is_sm10x
def to_int8(tensor: torch.Tensor) -> torch.Tensor:
return torch.round(tensor.clamp(min=-128, max=127)).to(dtype=torch.int8)
def torch_scaled_mm(a, b, scale_a, scale_b, out_dtype, bias):
o = torch.matmul(a... | 51 | 1,804 |
sglang | python/sglang/kernels/aot/tests/test_moe_topk_softmax.py | .py | import itertools
import sys
import pytest
import torch
from sgl_kernel import topk_softmax
def compare_topk_values(gating_output, topk_indices_ref, topk_indices):
values_ref = torch.gather(gating_output, 1, topk_indices_ref)
values = torch.gather(gating_output, 1, topk_indices)
return torch.equal(values_... | 185 | 6,188 |
sglang | python/sglang/kernels/aot/tests/test_awq_dequant.py | .py | import itertools
import sys
from typing import Optional, Tuple
import pytest
import torch
from sgl_kernel import awq_dequantize
def reverse_awq_order(t: torch.Tensor):
bits = 4
AWQ_REVERSE_ORDER = [0, 4, 1, 5, 2, 6, 3, 7]
reverse_order_tensor = torch.arange(
t.shape[-1],
dtype=torch.int32... | 117 | 3,264 |
sglang | python/sglang/kernels/aot/tests/test_dsv4_norm_rope.py | .py | """Tests for DeepSeek-V4 fused norm + RoPE kernels."""
import pytest
import sgl_kernel
import torch
def _ref_rmsnorm_self(x: torch.Tensor, eps: float) -> torch.Tensor:
"""Reference: RMSNorm without weight (identity weight)."""
rms = torch.sqrt(x.float().pow(2).mean(dim=-1, keepdim=True) + eps)
return (x.... | 129 | 4,597 |
sglang | python/sglang/kernels/aot/tests/test_fp8_gemm.py | .py | import sys
import pytest
import torch
from sgl_kernel import fp8_scaled_mm
def _cuda_version_at_least(major, minor):
if torch.version.cuda is None:
return False
version = tuple(int(component) for component in torch.version.cuda.split(".")[:2])
return version >= (major, minor)
def _native_scalar... | 199 | 7,230 |
sglang | python/sglang/kernels/aot/tests/test_norm.py | .py | # Adapted from https://github.com/flashinfer-ai/flashinfer/blob/4e8eb1879f9c3ba6d75511e5893183bf8f289a62/tests/test_norm.py
import sys
import pytest
import sgl_kernel
import torch
from sgl_kernel.utils import is_arch_support_pdl
def llama_rms_norm(x, w, eps=1e-6):
orig_dtype = x.dtype
x = x.float()
vari... | 203 | 6,620 |
sglang | python/sglang/kernels/aot/tests/test_moe_topk_sigmoid.py | .py | import itertools
import sys
import pytest
import torch
from sgl_kernel import topk_sigmoid
@pytest.fixture(autouse=True)
def _deterministic_seed():
# Pin RNG on every backend so torch.randn produces identical gating scores
# across runs. The exact index comparison can otherwise be tripped by
# near-tied ... | 194 | 6,590 |
sglang | python/sglang/kernels/aot/tests/test_sampling.py | .py | # Adapted from https://github.com/flashinfer-ai/flashinfer/blob/93e1a2634e22355b0856246b032b285ad1d1da6b/tests/test_sampling.py
import sys
import flashinfer.sampling
import pytest
import sgl_kernel
import torch
@pytest.mark.parametrize("batch_size", [1, 99, 989])
@pytest.mark.parametrize("vocab_size", [111, 32000, ... | 189 | 7,329 |
sglang | python/sglang/kernels/aot/tests/test_moe_align.py | .py | import itertools
import sys
import pytest
import torch
import triton
import triton.language as tl
from sgl_kernel import moe_align_block_size, moe_sum
def is_hip() -> bool:
return torch.version.hip is not None
_is_hip = is_hip()
def ceil_div(a, b):
return (a + b - 1) // b
@triton.jit
def moe_align_bloc... | 276 | 8,277 |
sglang | python/sglang/kernels/aot/tests/test_copy.py | .py | import sys
import pytest
import sgl_kernel
import torch
from sgl_kernel.elementwise import copy_to_gpu_no_ce
@pytest.mark.parametrize("size", [64, 72])
def test_copy_to_gpu_no_ce(size):
tensor_cpu = torch.randint(0, 1000000, (size,), dtype=torch.int32, device="cpu")
tensor_gpu = torch.empty_like(tensor_cpu, ... | 19 | 502 |
sglang | python/sglang/kernels/aot/tests/test_cutlass_w4a8_moe_mm.py | .py | import sys
import pytest
import torch
from sgl_kernel import cutlass_w4a8_moe_mm
from utils import is_hopper
from sglang.kernels.ops.quantization.per_tensor_quant_fp8 import (
per_tensor_quant_fp8,
)
def pack_int4_values_to_int8(int4_values_interleaved: torch.Tensor) -> torch.Tensor:
if int4_values_interlea... | 290 | 9,003 |
sglang | python/sglang/kernels/aot/tests/test_custom_allreduce.py | .py | import ctypes
import multiprocessing as mp
import random
import socket
import unittest
from typing import Any, List, Optional
import sgl_kernel.allreduce as custom_ops
import torch
import torch.distributed as dist
from torch.distributed import ProcessGroup
from sglang.srt.distributed.device_communicators.cuda_wrapper... | 186 | 6,176 |
sglang | python/sglang/kernels/aot/tests/test_activation.py | .py | # Adapted from https://github.com/flashinfer-ai/flashinfer/blob/4e8eb1879f9c3ba6d75511e5893183bf8f289a62/tests/test_activation.py
import sys
import pytest
import sgl_kernel
import torch
@pytest.mark.parametrize("dim", [128, 256, 512, 2048, 4096, 11008, 16384])
@pytest.mark.parametrize("batch_size", [1, 2, 4, 8, 16]... | 42 | 1,790 |
sglang | python/sglang/kernels/aot/tests/test_merge_state_v2.py | .py | import sys
from typing import Optional
import pytest
import torch
import triton
import triton.language as tl
from sgl_kernel import merge_state_v2
@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, # [... | 382 | 12,546 |
sglang | python/sglang/kernels/aot/tests/test_es_fp8_blockwise_moe.py | .py | import random
import sys
from typing import Tuple
import pytest
import torch
from sgl_kernel import es_fp8_blockwise_scaled_grouped_mm
def cdiv(a: int, b: int) -> int:
return -(a // -b)
def scale_shape(shape, group_shape):
return tuple(cdiv(shape[i], group_shape[i]) for i in range(len(group_shape)))
def ... | 207 | 6,921 |
sglang | python/sglang/kernels/aot/tests/test_infllm_v2_max_pooling.py | .py | import pytest
import torch
from sgl_kernel import max_pooling_1d_varlen
def _ref_varlen(
score: torch.Tensor, # [num_heads, total_q, max_k]
cu_seqlens_q: torch.Tensor,
cu_seqlens_k: torch.Tensor,
cache_lens: torch.Tensor,
max_context_len: int,
local_blocks: int,
init_blocks: int,
bloc... | 110 | 3,423 |
sglang | python/sglang/kernels/aot/tests/conftest.py | .py | import pytest
import torch
from sglang.srt.utils import is_musa
if is_musa():
import torchada # noqa: F401
# This fixture ensures the torch defaults don't get left in modified states between
# tests (e.g., when a test fails before restoring the original value), which
# can cause subsequent tests to fail.
@pyte... | 20 | 585 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.