[Feat] platform: Add initial T-HEAD SAIL platform support [2/N] (#43826)

Co-authored-by: Zhangheng <hzh0425@apache.org>
Co-authored-by: yzshi <163985193+Yunzshi310@users.noreply.github.com>
This commit is contained in:
Vinsmoke86
2026-10-20 22:19:07 +08:00
committed by GitHub
co-authored by Zhangheng yzshi
parent e262b44eef
commit 7656071309
33 changed files with 3668 additions and 81 deletions
+10
View File
@@ -161,6 +161,14 @@ diffusion_hip = [
# https://docs.vllm.ai/en/latest/getting_started/gaudi-installation.html
srt_hpu = ["sglang[runtime_common]"]
# https://docs.sglang.io/hardware-platforms/sail
srt_sail = [
"sailify==1.0.0",
"sglang[runtime_common]",
"torch-for-sail",
"triton-for-sail",
]
# https://docs.sglang.io/platforms/mthreads_gpu.md
srt_musa = [
"apache-tvm-ffi==0.1.11.post1+musa.1",
@@ -235,6 +243,7 @@ all_hip = ["sglang[diffusion_hip]", "sglang[srt_hip]", "sglang[tracing]"]
all_hip_rocm724 = ["sglang[diffusion_hip]", "sglang[srt_hip_rocm724]", "sglang[tracing]"]
all_hip_rocm101 = ["sglang[diffusion_hip]", "sglang[srt_hip_rocm101]", "sglang[tracing]"]
all_hpu = ["sglang[srt_hpu]"]
all_sail = ["sglang[srt_sail]"]
all_musa = ["sglang[diffusion_musa]", "sglang[srt_musa]"]
all_mps = ["sglang[diffusion_mps]", "sglang[srt_mps]"]
@@ -242,6 +251,7 @@ dev_hip = ["sglang[all_hip]", "sglang[test]"]
dev_hip_rocm724 = ["sglang[all_hip_rocm724]", "sglang[test]"]
dev_hip_rocm101 = ["sglang[all_hip_rocm101]", "sglang[test]"]
dev_hpu = ["sglang[all_hpu]", "sglang[test]"]
dev_sail = ["sglang[all_sail]", "sglang[test]"]
dev_musa = ["sglang[all_musa]", "sglang[test]"]
dev_mps = ["sglang[all_mps]", "sglang[test]"]
@@ -0,0 +1,300 @@
/* 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 agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <ATen/core/dispatch/Dispatcher.h>
#include <torch/all.h>
#include <torch/library.h>
#include "sgl_kernel_ops.h"
TORCH_LIBRARY_FRAGMENT(sgl_kernel, m) {
/*
* From csrc/allreduce
*/
m.def("get_graph_buffer_ipc_meta", &get_graph_buffer_ipc_meta);
m.def("register_graph_buffers", &register_graph_buffers);
m.def("dispose", &dispose);
m.def("meta_size", &meta_size);
m.def("register_buffer", &register_buffer);
m.def(
"init_custom_ar(int[] ipc_tensors, Tensor rank_data, "
"int rank, bool full_nvlink) -> int");
m.impl("init_custom_ar", torch::kCUDA, &init_custom_ar);
m.def(
"all_reduce(int fa, Tensor inp, Tensor! out, int reg_buffer, "
"int reg_buffer_sz_bytes) -> ()");
m.impl("all_reduce", torch::kCUDA, &all_reduce);
/*
* From csrc/attention
*/
m.def("merge_state_v2(Tensor v_a, Tensor s_a, Tensor v_b, Tensor s_b, Tensor! v_merged, Tensor! s_merged) -> ()");
m.impl("merge_state_v2", torch::kCUDA, &merge_state_v2);
/*
* From csrc/elementwise
*/
m.def("rmsnorm(Tensor! output, Tensor input, Tensor weight, float eps, bool enable_pdl) -> ()");
m.impl("rmsnorm", torch::kCUDA, &rmsnorm);
m.def("fused_add_rmsnorm(Tensor! input, Tensor! residual, Tensor weight, float eps, bool enable_pdl) -> ()");
m.impl("fused_add_rmsnorm", torch::kCUDA, &sgl_fused_add_rmsnorm);
m.def("gemma_rmsnorm(Tensor! output, Tensor input, Tensor weight, float eps, bool enable_pdl) -> ()");
m.impl("gemma_rmsnorm", torch::kCUDA, &gemma_rmsnorm);
m.def("gemma_fused_add_rmsnorm(Tensor! input, Tensor! residual, Tensor weight, float eps, bool enable_pdl) -> ()");
m.impl("gemma_fused_add_rmsnorm", torch::kCUDA, &gemma_fused_add_rmsnorm);
m.def("silu_and_mul(Tensor! out, Tensor input) -> ()");
m.impl("silu_and_mul", torch::kCUDA, &silu_and_mul);
m.def("gelu_tanh_and_mul(Tensor! out, Tensor input) -> ()");
m.impl("gelu_tanh_and_mul", torch::kCUDA, &gelu_tanh_and_mul);
m.def("gelu_and_mul(Tensor! out, Tensor input) -> ()");
m.impl("gelu_and_mul", torch::kCUDA, &gelu_and_mul);
m.def(
"rotary_embedding(Tensor positions, Tensor! query,"
" Tensor!? key, int head_size,"
" Tensor cos_sin_cache, bool is_neox) -> ()");
m.impl("rotary_embedding", torch::kCUDA, &rotary_embedding);
m.def("copy_to_gpu_no_ce(Tensor input, Tensor! output) -> ()");
m.impl("copy_to_gpu_no_ce", torch::kCUDA, &copy_to_gpu_no_ce);
m.def("concat_mla_k(Tensor! k, Tensor k_nope, Tensor k_rope) -> ()");
m.impl("concat_mla_k", torch::kCUDA, &concat_mla_k);
m.def("concat_mla_absorb_q(Tensor a, Tensor b, Tensor! out) -> ()");
m.impl("concat_mla_absorb_q", torch::kCUDA, &concat_mla_absorb_q);
m.def("fast_topk(Tensor score, Tensor indices, Tensor lengths, Tensor? row_starts) -> ()");
m.impl("fast_topk", torch::kCUDA, &fast_topk_interface);
m.def(
"fast_topk_transform_fused(Tensor score, Tensor lengths, Tensor dst_page_table, Tensor src_page_table, Tensor "
"cu_seqlens_q, Tensor? row_starts) -> ()");
m.impl("fast_topk_transform_fused", torch::kCUDA, &fast_topk_transform_interface);
m.def(
"fast_topk_transform_ragged_fused(Tensor score, Tensor lengths, Tensor topk_indices_ragged, Tensor "
"topk_indices_offset, Tensor ? row_starts) -> ()");
m.impl("fast_topk_transform_ragged_fused", torch::kCUDA, &fast_topk_transform_ragged_interface);
/*
* From csrc/gemm
*/
m.def(
"sgl_per_token_group_quant_8bit(Tensor input, Tensor! output_q, Tensor! output_s, int group_size,"
" float eps, float fp8_min, float fp8_max, bool scale_ue8m0) -> ()");
m.impl("sgl_per_token_group_quant_8bit", torch::kCUDA, &sgl_per_token_group_quant_8bit);
m.def(
"sgl_per_token_group_quant_8bit_v2(Tensor input, Tensor! output_q, Tensor! output_s, int group_size,"
" float eps, float fp8_min, float fp8_max, bool scale_ue8m0, bool fuse_silu_and_mul, Tensor? masked_m) -> ()");
m.impl("sgl_per_token_group_quant_8bit_v2", torch::kCUDA, &sgl_per_token_group_quant_8bit_v2);
m.def("sgl_per_token_quant_fp8(Tensor input, Tensor! output_q, Tensor! output_s) -> ()");
m.impl("sgl_per_token_quant_fp8", torch::kCUDA, &sgl_per_token_quant_fp8);
/*
* From csrc/moe
*/
m.def(
"moe_align_block_size(Tensor topk_ids, int num_experts, int block_size, Tensor! sorted_token_ids, Tensor! "
"experts_ids, Tensor! num_tokens_post_pad, Tensor! cumsum_buffer, bool "
"pad_sorted_token_ids, bool ignore_invalid_expert) -> ()");
m.impl("moe_align_block_size", torch::kCUDA, &moe_align_block_size);
m.def(
"topk_softmax(Tensor! topk_weights, Tensor! topk_indices, Tensor gating_output, bool renormalize, float "
"moe_softcapping, Tensor? correction_bias) -> ()");
m.impl("topk_softmax", torch::kCUDA, &topk_softmax);
m.def(
"topk_sigmoid(Tensor! topk_weights, Tensor! topk_indices, Tensor gating_output, bool renormalize, Tensor? "
"correction_bias) -> ()");
m.impl("topk_sigmoid", torch::kCUDA, &topk_sigmoid);
m.def("moe_sum_reduce(Tensor input, Tensor output, float routed_scaling_factor) -> ()");
m.impl("moe_sum_reduce", torch::kCUDA, &moe_sum_reduce);
m.def("moe_sum(Tensor input, Tensor! output) -> ()");
m.impl("moe_sum", torch::kCUDA, &moe_sum);
// moe_fused_gate / kimi_k2_moe_fused_gate (AOT) retired: the gate/topk path
// now routes through the unified Triton router
// (python/sglang/jit_kernel/moe_fused_gate.py).
m.def(
"prepare_moe_input(Tensor topk_ids, Tensor expert_offsets, Tensor? blockscale_offsets, Tensor problem_sizes1,"
" Tensor problem_sizes2, Tensor input_permutation, Tensor output_permutation, int num_experts, int n, int k) -> "
"()");
m.impl("prepare_moe_input", torch::kCUDA, &prepare_moe_input);
m.def("shuffle_rows(Tensor input, Tensor dst2src_map, Tensor output) -> ()");
m.impl("shuffle_rows", torch::kCUDA, &shuffle_rows);
m.def("apply_shuffle_mul_sum(Tensor input, Tensor output, Tensor permutation, Tensor? factors) -> ()");
m.impl("apply_shuffle_mul_sum", torch::kCUDA, &apply_shuffle_mul_sum);
m.def(
"fused_qk_norm_rope(Tensor! qkv, int num_heads_q, "
"int num_heads_k, int num_heads_v, int head_dim, float eps, "
"Tensor q_weight, Tensor k_weight, float base, "
"bool is_neox, Tensor position_ids, float factor, float low, float high, float attention_factor, int rotary_dim) "
"-> ()");
m.impl("fused_qk_norm_rope", torch::kCUDA, &fused_qk_norm_rope);
/*
* From csrc/kvcacheio
*/
m.def(
"transfer_kv_per_layer(Tensor src_k, Tensor dst_k, Tensor src_v, Tensor dst_v, Tensor src_indices, Tensor "
"dst_indices, int item_size, int block_quota, int num_warps_per_block) -> ()");
m.impl("transfer_kv_per_layer", torch::kCUDA, &transfer_kv_per_layer);
m.def(
"transfer_kv_per_layer_pf_lf(Tensor src_k, Tensor dst_k, Tensor src_v, Tensor dst_v, Tensor src_indices, Tensor "
"dst_indices, int layer_id, int item_size, int src_layout_dim, int block_quota, int num_warps_per_block) -> ()");
m.impl("transfer_kv_per_layer_pf_lf", torch::kCUDA, &transfer_kv_per_layer_pf_lf);
m.def(
"transfer_kv_per_layer_ph_lf(Tensor src_k, Tensor dst_k, Tensor src_v, Tensor dst_v, Tensor src_indices, Tensor "
"dst_indices, int layer_id, int item_size, int src_layout_dim, int page_size, int head_num, int block_quota, int "
"num_warps_per_block) -> ()");
m.impl("transfer_kv_per_layer_ph_lf", torch::kCUDA, &transfer_kv_per_layer_ph_lf);
m.def(
"transfer_kv_all_layer(Tensor src_k_layers, Tensor dst_k_layers, Tensor src_v_layers, Tensor dst_v_layers, "
"Tensor src_indices, Tensor dst_indices, int item_size, int num_layers, int block_quota, int "
"num_warps_per_block) -> ()");
m.impl("transfer_kv_all_layer", torch::kCUDA, &transfer_kv_all_layer);
m.def(
"transfer_kv_all_layer_lf_pf(Tensor src_k_layers, Tensor dst_k, Tensor src_v_layers, Tensor dst_v, "
"Tensor src_indices, Tensor dst_indices, int item_size, int dst_layout_dim, int num_layers, int block_quota, int "
"num_warps_per_block) -> ()");
m.impl("transfer_kv_all_layer_lf_pf", torch::kCUDA, &transfer_kv_all_layer_lf_pf);
m.def(
"transfer_kv_all_layer_lf_ph(Tensor src_k_layers, Tensor dst_k, Tensor src_v_layers, Tensor dst_v, "
"Tensor src_indices, Tensor dst_indices, int item_size, int dst_layout_dim, int num_layers, int page_size, int "
"head_num, int block_quota, int num_warps_per_block) -> ()");
m.impl("transfer_kv_all_layer_lf_ph", torch::kCUDA, &transfer_kv_all_layer_lf_ph);
m.def(
"transfer_kv_per_layer_mla(Tensor src, Tensor dst, Tensor src_indices, Tensor dst_indices, int item_size, int "
"block_quota, int num_warps_per_block) -> ()");
m.impl("transfer_kv_per_layer_mla", torch::kCUDA, &transfer_kv_per_layer_mla);
m.def(
"transfer_kv_per_layer_mla_pf_lf(Tensor src, Tensor dst, Tensor src_indices, Tensor dst_indices, int layer_id, "
"int item_size, int src_layout_dim, int block_quota, int num_warps_per_block) -> ()");
m.impl("transfer_kv_per_layer_mla_pf_lf", torch::kCUDA, &transfer_kv_per_layer_mla_pf_lf);
m.def(
"transfer_kv_all_layer_mla(Tensor src_layers, Tensor dst_layers, Tensor src_indices, Tensor dst_indices, int "
"item_size, int num_layers, int block_quota, int num_warps_per_block) -> ()");
m.impl("transfer_kv_all_layer_mla", torch::kCUDA, &transfer_kv_all_layer_mla);
m.def(
"transfer_kv_all_layer_mla_lf_pf(Tensor src_layers, Tensor dst, Tensor src_indices, Tensor dst_indices, "
"int item_size, int dst_layout_dim, int num_layers, int block_quota, int num_warps_per_block) -> ()");
m.impl("transfer_kv_all_layer_mla_lf_pf", torch::kCUDA, &transfer_kv_all_layer_mla_lf_pf);
m.def(
"transfer_kv_direct(Tensor[] src_layers, Tensor[] dst_layers, Tensor src_indices, Tensor dst_indices, int "
"page_size) -> ()");
m.impl("transfer_kv_direct", torch::kCUDA, &transfer_kv_direct);
m.def(
"transfer_kv_per_layer_direct_pf_lf(Tensor[] src_ptrs, Tensor[] dst_ptrs, Tensor src_indices, "
"Tensor dst_indices, int layer_id, int page_size)->() ");
m.impl("transfer_kv_per_layer_direct_pf_lf", torch::kCUDA, &transfer_kv_per_layer_direct_pf_lf);
m.def(
"transfer_kv_all_layer_direct_lf_pf(Tensor[] src_ptrs, Tensor[] dst_ptrs, Tensor src_indices, "
"Tensor dst_indices, int page_size) ->() ");
m.impl("transfer_kv_all_layer_direct_lf_pf", torch::kCUDA, &transfer_kv_all_layer_direct_lf_pf);
/*
* From csrc/memory
*/
m.def("weak_ref_tensor(Tensor tensor) -> Tensor");
m.impl("weak_ref_tensor", torch::kCUDA, &weak_ref_tensor);
/*
* From FlashInfer
*/
m.def("top_k_renorm_probs(Tensor probs, Tensor! renorm_probs, Tensor? maybe_top_k_arr, int top_k_val) -> ()");
m.impl("top_k_renorm_probs", torch::kCUDA, &top_k_renorm_probs);
m.def("top_p_renorm_probs(Tensor probs, Tensor! renorm_probs, Tensor? maybe_top_p_arr, float top_p_val) -> ()");
m.impl("top_p_renorm_probs", torch::kCUDA, &top_p_renorm_probs);
/*
* From csrc/grammar
*/
m.def("apply_token_bitmask_inplace_cuda(Tensor logits, Tensor bitmask, Tensor? indices=None) -> ()");
m.impl("apply_token_bitmask_inplace_cuda", &ApplyTokenBitmaskInplace);
/*
* From csrc/quantization/gguf
*/
m.def(
"ggml_dequantize(Tensor W, int type, SymInt m, SymInt n, ScalarType? "
"dtype) -> Tensor");
m.impl("ggml_dequantize", torch::kCUDA, &ggml_dequantize);
m.def(
"ggml_mul_mat_vec_a8(Tensor W, Tensor X, int type, SymInt row) "
"-> Tensor");
m.impl("ggml_mul_mat_vec_a8", torch::kCUDA, &ggml_mul_mat_vec_a8);
m.def("ggml_mul_mat_a8(Tensor W, Tensor X, int type, SymInt row) -> Tensor");
m.impl("ggml_mul_mat_a8", torch::kCUDA, &ggml_mul_mat_a8);
m.def(
"ggml_moe_a8(Tensor X, Tensor W, "
"Tensor sorted_token_ids, Tensor expert_ids, Tensor "
"num_tokens_post_padded, "
"int type, SymInt row, SymInt top_k, SymInt tokens) -> Tensor");
m.impl("ggml_moe_a8", torch::kCUDA, &ggml_moe_a8);
m.def(
"ggml_moe_a8_vec(Tensor X, Tensor W, "
"Tensor topk_ids, int top_k, "
"int type, SymInt row, SymInt tokens) -> Tensor");
m.impl("ggml_moe_a8_vec", torch::kCUDA, &ggml_moe_a8_vec);
m.def("ggml_moe_get_block_size(int type) -> int");
m.impl("ggml_moe_get_block_size", torch::kCUDA, &ggml_moe_get_block_size);
/*
* From csrc/mamba
*/
m.def(
"causal_conv1d_update(Tensor! x,"
"Tensor! conv_state,"
"Tensor! weight,"
"Tensor? bias_,"
"bool silu_activation,"
"Tensor? cache_seqlens_,"
"Tensor? conv_state_indices,"
"int pad_slot_id) -> ()");
m.impl("causal_conv1d_update", torch::kCUDA, &causal_conv1d_update);
m.def(
"causal_conv1d_fwd(Tensor! x, Tensor! weight,"
"Tensor? bias_,"
"Tensor!? conv_states,"
"Tensor? query_start_loc,"
"Tensor? cache_indices,"
"Tensor? has_initial_state,"
"bool silu_activation,"
"int pad_slot_id) -> ()");
m.impl("causal_conv1d_fwd", torch::kCUDA, &causal_conv1d_fwd);
}
REGISTER_EXTENSION(common_ops)
@@ -0,0 +1,32 @@
[build-system]
requires = [
"setuptools>=75.0",
"scikit-build-core>=0.10",
"torch>=2.8.0",
"wheel",
]
build-backend = "setuptools.build_meta"
[project]
name = "sglang-kernel"
version = "0.4.9"
description = "Kernel Library for SGLang"
readme = "README.md"
requires-python = ">=3.10"
license = { file = "LICENSE" }
classifiers = [
"Programming Language :: Python :: 3",
"License :: OSI Approved :: Apache Software License",
"Environment :: GPU :: T-HEAD SAIL"
]
dependencies = []
[project.urls]
"Homepage" = "https://github.com/sgl-project/sglang/tree/main/python/sglang/kernels/aot"
"Bug Tracker" = "https://github.com/sgl-project/sglang/issues"
[tool.wheel]
exclude = [
"dist*",
"tests*",
]
+545
View File
@@ -0,0 +1,545 @@
# 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
import atexit
import os
import platform
import shutil
import subprocess
from pathlib import Path
import torch
from setuptools import find_namespace_packages, setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
root = Path(__file__).parent.resolve()
third_party = Path(
os.environ.get("SGL_KERNEL_THIRD_PARTY_DIR", root / "build" / "_deps")
)
arch = platform.machine().lower()
# ======================= CUDA Version Detection ======================= #
cuda_version = torch.version.cuda
if cuda_version is None:
raise RuntimeError("CUDA is not available in the current PyTorch installation.")
cuda_version_tuple = tuple(int(x) for x in cuda_version.split(".")[:2])
print(f"Detected CUDA version: {cuda_version} ({cuda_version_tuple})")
# ======================= Third-Party Repository Info ======================= #
class _RepoInfo:
"""Configuration for a third-party git repository."""
def __init__(self, name, git_repository, git_tag, git_shallow=False):
self.name = name
self.git_repository = git_repository
self.git_tag = git_tag
self.git_shallow = git_shallow
self.source_dir = third_party / name
_ACTLIZE_REPO = _RepoInfo(
name="actlize",
git_repository="https://github.com/t-head/actlize",
git_tag="129651181ed29ec3d3e61df786f610926b739a9b",
git_shallow=False,
)
_ACTLIZE_DIR = Path(os.environ.get("SGL_KERNEL_ACTLIZE_DIR", _ACTLIZE_REPO.source_dir))
_FLASHINFER_REPO = _RepoInfo(
name="flashinfer",
git_repository="https://github.com/flashinfer-ai/flashinfer.git",
git_tag="bc29697ba20b7e6bdb728ded98f04788e16ee021",
git_shallow=False,
)
_TRITON_REPO = _RepoInfo(
name="triton",
git_repository="https://github.com/triton-lang/triton",
git_tag="v3.7.0",
git_shallow=False,
)
ALL_REPOS = [
_ACTLIZE_REPO,
_FLASHINFER_REPO,
_TRITON_REPO,
]
# ======================= Version ======================= #
def _get_version():
with open(root / "pyproject_sail.toml") as f:
for line in f:
if line.startswith("version"):
return line.split("=")[1].strip().strip('"')
return "0.0.0"
# ======================= Build Configuration ======================= #
operator_namespace = "sgl-kernel"
# Determine CXX ABI compatibility with PyTorch
torch_cxx11_abi = int(torch._C._GLIBCXX_USE_CXX11_ABI)
abi_flag = f"-D_GLIBCXX_USE_CXX11_ABI={torch_cxx11_abi}"
enable_bf16 = os.environ.get("SGL_KERNEL_ENABLE_BF16", "1").lower() in (
"1",
"true",
"on",
"yes",
)
enable_fp8 = os.environ.get("SGL_KERNEL_ENABLE_FP8", "1").lower() in (
"1",
"true",
"on",
"yes",
)
compile_threads = int(os.environ.get("SGL_KERNEL_COMPILE_THREADS", "32"))
if compile_threads < 1:
compile_threads = 1
# ======================= hgcc (device compiler) Flags ======================= #
# No `-gencode`: hgcc takes `--gpu-architecture=ppu_XX` instead, and SAIL torch
# emits that itself from the PYTORCH_SAIL_ARCH environment variable (see
# torch.utils.cpp_extension._get_cuda_arch_flags). Passing a CUDA `-gencode` here
# makes hgcc fail outright, so the arch selection is left entirely to
# PYTORCH_SAIL_ARCH (`ppu_10`, `ppu_15`, or a semicolon-separated list).
sgl_kernel_cuda_flags = [
"-DNDEBUG",
f"-DOPERATOR_NAMESPACE={operator_namespace}",
"-O3",
"-Xcompiler",
"-fPIC",
"-std=c++17",
"-DFLASHINFER_ENABLE_F16",
"-DCUTE_USE_PACKED_TUPLE=1",
"-DCUTLASS_ENABLE_TENSOR_CORE_MMA=1",
"-DCUTLASS_VERSIONS_GENERATED",
"-DCUTLASS_TEST_LEVEL=0",
"-DCUTLASS_TEST_ENABLE_CACHED_RESULTS=1",
"-DCUTLASS_DEBUG_TRACE_LEVEL=0",
"--expt-relaxed-constexpr",
"--expt-extended-lambda",
"-U__HGGC_NO_HALF_OPERATORS__",
"-U__HGGC_NO_HALF_CONVERSIONS__",
"-U__HGGC_NO_HALF2_OPERATORS__",
"-U__HGGC_NO_BFLOAT16_CONVERSIONS__",
f"--threads={compile_threads}",
# Suppress warnings
"-Xcompiler=-Wno-clang-format-violations",
"-Xcompiler=-Wno-conversion",
"-Xcompiler=-Wno-deprecated-declarations",
"-Xcompiler=-Wno-terminate",
"-Xcompiler=-Wfatal-errors",
"-Xcompiler=-ftemplate-backtrace-limit=1",
# `-Xcudafe` is an nvcc-only hand-off to cudafe++, which hgcc has no
# counterpart for and rejects. The diagnostics it used to suppress (177
# unused-variable, 2361) are nvcc frontend numbers with no hgcc analogue.
f"-Xcompiler={abi_flag}",
abi_flag,
]
if enable_bf16:
sgl_kernel_cuda_flags.append("-DFLASHINFER_ENABLE_BF16")
if enable_fp8:
sgl_kernel_cuda_flags.extend(
[
"-DFLASHINFER_ENABLE_FP8",
"-DFLASHINFER_ENABLE_FP8_E4M3",
"-DFLASHINFER_ENABLE_FP8_E5M2",
]
)
# ======================= Include Directories ======================= #
# Upstream (non-sailified) include directories. When sailify staging is
# active (see the "Sailify Source Staging" section below), the staged mirror
# directories are prepended so that converted headers shadow their upstream
# originals; the entries below then only act as a fallback for headers that
# were not part of the conversion closure.
base_include_dirs = [
str(root / "include"),
str(root / "csrc"),
str(_ACTLIZE_DIR / "include"),
str(_ACTLIZE_DIR / "tools" / "util" / "include"),
str(_FLASHINFER_REPO.source_dir / "include"),
str(_FLASHINFER_REPO.source_dir / "csrc"),
str(_ACTLIZE_DIR / "examples" / "77_blackwell_fmha"),
str(_ACTLIZE_DIR / "examples" / "common"),
]
# ======================= Source Files ======================= #
common_sources = [
"csrc/allreduce/custom_all_reduce.cu",
"csrc/attention/merge_attn_states.cu",
"csrc/common_extension_sail.cc",
"csrc/elementwise/activation.cu",
"csrc/elementwise/concat_mla.cu",
"csrc/elementwise/copy.cu",
"csrc/elementwise/fused_add_rms_norm_kernel.cu",
"csrc/elementwise/pos_enc.cu",
"csrc/elementwise/topk.cu",
"csrc/gemm/per_token_group_quant_8bit.cu",
"csrc/gemm/per_token_group_quant_8bit_v2.cu",
"csrc/gemm/per_token_quant_fp8.cu",
"csrc/grammar/apply_token_bitmask_inplace_cuda.cu",
"csrc/kvcacheio/transfer.cu",
"csrc/mamba/causal_conv1d.cu",
"csrc/memory/weak_ref_tensor.cpp",
"csrc/moe/moe_align_kernel.cu",
"csrc/moe/fused_qknorm_rope_kernel.cu",
"csrc/moe/moe_sum.cu",
"csrc/moe/moe_sum_reduce.cu",
"csrc/moe/moe_topk_softmax_kernels.cu",
"csrc/moe/moe_topk_sigmoid_kernels.cu",
"csrc/moe/prepare_moe_input.cu",
"csrc/quantization/gguf/gguf_kernel.cu",
]
# Third-party source files
flashinfer_sources = [
str(_FLASHINFER_REPO.source_dir / "csrc" / "norm.cu"),
str(_FLASHINFER_REPO.source_dir / "csrc" / "renorm.cu"),
]
all_common_sources = common_sources + flashinfer_sources
# Libraries to link.
#
# The cuda_free PPU SDK ships no libcuda/libcublas/libcublasLt; the sailified
# sources call the native spellings instead, so link their PPU counterparts:
# cudart -> hggcrt1 (libhggcrt1.so -> libhggcrt.13.0.so; there is no
# unversioned libhggcrt.so to satisfy a plain -lhggcrt)
# cublas -> acblas (PPU counterpart of cublas)
# cublasLt-> acblasLt
# The CUDA driver API (libcuda) is dropped: no csrc translation unit calls it.
# `library_paths()` from SAIL torch already contributes $PPU_SDK/lib, so no
# explicit library_dirs is needed.
libraries = ["c10", "hggcrt1", "hggc", "acblas", "acblasLt"]
extra_link_args = ["-Wl,-rpath,$ORIGIN/../../torch/lib"]
# ======================= Extension Modules ======================= #
def _make_common_ops():
"""common_ops for SM80/SM89."""
nvcc_flags = sgl_kernel_cuda_flags + ["-use_fast_math"]
return CUDAExtension(
name="sgl_kernel.common_ops",
sources=staged_common_sources,
include_dirs=include_dirs,
extra_compile_args={
"nvcc": nvcc_flags,
"cxx": ["-O3", "-std=c++17", abi_flag],
},
libraries=libraries,
extra_link_args=extra_link_args,
py_limited_api=False,
)
# ======================= Clone Third-Party Repositories ======================= #
def _clone_and_checkout(repo_path, repo_url, git_tag, git_shallow):
"""Clone a git repository and checkout a specific tag/commit."""
repo_path = Path(repo_path)
repo_path.parent.mkdir(parents=True, exist_ok=True)
if not repo_path.exists():
clone_cmd = ["git", "clone"]
if git_shallow:
clone_cmd += ["--depth", "1"]
clone_cmd += [repo_url, str(repo_path)]
print(f"Cloning {repo_url} -> {repo_path}")
subprocess.check_call(clone_cmd)
subprocess.check_call(["git", "checkout", git_tag], cwd=repo_path)
if os.environ.get("SGL_KERNEL_SKIP_THIRD_PARTY", "0") != "1":
for _repo in ALL_REPOS:
_clone_and_checkout(
_repo.source_dir,
_repo.git_repository,
_repo.git_tag,
_repo.git_shallow,
)
# ======================= Sailify Source Staging ======================= #
# The upstream sources (sglang aot + flashinfer) target CUDA; the cuda_free
# PPU SDK needs their hggc equivalents. Rather than modifying the upstream
# trees, every compiled source file -- plus every header they recursively
# #include -- is converted by sailify into a mirror tree under
# build/sailified/, and the extensions compile exclusively from that tree:
#
# build/sailified/.ppu_compat/ compat layer (generated)
# build/sailified/csrc/... aot sources + headers
# build/sailified/include/... aot headers
# build/sailified/flashinfer/csrc/... flashinfer sources + headers
# build/sailified/flashinfer/include/... flashinfer headers
#
# The staging tree is wiped and rebuilt on every invocation so no stale
# output survives an upstream or sailify change.
sailify_staging_dir = root / "build" / "sailified"
# Sailify toggle.
#
# SGL_KERNEL_USE_SAILIFY (default "1") enables the automatic cuda->hggc
# staging conversion described below; "0" skips staging and compiles the
# upstream sources directly, which requires a pre-sailified tree
# (root/.ppu_compat, see the skip branch). The legacy
# SGL_KERNEL_SKIP_SAILIFY variable is kept for backwards compatibility and
# takes precedence when explicitly set.
if "SGL_KERNEL_SKIP_SAILIFY" in os.environ:
skip_sailify = os.environ["SGL_KERNEL_SKIP_SAILIFY"] == "1"
else:
skip_sailify = os.environ.get("SGL_KERNEL_USE_SAILIFY", "1") != "1"
# Targeted fixes applied to the *staged* copies after the generic sailify
# pass, for CUDA constructs the identifier-level mapping cannot express.
# The -U__HGGC_NO_HALF* flags in sgl_kernel_cuda_flags disable
# constructor-style half/bfloat16 conversions, so numeric casts must use the
# functional __float2half / __float2bfloat16 API instead.
_SAILIFY_PATCHES = {
"csrc/moe/moe_sum_reduce.cu": [
("__half2float(__half(", "__half2float(__float2half("),
("__bfloat162float(__ppu_bfloat16(", "__bfloat162float(__float2bfloat16("),
],
"csrc/grammar/apply_token_bitmask_inplace_cuda.cu": [
("-CUDART_INF_FP16", "__float2half(-INFINITY)"),
("-CUDART_INF_BF16", "__float2bfloat16(-INFINITY)"),
("__ppu_bfloat16(-INFINITY)", "__float2bfloat16(-INFINITY)"),
],
}
def _sailify_stage(tree_roots, source_files):
"""Convert *source_files* and their #include closure into the staging tree.
Args:
tree_roots: {upstream_root: staged_subdir} -- each file under an
upstream root is written to
sailified_dir/staged_subdir/<relpath from the root>.
source_files: absolute paths of the .cu/.cc/.cpp files to convert.
Returns:
List of staged paths corresponding 1:1 to *source_files*.
"""
try:
from sailify.sailify_python import (
_discover_includes,
_ensure_ppu_compat,
preprocessor,
)
except ImportError as exc:
raise RuntimeError(
"sailify is required for SAIL builds (pip install -e /path/to/sailify)"
) from exc
staging = str(sailify_staging_dir)
if sailify_staging_dir.exists():
shutil.rmtree(sailify_staging_dir)
sailify_staging_dir.mkdir(parents=True)
# Longest root first so nested trees match the most specific entry.
roots = sorted(
((os.path.realpath(r), sub) for r, sub in tree_roots.items()),
key=lambda kv: -len(kv[0]),
)
def _staged_path(src_path):
"""Map an upstream file to (staged_path, project_directory anchor).
The anchor is the directory that preprocessor must receive as
project_directory so that output_directory + relpath(file, anchor)
equals staged_path.
"""
src_path = os.path.realpath(src_path)
for base, sub in roots:
if src_path.startswith(base + os.sep):
rel = os.path.relpath(src_path, base)
staged_rel = os.path.join(sub, rel) if sub else rel
return os.path.join(staging, staged_rel), (
os.path.dirname(base) if sub else base
)
return None
# Directories used to resolve #include targets while walking the
# dependency closure (mirrors the upstream -I layout).
header_include_dirs = []
for base, _sub in roots:
for name in ("include", "csrc"):
d = os.path.join(base, name)
if os.path.isdir(d) and d not in header_include_dirs:
header_include_dirs.append(d)
# BFS over the compiled sources and their #include closure. Headers
# outside the managed trees (system / torch / actlize SDK headers) are
# resolved by the discovery walk but intentionally left unconverted.
visited = {os.path.realpath(f) for f in source_files}
pending = list(visited)
stats = {}
failures = []
while pending:
src_path = pending.pop(0)
_discover_includes(src_path, header_include_dirs, visited, pending)
mapped = _staged_path(src_path)
if mapped is None:
continue # header outside the managed trees: used as-is
staged_path, anchor = mapped
result = preprocessor(
output_directory=staging,
filepath=src_path,
all_files=[],
stats=stats,
clean_ctx=None,
show_progress=False,
project_directory=anchor,
)
if result.status != "ok":
failures.append(f"{src_path}: {result.status}")
elif not os.path.isfile(staged_path):
failures.append(f"{src_path}: staged output {staged_path} missing")
if failures:
raise RuntimeError("sailify staging failed:\n " + "\n ".join(failures))
# Regenerate the compat layer inside the staging tree.
_ensure_ppu_compat(staging)
# Apply targeted post-sailify patches to the staged copies only; the
# upstream trees are never touched.
for rel_path, replacements in _SAILIFY_PATCHES.items():
staged = sailify_staging_dir / rel_path
if not staged.is_file():
print(f"sailify: patch target missing (skipped): {rel_path}")
continue
text = staged.read_text()
for old, new in replacements:
text = text.replace(old, new)
staged.write_text(text)
n_headers = max(len(stats.get("ppuified", [])) - len(source_files), 0)
print(
f"sailify: staged {len(source_files)} sources (+{n_headers} discovered "
f"headers) into {sailify_staging_dir}"
)
return [_staged_path(f)[0] for f in source_files]
if skip_sailify:
# Compile the upstream sources as-is. The target toolchain is not
# necessarily the cuda_free PPU SDK (this may be a plain CUDA build), so
# no fail-fast on .ppu_compat: if it exists (pre-generated for the PPU
# cuda_free toolchain) it is prepended to shadow the CUDA headers, and
# otherwise the upstream include layout is used unchanged.
print("WARNING: sailify disabled, compiling upstream sources directly")
staged_common_sources = [str(root / s) for s in common_sources] + flashinfer_sources
ppu_compat_dir = root / ".ppu_compat"
if ppu_compat_dir.is_dir():
print(f"note: using existing compat layer {ppu_compat_dir}")
include_dirs = [str(ppu_compat_dir)] + base_include_dirs
else:
include_dirs = list(base_include_dirs)
else:
_staged = _sailify_stage(
{
root: "", # aot tree mirrors directly onto the staging root
_FLASHINFER_REPO.source_dir: "flashinfer",
},
[str(root / s) for s in common_sources] + flashinfer_sources,
)
staged_common_sources = _staged
# Staged directories shadow their upstream originals. .ppu_compat MUST
# stay first: SAIL torch injects its own (possibly older) `.ppu_compat`
# through torch.utils.cpp_extension.include_paths(), which lands after
# the user include_dirs. Both copies contain compatible_wrapper.h, and
# SAIL torch also passes `-include compatible_wrapper.h` on the hgcc
# command line -- the compiler resolves that through -I order, so a
# stale compat layer shadowing ours breaks the build with e.g.
# "no template named 'maximum' in namespace 'hggc'".
include_dirs = [
str(sailify_staging_dir / ".ppu_compat"),
str(sailify_staging_dir / "include"),
str(sailify_staging_dir / "csrc"),
str(sailify_staging_dir / "flashinfer" / "include"),
str(sailify_staging_dir / "flashinfer" / "csrc"),
] + base_include_dirs
# ======================= Post-Build Cleanup ======================= #
# The build itself consumes the compat layer from
# build/sailified/.ppu_compat (first -I entry above), but tooling on the
# SAIL torch side may additionally drop a .ppu_compat directory into the
# aot tree (it shows up on the hgcc -I line). It is not part of the
# upstream sources, so remove it after every compilation / packaging step
# has finished. In skip-sailify mode root/.ppu_compat is an optional
# user-provided compat layer and must NOT be removed either (hence no
# registration there).
def _cleanup_upstream_ppu_compat():
upstream_compat = root / ".ppu_compat"
if upstream_compat.is_dir():
shutil.rmtree(upstream_compat, ignore_errors=True)
print(f"setup_sail: removed {upstream_compat} (post-build cleanup)")
atexit.register(_cleanup_upstream_ppu_compat)
# ======================= Build Extension Modules List ======================= #
ext_modules = [
_make_common_ops(),
]
# ======================= Custom Build Extension ======================= #
class _CustomBuildExt(BuildExtension):
"""Custom build extension with ninja support."""
pass
# ======================= Package Discovery ======================= #
_triton_kernels_root = _TRITON_REPO.source_dir / "python" / "triton_kernels"
_packages = find_namespace_packages(where="python")
_package_dir = {"": "python"}
# Discover triton_kernels packages (may not exist before first clone)
if _triton_kernels_root.exists():
_triton_pkgs = find_namespace_packages(
where=str(_triton_kernels_root),
exclude=["tests", "tests.*"],
)
else:
_triton_pkgs = ["triton_kernels"]
for pkg in _triton_pkgs:
_package_dir[pkg] = os.path.relpath(
_triton_kernels_root / pkg.replace(".", os.sep), root
)
_packages += _triton_pkgs
# ======================= Setup ======================= #
setup(
name="sglang-kernel",
version=_get_version(),
packages=_packages,
package_dir=_package_dir,
ext_modules=ext_modules,
cmdclass={"build_ext": _CustomBuildExt.with_options(use_ninja=True)},
options={"bdist_wheel": {"py_limited_api": "cp310"}},
)
+16 -5
View File
@@ -17,6 +17,7 @@ from sglang.kernels.jit.utils.common import (
cache_once,
is_hip_runtime,
is_musa_runtime,
is_sail_runtime,
)
from sglang.srt.utils.common import is_cuda
@@ -70,6 +71,14 @@ def _jit_cuda_version() -> tuple[int, ...]:
return get_cuda_version()
def _sail_arch_suffix(major: int, minor: int) -> str:
"""SAIL devices below the SM89 capability require the arch-specific target
variant for JIT compilation (the ``"a"`` suffix); SM89+ SAIL devices stay
unsuffixed like HIP/MUSA.
"""
return "a" if (major <= 8 and minor < 9) else ""
def _cuda_arch_suffix(major: int, minor: int) -> str:
"""Mirror FlashInfer's `_normalize_cuda_arch`: 9.x/10.x+ -> "a"; 12.0 -> "f"
and 12.x (x>0) -> "a" (SM120/SM121 need separate cubins to avoid
@@ -104,11 +113,13 @@ def _init_jit_cuda_arch_once():
# JIT builds target the exact local GPU, so the arch-specific target is
# always correct on Hopper+ and unlocks arch-only instructions (redux.f32).
# HIP/MUSA capability numbers aren't CUDA SM versions and stay unsuffixed.
suffix = (
""
if (is_hip_runtime() or is_musa_runtime())
else _cuda_arch_suffix(major, minor)
)
if is_hip_runtime() or is_musa_runtime():
suffix = ""
elif is_sail_runtime():
suffix = _sail_arch_suffix(major, minor)
else:
suffix = _cuda_arch_suffix(major, minor)
_CUDA_ARCH = ArchInfo(major, minor, suffix)
@@ -72,6 +72,13 @@ def is_musa_runtime() -> bool:
return getattr(torch.version, "musa", None) is not None
@cache_once
def is_sail_runtime() -> bool:
# T-HEAD SAIL device names carry the "ZW" tag; keep the check aligned with
# sglang.srt.utils.is_sail so all layers agree on what "running on SAIL" means.
return bool(torch.cuda.is_available() and "ZW" in torch.cuda.get_device_name())
_REGISTERED_CLASSES: Dict[type, type] = {}
@@ -12,6 +12,7 @@ Modules, in dependency order (there are no cycles)::
toolchain compilers, tvm-ffi locations, platform base flags
ninja generating and running build.ninja, reading its depfiles
cache build_key / deps_key, cache layout, publication
sailify CUDA -> PPU source conversion for hgcc builds
loader load_jit
parallel parallel_compile: several builds at once
"""
@@ -56,7 +56,12 @@ from typing import Dict, Iterable, List, Optional, Sequence, Tuple
import msgspec
from sglang.kernels.jit.utils.arch import get_jit_cuda_arch
from sglang.kernels.jit.utils.common import cache_once, is_hip_runtime, is_musa_runtime
from sglang.kernels.jit.utils.common import (
cache_once,
is_hip_runtime,
is_musa_runtime,
is_sail_runtime,
)
from sglang.kernels.jit.utils.compile import toolchain
from sglang.kernels.jit.utils.compile.paths import KERNEL_PATH
from sglang.kernels.jit.utils.compile.spec import BuildSpec
@@ -214,6 +219,10 @@ def _target_tag() -> str:
``(major, minor)`` capability: the latter maps gfx940/gfx941/gfx942 onto a
single ``9.4``, which are three different compile targets.
"""
if is_sail_runtime():
arch = envs.SGLANG_SAIL_GPU_ARCH.get()
safe = "".join(c if c.isalnum() or c in "-_." else "_" for c in arch)
return f"sail_{safe}"
if is_hip_runtime():
return toolchain.gpu_arch_name().split(":")[0] or "unknown"
arch = get_jit_cuda_arch()
@@ -232,7 +241,14 @@ def _environment_fingerprint() -> str:
different host compiler means different system headers and different host
codegen for otherwise identical inputs.
"""
if is_hip_runtime():
if is_sail_runtime():
# Imported lazily: sailify imports this module for file digests, so a
# top-level import would be circular.
from sglang.kernels.jit.utils.compile.sailify import sailify_version
arch = envs.SGLANG_SAIL_GPU_ARCH.get()
target = f"hgcc:{arch}:sailify-{sailify_version()}"
elif is_hip_runtime():
target = f"hip:{toolchain.gpu_arch_name()}"
else:
arch = get_jit_cuda_arch()
@@ -14,13 +14,14 @@ from typing import TYPE_CHECKING, List, Tuple
import torch
from sglang.kernels.jit.utils.arch import get_default_target_flags
from sglang.kernels.jit.utils.common import is_hip_runtime
from sglang.kernels.jit.utils.compile import cache, ninja
from sglang.kernels.jit.utils.common import is_hip_runtime, is_sail_runtime
from sglang.kernels.jit.utils.compile import cache, ninja, toolchain
from sglang.kernels.jit.utils.compile.paths import (
DEFAULT_CFLAGS,
DEFAULT_INCLUDE,
DEFAULT_LDFLAGS,
)
from sglang.kernels.jit.utils.compile.sailify import convert_cuda_sources
from sglang.kernels.jit.utils.compile.spec import BuildSpec, resolve_sources
from sglang.kernels.jit.utils.deps import REGISTERED_DEPENDENCIES
from sglang.srt.environ import envs
@@ -95,11 +96,21 @@ def load_jit(
)
includes = list(DEFAULT_INCLUDE) + (extra_include_paths or [])
if is_sail_runtime():
includes = toolchain.base_include_paths() + includes
for dep in sorted(set(extra_dependencies or [])):
if dep not in REGISTERED_DEPENDENCIES:
raise ValueError(f"Dependency {dep} is not registered.")
includes += REGISTERED_DEPENDENCIES[dep]()
if is_sail_runtime() and cuda_files:
resolved_cuda = list(resolve_sources(cuda_files))
converted, sailify_flags = convert_cuda_sources(resolved_cuda, includes)
cuda_files = converted # absolute paths pass through resolve_sources below
extra_cuda_cflags = (
_filter_hgcc_cuda_flags(extra_cuda_cflags or []) + sailify_flags
)
module_args = tuple(str(arg) for arg in args)
spec = BuildSpec(
module_args=module_args,
@@ -202,6 +213,37 @@ def _find_prebuilt(*, spec: BuildSpec, scope: pathlib.Path) -> pathlib.Path | No
return cache.find_prebuilt(scope=scope, module_name=spec.module_name)
# Verified against hgcc 2.2: it is an nvcc-style driver and accepts
# -Xcompiler, --use_fast_math, --expt-relaxed-constexpr and
# --expt-extended-lambda; the genuinely unsupported options are the
# nvcc-specific code-generation and ptxas ones below.
_HGCC_DROP_WITH_ARG = frozenset({"-Xptxas"})
_HGCC_DROP_PREFIX = ("-gencode", "--generate-code")
def _filter_hgcc_cuda_flags(flags: List[str]) -> List[str]:
"""Drop nvcc-only flags hgcc would not understand; keep everything else."""
kept: List[str] = []
dropped: List[str] = []
skip_next = False
for flag in flags:
if skip_next:
skip_next = False
dropped.append(flag)
continue
if flag in _HGCC_DROP_WITH_ARG:
skip_next = True
dropped.append(flag)
continue
if flag.startswith(_HGCC_DROP_PREFIX):
dropped.append(flag)
continue
kept.append(flag)
if dropped:
logger.warning("Dropping nvcc-only flags hgcc does not accept: %s", dropped)
return kept
@contextlib.contextmanager
def _build_lock(scope: pathlib.Path):
"""Serialize builds of one module variant across processes.
@@ -0,0 +1,237 @@
"""Convert CUDA sources with sailify before they are handed to hgcc.
hgcc cannot read CUDA: identifiers, API names and header paths first have to
be rewritten by sailify. Two properties of the converter shape everything in
this module:
* ``sailify_extra_files_recursive`` converts **in place** — its per-file
output path is ``join(output_directory, relpath(input, output_directory))``,
which normalizes back onto the input itself; only the generated
``.ppu_compat/`` headers actually land in ``output_directory``. The kernel
sources in the tree must never be rewritten, so conversion runs on a
mirror-copy of the sources, made under the JIT cache root.
* Conversion also rewrites every transitively ``#include``d header it can
discover, so the mirror has to cover the whole include closure, and the
digest that keys the mirror has to cover it too — otherwise a header edit
would be invisible to both the mirror and, transitively, the build cache.
The mirror preserves each file's absolute path relative to ``/``, so relative
includes keep resolving inside it exactly as they did in the original tree.
"""
from __future__ import annotations
import hashlib
import logging
import os
import pathlib
import re
import shutil
import uuid
from typing import Dict, List, Optional, Set, Tuple
from sglang.kernels.jit.utils.common import cache_once
from sglang.srt.environ import envs
logger = logging.getLogger(__name__)
# Mirrors sailify's `_RE_INCLUDE` / `DEFAULT_EXTENSIONS`: the closure below
# must contain exactly the files sailify itself would discover and convert.
_INCLUDE_RE = re.compile(r'^[ \t]*#[ \t]*include[ \t]+[<"]([^>"]+)[>"]', re.MULTILINE)
_SOURCE_EXTENSIONS = (".cu", ".cuh", ".c", ".cc", ".cpp", ".h", ".hpp", ".inl")
_KEY_HEX_LEN = 16
@cache_once
def sailify_version() -> str:
"""Installed sailify version, or 'unknown' (never raises)."""
try:
from importlib.metadata import version as dist_version
return dist_version("sailify")
except Exception:
pass
try:
from sailify.version import __version__
return str(__version__)
except Exception:
return "unknown"
@cache_once
def _ppu_sdk_version() -> str:
"""PPU SDK version as sailify detects it, or 'unknown' (never raises).
The SDK version is baked into the generated ``compatible_wrapper.h``, so
it is part of the mirror digest.
"""
try:
from sailify.ppu_sdk_version import (
detect_ppu_sdk_version,
format_version_string,
)
return format_version_string(detect_ppu_sdk_version())
except Exception:
return "unknown"
def _sailify_root() -> pathlib.Path:
configured = envs.SGLANG_JIT_CACHE_DIR.get() or "~/.cache/sglang/jit"
return pathlib.Path(configured).expanduser() / "sailified"
def _mirror_path(root: pathlib.Path, source: str) -> pathlib.Path:
"""The mirrored location of an absolute *source* path under *root*."""
path = pathlib.Path(source)
return root / path.relative_to(path.anchor)
def _discover_closure(
cuda_files: List[str], include_dirs: List[str]
) -> Tuple[Set[str], Dict[str, Optional[str]]]:
"""Every file sailify would convert, with the base each resolved against.
Replicates sailify's own discovery: an include is tried against the
including file's directory first, then each include dir in order; the
first candidate that exists on disk wins, whether or not it is a source
extension. The base is ``None`` for includes resolved against the
including file's directory (the mirror reproduces those relative
relationships on its own) and the include dir otherwise (whose mirrored
location has to reach the compile line for the converted header to win
over the original).
"""
visited: Set[str] = set()
bases: Dict[str, Optional[str]] = {}
queue: List[str] = []
for filepath in cuda_files:
filepath = os.path.abspath(filepath)
if filepath not in visited:
visited.add(filepath)
bases[filepath] = None
queue.append(filepath)
while queue:
filepath = queue.pop(0)
try:
source = pathlib.Path(filepath).read_text(errors="replace")
except OSError:
continue
file_dir = os.path.dirname(filepath)
for match in _INCLUDE_RE.finditer(source):
inc = match.group(1)
candidates = [(os.path.join(file_dir, inc), None)] + [
(os.path.join(inc_dir, inc), os.path.abspath(inc_dir))
for inc_dir in include_dirs
]
for candidate, base in candidates:
candidate = os.path.abspath(candidate)
if candidate in visited:
break
if os.path.isfile(candidate):
if os.path.splitext(candidate)[1] in _SOURCE_EXTENSIONS:
visited.add(candidate)
bases[candidate] = base
queue.append(candidate)
break
return visited, bases
def _mirror_digest(closure: Set[str], include_dirs: List[str]) -> str:
# Imported lazily: cache imports this module for the environment
# fingerprint, so a top-level import would be circular.
from sglang.kernels.jit.utils.compile import cache
digest = hashlib.sha256()
for part in (sailify_version(), _ppu_sdk_version(), tuple(include_dirs)):
digest.update(repr(part).encode())
digest.update(b"\0")
for path in sorted(closure):
digest.update(path.encode())
digest.update(b"\0")
digest.update((cache._file_digest(pathlib.Path(path)) or "").encode())
digest.update(b"\0")
return digest.hexdigest()[:_KEY_HEX_LEN]
def convert_cuda_sources(
cuda_files: List[str], include_dirs: List[str]
) -> Tuple[List[str], List[str]]:
"""Convert .cu sources with sailify into a content-addressed dir.
Returns (converted_cuda_files, extra_cuda_cflags) where extra flags add
the mirrored include dirs, the generated .ppu_compat include dir, and a
force-include of compatible_wrapper.h.
"""
try:
from sailify.sailify_python import sailify_extra_files_recursive
except ImportError as error:
raise RuntimeError(
"JIT builds on SAIL require the sailify converter, which is not "
"installed. Install it with `pip install -e cuda_free/sailify` from "
"the sglang repository."
) from error
closure, bases = _discover_closure(cuda_files, include_dirs)
outdir = _sailify_root() / _mirror_digest(closure, include_dirs)
converted = [str(_mirror_path(outdir, os.path.abspath(f))) for f in cuda_files]
compat_header = outdir / ".ppu_compat" / "compatible_wrapper.h"
if not (
outdir.is_dir()
and compat_header.is_file()
and all(pathlib.Path(path).is_file() for path in converted)
):
tmp = outdir.parent / f"{outdir.name}.tmp-{uuid.uuid4().hex}"
try:
mirror: Dict[str, str] = {}
for source in sorted(closure):
target = _mirror_path(tmp, source)
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source, target)
mirror[source] = str(target)
sailify_extra_files_recursive(
output_directory=str(tmp),
extra_files=[mirror[source] for source in sorted(closure)],
header_include_dirs=[],
)
outdir.parent.mkdir(parents=True, exist_ok=True)
try:
os.rename(tmp, outdir)
except OSError:
# A concurrent process published the identical content first.
if not outdir.is_dir():
raise
except Exception as error:
raise RuntimeError(
f"sailify failed to convert CUDA sources for hgcc: {error}"
) from error
finally:
shutil.rmtree(tmp, ignore_errors=True)
missing = [path for path in converted if not pathlib.Path(path).is_file()]
if missing:
raise RuntimeError(
"sailify did not produce the expected converted sources: "
+ ", ".join(missing)
)
for source, path in zip(cuda_files, converted):
src_ext = os.path.splitext(source)[1]
out_ext = os.path.splitext(path)[1]
assert src_ext == out_ext, (
f"sailify changed the extension of {source}: converted to {path}"
)
mirrored_include_dirs = [
f"-I{_mirror_path(outdir, base)}"
for base in dict.fromkeys(bases.values())
if base is not None
]
flags = mirrored_include_dirs + [
f"-I{outdir / '.ppu_compat'}",
"-include",
"compatible_wrapper.h",
]
return converted, flags
@@ -22,10 +22,22 @@ from typing import List, Tuple
import torch
from sglang.kernels.jit.utils.arch import get_jit_cuda_arch
from sglang.kernels.jit.utils.common import cache_once, is_hip_runtime
from sglang.kernels.jit.utils.common import cache_once, is_hip_runtime, is_sail_runtime
from sglang.srt.environ import envs
logger = logging.getLogger(__name__)
_SAIL_GPU_ARCHS = (
"native",
"all",
"all-ppu",
"all-vm",
"ppu_10",
"ppu_15",
"vm_10",
"vm_15",
)
@cache_once
def cuda_home() -> str:
@@ -64,16 +76,59 @@ def rocm_home() -> str:
@cache_once
def device_compiler_path() -> str:
"""The nvcc/hipcc that JIT builds actually invoke.
"""The nvcc/hipcc/hgcc that JIT builds actually invoke.
Resolved the same way tvm-ffi resolves it, so the binary the cache
fingerprints is the binary that does the compiling.
"""
if is_sail_runtime():
return hgcc_path()
if is_hip_runtime():
return os.path.join(rocm_home(), "bin", "hipcc")
return os.path.join(cuda_home(), "bin", "nvcc")
@cache_once
def hgcc_path() -> str:
"""The hgcc compiler, from PATH or the PPU SDK install."""
searched = ["hgcc on PATH"]
on_path = shutil.which("hgcc")
if on_path is not None:
return on_path
for root in (
os.environ.get("PPU_SDK"),
os.environ.get("PPU_HOME"),
"/usr/local/PPU_SDK",
):
if root is None:
continue
candidate = os.path.join(root, "bin", "hgcc")
searched.append(candidate)
if os.path.isfile(candidate):
return candidate
raise RuntimeError(
"JIT builds on SAIL require the hgcc compiler, which was not found. Searched: "
+ ", ".join(searched)
)
@cache_once
def ppu_sdk_home() -> str:
"""The PPU SDK root providing the hggc libraries to link against.
Two layers live in ``lib/`` and they are not interchangeable:
* ``libhggcrt1`` (SONAME ``libhggcrt.13.0.so``) is the *runtime*, the
counterpart of cudart. It alone exports the ``hggc*`` Runtime-API
symbols and the ``__hggcRegister*`` entry points that hgcc's generated
fat-binary registration code calls from every translation unit with
device code.
* ``libhggc`` is the *driver*, the counterpart of libcuda. It exports the
``hg*`` Driver-API symbols (e.g. ``hgPointerGetAttribute``) and none of
the ``hggc*`` ones.
"""
return os.environ.get("PPU_SDK") or "/usr/local/PPU_SDK"
@cache_once
def host_compiler_path() -> str:
"""The C++ compiler host code is handed to.
@@ -129,6 +184,14 @@ def target_flags() -> List[str]:
the compiler driver to probe: the value is part of the cache key, so it has
to be decided here and not rediscovered at build time.
"""
if is_sail_runtime():
arch = envs.SGLANG_SAIL_GPU_ARCH.get()
if arch not in _SAIL_GPU_ARCHS:
raise ValueError(
f"Invalid SGLANG_SAIL_GPU_ARCH={arch!r}; expected one of "
f"{', '.join(_SAIL_GPU_ARCHS)}"
)
return [f"--gpu-architecture={arch}"]
if is_hip_runtime():
return [f"--offload-arch={gpu_arch_name()}"]
arch = get_jit_cuda_arch()
@@ -170,6 +233,12 @@ def base_link_flags(*, with_device: bool) -> List[str]:
flags = ["-shared", f"-L{lib_dir}", f"-l{lib_name}"]
if not with_device:
return flags
if is_sail_runtime():
return flags + [
f"-L{ppu_sdk_home()}/lib",
"-lhggcrt1",
"-lhggc",
]
if is_hip_runtime():
return flags + [f"-L{rocm_home()}/lib", "-lamdhip64"]
return flags + [f"-L{cuda_home()}/lib64", "-lcudart"]
+6
View File
@@ -1331,6 +1331,12 @@ class Envs:
# Drop the GB/s and TFLOPS columns from the benchmark marker's table.
SGLANG_JIT_BENCHMARK_DISABLE_LOG_BANDWIDTH = EnvBool(False)
SGLANG_JIT_BENCHMARK_DISABLE_LOG_FLOPS = EnvBool(False)
# The hgcc --gpu-architecture target used by JIT builds on SAIL (hgcc
# cannot read CUDA sources, so they are converted by sailify first).
# One of: native, all, all-ppu,
# all-vm, ppu_10, ppu_15, vm_10, vm_15. "native" builds for the local
# device only, matching how the nvcc path pins -gencode to this GPU.
SGLANG_SAIL_GPU_ARCH = EnvStr("native")
# ===================================================================
# Expert-parallel dispatch and MoE execution
+12
View File
@@ -25,6 +25,7 @@ from sglang.srt.platforms.mps import MpsSRTPlatform
from sglang.srt.platforms.musa import MusaSRTPlatform
from sglang.srt.platforms.npu import NPUSRTPlatform
from sglang.srt.platforms.rocm import RocmSRTPlatform
from sglang.srt.platforms.sail import SailSRTPlatform
from sglang.srt.platforms.xpu import XpuSRTPlatform
from sglang.srt.plugins import PLATFORM_PLUGINS_GROUP, load_plugins_by_group
@@ -41,6 +42,10 @@ def _is_rocm_available() -> bool:
return bool(torch.cuda.is_available() and torch.version.hip is not None)
def _is_sail_available() -> bool:
return bool(torch.cuda.is_available() and "ZW" in torch.cuda.get_device_name())
def _is_cpu_available() -> bool:
return os.getenv("SGLANG_USE_CPU_ENGINE", "0") == "1"
@@ -86,6 +91,8 @@ def _resolve_platform() -> SRTPlatform:
- 0 activated + SGLANG_USE_CPU_ENGINE=1 → fallback CpuSRTPlatform
(checked first; an explicit opt-in wins over CUDA/ROCm availability,
so developers on GPU hosts can intentionally exercise the CPU path)
- 0 activated + SAIL available → fallback SailSRTPlatform
(checked before CUDA; SAIL also reports torch.cuda.is_available())
- 0 activated + CUDA available → fallback CudaSRTPlatform
- 0 activated + NPU available → fallback NPUSRTPlatform
- 0 activated + ROCm available → fallback RocmSRTPlatform
@@ -146,6 +153,11 @@ def _resolve_platform() -> SRTPlatform:
if _is_cpu_available():
logger.debug("SGLANG_USE_CPU_ENGINE=1. Using CPU SRTPlatform defaults.")
return CpuSRTPlatform()
if _is_sail_available():
logger.debug(
"No platform plugin detected. Using SAIL SRTPlatform defaults."
)
return SailSRTPlatform()
if _is_cuda_available():
logger.debug(
"No platform plugin detected. Using CUDA SRTPlatform defaults."
+6 -1
View File
@@ -53,6 +53,7 @@ class PlatformEnum(enum.Enum):
NPU = enum.auto()
TPU = enum.auto()
MPS = enum.auto()
SAIL = enum.auto()
OOT = enum.auto() # Out-of-tree (external plugin)
UNSPECIFIED = enum.auto()
@@ -135,12 +136,16 @@ class DeviceMixin:
def is_mps(self) -> bool:
return self._enum == PlatformEnum.MPS
def is_sail(self) -> bool:
return self._enum == PlatformEnum.SAIL
def is_cuda_alike(self) -> bool:
"""True for CUDA, ROCm, or MUSA (all expose CUDA-like APIs)."""
"""True for CUDA, ROCm, MUSA, or SAIL (all expose CUDA-like APIs)."""
return self._enum in (
PlatformEnum.CUDA,
PlatformEnum.ROCM,
PlatformEnum.MUSA,
PlatformEnum.SAIL,
)
def is_out_of_tree(self) -> bool:
+29
View File
@@ -0,0 +1,29 @@
"""SAIL device operations for the SRT platform layer.
T-HEAD SAIL exposes a CUDA-compatible API through its torch backend, so
``SailDeviceMixin`` inherits all device ops from ``CudaDeviceMixin`` and
only overrides identity (``_enum``, ``device_name``).
"""
from sglang.srt.platforms.cuda import CudaDeviceMixin
from sglang.srt.platforms.device_mixin import PlatformEnum
from sglang.srt.platforms.interface import PlatformCapabilities, SRTPlatform
class SailDeviceMixin(CudaDeviceMixin):
"""SAIL device ops — identical surface to CUDA via T-HEAD's torch backend."""
_enum: PlatformEnum = PlatformEnum.SAIL
device_name: str = "sail"
# device_type stays "cuda" — torch.device("cuda") is the only valid
# device-type string for SAIL devices in PyTorch.
class SailSRTPlatform(SailDeviceMixin, SRTPlatform):
"""Default in-tree T-HEAD SAIL SRT platform."""
capabilities = PlatformCapabilities(
supports_triton=True,
graph_capture=True,
piecewise_graph=True,
)
@@ -407,8 +407,6 @@ class EagleDraftWorker(EagleDraftWorkerBase):
def _configure_qsa_mtp_index_share(self) -> None:
"""Reuse the draft-extend QSA selection across the MTP decode steps;
chain speculation only: with topk > 1 decode rows are not request-major."""
from sglang.srt.layers.attention.qsa.qsa_indexer import QSAIndexer
hf_config = self.draft_runner.model_config.hf_config
if (
not _qsa_index_share_requested(hf_config)
@@ -426,6 +424,8 @@ class EagleDraftWorker(EagleDraftWorkerBase):
"speculative decoding"
)
return
from sglang.srt.layers.attention.qsa.qsa_indexer import QSAIndexer
layer_ids = sorted(
{
module.layer_id
+6 -1
View File
@@ -161,7 +161,7 @@ def is_cuda():
@lru_cache(maxsize=1)
def is_cuda_alike():
return is_cuda() or is_hip()
return is_cuda() or is_hip() or is_sail()
@lru_cache(maxsize=1)
@@ -239,6 +239,11 @@ def is_mps() -> bool:
return hasattr(torch, "mps") and torch.mps.is_available()
@lru_cache(maxsize=1)
def is_sail() -> bool:
return torch.cuda.is_available() and "ZW" in torch.cuda.get_device_name()
def is_float4_e2m1fn_x2(dtype) -> bool:
"""Check if dtype is float4_e2m1fn_x2 and CUDA is available."""
target_dtype = getattr(torch, "float4_e2m1fn_x2", None)