Files
sgl-project--sglang/python/sglang/jit_kernel/fp8_quantize.py
T
wehub-resource-sync 94057c3d3e
PR Test (NPU) / check-changes (push) Has been cancelled
PR Test (NPU) / pr-gate (push) Has been cancelled
PR Test (NPU) / set-image-config (push) Has been cancelled
PR Test (NPU) / stage-b-test-1-npu-a2 (0) (push) Has been cancelled
PR Test (NPU) / stage-b-test-1-npu-a2 (1) (push) Has been cancelled
PR Test (NPU) / stage-b-test-2-npu-a2 (0) (push) Has been cancelled
PR Test (NPU) / stage-b-test-2-npu-a2 (1) (push) Has been cancelled
PR Test (NPU) / stage-b-test-4-npu-a3 (push) Has been cancelled
PR Test (NPU) / stage-b-test-16-npu-a3 (push) Has been cancelled
PR Test (NPU) / multimodal-gen-test-1-npu-a3 (push) Has been cancelled
PR Test (NPU) / multimodal-gen-test-2-npu-a3 (push) Has been cancelled
PR Test (Arm64) / pr-gate (push) Has been cancelled
PR Test (Arm64) / check-changes (push) Has been cancelled
PR Test (Arm64) / build-test (push) Has been cancelled
PR Test (sgl-router) / gate (push) Has been cancelled
PR Test (sgl-router) / tier-1 — lint (push) Has been cancelled
PR Test (sgl-router) / tier-2 — build + test (push) Has been cancelled
PR Test (sgl-router) / tier-3 — docker (placeholder) (push) Has been cancelled
PR Test (sgl-router) / tier-3 — k8s integration (push) Has been cancelled
PR Test (sgl-router) / tier-3 — e2e (push) Has been cancelled
PR Test (sgl-router) / finish (push) Has been cancelled
PR Test (NPU) / single-node-poc (map[name:qwen3_6_27b_w8a8_1p_in64k_out1k_50ms runner:linux-aarch64-a3-2 test_case:test/registered/ascend/performance/qwen3_6_27b/test_npu_qwen3_6_27b_w8a8_1p_in64k_out1k_50ms.py test_type:perf]) (push) Has been cancelled
PR Test (NPU) / pr-test-npu-finish (push) Has been cancelled
PR Test (Xeon) / pr-gate (push) Has been cancelled
PR Test (Xeon) / check-changes (push) Has been cancelled
PR Test (Xeon) / build-test (, xeon-gnr, base-b-test-cpu) (push) Has been cancelled
PR Test (XPU) / check-changes (push) Has been cancelled
PR Test (XPU) / pr-gate (push) Has been cancelled
PR Test (XPU) / stage-a-test-1-gpu-xpu (push) Has been cancelled
PR Test (XPU) / wait-for-stage-a (push) Has been cancelled
PR Test (XPU) / stage-b-test-1-gpu-xpu (push) Has been cancelled
PR Test (XPU) / finish (push) Has been cancelled
CI Model Inventory / build-inventory (push) Has been cancelled
Lint / lint (push) Has been cancelled
PR Benchmark (SMG Components) / Benchmark Compilation Check (push) Has been cancelled
PR Benchmark (SMG Components) / Benchmark - Manual Policy (push) Has been cancelled
PR Benchmark (SMG Components) / Benchmark - Request Processing (push) Has been cancelled
PR Benchmark (SMG Components) / Benchmark Summary (push) Has been cancelled
PR Test (SMG) / build-wheel (push) Has been cancelled
Release SGLang Model Gateway to PyPI / build on windows (x86_64 - auto) (push) Has been cancelled
Release SGLang Model Gateway to PyPI / build on macos (x86_64 - auto) (push) Has been cancelled
PR Test (SMG) / python-unit-tests (push) Has been cancelled
PR Test (SMG) / unit-tests (push) Has been cancelled
PR Test (SMG) / benchmarks (push) Has been cancelled
PR Test (SMG) / chat-completions (push) Has been cancelled
PR Test (SMG) / chat-completions-4gpu (push) Has been cancelled
PR Test (SMG) / e2e (push) Has been cancelled
PR Test (SMG) / docker-build-test (push) Has been cancelled
PR Test (SMG) / k8s-integration (push) Has been cancelled
PR Test (SMG) / finish (push) Has been cancelled
PR Test (SMG) / summarize-benchmarks (push) Has been cancelled
Release SGLang Model Gateway Docker Image / publish (push) Has been cancelled
Release SGLang Model Gateway to PyPI / build on macos (aarch64 - auto) (push) Has been cancelled
Release SGLang Model Gateway to PyPI / build on linux (aarch64 - auto) (push) Has been cancelled
Release SGLang Model Gateway to PyPI / build on linux (x86_64 - auto) (push) Has been cancelled
Release SGLang Model Gateway to PyPI / build on linux (aarch64 - musllinux_1_1) (push) Has been cancelled
Release SGLang Model Gateway to PyPI / build on linux (x86_64 - musllinux_1_1) (push) Has been cancelled
Release SGLang Model Gateway to PyPI / Build SDist (push) Has been cancelled
Release SGLang Model Gateway to PyPI / Upload to PyPI (push) Has been cancelled
Release SGLang Kernels / build-cu129-matrix (aarch64, 12.9, 3.10, arm-kernel-build-node) (push) Has been cancelled
Release SGLang Kernels / build-cu129-matrix (x86_64, 12.9, 3.10, x64-kernel-build-node) (push) Has been cancelled
Release SGLang Kernels / release-cu129 (push) Has been cancelled
Release SGLang Kernels / build-cu130-matrix (aarch64, 13.0, 3.10, arm-kernel-build-node) (push) Has been cancelled
Release SGLang Kernels / build-cu130-matrix (x86_64, 13.0, 3.10, x64-kernel-build-node) (push) Has been cancelled
Release SGLang Kernels / release-cu130 (push) Has been cancelled
Release SGLang Kernels / build-rocm-matrix (3.10, 700) (push) Has been cancelled
Release SGLang Kernels / build-rocm-matrix (3.10, 720) (push) Has been cancelled
Release SGLang Kernels / release-rocm700 (push) Has been cancelled
Release SGLang Kernels / release-rocm720 (push) Has been cancelled
Release SGLang Kernels / build-musa43 (43, 3.10) (push) Has been cancelled
Release SGLang Kernels / release-musa43 (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 12:38:16 +08:00

158 lines
5.0 KiB
Python

# Copyright (c) 2026 LightSeek Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import annotations
from typing import Optional
import torch
import triton
import triton.language as tl
@triton.jit
def _fp8_quantize_kernel(
x_ptr,
out_ptr,
scale_inv,
M,
x_row_stride,
out_row_stride,
N: tl.constexpr,
FP8_DTYPE: tl.constexpr,
BLOCK_M: tl.constexpr,
ENABLE_PDL: tl.constexpr,
):
pid = tl.program_id(0)
m_idx = pid * BLOCK_M + tl.arange(0, BLOCK_M)
m_mask = m_idx < M
n_idx = tl.arange(0, N)
if ENABLE_PDL:
tl.extra.cuda.gdc_wait()
x_off = m_idx[:, None] * x_row_stride + n_idx[None, :]
x = tl.load(x_ptr + x_off, mask=m_mask[:, None])
x_fp8 = (x.to(tl.float32) * scale_inv).to(FP8_DTYPE)
out_off = m_idx[:, None] * out_row_stride + n_idx[None, :]
tl.store(out_ptr + out_off, x_fp8, mask=m_mask[:, None])
if ENABLE_PDL:
tl.extra.cuda.gdc_launch_dependents()
def _flatten_to_2d(x: torch.Tensor):
"""Flatten leading dims onto the row stride; returns (M, N, row_stride).
Accepts contiguous tensors and last-dim slice views (e.g.
``kv[..., qk_nope:]``) where leading dims still pack onto a uniform row
stride.
"""
assert x.stride(-1) == 1, f"expected stride-1 inner dim, got stride={x.stride(-1)}"
N = x.shape[-1]
if x.ndim == 1:
return 1, N, N
M = x.numel() // N
row_stride = x.stride(-2)
for d in range(x.ndim - 2):
expected = x.shape[d + 1] * x.stride(d + 1)
if x.stride(d) != expected:
raise ValueError(
f"cannot flatten dim {d}: stride={x.stride(d)} but expected "
f"shape[{d+1}]*stride[{d+1}]={expected}. Tensor shape={tuple(x.shape)}, "
f"stride={tuple(x.stride())}."
)
return M, N, row_stride
def fp8_quantize(
x: torch.Tensor,
scale_inv: float = 1.0,
out: Optional[torch.Tensor] = None,
fp8_dtype: torch.dtype = torch.float8_e4m3fn,
enable_pdl: bool = False,
) -> torch.Tensor:
"""Cast a BF16/FP16 tensor to FP8 with an optional per-tensor scale.
Computes ``out = saturate((x * scale_inv) -> fp8)`` element-wise. When
``scale_inv == 1.0`` the multiply is dropped at compile time (pure cast).
Args:
x: BF16 or FP16 tensor. Must have stride(-1) == 1; leading dims must
pack uniformly onto the row stride (true for contiguous tensors and
for last-dim slice views like ``kv[..., qk_nope:]``).
scale_inv: scalar multiplier applied before the cast (i.e. ``1/scale``).
out: optional pre-allocated FP8 output. Same shape as ``x``.
fp8_dtype: ``torch.float8_e4m3fn`` (default) or ``torch.float8_e5m2``.
enable_pdl: opt into Programmatic Dependent Launch (Hopper+).
Returns:
FP8 tensor with the same shape as ``x``.
"""
assert x.dtype in (
torch.bfloat16,
torch.float16,
), f"fp8_quantize input must be bf16/fp16, got {x.dtype}"
assert fp8_dtype in (torch.float8_e4m3fn, torch.float8_e5m2)
M, N, x_row_stride = _flatten_to_2d(x)
if out is None:
out = torch.empty(x.shape, dtype=fp8_dtype, device=x.device)
else:
assert out.shape == x.shape and out.dtype == fp8_dtype
out_M, _, out_row_stride = _flatten_to_2d(out)
assert out_M == M
fp8_dtype_const = tl.float8e4nv if fp8_dtype is torch.float8_e4m3fn else tl.float8e5
if M <= 2048:
block_m = 4
elif M <= 16384:
block_m = 16
else:
block_m = 32
num_warps = 4
num_stages = 2
grid = (triton.cdiv(M, block_m),)
# launch_pdl is NVIDIA-only; the HIP backend rejects unknown kwargs.
extra_kwargs = {"launch_pdl": True} if enable_pdl else {}
_fp8_quantize_kernel[grid](
x,
out,
scale_inv,
M,
x_row_stride,
out_row_stride,
N=N,
FP8_DTYPE=fp8_dtype_const,
BLOCK_M=block_m,
ENABLE_PDL=enable_pdl,
num_warps=num_warps,
num_stages=num_stages,
**extra_kwargs,
)
return out