Instructions to use replicate/finegrained-fp8 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Kernels
How to use replicate/finegrained-fp8 with Kernels:
# !pip install kernels from kernels import get_kernel # a version (or an explicit revision) is required; see the "Files and versions" tab for the available ones kernel = get_kernel("replicate/finegrained-fp8", version=1) - Notebooks
- Google Colab
- Kaggle
Build uploaded using `kernels`.
Browse files- build/torch-cuda/_ops.py +2 -2
- build/torch-cuda/act_quant.py +6 -2
- build/torch-cuda/batched.py +152 -199
- build/torch-cuda/grouped.py +162 -230
- build/torch-cuda/matmul.py +150 -175
- build/torch-cuda/utils.py +13 -0
- build/torch-rocm/_ops.py +2 -2
- build/torch-rocm/act_quant.py +6 -2
- build/torch-rocm/batched.py +152 -199
- build/torch-rocm/grouped.py +162 -230
- build/torch-rocm/matmul.py +150 -175
- build/torch-rocm/utils.py +13 -0
- build/torch-xpu/_ops.py +2 -2
- build/torch-xpu/act_quant.py +6 -2
- build/torch-xpu/batched.py +152 -199
- build/torch-xpu/grouped.py +162 -230
- build/torch-xpu/matmul.py +150 -175
- build/torch-xpu/utils.py +13 -0
build/torch-cuda/_ops.py
CHANGED
|
@@ -1,8 +1,8 @@
|
|
| 1 |
import torch
|
| 2 |
-
ops = torch.ops.
|
| 3 |
|
| 4 |
def add_op_namespace_prefix(op_name: str):
|
| 5 |
"""
|
| 6 |
Prefix op by namespace.
|
| 7 |
"""
|
| 8 |
-
return f"
|
|
|
|
| 1 |
import torch
|
| 2 |
+
ops = torch.ops._finegrained_fp8_75cbe1b
|
| 3 |
|
| 4 |
def add_op_namespace_prefix(op_name: str):
|
| 5 |
"""
|
| 6 |
Prefix op by namespace.
|
| 7 |
"""
|
| 8 |
+
return f"_finegrained_fp8_75cbe1b::{op_name}"
|
build/torch-cuda/act_quant.py
CHANGED
|
@@ -17,6 +17,8 @@ import triton
|
|
| 17 |
import triton.language as tl
|
| 18 |
from torch.library import triton_op, wrap_triton
|
| 19 |
|
|
|
|
|
|
|
| 20 |
|
| 21 |
_FP8_DTYPE = torch.float8_e4m3fn
|
| 22 |
|
|
@@ -40,10 +42,12 @@ def _fp8_act_quant(
|
|
| 40 |
assert x.is_contiguous()
|
| 41 |
assert x.shape[-1] % block_size == 0
|
| 42 |
y = torch.empty_like(x, dtype=_FP8_DTYPE)
|
|
|
|
| 43 |
s = x.new_empty(*x.size()[:-1], x.size(-1) // block_size, dtype=torch.float32)
|
| 44 |
|
| 45 |
-
|
| 46 |
-
|
|
|
|
| 47 |
return y, s
|
| 48 |
|
| 49 |
|
|
|
|
| 17 |
import triton.language as tl
|
| 18 |
from torch.library import triton_op, wrap_triton
|
| 19 |
|
| 20 |
+
from .utils import device_context
|
| 21 |
+
|
| 22 |
|
| 23 |
_FP8_DTYPE = torch.float8_e4m3fn
|
| 24 |
|
|
|
|
| 42 |
assert x.is_contiguous()
|
| 43 |
assert x.shape[-1] % block_size == 0
|
| 44 |
y = torch.empty_like(x, dtype=_FP8_DTYPE)
|
| 45 |
+
grid = (triton.cdiv(x.numel(), block_size),)
|
| 46 |
s = x.new_empty(*x.size()[:-1], x.size(-1) // block_size, dtype=torch.float32)
|
| 47 |
|
| 48 |
+
with device_context(x.device):
|
| 49 |
+
wrap_triton(_fp8_act_quant_kernel)[grid](x, y, s, BLOCK_SIZE=block_size)
|
| 50 |
+
|
| 51 |
return y, s
|
| 52 |
|
| 53 |
|
build/torch-cuda/batched.py
CHANGED
|
@@ -18,6 +18,8 @@ import triton.language as tl
|
|
| 18 |
from .act_quant import fp8_act_quant
|
| 19 |
from torch.library import triton_op, wrap_triton
|
| 20 |
|
|
|
|
|
|
|
| 21 |
|
| 22 |
@triton.autotune(
|
| 23 |
configs=[
|
|
@@ -32,27 +34,25 @@ def w8a8_block_fp8_matmul_batched_kernel(
|
|
| 32 |
A, # (S, K) raw BF16/FP16 activations
|
| 33 |
B, # (E, N, K) FP8 weight matrices
|
| 34 |
C, # (S, N) output
|
| 35 |
-
Bs, # (E, N //
|
| 36 |
ExpertIds, # (S,) — which expert each batch element routes to
|
| 37 |
# Shape
|
| 38 |
S,
|
| 39 |
N,
|
| 40 |
K,
|
| 41 |
-
|
| 42 |
stride_ak,
|
|
|
|
| 43 |
stride_bk,
|
| 44 |
stride_bn,
|
|
|
|
| 45 |
stride_cn,
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
stride_Ab, # stride between rows in A (one token per program)
|
| 50 |
-
stride_Eb, # stride between experts in B
|
| 51 |
-
stride_Cb, # stride between rows in C (one token per program)
|
| 52 |
-
stride_Esb, # stride between experts in Bs
|
| 53 |
# Meta-parameters
|
| 54 |
-
|
| 55 |
-
|
| 56 |
BLOCK_SIZE_M: tl.constexpr,
|
| 57 |
):
|
| 58 |
"""Block-scale batched FP8 expert matmul kernel.
|
|
@@ -63,40 +63,35 @@ def w8a8_block_fp8_matmul_batched_kernel(
|
|
| 63 |
batch_id = tl.program_id(axis=0)
|
| 64 |
pid_n = tl.program_id(axis=1)
|
| 65 |
|
| 66 |
-
# Advance base pointers to this token's activation row and its expert's
|
| 67 |
-
# weight / scale slice. No pre-gather of weights needed (like in non-fp8 impls)
|
| 68 |
# Cast expert_id to int64 to prevent int32 overflow when computing
|
| 69 |
# expert_id * stride_Eb (e.g. 255 * 9_437_184 > 2^31 for 256 experts of
|
| 70 |
# 3072×3072 FP8 weights).
|
| 71 |
expert_id = tl.load(ExpertIds + batch_id).to(tl.int64)
|
| 72 |
|
| 73 |
-
A = A + batch_id *
|
| 74 |
-
B = B + expert_id *
|
| 75 |
-
C = C + batch_id *
|
| 76 |
-
Bs = Bs + expert_id *
|
| 77 |
|
| 78 |
-
offs_bn = pid_n *
|
| 79 |
-
offs_k = tl.arange(0,
|
| 80 |
a_ptrs = A + tl.arange(0, BLOCK_SIZE_M)[:, None] * 0 + offs_k[None, :] * stride_ak
|
| 81 |
b_ptrs = B + (offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn)
|
| 82 |
|
| 83 |
-
|
| 84 |
-
Bs_ptrs = Bs + offs_bsn * stride_Bs_n
|
| 85 |
|
| 86 |
-
accumulator = tl.zeros((BLOCK_SIZE_M,
|
| 87 |
-
for k in range(0, tl.cdiv(K,
|
| 88 |
# ---- fused fp8_act_quant ----
|
| 89 |
a_raw = tl.load(a_ptrs).to(tl.float32)
|
| 90 |
-
a_s = tl.max(tl.abs(a_raw)) / 448.0
|
| 91 |
a = (a_raw / tl.maximum(a_s, 1e-12)).to(tl.float8e4nv)
|
| 92 |
-
# ----
|
| 93 |
b = tl.load(b_ptrs)
|
| 94 |
-
|
| 95 |
-
offs_ks = k_start // block_k
|
| 96 |
-
b_s = tl.load(Bs_ptrs + offs_ks * stride_Bs_k)
|
| 97 |
accumulator += tl.dot(a, b) * a_s * b_s[None, :]
|
| 98 |
-
a_ptrs +=
|
| 99 |
-
b_ptrs +=
|
| 100 |
|
| 101 |
if C.dtype.element_ty == tl.bfloat16:
|
| 102 |
c = accumulator.to(tl.bfloat16)
|
|
@@ -106,7 +101,7 @@ def w8a8_block_fp8_matmul_batched_kernel(
|
|
| 106 |
c = accumulator.to(tl.float32)
|
| 107 |
|
| 108 |
offs_cm = tl.arange(0, BLOCK_SIZE_M)
|
| 109 |
-
offs_cn = pid_n *
|
| 110 |
c_ptrs = C + offs_cm[:, None] * 0 + stride_cn * offs_cn[None, :]
|
| 111 |
tl.store(c_ptrs, c)
|
| 112 |
|
|
@@ -130,17 +125,17 @@ def w8a8_tensor_fp8_matmul_batched_kernel(
|
|
| 130 |
S,
|
| 131 |
N,
|
| 132 |
K,
|
|
|
|
| 133 |
stride_ak,
|
|
|
|
| 134 |
stride_bk,
|
| 135 |
stride_bn,
|
|
|
|
| 136 |
stride_cn,
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
stride_Esb,
|
| 142 |
-
block_n: tl.constexpr,
|
| 143 |
-
block_k: tl.constexpr,
|
| 144 |
BLOCK_SIZE_M: tl.constexpr,
|
| 145 |
):
|
| 146 |
"""Tensor-scale batched FP8 expert matmul kernel.
|
|
@@ -153,27 +148,28 @@ def w8a8_tensor_fp8_matmul_batched_kernel(
|
|
| 153 |
|
| 154 |
expert_id = tl.load(ExpertIds + batch_id).to(tl.int64)
|
| 155 |
|
| 156 |
-
A = A + batch_id *
|
| 157 |
-
B = B + expert_id *
|
| 158 |
-
C = C + batch_id *
|
| 159 |
-
Bs = Bs + expert_id *
|
| 160 |
|
| 161 |
-
offs_bn = pid_n *
|
| 162 |
-
offs_k = tl.arange(0,
|
| 163 |
a_ptrs = A + tl.arange(0, BLOCK_SIZE_M)[:, None] * 0 + offs_k[None, :] * stride_ak
|
| 164 |
b_ptrs = B + (offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn)
|
| 165 |
|
| 166 |
b_s = tl.load(Bs)
|
| 167 |
-
a_s = tl.load(As + batch_id *
|
| 168 |
|
| 169 |
-
accumulator = tl.zeros((BLOCK_SIZE_M,
|
| 170 |
-
for _ in range(0, tl.cdiv(K,
|
| 171 |
a = tl.load(a_ptrs)
|
| 172 |
b = tl.load(b_ptrs)
|
|
|
|
|
|
|
|
|
|
| 173 |
|
| 174 |
-
|
| 175 |
-
a_ptrs += block_k * stride_ak
|
| 176 |
-
b_ptrs += block_k * stride_bk
|
| 177 |
|
| 178 |
if C.dtype.element_ty == tl.bfloat16:
|
| 179 |
c = accumulator.to(tl.bfloat16)
|
|
@@ -183,7 +179,7 @@ def w8a8_tensor_fp8_matmul_batched_kernel(
|
|
| 183 |
c = accumulator.to(tl.float32)
|
| 184 |
|
| 185 |
offs_cm = tl.arange(0, BLOCK_SIZE_M)
|
| 186 |
-
offs_cn = pid_n *
|
| 187 |
c_ptrs = C + offs_cm[:, None] * 0 + stride_cn * offs_cn[None, :]
|
| 188 |
tl.store(c_ptrs, c)
|
| 189 |
|
|
@@ -194,91 +190,70 @@ def _w8a8_block_fp8_matmul_batched(
|
|
| 194 |
B: torch.Tensor,
|
| 195 |
Bs: torch.Tensor,
|
| 196 |
expert_ids: torch.Tensor,
|
| 197 |
-
block_size: list[int]
|
| 198 |
) -> torch.Tensor:
|
| 199 |
-
"""
|
| 200 |
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
"""
|
| 205 |
-
assert A.ndim == 2, "A must be (S, K)"
|
| 206 |
assert A.is_contiguous(), "A must be contiguous"
|
| 207 |
-
|
| 208 |
-
assert B.ndim == 3, "B must be (E, N, K)"
|
| 209 |
assert B.is_contiguous(), "B must be contiguous"
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
assert Bs.is_contiguous(), "Bs must be contiguous"
|
| 214 |
|
| 215 |
S, K = A.shape
|
| 216 |
-
E, N,
|
| 217 |
|
| 218 |
-
|
| 219 |
-
block_n, block_k
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
# if we have per-tensor quantization, we use 128x128 block size for tiled matmul multiplication
|
| 224 |
-
if block_n == N and block_k == K:
|
| 225 |
-
block_n, block_k = 128, 128
|
| 226 |
-
|
| 227 |
-
# we specifically require block-aligned shapes to keep the kernel simpler
|
| 228 |
assert N % block_n == 0, f"N ({N}) must be divisible by block_n ({block_n})"
|
| 229 |
assert K % block_k == 0, f"K ({K}) must be divisible by block_k ({block_k})"
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
Bs
|
| 235 |
-
|
| 236 |
-
Bs = Bs.expand(E, N // block_n, K // block_k)
|
| 237 |
-
else:
|
| 238 |
-
assert Bs.ndim == 3, (
|
| 239 |
-
"Bs must be either (E,) / (E,1,1) for per-tensor scales or (E,N//block_n,K//block_k)"
|
| 240 |
-
)
|
| 241 |
-
assert Bs.shape[0] == E, (
|
| 242 |
-
f"Bs expert dim mismatch: expected {E}, got {Bs.shape[0]}"
|
| 243 |
-
)
|
| 244 |
-
assert Bs.shape[1] == N // block_n, (
|
| 245 |
-
f"Bs N-block dim mismatch: expected {N // block_n}, got {Bs.shape[1]}"
|
| 246 |
-
)
|
| 247 |
-
assert Bs.shape[2] == K // block_k, (
|
| 248 |
-
f"Bs K-block dim mismatch: expected {K // block_k}, got {Bs.shape[2]}"
|
| 249 |
-
)
|
| 250 |
|
| 251 |
C = A.new_empty(S, N)
|
| 252 |
-
grid = (S, triton.cdiv(N, block_n))
|
| 253 |
# Adaptive BLOCK_SIZE_M: smallest power-of-2 >= M, floored at 16, capped at 128.
|
| 254 |
# Matches the WGMMA tile to the actual row count — smaller tiles use less
|
| 255 |
# register pressure and a better-matched FP8 WGMMA instruction, improving
|
| 256 |
# both accuracy and performance for small M (decode).
|
| 257 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2((S + E - 1) // E), 16), 128)
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
|
|
|
| 282 |
|
| 283 |
return C
|
| 284 |
|
|
@@ -289,71 +264,68 @@ def _w8a8_tensor_fp8_matmul_batched(
|
|
| 289 |
B: torch.Tensor,
|
| 290 |
Bs: torch.Tensor,
|
| 291 |
expert_ids: torch.Tensor,
|
| 292 |
-
block_size: list[int] | None,
|
| 293 |
) -> torch.Tensor:
|
| 294 |
-
"""Tensor-scale batched FP8 matmul
|
| 295 |
-
|
| 296 |
-
Activations are quantized once with per-token tensor scales and multiplied
|
| 297 |
-
with expert-selected FP8 weights using per-expert tensor scales.
|
| 298 |
|
| 299 |
-
|
|
|
|
|
|
|
| 300 |
"""
|
| 301 |
-
assert A.ndim == 2, "A must be (S, K)"
|
| 302 |
assert A.is_contiguous(), "A must be contiguous"
|
| 303 |
-
|
| 304 |
-
assert B.ndim == 3, "B must be (E, N, K)"
|
| 305 |
assert B.is_contiguous(), "B must be contiguous"
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
assert Bs.is_contiguous(), "Bs must be contiguous"
|
| 310 |
|
| 311 |
S, K = A.shape
|
| 312 |
-
E, N,
|
| 313 |
|
|
|
|
| 314 |
if Bs.ndim == 1:
|
|
|
|
| 315 |
Bs = Bs.reshape(E, 1, 1)
|
| 316 |
-
elif Bs.ndim == 3 and Bs.shape[0] == E and Bs.shape[1] == 1 and Bs.shape[2] == 1:
|
| 317 |
-
pass
|
| 318 |
else:
|
| 319 |
-
assert Bs.
|
| 320 |
-
|
| 321 |
-
f"Tensor mode expects Bs shape (E,1,1), got {tuple(Bs.shape)}"
|
| 322 |
)
|
| 323 |
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
assert N % block_n == 0, f"N ({N}) must be divisible by block_n ({block_n})"
|
| 327 |
-
assert K % block_k == 0, f"K ({K}) must be divisible by block_k ({block_k})"
|
| 328 |
-
|
| 329 |
C = A.new_empty(S, N)
|
| 330 |
-
BLOCK_SIZE_M = min(max(triton.next_power_of_2((S + E - 1) // E), 16), 128)
|
| 331 |
qA, As = fp8_act_quant(A, K)
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 357 |
|
| 358 |
return C
|
| 359 |
|
|
@@ -363,25 +335,13 @@ def w8a8_block_fp8_matmul_batched(
|
|
| 363 |
B: torch.Tensor,
|
| 364 |
Bs: torch.Tensor,
|
| 365 |
expert_ids: torch.Tensor,
|
| 366 |
-
block_size: list[int]
|
| 367 |
) -> torch.Tensor:
|
| 368 |
-
"""
|
| 369 |
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
``(S, N, K)`` weight gather needed — and accumulates in float32.
|
| 374 |
-
|
| 375 |
-
Args:
|
| 376 |
-
A: Raw activation matrix ``[S, K]`` in bf16/fp16/fp32.
|
| 377 |
-
B: Stacked expert weight tensor ``[E, N, K]`` in ``float8_e4m3fn``.
|
| 378 |
-
Bs: Expert weight scales, accepted as ``[E, nb, kb]`` (block)
|
| 379 |
-
or ``[E]`` / ``[E,1,1]`` (per-tensor; expanded internally).
|
| 380 |
-
expert_ids: Expert index per token ``[S]``, values in ``[0, E)``.
|
| 381 |
-
block_size: ``[block_n, block_k]`` quantization block dimensions, e.g. ``[128, 128]``.
|
| 382 |
-
|
| 383 |
-
Returns:
|
| 384 |
-
Output tensor ``[S, N]`` in the same dtype as ``A``.
|
| 385 |
"""
|
| 386 |
return torch.ops.finegrained_fp8.w8a8_block_fp8_matmul_batched(
|
| 387 |
A, B, Bs, expert_ids, block_size
|
|
@@ -393,22 +353,15 @@ def w8a8_tensor_fp8_matmul_batched(
|
|
| 393 |
B: torch.Tensor,
|
| 394 |
Bs: torch.Tensor,
|
| 395 |
expert_ids: torch.Tensor,
|
| 396 |
-
block_size: list[int] | None,
|
| 397 |
) -> torch.Tensor:
|
| 398 |
-
"""Tensor-scale batched
|
| 399 |
-
|
| 400 |
-
Args:
|
| 401 |
-
A: Raw activation matrix ``[S, K]`` in bf16/fp16/fp32.
|
| 402 |
-
B: Stacked expert weight tensor ``[E, N, K]`` in ``float8_e4m3fn``.
|
| 403 |
-
Bs: Per-expert tensor scales ``[E]`` or ``[E,1,1]``.
|
| 404 |
-
expert_ids: Expert index per token ``[S]``, values in ``[0, E)``.
|
| 405 |
-
block_size: Kept for API consistency; tensor path derives tile sizes from ``N`` and ``K``.
|
| 406 |
|
| 407 |
-
|
| 408 |
-
|
|
|
|
| 409 |
"""
|
| 410 |
return torch.ops.finegrained_fp8.w8a8_tensor_fp8_matmul_batched(
|
| 411 |
-
A, B, Bs, expert_ids
|
| 412 |
)
|
| 413 |
|
| 414 |
|
|
@@ -432,6 +385,6 @@ def w8a8_fp8_matmul_batched(
|
|
| 432 |
if block_size is None or (
|
| 433 |
block_size[0] == B.size(1) and block_size[1] == B.size(2)
|
| 434 |
):
|
| 435 |
-
return w8a8_tensor_fp8_matmul_batched(A, B, Bs, expert_ids
|
| 436 |
|
| 437 |
return w8a8_block_fp8_matmul_batched(A, B, Bs, expert_ids, block_size)
|
|
|
|
| 18 |
from .act_quant import fp8_act_quant
|
| 19 |
from torch.library import triton_op, wrap_triton
|
| 20 |
|
| 21 |
+
from .utils import device_context
|
| 22 |
+
|
| 23 |
|
| 24 |
@triton.autotune(
|
| 25 |
configs=[
|
|
|
|
| 34 |
A, # (S, K) raw BF16/FP16 activations
|
| 35 |
B, # (E, N, K) FP8 weight matrices
|
| 36 |
C, # (S, N) output
|
| 37 |
+
Bs, # (E, N // BLOCK_SIZE_N, K // BLOCK_SIZE_K) weight scales
|
| 38 |
ExpertIds, # (S,) — which expert each batch element routes to
|
| 39 |
# Shape
|
| 40 |
S,
|
| 41 |
N,
|
| 42 |
K,
|
| 43 |
+
stride_am,
|
| 44 |
stride_ak,
|
| 45 |
+
stride_be,
|
| 46 |
stride_bk,
|
| 47 |
stride_bn,
|
| 48 |
+
stride_cm,
|
| 49 |
stride_cn,
|
| 50 |
+
stride_bs_e,
|
| 51 |
+
stride_bs_k,
|
| 52 |
+
stride_bs_n,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
# Meta-parameters
|
| 54 |
+
BLOCK_SIZE_N: tl.constexpr,
|
| 55 |
+
BLOCK_SIZE_K: tl.constexpr,
|
| 56 |
BLOCK_SIZE_M: tl.constexpr,
|
| 57 |
):
|
| 58 |
"""Block-scale batched FP8 expert matmul kernel.
|
|
|
|
| 63 |
batch_id = tl.program_id(axis=0)
|
| 64 |
pid_n = tl.program_id(axis=1)
|
| 65 |
|
|
|
|
|
|
|
| 66 |
# Cast expert_id to int64 to prevent int32 overflow when computing
|
| 67 |
# expert_id * stride_Eb (e.g. 255 * 9_437_184 > 2^31 for 256 experts of
|
| 68 |
# 3072×3072 FP8 weights).
|
| 69 |
expert_id = tl.load(ExpertIds + batch_id).to(tl.int64)
|
| 70 |
|
| 71 |
+
A = A + batch_id * stride_am
|
| 72 |
+
B = B + expert_id * stride_be
|
| 73 |
+
C = C + batch_id * stride_cm
|
| 74 |
+
Bs = Bs + expert_id * stride_bs_e
|
| 75 |
|
| 76 |
+
offs_bn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 77 |
+
offs_k = tl.arange(0, BLOCK_SIZE_K)
|
| 78 |
a_ptrs = A + tl.arange(0, BLOCK_SIZE_M)[:, None] * 0 + offs_k[None, :] * stride_ak
|
| 79 |
b_ptrs = B + (offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn)
|
| 80 |
|
| 81 |
+
bs_ptrs = Bs + pid_n * stride_bs_n
|
|
|
|
| 82 |
|
| 83 |
+
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 84 |
+
for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
|
| 85 |
# ---- fused fp8_act_quant ----
|
| 86 |
a_raw = tl.load(a_ptrs).to(tl.float32)
|
| 87 |
+
a_s = tl.max(tl.abs(a_raw)) / 448.0
|
| 88 |
a = (a_raw / tl.maximum(a_s, 1e-12)).to(tl.float8e4nv)
|
| 89 |
+
# ---- matmul ----
|
| 90 |
b = tl.load(b_ptrs)
|
| 91 |
+
b_s = tl.load(bs_ptrs + k * stride_bs_k)
|
|
|
|
|
|
|
| 92 |
accumulator += tl.dot(a, b) * a_s * b_s[None, :]
|
| 93 |
+
a_ptrs += BLOCK_SIZE_K * stride_ak
|
| 94 |
+
b_ptrs += BLOCK_SIZE_K * stride_bk
|
| 95 |
|
| 96 |
if C.dtype.element_ty == tl.bfloat16:
|
| 97 |
c = accumulator.to(tl.bfloat16)
|
|
|
|
| 101 |
c = accumulator.to(tl.float32)
|
| 102 |
|
| 103 |
offs_cm = tl.arange(0, BLOCK_SIZE_M)
|
| 104 |
+
offs_cn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 105 |
c_ptrs = C + offs_cm[:, None] * 0 + stride_cn * offs_cn[None, :]
|
| 106 |
tl.store(c_ptrs, c)
|
| 107 |
|
|
|
|
| 125 |
S,
|
| 126 |
N,
|
| 127 |
K,
|
| 128 |
+
stride_am,
|
| 129 |
stride_ak,
|
| 130 |
+
stride_be,
|
| 131 |
stride_bk,
|
| 132 |
stride_bn,
|
| 133 |
+
stride_cm,
|
| 134 |
stride_cn,
|
| 135 |
+
stride_as_m,
|
| 136 |
+
stride_bs_e,
|
| 137 |
+
BLOCK_SIZE_N: tl.constexpr,
|
| 138 |
+
BLOCK_SIZE_K: tl.constexpr,
|
|
|
|
|
|
|
|
|
|
| 139 |
BLOCK_SIZE_M: tl.constexpr,
|
| 140 |
):
|
| 141 |
"""Tensor-scale batched FP8 expert matmul kernel.
|
|
|
|
| 148 |
|
| 149 |
expert_id = tl.load(ExpertIds + batch_id).to(tl.int64)
|
| 150 |
|
| 151 |
+
A = A + batch_id * stride_am
|
| 152 |
+
B = B + expert_id * stride_be
|
| 153 |
+
C = C + batch_id * stride_cm
|
| 154 |
+
Bs = Bs + expert_id * stride_bs_e
|
| 155 |
|
| 156 |
+
offs_bn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 157 |
+
offs_k = tl.arange(0, BLOCK_SIZE_K)
|
| 158 |
a_ptrs = A + tl.arange(0, BLOCK_SIZE_M)[:, None] * 0 + offs_k[None, :] * stride_ak
|
| 159 |
b_ptrs = B + (offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn)
|
| 160 |
|
| 161 |
b_s = tl.load(Bs)
|
| 162 |
+
a_s = tl.load(As + batch_id * stride_as_m)
|
| 163 |
|
| 164 |
+
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 165 |
+
for _ in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
|
| 166 |
a = tl.load(a_ptrs)
|
| 167 |
b = tl.load(b_ptrs)
|
| 168 |
+
accumulator += tl.dot(a, b)
|
| 169 |
+
a_ptrs += BLOCK_SIZE_K * stride_ak
|
| 170 |
+
b_ptrs += BLOCK_SIZE_K * stride_bk
|
| 171 |
|
| 172 |
+
accumulator = accumulator * a_s * b_s
|
|
|
|
|
|
|
| 173 |
|
| 174 |
if C.dtype.element_ty == tl.bfloat16:
|
| 175 |
c = accumulator.to(tl.bfloat16)
|
|
|
|
| 179 |
c = accumulator.to(tl.float32)
|
| 180 |
|
| 181 |
offs_cm = tl.arange(0, BLOCK_SIZE_M)
|
| 182 |
+
offs_cn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 183 |
c_ptrs = C + offs_cm[:, None] * 0 + stride_cn * offs_cn[None, :]
|
| 184 |
tl.store(c_ptrs, c)
|
| 185 |
|
|
|
|
| 190 |
B: torch.Tensor,
|
| 191 |
Bs: torch.Tensor,
|
| 192 |
expert_ids: torch.Tensor,
|
| 193 |
+
block_size: list[int],
|
| 194 |
) -> torch.Tensor:
|
| 195 |
+
"""Block-scale batched FP8 matmul: C[s] = A[s] @ B[expert_ids[s]].T, with fused act quant.
|
| 196 |
|
| 197 |
+
A: (S, K) raw bf16/fp16 activations
|
| 198 |
+
B: (E, N, K) FP8 expert weights
|
| 199 |
+
Bs: (E, N // block_n, K // block_k) per-block weight scales
|
| 200 |
"""
|
| 201 |
+
assert A.ndim == 2, f"A must be 2D (S, K), got ndim={A.ndim}"
|
| 202 |
assert A.is_contiguous(), "A must be contiguous"
|
| 203 |
+
assert B.ndim == 3, f"B must be 3D (E, N, K), got ndim={B.ndim}"
|
|
|
|
| 204 |
assert B.is_contiguous(), "B must be contiguous"
|
| 205 |
+
assert A.shape[1] == B.shape[2], (
|
| 206 |
+
f"K mismatch: A has K={A.shape[1]}, B has K={B.shape[2]}"
|
| 207 |
+
)
|
|
|
|
| 208 |
|
| 209 |
S, K = A.shape
|
| 210 |
+
E, N, _ = B.shape
|
| 211 |
|
| 212 |
+
assert len(block_size) == 2, (
|
| 213 |
+
f"block_size must be [block_n, block_k], got {block_size}"
|
| 214 |
+
)
|
| 215 |
+
block_n, block_k = block_size[0], block_size[1]
|
| 216 |
+
# MoE expert dimensions must be block-aligned; non-aligned N/K is not supported.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
assert N % block_n == 0, f"N ({N}) must be divisible by block_n ({block_n})"
|
| 218 |
assert K % block_k == 0, f"K ({K}) must be divisible by block_k ({block_k})"
|
| 219 |
+
assert Bs.ndim == 3, (
|
| 220 |
+
f"Bs must be 3D (E, N//block_n, K//block_k), got ndim={Bs.ndim}"
|
| 221 |
+
)
|
| 222 |
+
assert Bs.shape == (E, N // block_n, K // block_k), (
|
| 223 |
+
f"Bs shape {tuple(Bs.shape)} != expected ({E}, {N // block_n}, {K // block_k})"
|
| 224 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
|
| 226 |
C = A.new_empty(S, N)
|
|
|
|
| 227 |
# Adaptive BLOCK_SIZE_M: smallest power-of-2 >= M, floored at 16, capped at 128.
|
| 228 |
# Matches the WGMMA tile to the actual row count — smaller tiles use less
|
| 229 |
# register pressure and a better-matched FP8 WGMMA instruction, improving
|
| 230 |
# both accuracy and performance for small M (decode).
|
| 231 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2((S + E - 1) // E), 16), 128)
|
| 232 |
+
grid = (S, triton.cdiv(N, block_n))
|
| 233 |
+
with device_context(A.device):
|
| 234 |
+
wrap_triton(w8a8_block_fp8_matmul_batched_kernel)[grid](
|
| 235 |
+
A,
|
| 236 |
+
B,
|
| 237 |
+
C,
|
| 238 |
+
Bs,
|
| 239 |
+
expert_ids,
|
| 240 |
+
S,
|
| 241 |
+
N,
|
| 242 |
+
K,
|
| 243 |
+
A.stride(0),
|
| 244 |
+
A.stride(1),
|
| 245 |
+
B.stride(0),
|
| 246 |
+
B.stride(2),
|
| 247 |
+
B.stride(1),
|
| 248 |
+
C.stride(0),
|
| 249 |
+
C.stride(1),
|
| 250 |
+
Bs.stride(0),
|
| 251 |
+
Bs.stride(2),
|
| 252 |
+
Bs.stride(1),
|
| 253 |
+
BLOCK_SIZE_N=block_n,
|
| 254 |
+
BLOCK_SIZE_K=block_k,
|
| 255 |
+
BLOCK_SIZE_M=BLOCK_SIZE_M,
|
| 256 |
+
)
|
| 257 |
|
| 258 |
return C
|
| 259 |
|
|
|
|
| 264 |
B: torch.Tensor,
|
| 265 |
Bs: torch.Tensor,
|
| 266 |
expert_ids: torch.Tensor,
|
|
|
|
| 267 |
) -> torch.Tensor:
|
| 268 |
+
"""Tensor-scale batched FP8 matmul: C[s] = A[s] @ B[expert_ids[s]].T, with fused act quant.
|
|
|
|
|
|
|
|
|
|
| 269 |
|
| 270 |
+
A: (S, K) raw bf16/fp16 activations
|
| 271 |
+
B: (E, N, K) FP8 expert weights
|
| 272 |
+
Bs: (E,) or (E, 1, 1) per-expert weight scales
|
| 273 |
"""
|
| 274 |
+
assert A.ndim == 2, f"A must be 2D (S, K), got ndim={A.ndim}"
|
| 275 |
assert A.is_contiguous(), "A must be contiguous"
|
| 276 |
+
assert B.ndim == 3, f"B must be 3D (E, N, K), got ndim={B.ndim}"
|
|
|
|
| 277 |
assert B.is_contiguous(), "B must be contiguous"
|
| 278 |
+
assert A.shape[1] == B.shape[2], (
|
| 279 |
+
f"K mismatch: A has K={A.shape[1]}, B has K={B.shape[2]}"
|
| 280 |
+
)
|
|
|
|
| 281 |
|
| 282 |
S, K = A.shape
|
| 283 |
+
E, N, _ = B.shape
|
| 284 |
|
| 285 |
+
# Normalize Bs to (E, 1, 1)
|
| 286 |
if Bs.ndim == 1:
|
| 287 |
+
assert Bs.shape[0] == E, f"Bs shape {tuple(Bs.shape)} != expected ({E},)"
|
| 288 |
Bs = Bs.reshape(E, 1, 1)
|
|
|
|
|
|
|
| 289 |
else:
|
| 290 |
+
assert Bs.shape == (E, 1, 1), (
|
| 291 |
+
f"Bs shape {tuple(Bs.shape)} != expected ({E}, 1, 1)"
|
|
|
|
| 292 |
)
|
| 293 |
|
| 294 |
+
BLOCK_SIZE_N = 128
|
| 295 |
+
BLOCK_SIZE_K = 128
|
|
|
|
|
|
|
|
|
|
| 296 |
C = A.new_empty(S, N)
|
|
|
|
| 297 |
qA, As = fp8_act_quant(A, K)
|
| 298 |
+
grid = (S, triton.cdiv(N, BLOCK_SIZE_N))
|
| 299 |
+
# Adaptive BLOCK_SIZE_M: smallest power-of-2 >= M, floored at 16, capped at 128.
|
| 300 |
+
# Matches the WGMMA tile to the actual row count — smaller tiles use less
|
| 301 |
+
# register pressure and a better-matched FP8 WGMMA instruction, improving
|
| 302 |
+
# both accuracy and performance for small M (decode).
|
| 303 |
+
BLOCK_SIZE_M = min(max(triton.next_power_of_2((S + E - 1) // E), 16), 128)
|
| 304 |
+
grid = (S, triton.cdiv(N, BLOCK_SIZE_N))
|
| 305 |
+
with device_context(A.device):
|
| 306 |
+
wrap_triton(w8a8_tensor_fp8_matmul_batched_kernel)[grid](
|
| 307 |
+
qA,
|
| 308 |
+
B,
|
| 309 |
+
C,
|
| 310 |
+
As,
|
| 311 |
+
Bs,
|
| 312 |
+
expert_ids,
|
| 313 |
+
S,
|
| 314 |
+
N,
|
| 315 |
+
K,
|
| 316 |
+
qA.stride(0),
|
| 317 |
+
qA.stride(1),
|
| 318 |
+
B.stride(0),
|
| 319 |
+
B.stride(2),
|
| 320 |
+
B.stride(1),
|
| 321 |
+
C.stride(0),
|
| 322 |
+
C.stride(1),
|
| 323 |
+
As.stride(0),
|
| 324 |
+
Bs.stride(0),
|
| 325 |
+
BLOCK_SIZE_N=BLOCK_SIZE_N,
|
| 326 |
+
BLOCK_SIZE_K=BLOCK_SIZE_K,
|
| 327 |
+
BLOCK_SIZE_M=BLOCK_SIZE_M,
|
| 328 |
+
)
|
| 329 |
|
| 330 |
return C
|
| 331 |
|
|
|
|
| 335 |
B: torch.Tensor,
|
| 336 |
Bs: torch.Tensor,
|
| 337 |
expert_ids: torch.Tensor,
|
| 338 |
+
block_size: list[int],
|
| 339 |
) -> torch.Tensor:
|
| 340 |
+
"""Block-scale batched FP8 matmul with fused activation quantization.
|
| 341 |
|
| 342 |
+
A: (S, K) raw activations, bf16/fp16/fp32
|
| 343 |
+
B: (E, N, K) FP8 expert weights
|
| 344 |
+
Bs: (E, N // block_n, K // block_k) per-block weight scales
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 345 |
"""
|
| 346 |
return torch.ops.finegrained_fp8.w8a8_block_fp8_matmul_batched(
|
| 347 |
A, B, Bs, expert_ids, block_size
|
|
|
|
| 353 |
B: torch.Tensor,
|
| 354 |
Bs: torch.Tensor,
|
| 355 |
expert_ids: torch.Tensor,
|
|
|
|
| 356 |
) -> torch.Tensor:
|
| 357 |
+
"""Tensor-scale batched FP8 matmul with fused activation quantization.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
|
| 359 |
+
A: (S, K) raw activations, bf16/fp16/fp32
|
| 360 |
+
B: (E, N, K) FP8 expert weights
|
| 361 |
+
Bs: (E,) or (E, 1, 1) per-expert weight scales
|
| 362 |
"""
|
| 363 |
return torch.ops.finegrained_fp8.w8a8_tensor_fp8_matmul_batched(
|
| 364 |
+
A, B, Bs, expert_ids
|
| 365 |
)
|
| 366 |
|
| 367 |
|
|
|
|
| 385 |
if block_size is None or (
|
| 386 |
block_size[0] == B.size(1) and block_size[1] == B.size(2)
|
| 387 |
):
|
| 388 |
+
return w8a8_tensor_fp8_matmul_batched(A, B, Bs, expert_ids)
|
| 389 |
|
| 390 |
return w8a8_block_fp8_matmul_batched(A, B, Bs, expert_ids, block_size)
|
build/torch-cuda/grouped.py
CHANGED
|
@@ -18,6 +18,8 @@ import triton.language as tl
|
|
| 18 |
from .act_quant import fp8_act_quant
|
| 19 |
from torch.library import triton_op, wrap_triton
|
| 20 |
|
|
|
|
|
|
|
| 21 |
|
| 22 |
@triton.autotune(
|
| 23 |
configs=[
|
|
@@ -25,14 +27,14 @@ from torch.library import triton_op, wrap_triton
|
|
| 25 |
for w in [2, 4, 8, 16]
|
| 26 |
for s in [2, 3, 4, 5]
|
| 27 |
],
|
| 28 |
-
key=["N", "K"],
|
| 29 |
)
|
| 30 |
@triton.jit
|
| 31 |
def w8a8_block_fp8_matmul_grouped_kernel(
|
| 32 |
A, # (S, K) raw BF16/FP16 activations, sorted/grouped by expert id
|
| 33 |
B, # (E, N, K) FP8 weight matrices
|
| 34 |
C, # (S, N) output
|
| 35 |
-
Bs, # (E, N //
|
| 36 |
Offsets, # (E,) int32 — cumulative row-end per expert
|
| 37 |
TileOffsets, # (E,) int32 — cumulative tile-end per expert
|
| 38 |
# Shape
|
|
@@ -42,19 +44,19 @@ def w8a8_block_fp8_matmul_grouped_kernel(
|
|
| 42 |
# Strides
|
| 43 |
stride_am,
|
| 44 |
stride_ak,
|
| 45 |
-
|
| 46 |
stride_bk,
|
| 47 |
stride_bn,
|
| 48 |
stride_cm,
|
| 49 |
stride_cn,
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
# Meta-parameters
|
| 54 |
-
block_n: tl.constexpr,
|
| 55 |
-
block_k: tl.constexpr,
|
| 56 |
-
BLOCK_SIZE_M: tl.constexpr,
|
| 57 |
NUM_EXPERTS: tl.constexpr,
|
|
|
|
|
|
|
|
|
|
| 58 |
NUM_EXPERTS_BIT_LENGTH: tl.constexpr,
|
| 59 |
):
|
| 60 |
"""Block-scale grouped FP8 expert matmul kernel.
|
|
@@ -87,12 +89,11 @@ def w8a8_block_fp8_matmul_grouped_kernel(
|
|
| 87 |
hi = tl.where(is_left, hi, mid)
|
| 88 |
|
| 89 |
# Cast expert_id to int64 to prevent int32 overflow when computing
|
| 90 |
-
# expert_id *
|
| 91 |
# 3072×3072 FP8 weights).
|
| 92 |
expert_id = lo.to(tl.int64)
|
| 93 |
|
| 94 |
prev_eid = tl.maximum(expert_id - 1, 0)
|
| 95 |
-
|
| 96 |
expert_start = tl.where(expert_id == 0, 0, tl.load(Offsets + prev_eid))
|
| 97 |
expert_end = tl.load(Offsets + expert_id)
|
| 98 |
M_expert = expert_end - expert_start
|
|
@@ -105,31 +106,30 @@ def w8a8_block_fp8_matmul_grouped_kernel(
|
|
| 105 |
row_mask = offs_am < M_expert
|
| 106 |
offs_global_m = expert_start + offs_am
|
| 107 |
|
| 108 |
-
offs_bn = pid_n *
|
| 109 |
-
offs_k = tl.arange(0,
|
| 110 |
|
| 111 |
a_ptrs = A + offs_global_m[:, None] * stride_am + offs_k[None, :] * stride_ak
|
| 112 |
b_ptrs = (
|
| 113 |
B
|
| 114 |
-
+ expert_id *
|
| 115 |
+ offs_k[:, None] * stride_bk
|
| 116 |
+ offs_bn[None, :] * stride_bn
|
| 117 |
)
|
| 118 |
-
|
| 119 |
-
Bs_ptrs = Bs + expert_id * stride_Esb + offs_bsn * stride_Bsn
|
| 120 |
|
| 121 |
-
accumulator = tl.zeros((BLOCK_SIZE_M,
|
| 122 |
-
for k in range(0, tl.cdiv(K,
|
| 123 |
# ---- fused fp8_act_quant ----
|
| 124 |
a_raw = tl.load(a_ptrs, mask=row_mask[:, None], other=0.0).to(tl.float32)
|
| 125 |
-
a_s = tl.max(tl.abs(a_raw), axis=1) / 448.0
|
| 126 |
a = (a_raw / tl.maximum(a_s[:, None], 1e-12)).to(tl.float8e4nv)
|
| 127 |
-
# ----
|
| 128 |
b = tl.load(b_ptrs)
|
| 129 |
-
b_s = tl.load(
|
| 130 |
accumulator += tl.dot(a, b) * a_s[:, None] * b_s[None, :]
|
| 131 |
-
a_ptrs +=
|
| 132 |
-
b_ptrs +=
|
| 133 |
|
| 134 |
if C.dtype.element_ty == tl.bfloat16:
|
| 135 |
c = accumulator.to(tl.bfloat16)
|
|
@@ -149,11 +149,11 @@ def w8a8_block_fp8_matmul_grouped_kernel(
|
|
| 149 |
for w in [2, 4, 8, 16]
|
| 150 |
for s in [2, 3, 4, 5]
|
| 151 |
],
|
| 152 |
-
key=["N", "K"],
|
| 153 |
)
|
| 154 |
@triton.jit
|
| 155 |
def w8a8_tensor_fp8_matmul_grouped_kernel(
|
| 156 |
-
A, # (S, K)
|
| 157 |
B, # (E, N, K) FP8 weight matrices
|
| 158 |
C, # (S, N) output
|
| 159 |
As, # (S, 1) activation scales
|
|
@@ -165,17 +165,17 @@ def w8a8_tensor_fp8_matmul_grouped_kernel(
|
|
| 165 |
K,
|
| 166 |
stride_am,
|
| 167 |
stride_ak,
|
| 168 |
-
|
| 169 |
stride_bk,
|
| 170 |
stride_bn,
|
| 171 |
stride_cm,
|
| 172 |
stride_cn,
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
block_n: tl.constexpr,
|
| 176 |
-
block_k: tl.constexpr,
|
| 177 |
-
BLOCK_SIZE_M: tl.constexpr,
|
| 178 |
NUM_EXPERTS: tl.constexpr,
|
|
|
|
|
|
|
|
|
|
| 179 |
NUM_EXPERTS_BIT_LENGTH: tl.constexpr,
|
| 180 |
):
|
| 181 |
"""Tensor-scale grouped FP8 expert matmul kernel.
|
|
@@ -213,28 +213,30 @@ def w8a8_tensor_fp8_matmul_grouped_kernel(
|
|
| 213 |
row_mask = offs_am < M_expert
|
| 214 |
offs_global_m = expert_start + offs_am
|
| 215 |
|
| 216 |
-
offs_bn = pid_n *
|
| 217 |
-
offs_k = tl.arange(0,
|
| 218 |
|
| 219 |
a_ptrs = A + offs_global_m[:, None] * stride_am + offs_k[None, :] * stride_ak
|
| 220 |
b_ptrs = (
|
| 221 |
B
|
| 222 |
-
+ expert_id *
|
| 223 |
+ offs_k[:, None] * stride_bk
|
| 224 |
+ offs_bn[None, :] * stride_bn
|
| 225 |
)
|
| 226 |
|
| 227 |
-
a_s = tl.load(As + offs_global_m *
|
| 228 |
-
b_s = tl.load(Bs + expert_id *
|
| 229 |
|
| 230 |
-
accumulator = tl.zeros((BLOCK_SIZE_M,
|
| 231 |
-
for _ in range(0, tl.cdiv(K,
|
| 232 |
a = tl.load(a_ptrs, mask=row_mask[:, None], other=0.0)
|
| 233 |
b = tl.load(b_ptrs)
|
| 234 |
|
| 235 |
-
accumulator += tl.dot(a, b)
|
| 236 |
-
a_ptrs +=
|
| 237 |
-
b_ptrs +=
|
|
|
|
|
|
|
| 238 |
|
| 239 |
if C.dtype.element_ty == tl.bfloat16:
|
| 240 |
c = accumulator.to(tl.bfloat16)
|
|
@@ -255,104 +257,78 @@ def _w8a8_block_fp8_matmul_grouped(
|
|
| 255 |
Bs: torch.Tensor,
|
| 256 |
offsets: torch.Tensor,
|
| 257 |
tokens_per_expert: torch.Tensor,
|
| 258 |
-
block_size: list[int]
|
| 259 |
-
allow_sync: bool = False,
|
| 260 |
) -> torch.Tensor:
|
| 261 |
-
"""
|
| 262 |
|
| 263 |
-
|
| 264 |
-
|
|
|
|
| 265 |
"""
|
| 266 |
-
assert A.ndim == 2, "A must be (S, K)"
|
| 267 |
assert A.is_contiguous(), "A must be contiguous"
|
| 268 |
-
|
| 269 |
-
assert B.ndim == 3, "B must be (E, N, K)"
|
| 270 |
assert B.is_contiguous(), "B must be contiguous"
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
assert offsets.is_contiguous(), "offsets must be contiguous"
|
| 275 |
-
assert Bs.is_contiguous(), "Bs must be contiguous"
|
| 276 |
|
| 277 |
S, K = A.shape
|
| 278 |
-
E, N,
|
| 279 |
-
|
| 280 |
-
if block_size is None:
|
| 281 |
-
block_n, block_k = 128, 128
|
| 282 |
-
else:
|
| 283 |
-
block_n, block_k = block_size[0], block_size[1]
|
| 284 |
-
|
| 285 |
-
if block_n == N and block_k == K:
|
| 286 |
-
block_n, block_k = 128, 128
|
| 287 |
|
| 288 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 289 |
assert N % block_n == 0, f"N ({N}) must be divisible by block_n ({block_n})"
|
| 290 |
assert K % block_k == 0, f"K ({K}) must be divisible by block_k ({block_k})"
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
Bs
|
| 296 |
-
|
| 297 |
-
Bs = Bs.expand(E, N // block_n, K // block_k)
|
| 298 |
-
else:
|
| 299 |
-
assert Bs.ndim == 3, (
|
| 300 |
-
"Bs must be either (E,) / (E,1,1) for per-tensor scales or (E,N//block_n,K//block_k)"
|
| 301 |
-
)
|
| 302 |
-
assert Bs.shape[0] == E, (
|
| 303 |
-
f"Bs expert dim mismatch: expected {E}, got {Bs.shape[0]}"
|
| 304 |
-
)
|
| 305 |
-
assert Bs.shape[1] == N // block_n, (
|
| 306 |
-
f"Bs N-block dim mismatch: expected {N // block_n}, got {Bs.shape[1]}"
|
| 307 |
-
)
|
| 308 |
-
assert Bs.shape[2] == K // block_k, (
|
| 309 |
-
f"Bs K-block dim mismatch: expected {K // block_k}, got {Bs.shape[2]}"
|
| 310 |
-
)
|
| 311 |
|
| 312 |
C = A.new_empty(S, N)
|
| 313 |
-
|
| 314 |
# Adaptive BLOCK_SIZE_M: match tile to average tokens per expert.
|
| 315 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2((S + E - 1) // E), 16), 128)
|
| 316 |
tiles_per_expert = (tokens_per_expert + BLOCK_SIZE_M - 1) // BLOCK_SIZE_M
|
| 317 |
tile_offsets = torch.cumsum(tiles_per_expert, dim=0).to(torch.int32)
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
# Using a static upper bound keeps the grid size data-independent, which is
|
| 324 |
-
# required for cuda-graph compatibility. Programs beyond the real tile count
|
| 325 |
-
# exit immediately via the early-return guard inside the kernel.
|
| 326 |
-
max_M_tiles = triton.cdiv(S, BLOCK_SIZE_M) + E
|
| 327 |
-
|
| 328 |
grid = (max_M_tiles, triton.cdiv(N, block_n))
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
|
|
|
| 356 |
|
| 357 |
return C
|
| 358 |
|
|
@@ -364,88 +340,74 @@ def _w8a8_tensor_fp8_matmul_grouped(
|
|
| 364 |
Bs: torch.Tensor,
|
| 365 |
offsets: torch.Tensor,
|
| 366 |
tokens_per_expert: torch.Tensor,
|
| 367 |
-
block_size: list[int] | None,
|
| 368 |
-
allow_sync: bool = False,
|
| 369 |
) -> torch.Tensor:
|
| 370 |
-
"""Tensor-scale grouped FP8 matmul
|
| 371 |
-
|
| 372 |
-
Uses the same grouped scheduling as block mode, but with per-token tensor
|
| 373 |
-
activation scales and per-expert tensor weight scales.
|
| 374 |
|
| 375 |
-
|
|
|
|
|
|
|
| 376 |
"""
|
| 377 |
-
assert A.ndim == 2, "A must be (S, K)"
|
| 378 |
assert A.is_contiguous(), "A must be contiguous"
|
| 379 |
-
|
| 380 |
-
assert B.ndim == 3, "B must be (E, N, K)"
|
| 381 |
assert B.is_contiguous(), "B must be contiguous"
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
assert offsets.is_contiguous(), "offsets must be contiguous"
|
| 386 |
-
assert Bs.is_contiguous(), "Bs must be contiguous"
|
| 387 |
|
| 388 |
S, K = A.shape
|
| 389 |
-
E, N,
|
| 390 |
|
|
|
|
| 391 |
if Bs.ndim == 1:
|
|
|
|
| 392 |
Bs = Bs.reshape(E, 1, 1)
|
| 393 |
-
elif Bs.ndim == 3 and Bs.shape[0] == E and Bs.shape[1] == 1 and Bs.shape[2] == 1:
|
| 394 |
-
pass
|
| 395 |
else:
|
| 396 |
-
assert Bs.
|
| 397 |
-
|
| 398 |
-
f"Tensor mode expects Bs shape (E,1,1), got {tuple(Bs.shape)}"
|
| 399 |
)
|
| 400 |
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
assert N % block_n == 0, f"N ({N}) must be divisible by block_n ({block_n})"
|
| 404 |
-
assert K % block_k == 0, f"K ({K}) must be divisible by block_k ({block_k})"
|
| 405 |
-
|
| 406 |
C = A.new_empty(S, N)
|
| 407 |
-
|
| 408 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2((S + E - 1) // E), 16), 128)
|
| 409 |
tiles_per_expert = (tokens_per_expert + BLOCK_SIZE_M - 1) // BLOCK_SIZE_M
|
| 410 |
tile_offsets = torch.cumsum(tiles_per_expert, dim=0).to(torch.int32)
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
BLOCK_SIZE_M=BLOCK_SIZE_M,
|
| 446 |
-
NUM_EXPERTS=E,
|
| 447 |
-
NUM_EXPERTS_BIT_LENGTH=E.bit_length(),
|
| 448 |
-
)
|
| 449 |
|
| 450 |
return C
|
| 451 |
|
|
@@ -456,33 +418,16 @@ def w8a8_block_fp8_matmul_grouped(
|
|
| 456 |
Bs: torch.Tensor,
|
| 457 |
offsets: torch.Tensor,
|
| 458 |
tokens_per_expert: torch.Tensor,
|
| 459 |
-
block_size: list[int]
|
| 460 |
-
allow_sync: bool = False,
|
| 461 |
) -> torch.Tensor:
|
| 462 |
-
"""
|
| 463 |
-
|
| 464 |
-
Tokens in ``A`` must be pre-sorted by expert id. The kernel quantizes ``A``
|
| 465 |
-
to FP8 on-the-fly (fused ``act_quant``), uses a static over-provisioned grid
|
| 466 |
-
for CUDA-graph compatibility, and resolves each tile's expert via an O(log E)
|
| 467 |
-
binary search over ``offsets``.
|
| 468 |
-
|
| 469 |
-
Args:
|
| 470 |
-
A: Raw activation matrix ``[S, K]`` sorted by expert, in bf16/fp16/fp32.
|
| 471 |
-
B: Stacked expert weight tensor ``[E, N, K]`` in ``float8_e4m3fn``.
|
| 472 |
-
Bs: Expert weight scales, accepted as ``[E, nb, kb]`` (block)
|
| 473 |
-
or ``[E]`` / ``[E,1,1]`` (per-tensor; expanded internally).
|
| 474 |
-
offsets: Cumulative token counts per expert ``[E]`` (i.e. ``cumsum(tokens_per_expert)``).
|
| 475 |
-
tokens_per_expert: Number of tokens routed to each expert ``[E]``.
|
| 476 |
-
block_size: ``[block_n, block_k]`` quantization block dimensions, e.g. ``[128, 128]``.
|
| 477 |
-
allow_sync: If True (default), read back the exact tile count from the GPU
|
| 478 |
-
(avoids wasted programs). If False, use a data-independent upper bound
|
| 479 |
-
(required for CUDA-graph / torch.compile compatibility).
|
| 480 |
|
| 481 |
-
|
| 482 |
-
|
|
|
|
| 483 |
"""
|
| 484 |
return torch.ops.finegrained_fp8.w8a8_block_fp8_matmul_grouped(
|
| 485 |
-
A, B, Bs, offsets, tokens_per_expert, block_size
|
| 486 |
)
|
| 487 |
|
| 488 |
|
|
@@ -492,25 +437,15 @@ def w8a8_tensor_fp8_matmul_grouped(
|
|
| 492 |
Bs: torch.Tensor,
|
| 493 |
offsets: torch.Tensor,
|
| 494 |
tokens_per_expert: torch.Tensor,
|
| 495 |
-
block_size: list[int] | None,
|
| 496 |
-
allow_sync: bool = False,
|
| 497 |
) -> torch.Tensor:
|
| 498 |
-
"""Tensor-scale grouped
|
| 499 |
-
|
| 500 |
-
Args:
|
| 501 |
-
A: Raw activation matrix ``[S, K]`` sorted by expert, in bf16/fp16/fp32.
|
| 502 |
-
B: Stacked expert weight tensor ``[E, N, K]`` in ``float8_e4m3fn``.
|
| 503 |
-
Bs: Per-expert tensor scales ``[E]`` or ``[E,1,1]``.
|
| 504 |
-
offsets: Cumulative token counts per expert ``[E]``.
|
| 505 |
-
tokens_per_expert: Number of tokens routed to each expert ``[E]``.
|
| 506 |
-
block_size: Kept for API consistency; tensor path derives tile sizes from ``N`` and ``K``.
|
| 507 |
-
allow_sync: If True, sync for exact grid; if False, use upper bound.
|
| 508 |
|
| 509 |
-
|
| 510 |
-
|
|
|
|
| 511 |
"""
|
| 512 |
return torch.ops.finegrained_fp8.w8a8_tensor_fp8_matmul_grouped(
|
| 513 |
-
A, B, Bs, offsets, tokens_per_expert
|
| 514 |
)
|
| 515 |
|
| 516 |
|
|
@@ -521,7 +456,6 @@ def w8a8_fp8_matmul_grouped(
|
|
| 521 |
offsets: torch.Tensor,
|
| 522 |
tokens_per_expert: torch.Tensor,
|
| 523 |
block_size: list[int] | None,
|
| 524 |
-
allow_sync: bool = False,
|
| 525 |
) -> torch.Tensor:
|
| 526 |
"""Unified grouped W8A8 FP8 matmul dispatcher.
|
| 527 |
|
|
@@ -536,10 +470,8 @@ def w8a8_fp8_matmul_grouped(
|
|
| 536 |
if block_size is None or (
|
| 537 |
block_size[0] == B.size(1) and block_size[1] == B.size(2)
|
| 538 |
):
|
| 539 |
-
return w8a8_tensor_fp8_matmul_grouped(
|
| 540 |
-
A, B, Bs, offsets, tokens_per_expert, block_size, allow_sync
|
| 541 |
-
)
|
| 542 |
|
| 543 |
return w8a8_block_fp8_matmul_grouped(
|
| 544 |
-
A, B, Bs, offsets, tokens_per_expert, block_size
|
| 545 |
)
|
|
|
|
| 18 |
from .act_quant import fp8_act_quant
|
| 19 |
from torch.library import triton_op, wrap_triton
|
| 20 |
|
| 21 |
+
from .utils import device_context
|
| 22 |
+
|
| 23 |
|
| 24 |
@triton.autotune(
|
| 25 |
configs=[
|
|
|
|
| 27 |
for w in [2, 4, 8, 16]
|
| 28 |
for s in [2, 3, 4, 5]
|
| 29 |
],
|
| 30 |
+
key=["N", "K", "BLOCK_SIZE_M"],
|
| 31 |
)
|
| 32 |
@triton.jit
|
| 33 |
def w8a8_block_fp8_matmul_grouped_kernel(
|
| 34 |
A, # (S, K) raw BF16/FP16 activations, sorted/grouped by expert id
|
| 35 |
B, # (E, N, K) FP8 weight matrices
|
| 36 |
C, # (S, N) output
|
| 37 |
+
Bs, # (E, N // BLOCK_SIZE_N, K // BLOCK_SIZE_K) weight scales
|
| 38 |
Offsets, # (E,) int32 — cumulative row-end per expert
|
| 39 |
TileOffsets, # (E,) int32 — cumulative tile-end per expert
|
| 40 |
# Shape
|
|
|
|
| 44 |
# Strides
|
| 45 |
stride_am,
|
| 46 |
stride_ak,
|
| 47 |
+
stride_be,
|
| 48 |
stride_bk,
|
| 49 |
stride_bn,
|
| 50 |
stride_cm,
|
| 51 |
stride_cn,
|
| 52 |
+
stride_bs_e,
|
| 53 |
+
stride_bs_k,
|
| 54 |
+
stride_bs_n,
|
| 55 |
# Meta-parameters
|
|
|
|
|
|
|
|
|
|
| 56 |
NUM_EXPERTS: tl.constexpr,
|
| 57 |
+
BLOCK_SIZE_N: tl.constexpr,
|
| 58 |
+
BLOCK_SIZE_K: tl.constexpr,
|
| 59 |
+
BLOCK_SIZE_M: tl.constexpr,
|
| 60 |
NUM_EXPERTS_BIT_LENGTH: tl.constexpr,
|
| 61 |
):
|
| 62 |
"""Block-scale grouped FP8 expert matmul kernel.
|
|
|
|
| 89 |
hi = tl.where(is_left, hi, mid)
|
| 90 |
|
| 91 |
# Cast expert_id to int64 to prevent int32 overflow when computing
|
| 92 |
+
# expert_id * stride_be (e.g. 255 * 9_437_184 > 2^31 for 256 experts of
|
| 93 |
# 3072×3072 FP8 weights).
|
| 94 |
expert_id = lo.to(tl.int64)
|
| 95 |
|
| 96 |
prev_eid = tl.maximum(expert_id - 1, 0)
|
|
|
|
| 97 |
expert_start = tl.where(expert_id == 0, 0, tl.load(Offsets + prev_eid))
|
| 98 |
expert_end = tl.load(Offsets + expert_id)
|
| 99 |
M_expert = expert_end - expert_start
|
|
|
|
| 106 |
row_mask = offs_am < M_expert
|
| 107 |
offs_global_m = expert_start + offs_am
|
| 108 |
|
| 109 |
+
offs_bn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 110 |
+
offs_k = tl.arange(0, BLOCK_SIZE_K)
|
| 111 |
|
| 112 |
a_ptrs = A + offs_global_m[:, None] * stride_am + offs_k[None, :] * stride_ak
|
| 113 |
b_ptrs = (
|
| 114 |
B
|
| 115 |
+
+ expert_id * stride_be
|
| 116 |
+ offs_k[:, None] * stride_bk
|
| 117 |
+ offs_bn[None, :] * stride_bn
|
| 118 |
)
|
| 119 |
+
bs_ptrs = Bs + expert_id * stride_bs_e + pid_n * stride_bs_n
|
|
|
|
| 120 |
|
| 121 |
+
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 122 |
+
for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
|
| 123 |
# ---- fused fp8_act_quant ----
|
| 124 |
a_raw = tl.load(a_ptrs, mask=row_mask[:, None], other=0.0).to(tl.float32)
|
| 125 |
+
a_s = tl.max(tl.abs(a_raw), axis=1) / 448.0
|
| 126 |
a = (a_raw / tl.maximum(a_s[:, None], 1e-12)).to(tl.float8e4nv)
|
| 127 |
+
# ---- matmul ----
|
| 128 |
b = tl.load(b_ptrs)
|
| 129 |
+
b_s = tl.load(bs_ptrs + k * stride_bs_k)
|
| 130 |
accumulator += tl.dot(a, b) * a_s[:, None] * b_s[None, :]
|
| 131 |
+
a_ptrs += BLOCK_SIZE_K * stride_ak
|
| 132 |
+
b_ptrs += BLOCK_SIZE_K * stride_bk
|
| 133 |
|
| 134 |
if C.dtype.element_ty == tl.bfloat16:
|
| 135 |
c = accumulator.to(tl.bfloat16)
|
|
|
|
| 149 |
for w in [2, 4, 8, 16]
|
| 150 |
for s in [2, 3, 4, 5]
|
| 151 |
],
|
| 152 |
+
key=["N", "K", "BLOCK_SIZE_M"],
|
| 153 |
)
|
| 154 |
@triton.jit
|
| 155 |
def w8a8_tensor_fp8_matmul_grouped_kernel(
|
| 156 |
+
A, # (S, K) raw BF16/FP16 activations, sorted/grouped by expert idc
|
| 157 |
B, # (E, N, K) FP8 weight matrices
|
| 158 |
C, # (S, N) output
|
| 159 |
As, # (S, 1) activation scales
|
|
|
|
| 165 |
K,
|
| 166 |
stride_am,
|
| 167 |
stride_ak,
|
| 168 |
+
stride_be,
|
| 169 |
stride_bk,
|
| 170 |
stride_bn,
|
| 171 |
stride_cm,
|
| 172 |
stride_cn,
|
| 173 |
+
stride_as_m,
|
| 174 |
+
stride_bs_e,
|
|
|
|
|
|
|
|
|
|
| 175 |
NUM_EXPERTS: tl.constexpr,
|
| 176 |
+
BLOCK_SIZE_N: tl.constexpr,
|
| 177 |
+
BLOCK_SIZE_K: tl.constexpr,
|
| 178 |
+
BLOCK_SIZE_M: tl.constexpr,
|
| 179 |
NUM_EXPERTS_BIT_LENGTH: tl.constexpr,
|
| 180 |
):
|
| 181 |
"""Tensor-scale grouped FP8 expert matmul kernel.
|
|
|
|
| 213 |
row_mask = offs_am < M_expert
|
| 214 |
offs_global_m = expert_start + offs_am
|
| 215 |
|
| 216 |
+
offs_bn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 217 |
+
offs_k = tl.arange(0, BLOCK_SIZE_K)
|
| 218 |
|
| 219 |
a_ptrs = A + offs_global_m[:, None] * stride_am + offs_k[None, :] * stride_ak
|
| 220 |
b_ptrs = (
|
| 221 |
B
|
| 222 |
+
+ expert_id * stride_be
|
| 223 |
+ offs_k[:, None] * stride_bk
|
| 224 |
+ offs_bn[None, :] * stride_bn
|
| 225 |
)
|
| 226 |
|
| 227 |
+
a_s = tl.load(As + offs_global_m * stride_as_m, mask=row_mask, other=0.0)
|
| 228 |
+
b_s = tl.load(Bs + expert_id * stride_bs_e)
|
| 229 |
|
| 230 |
+
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 231 |
+
for _ in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
|
| 232 |
a = tl.load(a_ptrs, mask=row_mask[:, None], other=0.0)
|
| 233 |
b = tl.load(b_ptrs)
|
| 234 |
|
| 235 |
+
accumulator += tl.dot(a, b)
|
| 236 |
+
a_ptrs += BLOCK_SIZE_K * stride_ak
|
| 237 |
+
b_ptrs += BLOCK_SIZE_K * stride_bk
|
| 238 |
+
|
| 239 |
+
accumulator = accumulator * a_s[:, None] * b_s
|
| 240 |
|
| 241 |
if C.dtype.element_ty == tl.bfloat16:
|
| 242 |
c = accumulator.to(tl.bfloat16)
|
|
|
|
| 257 |
Bs: torch.Tensor,
|
| 258 |
offsets: torch.Tensor,
|
| 259 |
tokens_per_expert: torch.Tensor,
|
| 260 |
+
block_size: list[int],
|
|
|
|
| 261 |
) -> torch.Tensor:
|
| 262 |
+
"""Block-scale grouped FP8 matmul: C = A @ B.T per expert, with fused act quant.
|
| 263 |
|
| 264 |
+
A: (S, K) raw bf16/fp16 activations, sorted by expert
|
| 265 |
+
B: (E, N, K) FP8 expert weights
|
| 266 |
+
Bs: (E, N // block_n, K // block_k) per-block weight scales
|
| 267 |
"""
|
| 268 |
+
assert A.ndim == 2, f"A must be 2D (S, K), got ndim={A.ndim}"
|
| 269 |
assert A.is_contiguous(), "A must be contiguous"
|
| 270 |
+
assert B.ndim == 3, f"B must be 3D (E, N, K), got ndim={B.ndim}"
|
|
|
|
| 271 |
assert B.is_contiguous(), "B must be contiguous"
|
| 272 |
+
assert A.shape[1] == B.shape[2], (
|
| 273 |
+
f"K mismatch: A has K={A.shape[1]}, B has K={B.shape[2]}"
|
| 274 |
+
)
|
|
|
|
|
|
|
| 275 |
|
| 276 |
S, K = A.shape
|
| 277 |
+
E, N, _ = B.shape
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
|
| 279 |
+
assert len(block_size) == 2, (
|
| 280 |
+
f"block_size must be [block_n, block_k], got {block_size}"
|
| 281 |
+
)
|
| 282 |
+
block_n, block_k = block_size[0], block_size[1]
|
| 283 |
+
# MoE expert dimensions must be block-aligned; non-aligned N/K is not supported.
|
| 284 |
assert N % block_n == 0, f"N ({N}) must be divisible by block_n ({block_n})"
|
| 285 |
assert K % block_k == 0, f"K ({K}) must be divisible by block_k ({block_k})"
|
| 286 |
+
assert Bs.ndim == 3, (
|
| 287 |
+
f"Bs must be 3D (E, N//block_n, K//block_k), got ndim={Bs.ndim}"
|
| 288 |
+
)
|
| 289 |
+
assert Bs.shape == (E, N // block_n, K // block_k), (
|
| 290 |
+
f"Bs shape {tuple(Bs.shape)} != expected ({E}, {N // block_n}, {K // block_k})"
|
| 291 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
|
| 293 |
C = A.new_empty(S, N)
|
|
|
|
| 294 |
# Adaptive BLOCK_SIZE_M: match tile to average tokens per expert.
|
| 295 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2((S + E - 1) // E), 16), 128)
|
| 296 |
tiles_per_expert = (tokens_per_expert + BLOCK_SIZE_M - 1) // BLOCK_SIZE_M
|
| 297 |
tile_offsets = torch.cumsum(tiles_per_expert, dim=0).to(torch.int32)
|
| 298 |
+
# Upper bound on M-tiles: sum_e ceil(M_e / BLOCK_M) <= ceil(S / BLOCK_M) + E.
|
| 299 |
+
# Programs beyond the real tile count exit immediately via the early-return
|
| 300 |
+
# guard inside the kernel. This is faster than syncing for the exact count
|
| 301 |
+
# and keeps the grid size data-independent (cuda-graph / torch.compile safe).
|
| 302 |
+
max_M_tiles = triton.cdiv(S, BLOCK_SIZE_M) + E
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 303 |
grid = (max_M_tiles, triton.cdiv(N, block_n))
|
| 304 |
+
with device_context(A.device):
|
| 305 |
+
wrap_triton(w8a8_block_fp8_matmul_grouped_kernel)[grid](
|
| 306 |
+
A,
|
| 307 |
+
B,
|
| 308 |
+
C,
|
| 309 |
+
Bs,
|
| 310 |
+
offsets,
|
| 311 |
+
tile_offsets,
|
| 312 |
+
S,
|
| 313 |
+
N,
|
| 314 |
+
K,
|
| 315 |
+
A.stride(0),
|
| 316 |
+
A.stride(1),
|
| 317 |
+
B.stride(0),
|
| 318 |
+
B.stride(2),
|
| 319 |
+
B.stride(1),
|
| 320 |
+
C.stride(0),
|
| 321 |
+
C.stride(1),
|
| 322 |
+
Bs.stride(0),
|
| 323 |
+
Bs.stride(2),
|
| 324 |
+
Bs.stride(1),
|
| 325 |
+
# Meta-parameters
|
| 326 |
+
NUM_EXPERTS=E,
|
| 327 |
+
BLOCK_SIZE_N=block_n,
|
| 328 |
+
BLOCK_SIZE_K=block_k,
|
| 329 |
+
BLOCK_SIZE_M=BLOCK_SIZE_M,
|
| 330 |
+
NUM_EXPERTS_BIT_LENGTH=E.bit_length(),
|
| 331 |
+
)
|
| 332 |
|
| 333 |
return C
|
| 334 |
|
|
|
|
| 340 |
Bs: torch.Tensor,
|
| 341 |
offsets: torch.Tensor,
|
| 342 |
tokens_per_expert: torch.Tensor,
|
|
|
|
|
|
|
| 343 |
) -> torch.Tensor:
|
| 344 |
+
"""Tensor-scale grouped FP8 matmul: C = A @ B.T per expert, with fused act quant.
|
|
|
|
|
|
|
|
|
|
| 345 |
|
| 346 |
+
A: (S, K) raw bf16/fp16 activations, sorted by expert
|
| 347 |
+
B: (E, N, K) FP8 expert weights
|
| 348 |
+
Bs: (E,) or (E, 1, 1) per-expert weight scales
|
| 349 |
"""
|
| 350 |
+
assert A.ndim == 2, f"A must be 2D (S, K), got ndim={A.ndim}"
|
| 351 |
assert A.is_contiguous(), "A must be contiguous"
|
| 352 |
+
assert B.ndim == 3, f"B must be 3D (E, N, K), got ndim={B.ndim}"
|
|
|
|
| 353 |
assert B.is_contiguous(), "B must be contiguous"
|
| 354 |
+
assert A.shape[1] == B.shape[2], (
|
| 355 |
+
f"K mismatch: A has K={A.shape[1]}, B has K={B.shape[2]}"
|
| 356 |
+
)
|
|
|
|
|
|
|
| 357 |
|
| 358 |
S, K = A.shape
|
| 359 |
+
E, N, _ = B.shape
|
| 360 |
|
| 361 |
+
# Normalize Bs to (E, 1, 1)
|
| 362 |
if Bs.ndim == 1:
|
| 363 |
+
assert Bs.shape[0] == E, f"Bs shape {tuple(Bs.shape)} != expected ({E},)"
|
| 364 |
Bs = Bs.reshape(E, 1, 1)
|
|
|
|
|
|
|
| 365 |
else:
|
| 366 |
+
assert Bs.shape == (E, 1, 1), (
|
| 367 |
+
f"Bs shape {tuple(Bs.shape)} != expected ({E}, 1, 1)"
|
|
|
|
| 368 |
)
|
| 369 |
|
| 370 |
+
BLOCK_SIZE_N = 128
|
| 371 |
+
BLOCK_SIZE_K = 128
|
|
|
|
|
|
|
|
|
|
| 372 |
C = A.new_empty(S, N)
|
| 373 |
+
qA, As = fp8_act_quant(A, K)
|
| 374 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2((S + E - 1) // E), 16), 128)
|
| 375 |
tiles_per_expert = (tokens_per_expert + BLOCK_SIZE_M - 1) // BLOCK_SIZE_M
|
| 376 |
tile_offsets = torch.cumsum(tiles_per_expert, dim=0).to(torch.int32)
|
| 377 |
+
# Upper bound on M-tiles: sum_e ceil(M_e / BLOCK_M) <= ceil(S / BLOCK_M) + E.
|
| 378 |
+
# Programs beyond the real tile count exit immediately via the early-return
|
| 379 |
+
# guard inside the kernel. This is faster than syncing for the exact count
|
| 380 |
+
# and keeps the grid size data-independent (cuda-graph / torch.compile safe).
|
| 381 |
+
max_M_tiles = triton.cdiv(S, BLOCK_SIZE_M) + E
|
| 382 |
+
grid = (max_M_tiles, triton.cdiv(N, BLOCK_SIZE_N))
|
| 383 |
+
with device_context(A.device):
|
| 384 |
+
wrap_triton(w8a8_tensor_fp8_matmul_grouped_kernel)[grid](
|
| 385 |
+
qA,
|
| 386 |
+
B,
|
| 387 |
+
C,
|
| 388 |
+
As,
|
| 389 |
+
Bs,
|
| 390 |
+
offsets,
|
| 391 |
+
tile_offsets,
|
| 392 |
+
S,
|
| 393 |
+
N,
|
| 394 |
+
K,
|
| 395 |
+
qA.stride(0),
|
| 396 |
+
qA.stride(1),
|
| 397 |
+
B.stride(0),
|
| 398 |
+
B.stride(2),
|
| 399 |
+
B.stride(1),
|
| 400 |
+
C.stride(0),
|
| 401 |
+
C.stride(1),
|
| 402 |
+
As.stride(0),
|
| 403 |
+
Bs.stride(0),
|
| 404 |
+
# Meta-parameters
|
| 405 |
+
NUM_EXPERTS=E,
|
| 406 |
+
BLOCK_SIZE_N=BLOCK_SIZE_N,
|
| 407 |
+
BLOCK_SIZE_K=BLOCK_SIZE_K,
|
| 408 |
+
BLOCK_SIZE_M=BLOCK_SIZE_M,
|
| 409 |
+
NUM_EXPERTS_BIT_LENGTH=E.bit_length(),
|
| 410 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 411 |
|
| 412 |
return C
|
| 413 |
|
|
|
|
| 418 |
Bs: torch.Tensor,
|
| 419 |
offsets: torch.Tensor,
|
| 420 |
tokens_per_expert: torch.Tensor,
|
| 421 |
+
block_size: list[int],
|
|
|
|
| 422 |
) -> torch.Tensor:
|
| 423 |
+
"""Block-scale grouped FP8 matmul with fused activation quantization.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 424 |
|
| 425 |
+
A: (S, K) raw activations sorted by expert, bf16/fp16/fp32
|
| 426 |
+
B: (E, N, K) FP8 expert weights
|
| 427 |
+
Bs: (E, N // block_n, K // block_k) per-block weight scales
|
| 428 |
"""
|
| 429 |
return torch.ops.finegrained_fp8.w8a8_block_fp8_matmul_grouped(
|
| 430 |
+
A, B, Bs, offsets, tokens_per_expert, block_size
|
| 431 |
)
|
| 432 |
|
| 433 |
|
|
|
|
| 437 |
Bs: torch.Tensor,
|
| 438 |
offsets: torch.Tensor,
|
| 439 |
tokens_per_expert: torch.Tensor,
|
|
|
|
|
|
|
| 440 |
) -> torch.Tensor:
|
| 441 |
+
"""Tensor-scale grouped FP8 matmul with fused activation quantization.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 442 |
|
| 443 |
+
A: (S, K) raw activations sorted by expert, bf16/fp16/fp32
|
| 444 |
+
B: (E, N, K) FP8 expert weights
|
| 445 |
+
Bs: (E,) or (E, 1, 1) per-expert weight scales
|
| 446 |
"""
|
| 447 |
return torch.ops.finegrained_fp8.w8a8_tensor_fp8_matmul_grouped(
|
| 448 |
+
A, B, Bs, offsets, tokens_per_expert
|
| 449 |
)
|
| 450 |
|
| 451 |
|
|
|
|
| 456 |
offsets: torch.Tensor,
|
| 457 |
tokens_per_expert: torch.Tensor,
|
| 458 |
block_size: list[int] | None,
|
|
|
|
| 459 |
) -> torch.Tensor:
|
| 460 |
"""Unified grouped W8A8 FP8 matmul dispatcher.
|
| 461 |
|
|
|
|
| 470 |
if block_size is None or (
|
| 471 |
block_size[0] == B.size(1) and block_size[1] == B.size(2)
|
| 472 |
):
|
| 473 |
+
return w8a8_tensor_fp8_matmul_grouped(A, B, Bs, offsets, tokens_per_expert)
|
|
|
|
|
|
|
| 474 |
|
| 475 |
return w8a8_block_fp8_matmul_grouped(
|
| 476 |
+
A, B, Bs, offsets, tokens_per_expert, block_size
|
| 477 |
)
|
build/torch-cuda/matmul.py
CHANGED
|
@@ -17,8 +17,18 @@ import triton
|
|
| 17 |
import triton.language as tl
|
| 18 |
from torch.library import triton_op, wrap_triton
|
| 19 |
|
|
|
|
|
|
|
| 20 |
|
| 21 |
# Adapted from https://github.com/sgl-project/sglang/blob/main/python/sglang/srt/layers/quantization/fp8_kernel.py
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
@triton.jit
|
| 23 |
def w8a8_block_fp8_matmul_kernel(
|
| 24 |
# Pointers to inputs and output
|
|
@@ -31,20 +41,16 @@ def w8a8_block_fp8_matmul_kernel(
|
|
| 31 |
M,
|
| 32 |
N,
|
| 33 |
K,
|
| 34 |
-
# Block size for block-wise quantization
|
| 35 |
-
group_n,
|
| 36 |
-
group_k,
|
| 37 |
-
# Stride for inputs and output
|
| 38 |
stride_am,
|
| 39 |
stride_ak,
|
| 40 |
stride_bk,
|
| 41 |
stride_bn,
|
| 42 |
stride_cm,
|
| 43 |
stride_cn,
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
# Meta-parameters
|
| 49 |
BLOCK_SIZE_M: tl.constexpr,
|
| 50 |
BLOCK_SIZE_N: tl.constexpr,
|
|
@@ -54,17 +60,13 @@ def w8a8_block_fp8_matmul_kernel(
|
|
| 54 |
"""Block-scale FP8 GEMM kernel.
|
| 55 |
|
| 56 |
Computes ``C = A @ B.T`` with block-wise activation/weight scales.
|
|
|
|
| 57 |
"""
|
| 58 |
-
|
| 59 |
-
|
| 60 |
num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
|
| 61 |
num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)
|
| 62 |
-
|
| 63 |
-
group_id = pid // num_pid_in_group
|
| 64 |
-
first_pid_m = group_id * GROUP_SIZE_M
|
| 65 |
-
group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M)
|
| 66 |
-
pid_m = first_pid_m + (pid % group_size_m)
|
| 67 |
-
pid_n = (pid % num_pid_in_group) // group_size_m
|
| 68 |
|
| 69 |
offs_am = (pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
|
| 70 |
offs_bn = (pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)) % N
|
|
@@ -72,19 +74,18 @@ def w8a8_block_fp8_matmul_kernel(
|
|
| 72 |
a_ptrs = A + (offs_am[:, None] * stride_am + offs_k[None, :] * stride_ak)
|
| 73 |
b_ptrs = B + (offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn)
|
| 74 |
|
| 75 |
-
|
| 76 |
-
offs_bsn = offs_bn //
|
| 77 |
-
|
| 78 |
|
| 79 |
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 80 |
for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
|
| 81 |
-
|
| 82 |
-
|
|
|
|
| 83 |
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
a_s = tl.load(As_ptrs + offs_ks * stride_As_k)
|
| 87 |
-
b_s = tl.load(Bs_ptrs + offs_ks * stride_Bs_k)
|
| 88 |
|
| 89 |
accumulator += tl.dot(a, b) * a_s[:, None] * b_s[None, :]
|
| 90 |
a_ptrs += BLOCK_SIZE_K * stride_ak
|
|
@@ -104,6 +105,14 @@ def w8a8_block_fp8_matmul_kernel(
|
|
| 104 |
tl.store(c_ptrs, c, mask=c_mask)
|
| 105 |
|
| 106 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
@triton.jit
|
| 108 |
def w8a8_tensor_fp8_matmul_kernel(
|
| 109 |
A,
|
|
@@ -120,7 +129,7 @@ def w8a8_tensor_fp8_matmul_kernel(
|
|
| 120 |
stride_bn,
|
| 121 |
stride_cm,
|
| 122 |
stride_cn,
|
| 123 |
-
|
| 124 |
BLOCK_SIZE_M: tl.constexpr,
|
| 125 |
BLOCK_SIZE_N: tl.constexpr,
|
| 126 |
BLOCK_SIZE_K: tl.constexpr,
|
|
@@ -130,40 +139,36 @@ def w8a8_tensor_fp8_matmul_kernel(
|
|
| 130 |
|
| 131 |
Computes ``C = A @ B.T`` with one activation scale per row and one
|
| 132 |
weight scale for the full matrix.
|
|
|
|
| 133 |
"""
|
| 134 |
-
|
|
|
|
| 135 |
num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
|
| 136 |
num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
pid_m = first_pid_m + (pid % group_size_m)
|
| 142 |
-
pid_n = (pid % num_pid_in_group) // group_size_m
|
| 143 |
-
|
| 144 |
-
offs_am = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
|
| 145 |
-
offs_bn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 146 |
offs_k = tl.arange(0, BLOCK_SIZE_K)
|
| 147 |
|
| 148 |
a_ptrs = A + offs_am[:, None] * stride_am + offs_k[None, :] * stride_ak
|
| 149 |
b_ptrs = B + offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn
|
| 150 |
|
| 151 |
-
a_s = tl.load(As + offs_am *
|
| 152 |
b_s = tl.load(Bs)
|
| 153 |
|
|
|
|
| 154 |
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 155 |
for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
|
| 156 |
-
|
| 157 |
-
a = tl.load(
|
| 158 |
-
|
| 159 |
-
)
|
| 160 |
-
b = tl.load(
|
| 161 |
-
b_ptrs, mask=(k_offs[:, None] < K) & (offs_bn[None, :] < N), other=0.0
|
| 162 |
-
)
|
| 163 |
-
accumulator += tl.dot(a, b) * a_s[:, None] * b_s
|
| 164 |
a_ptrs += BLOCK_SIZE_K * stride_ak
|
| 165 |
b_ptrs += BLOCK_SIZE_K * stride_bk
|
| 166 |
|
|
|
|
|
|
|
| 167 |
if C.dtype.element_ty == tl.bfloat16:
|
| 168 |
c = accumulator.to(tl.bfloat16)
|
| 169 |
elif C.dtype.element_ty == tl.float16:
|
|
@@ -184,82 +189,74 @@ def _w8a8_block_fp8_matmul(
|
|
| 184 |
B: torch.Tensor,
|
| 185 |
As: torch.Tensor,
|
| 186 |
Bs: torch.Tensor,
|
| 187 |
-
block_size: list[int]
|
| 188 |
output_dtype: torch.dtype = torch.float32,
|
| 189 |
) -> torch.Tensor:
|
| 190 |
-
"""
|
| 191 |
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
block-scale shapes.
|
| 195 |
"""
|
| 196 |
-
|
| 197 |
-
block_n, block_k
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
block_n, block_k = block_size[0], block_size[1]
|
| 201 |
-
|
| 202 |
-
assert A.shape[-1] == B.shape[-1]
|
| 203 |
-
assert A.is_contiguous()
|
| 204 |
|
| 205 |
-
assert
|
| 206 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
|
| 208 |
N, K = B.shape
|
| 209 |
M = A.numel() // A.shape[-1]
|
| 210 |
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
Bs = Bs.reshape(1, 1).expand(triton.cdiv(N, block_n), triton.cdiv(K, block_k))
|
| 220 |
-
else:
|
| 221 |
-
assert Bs.ndim == 2
|
| 222 |
-
assert triton.cdiv(N, block_n) == Bs.shape[0], f"{N}, {block_n}, {Bs.shape}"
|
| 223 |
-
assert triton.cdiv(K, block_k) == Bs.shape[1], f"{K}, {block_k}, {Bs.shape}"
|
| 224 |
|
|
|
|
|
|
|
| 225 |
C_shape = A.shape[:-1] + (N,)
|
| 226 |
C = A.new_empty(C_shape, dtype=output_dtype)
|
| 227 |
-
|
| 228 |
# Adaptive BLOCK_SIZE_M: smallest power-of-2 >= M, floored at 16, capped at 128.
|
| 229 |
# Matches the WGMMA tile to the actual row count — smaller tiles use less
|
| 230 |
# register pressure and a better-matched FP8 WGMMA instruction, improving
|
| 231 |
# both accuracy and performance for small M (decode).
|
| 232 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2(M), 16), 128)
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
BLOCK_SIZE_K=BLOCK_SIZE_K,
|
| 261 |
-
GROUP_SIZE_M=8,
|
| 262 |
-
)
|
| 263 |
|
| 264 |
return C
|
| 265 |
|
|
@@ -270,83 +267,65 @@ def _w8a8_tensor_fp8_matmul(
|
|
| 270 |
B: torch.Tensor,
|
| 271 |
As: torch.Tensor,
|
| 272 |
Bs: torch.Tensor,
|
| 273 |
-
block_size: list[int] | None,
|
| 274 |
output_dtype: torch.dtype = torch.float32,
|
| 275 |
) -> torch.Tensor:
|
| 276 |
-
"""Tensor-scale
|
| 277 |
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
- ``As``: scalar, ``[M]``, or ``[M,1]`` -> ``[M]``
|
| 281 |
-
- ``Bs``: scalar, ``[1]``, or ``[1,1]`` -> ``[1]``
|
| 282 |
"""
|
| 283 |
-
assert A.shape[-1] == B.shape[-1]
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
assert
|
| 287 |
-
assert B.
|
|
|
|
| 288 |
|
| 289 |
N, K = B.shape
|
| 290 |
M = A.numel() // A.shape[-1]
|
| 291 |
|
| 292 |
-
|
| 293 |
-
block_k = 128 if K % 128 == 0 else K
|
| 294 |
-
|
| 295 |
if As.numel() == 1:
|
| 296 |
As = As.reshape(1).expand(M).contiguous()
|
| 297 |
-
elif As.ndim ==
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
)
|
| 301 |
-
|
| 302 |
-
else:
|
| 303 |
-
assert As.ndim == 2 and As.shape[0] == M and As.shape[1] == 1, (
|
| 304 |
-
f"Tensor mode expects As shape [M,1], got {tuple(As.shape)}"
|
| 305 |
-
)
|
| 306 |
-
As = As.reshape(M).contiguous()
|
| 307 |
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
assert Bs.shape[0] == 1, (
|
| 312 |
-
f"Tensor mode expects Bs shape [1], got {tuple(Bs.shape)}"
|
| 313 |
-
)
|
| 314 |
-
Bs = Bs.contiguous()
|
| 315 |
-
else:
|
| 316 |
-
assert Bs.ndim == 2 and Bs.shape[0] == 1 and Bs.shape[1] == 1, (
|
| 317 |
-
f"Tensor mode expects Bs shape [1,1], got {tuple(Bs.shape)}"
|
| 318 |
-
)
|
| 319 |
-
Bs = Bs.reshape(1).contiguous()
|
| 320 |
|
|
|
|
|
|
|
| 321 |
C_shape = A.shape[:-1] + (N,)
|
| 322 |
C = A.new_empty(C_shape, dtype=output_dtype)
|
| 323 |
-
|
| 324 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2(M), 16), 128)
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
)
|
| 350 |
|
| 351 |
return C
|
| 352 |
|
|
@@ -356,7 +335,7 @@ def w8a8_block_fp8_matmul(
|
|
| 356 |
B: torch.Tensor,
|
| 357 |
As: torch.Tensor,
|
| 358 |
Bs: torch.Tensor,
|
| 359 |
-
block_size: list[int]
|
| 360 |
output_dtype: torch.dtype = torch.float32,
|
| 361 |
) -> torch.Tensor:
|
| 362 |
"""Block-wise W8A8 FP8 matrix multiplication.
|
|
@@ -386,7 +365,6 @@ def w8a8_tensor_fp8_matmul(
|
|
| 386 |
B: torch.Tensor,
|
| 387 |
As: torch.Tensor,
|
| 388 |
Bs: torch.Tensor,
|
| 389 |
-
block_size: list[int] | None,
|
| 390 |
output_dtype: torch.dtype = torch.float32,
|
| 391 |
) -> torch.Tensor:
|
| 392 |
"""Tensor-scale W8A8 FP8 matrix multiplication.
|
|
@@ -397,17 +375,14 @@ def w8a8_tensor_fp8_matmul(
|
|
| 397 |
Args:
|
| 398 |
A: Quantized activation tensor ``[M, K]`` in ``float8_e4m3fn``.
|
| 399 |
B: Quantized weight tensor ``[N, K]`` in ``float8_e4m3fn``.
|
| 400 |
-
As:
|
| 401 |
-
Bs:
|
| 402 |
-
block_size: Kept for API consistency; tensor path derives tile sizes from ``N`` and ``K``.
|
| 403 |
output_dtype: dtype of the returned tensor.
|
| 404 |
|
| 405 |
Returns:
|
| 406 |
Output tensor ``[M, N]`` in ``output_dtype``.
|
| 407 |
"""
|
| 408 |
-
return torch.ops.finegrained_fp8.w8a8_tensor_fp8_matmul(
|
| 409 |
-
A, B, As, Bs, block_size, output_dtype
|
| 410 |
-
)
|
| 411 |
|
| 412 |
|
| 413 |
def w8a8_fp8_matmul(
|
|
@@ -431,6 +406,6 @@ def w8a8_fp8_matmul(
|
|
| 431 |
if block_size is None or (
|
| 432 |
block_size[0] == B.size(0) and block_size[1] == B.size(1)
|
| 433 |
):
|
| 434 |
-
return w8a8_tensor_fp8_matmul(A, B, As, Bs,
|
| 435 |
|
| 436 |
return w8a8_block_fp8_matmul(A, B, As, Bs, block_size, output_dtype)
|
|
|
|
| 17 |
import triton.language as tl
|
| 18 |
from torch.library import triton_op, wrap_triton
|
| 19 |
|
| 20 |
+
from .utils import device_context
|
| 21 |
+
|
| 22 |
|
| 23 |
# Adapted from https://github.com/sgl-project/sglang/blob/main/python/sglang/srt/layers/quantization/fp8_kernel.py
|
| 24 |
+
@triton.autotune(
|
| 25 |
+
configs=[
|
| 26 |
+
triton.Config({}, num_warps=w, num_stages=s)
|
| 27 |
+
for w in [2, 4, 8, 16]
|
| 28 |
+
for s in [2, 3, 4]
|
| 29 |
+
],
|
| 30 |
+
key=["N", "K", "BLOCK_SIZE_M"],
|
| 31 |
+
)
|
| 32 |
@triton.jit
|
| 33 |
def w8a8_block_fp8_matmul_kernel(
|
| 34 |
# Pointers to inputs and output
|
|
|
|
| 41 |
M,
|
| 42 |
N,
|
| 43 |
K,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
stride_am,
|
| 45 |
stride_ak,
|
| 46 |
stride_bk,
|
| 47 |
stride_bn,
|
| 48 |
stride_cm,
|
| 49 |
stride_cn,
|
| 50 |
+
stride_as_m,
|
| 51 |
+
stride_as_k,
|
| 52 |
+
stride_bs_k,
|
| 53 |
+
stride_bs_n,
|
| 54 |
# Meta-parameters
|
| 55 |
BLOCK_SIZE_M: tl.constexpr,
|
| 56 |
BLOCK_SIZE_N: tl.constexpr,
|
|
|
|
| 60 |
"""Block-scale FP8 GEMM kernel.
|
| 61 |
|
| 62 |
Computes ``C = A @ B.T`` with block-wise activation/weight scales.
|
| 63 |
+
Uses a 2D grid with swizzle for L2 cache locality on B tiles.
|
| 64 |
"""
|
| 65 |
+
pid_m = tl.program_id(axis=0)
|
| 66 |
+
pid_n = tl.program_id(axis=1)
|
| 67 |
num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
|
| 68 |
num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)
|
| 69 |
+
pid_m, pid_n = tl.swizzle2d(pid_m, pid_n, num_pid_m, num_pid_n, GROUP_SIZE_M)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
offs_am = (pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
|
| 72 |
offs_bn = (pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)) % N
|
|
|
|
| 74 |
a_ptrs = A + (offs_am[:, None] * stride_am + offs_k[None, :] * stride_ak)
|
| 75 |
b_ptrs = B + (offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn)
|
| 76 |
|
| 77 |
+
as_ptrs = As + offs_am * stride_as_m
|
| 78 |
+
offs_bsn = offs_bn // BLOCK_SIZE_N
|
| 79 |
+
bs_ptrs = Bs + offs_bsn * stride_bs_n
|
| 80 |
|
| 81 |
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 82 |
for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
|
| 83 |
+
k_remaining = K - k * BLOCK_SIZE_K
|
| 84 |
+
a = tl.load(a_ptrs, mask=offs_k[None, :] < k_remaining, other=0.0)
|
| 85 |
+
b = tl.load(b_ptrs, mask=offs_k[:, None] < k_remaining, other=0.0)
|
| 86 |
|
| 87 |
+
a_s = tl.load(as_ptrs + k * stride_as_k)
|
| 88 |
+
b_s = tl.load(bs_ptrs + k * stride_bs_k)
|
|
|
|
|
|
|
| 89 |
|
| 90 |
accumulator += tl.dot(a, b) * a_s[:, None] * b_s[None, :]
|
| 91 |
a_ptrs += BLOCK_SIZE_K * stride_ak
|
|
|
|
| 105 |
tl.store(c_ptrs, c, mask=c_mask)
|
| 106 |
|
| 107 |
|
| 108 |
+
@triton.autotune(
|
| 109 |
+
configs=[
|
| 110 |
+
triton.Config({}, num_warps=w, num_stages=s)
|
| 111 |
+
for w in [2, 4, 8, 16]
|
| 112 |
+
for s in [2, 3, 4]
|
| 113 |
+
],
|
| 114 |
+
key=["N", "K", "BLOCK_SIZE_M"],
|
| 115 |
+
)
|
| 116 |
@triton.jit
|
| 117 |
def w8a8_tensor_fp8_matmul_kernel(
|
| 118 |
A,
|
|
|
|
| 129 |
stride_bn,
|
| 130 |
stride_cm,
|
| 131 |
stride_cn,
|
| 132 |
+
stride_as_m,
|
| 133 |
BLOCK_SIZE_M: tl.constexpr,
|
| 134 |
BLOCK_SIZE_N: tl.constexpr,
|
| 135 |
BLOCK_SIZE_K: tl.constexpr,
|
|
|
|
| 139 |
|
| 140 |
Computes ``C = A @ B.T`` with one activation scale per row and one
|
| 141 |
weight scale for the full matrix.
|
| 142 |
+
Uses a 2D grid with swizzle for L2 cache locality on B tiles.
|
| 143 |
"""
|
| 144 |
+
pid_m = tl.program_id(axis=0)
|
| 145 |
+
pid_n = tl.program_id(axis=1)
|
| 146 |
num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
|
| 147 |
num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)
|
| 148 |
+
pid_m, pid_n = tl.swizzle2d(pid_m, pid_n, num_pid_m, num_pid_n, GROUP_SIZE_M)
|
| 149 |
+
|
| 150 |
+
offs_am = (pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
|
| 151 |
+
offs_bn = (pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)) % N
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
offs_k = tl.arange(0, BLOCK_SIZE_K)
|
| 153 |
|
| 154 |
a_ptrs = A + offs_am[:, None] * stride_am + offs_k[None, :] * stride_ak
|
| 155 |
b_ptrs = B + offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn
|
| 156 |
|
| 157 |
+
a_s = tl.load(As + offs_am * stride_as_m)
|
| 158 |
b_s = tl.load(Bs)
|
| 159 |
|
| 160 |
+
# Accumulate raw dot products, apply scales once after the loop.
|
| 161 |
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 162 |
for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
|
| 163 |
+
k_remaining = K - k * BLOCK_SIZE_K
|
| 164 |
+
a = tl.load(a_ptrs, mask=offs_k[None, :] < k_remaining, other=0.0)
|
| 165 |
+
b = tl.load(b_ptrs, mask=offs_k[:, None] < k_remaining, other=0.0)
|
| 166 |
+
accumulator += tl.dot(a, b)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
a_ptrs += BLOCK_SIZE_K * stride_ak
|
| 168 |
b_ptrs += BLOCK_SIZE_K * stride_bk
|
| 169 |
|
| 170 |
+
accumulator = accumulator * a_s[:, None] * b_s
|
| 171 |
+
|
| 172 |
if C.dtype.element_ty == tl.bfloat16:
|
| 173 |
c = accumulator.to(tl.bfloat16)
|
| 174 |
elif C.dtype.element_ty == tl.float16:
|
|
|
|
| 189 |
B: torch.Tensor,
|
| 190 |
As: torch.Tensor,
|
| 191 |
Bs: torch.Tensor,
|
| 192 |
+
block_size: list[int],
|
| 193 |
output_dtype: torch.dtype = torch.float32,
|
| 194 |
) -> torch.Tensor:
|
| 195 |
+
"""Block-scale FP8 matmul: C = A @ B.T with per-block scales.
|
| 196 |
|
| 197 |
+
As: (M, K // block_k) — per-token-group activation scales
|
| 198 |
+
Bs: (N // block_n, K // block_k) — per-block weight scales
|
|
|
|
| 199 |
"""
|
| 200 |
+
assert len(block_size) == 2, (
|
| 201 |
+
f"block_size must be [block_n, block_k], got {block_size}"
|
| 202 |
+
)
|
| 203 |
+
block_n, block_k = block_size[0], block_size[1]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
|
| 205 |
+
assert A.shape[-1] == B.shape[-1], (
|
| 206 |
+
f"K mismatch: A has K={A.shape[-1]}, B has K={B.shape[-1]}"
|
| 207 |
+
)
|
| 208 |
+
assert A.is_contiguous(), "A must be contiguous"
|
| 209 |
+
assert B.ndim == 2, f"B must be 2D (N, K), got ndim={B.ndim}"
|
| 210 |
+
assert B.is_contiguous(), "B must be contiguous"
|
| 211 |
|
| 212 |
N, K = B.shape
|
| 213 |
M = A.numel() // A.shape[-1]
|
| 214 |
|
| 215 |
+
assert As.ndim >= 2, f"As must be at least 2D, got ndim={As.ndim}"
|
| 216 |
+
assert As.shape[-1] == triton.cdiv(K, block_k), (
|
| 217 |
+
f"As last dim {As.shape[-1]} != expected {triton.cdiv(K, block_k)} (cdiv(K={K}, block_k={block_k}))"
|
| 218 |
+
)
|
| 219 |
+
assert Bs.ndim == 2, f"Bs must be 2D (N//block_n, K//block_k), got ndim={Bs.ndim}"
|
| 220 |
+
assert Bs.shape == (triton.cdiv(N, block_n), triton.cdiv(K, block_k)), (
|
| 221 |
+
f"Bs shape {tuple(Bs.shape)} != expected ({triton.cdiv(N, block_n)}, {triton.cdiv(K, block_k)})"
|
| 222 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
|
| 224 |
+
BLOCK_SIZE_K = block_k
|
| 225 |
+
BLOCK_SIZE_N = block_n
|
| 226 |
C_shape = A.shape[:-1] + (N,)
|
| 227 |
C = A.new_empty(C_shape, dtype=output_dtype)
|
|
|
|
| 228 |
# Adaptive BLOCK_SIZE_M: smallest power-of-2 >= M, floored at 16, capped at 128.
|
| 229 |
# Matches the WGMMA tile to the actual row count — smaller tiles use less
|
| 230 |
# register pressure and a better-matched FP8 WGMMA instruction, improving
|
| 231 |
# both accuracy and performance for small M (decode).
|
| 232 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2(M), 16), 128)
|
| 233 |
+
grid = (triton.cdiv(M, BLOCK_SIZE_M), triton.cdiv(N, BLOCK_SIZE_N))
|
| 234 |
+
with device_context(A.device):
|
| 235 |
+
wrap_triton(w8a8_block_fp8_matmul_kernel)[grid](
|
| 236 |
+
A,
|
| 237 |
+
B,
|
| 238 |
+
C,
|
| 239 |
+
As,
|
| 240 |
+
Bs,
|
| 241 |
+
M,
|
| 242 |
+
N,
|
| 243 |
+
K,
|
| 244 |
+
A.stride(-2),
|
| 245 |
+
A.stride(-1),
|
| 246 |
+
B.stride(1),
|
| 247 |
+
B.stride(0),
|
| 248 |
+
C.stride(-2),
|
| 249 |
+
C.stride(-1),
|
| 250 |
+
As.stride(-2),
|
| 251 |
+
As.stride(-1),
|
| 252 |
+
Bs.stride(1),
|
| 253 |
+
Bs.stride(0),
|
| 254 |
+
# Meta-parameters
|
| 255 |
+
BLOCK_SIZE_M=BLOCK_SIZE_M,
|
| 256 |
+
BLOCK_SIZE_N=BLOCK_SIZE_N,
|
| 257 |
+
BLOCK_SIZE_K=BLOCK_SIZE_K,
|
| 258 |
+
GROUP_SIZE_M=8,
|
| 259 |
+
)
|
|
|
|
|
|
|
|
|
|
| 260 |
|
| 261 |
return C
|
| 262 |
|
|
|
|
| 267 |
B: torch.Tensor,
|
| 268 |
As: torch.Tensor,
|
| 269 |
Bs: torch.Tensor,
|
|
|
|
| 270 |
output_dtype: torch.dtype = torch.float32,
|
| 271 |
) -> torch.Tensor:
|
| 272 |
+
"""Tensor-scale FP8 matmul: C = A @ B.T with per-row / per-tensor scales.
|
| 273 |
|
| 274 |
+
As: scalar, (M,), or (M, 1) — per-row activation scales
|
| 275 |
+
Bs: scalar, (1,), or (1, 1) — single weight scale
|
|
|
|
|
|
|
| 276 |
"""
|
| 277 |
+
assert A.shape[-1] == B.shape[-1], (
|
| 278 |
+
f"K mismatch: A has K={A.shape[-1]}, B has K={B.shape[-1]}"
|
| 279 |
+
)
|
| 280 |
+
assert A.is_contiguous(), "A must be contiguous"
|
| 281 |
+
assert B.ndim == 2, f"B must be 2D (N, K), got ndim={B.ndim}"
|
| 282 |
+
assert B.is_contiguous(), "B must be contiguous"
|
| 283 |
|
| 284 |
N, K = B.shape
|
| 285 |
M = A.numel() // A.shape[-1]
|
| 286 |
|
| 287 |
+
# Normalize As to (M,)
|
|
|
|
|
|
|
| 288 |
if As.numel() == 1:
|
| 289 |
As = As.reshape(1).expand(M).contiguous()
|
| 290 |
+
elif As.ndim == 2:
|
| 291 |
+
As = As.reshape(M)
|
| 292 |
+
assert As.ndim == 1 and As.shape[0] == M, (
|
| 293 |
+
f"As must be scalar, (M,), or (M,1) with M={M}, got {tuple(As.shape)}"
|
| 294 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 295 |
|
| 296 |
+
# Normalize Bs to (1,)
|
| 297 |
+
assert Bs.numel() == 1, f"Bs must be scalar or (1,), got {tuple(Bs.shape)}"
|
| 298 |
+
Bs = Bs.reshape(1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
|
| 300 |
+
BLOCK_SIZE_N = 128
|
| 301 |
+
BLOCK_SIZE_K = 128
|
| 302 |
C_shape = A.shape[:-1] + (N,)
|
| 303 |
C = A.new_empty(C_shape, dtype=output_dtype)
|
|
|
|
| 304 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2(M), 16), 128)
|
| 305 |
+
grid = (triton.cdiv(M, BLOCK_SIZE_M), triton.cdiv(N, BLOCK_SIZE_N))
|
| 306 |
+
with device_context(A.device):
|
| 307 |
+
wrap_triton(w8a8_tensor_fp8_matmul_kernel)[grid](
|
| 308 |
+
A,
|
| 309 |
+
B,
|
| 310 |
+
C,
|
| 311 |
+
As,
|
| 312 |
+
Bs,
|
| 313 |
+
M,
|
| 314 |
+
N,
|
| 315 |
+
K,
|
| 316 |
+
A.stride(-2),
|
| 317 |
+
A.stride(-1),
|
| 318 |
+
B.stride(1),
|
| 319 |
+
B.stride(0),
|
| 320 |
+
C.stride(-2),
|
| 321 |
+
C.stride(-1),
|
| 322 |
+
As.stride(0),
|
| 323 |
+
# Meta-parameters
|
| 324 |
+
BLOCK_SIZE_M=BLOCK_SIZE_M,
|
| 325 |
+
BLOCK_SIZE_N=BLOCK_SIZE_N,
|
| 326 |
+
BLOCK_SIZE_K=BLOCK_SIZE_K,
|
| 327 |
+
GROUP_SIZE_M=8,
|
| 328 |
+
)
|
|
|
|
| 329 |
|
| 330 |
return C
|
| 331 |
|
|
|
|
| 335 |
B: torch.Tensor,
|
| 336 |
As: torch.Tensor,
|
| 337 |
Bs: torch.Tensor,
|
| 338 |
+
block_size: list[int],
|
| 339 |
output_dtype: torch.dtype = torch.float32,
|
| 340 |
) -> torch.Tensor:
|
| 341 |
"""Block-wise W8A8 FP8 matrix multiplication.
|
|
|
|
| 365 |
B: torch.Tensor,
|
| 366 |
As: torch.Tensor,
|
| 367 |
Bs: torch.Tensor,
|
|
|
|
| 368 |
output_dtype: torch.dtype = torch.float32,
|
| 369 |
) -> torch.Tensor:
|
| 370 |
"""Tensor-scale W8A8 FP8 matrix multiplication.
|
|
|
|
| 375 |
Args:
|
| 376 |
A: Quantized activation tensor ``[M, K]`` in ``float8_e4m3fn``.
|
| 377 |
B: Quantized weight tensor ``[N, K]`` in ``float8_e4m3fn``.
|
| 378 |
+
As: Per-row activation scales ``[M]``.
|
| 379 |
+
Bs: Single weight scale, scalar or ``[1]``.
|
|
|
|
| 380 |
output_dtype: dtype of the returned tensor.
|
| 381 |
|
| 382 |
Returns:
|
| 383 |
Output tensor ``[M, N]`` in ``output_dtype``.
|
| 384 |
"""
|
| 385 |
+
return torch.ops.finegrained_fp8.w8a8_tensor_fp8_matmul(A, B, As, Bs, output_dtype)
|
|
|
|
|
|
|
| 386 |
|
| 387 |
|
| 388 |
def w8a8_fp8_matmul(
|
|
|
|
| 406 |
if block_size is None or (
|
| 407 |
block_size[0] == B.size(0) and block_size[1] == B.size(1)
|
| 408 |
):
|
| 409 |
+
return w8a8_tensor_fp8_matmul(A, B, As, Bs, output_dtype)
|
| 410 |
|
| 411 |
return w8a8_block_fp8_matmul(A, B, As, Bs, block_size, output_dtype)
|
build/torch-cuda/utils.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from contextlib import contextmanager
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
@contextmanager
|
| 6 |
+
def device_context(device: torch.device):
|
| 7 |
+
"""Context manager that sets the active device for any backend (cuda, xpu, etc.)."""
|
| 8 |
+
backend = getattr(torch, device.type, None)
|
| 9 |
+
if backend is not None and hasattr(backend, "device"):
|
| 10 |
+
with backend.device(device):
|
| 11 |
+
yield
|
| 12 |
+
else:
|
| 13 |
+
yield
|
build/torch-rocm/_ops.py
CHANGED
|
@@ -1,8 +1,8 @@
|
|
| 1 |
import torch
|
| 2 |
-
ops = torch.ops.
|
| 3 |
|
| 4 |
def add_op_namespace_prefix(op_name: str):
|
| 5 |
"""
|
| 6 |
Prefix op by namespace.
|
| 7 |
"""
|
| 8 |
-
return f"
|
|
|
|
| 1 |
import torch
|
| 2 |
+
ops = torch.ops._finegrained_fp8_75cbe1b
|
| 3 |
|
| 4 |
def add_op_namespace_prefix(op_name: str):
|
| 5 |
"""
|
| 6 |
Prefix op by namespace.
|
| 7 |
"""
|
| 8 |
+
return f"_finegrained_fp8_75cbe1b::{op_name}"
|
build/torch-rocm/act_quant.py
CHANGED
|
@@ -17,6 +17,8 @@ import triton
|
|
| 17 |
import triton.language as tl
|
| 18 |
from torch.library import triton_op, wrap_triton
|
| 19 |
|
|
|
|
|
|
|
| 20 |
|
| 21 |
_FP8_DTYPE = torch.float8_e4m3fn
|
| 22 |
|
|
@@ -40,10 +42,12 @@ def _fp8_act_quant(
|
|
| 40 |
assert x.is_contiguous()
|
| 41 |
assert x.shape[-1] % block_size == 0
|
| 42 |
y = torch.empty_like(x, dtype=_FP8_DTYPE)
|
|
|
|
| 43 |
s = x.new_empty(*x.size()[:-1], x.size(-1) // block_size, dtype=torch.float32)
|
| 44 |
|
| 45 |
-
|
| 46 |
-
|
|
|
|
| 47 |
return y, s
|
| 48 |
|
| 49 |
|
|
|
|
| 17 |
import triton.language as tl
|
| 18 |
from torch.library import triton_op, wrap_triton
|
| 19 |
|
| 20 |
+
from .utils import device_context
|
| 21 |
+
|
| 22 |
|
| 23 |
_FP8_DTYPE = torch.float8_e4m3fn
|
| 24 |
|
|
|
|
| 42 |
assert x.is_contiguous()
|
| 43 |
assert x.shape[-1] % block_size == 0
|
| 44 |
y = torch.empty_like(x, dtype=_FP8_DTYPE)
|
| 45 |
+
grid = (triton.cdiv(x.numel(), block_size),)
|
| 46 |
s = x.new_empty(*x.size()[:-1], x.size(-1) // block_size, dtype=torch.float32)
|
| 47 |
|
| 48 |
+
with device_context(x.device):
|
| 49 |
+
wrap_triton(_fp8_act_quant_kernel)[grid](x, y, s, BLOCK_SIZE=block_size)
|
| 50 |
+
|
| 51 |
return y, s
|
| 52 |
|
| 53 |
|
build/torch-rocm/batched.py
CHANGED
|
@@ -18,6 +18,8 @@ import triton.language as tl
|
|
| 18 |
from .act_quant import fp8_act_quant
|
| 19 |
from torch.library import triton_op, wrap_triton
|
| 20 |
|
|
|
|
|
|
|
| 21 |
|
| 22 |
@triton.autotune(
|
| 23 |
configs=[
|
|
@@ -32,27 +34,25 @@ def w8a8_block_fp8_matmul_batched_kernel(
|
|
| 32 |
A, # (S, K) raw BF16/FP16 activations
|
| 33 |
B, # (E, N, K) FP8 weight matrices
|
| 34 |
C, # (S, N) output
|
| 35 |
-
Bs, # (E, N //
|
| 36 |
ExpertIds, # (S,) — which expert each batch element routes to
|
| 37 |
# Shape
|
| 38 |
S,
|
| 39 |
N,
|
| 40 |
K,
|
| 41 |
-
|
| 42 |
stride_ak,
|
|
|
|
| 43 |
stride_bk,
|
| 44 |
stride_bn,
|
|
|
|
| 45 |
stride_cn,
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
stride_Ab, # stride between rows in A (one token per program)
|
| 50 |
-
stride_Eb, # stride between experts in B
|
| 51 |
-
stride_Cb, # stride between rows in C (one token per program)
|
| 52 |
-
stride_Esb, # stride between experts in Bs
|
| 53 |
# Meta-parameters
|
| 54 |
-
|
| 55 |
-
|
| 56 |
BLOCK_SIZE_M: tl.constexpr,
|
| 57 |
):
|
| 58 |
"""Block-scale batched FP8 expert matmul kernel.
|
|
@@ -63,40 +63,35 @@ def w8a8_block_fp8_matmul_batched_kernel(
|
|
| 63 |
batch_id = tl.program_id(axis=0)
|
| 64 |
pid_n = tl.program_id(axis=1)
|
| 65 |
|
| 66 |
-
# Advance base pointers to this token's activation row and its expert's
|
| 67 |
-
# weight / scale slice. No pre-gather of weights needed (like in non-fp8 impls)
|
| 68 |
# Cast expert_id to int64 to prevent int32 overflow when computing
|
| 69 |
# expert_id * stride_Eb (e.g. 255 * 9_437_184 > 2^31 for 256 experts of
|
| 70 |
# 3072×3072 FP8 weights).
|
| 71 |
expert_id = tl.load(ExpertIds + batch_id).to(tl.int64)
|
| 72 |
|
| 73 |
-
A = A + batch_id *
|
| 74 |
-
B = B + expert_id *
|
| 75 |
-
C = C + batch_id *
|
| 76 |
-
Bs = Bs + expert_id *
|
| 77 |
|
| 78 |
-
offs_bn = pid_n *
|
| 79 |
-
offs_k = tl.arange(0,
|
| 80 |
a_ptrs = A + tl.arange(0, BLOCK_SIZE_M)[:, None] * 0 + offs_k[None, :] * stride_ak
|
| 81 |
b_ptrs = B + (offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn)
|
| 82 |
|
| 83 |
-
|
| 84 |
-
Bs_ptrs = Bs + offs_bsn * stride_Bs_n
|
| 85 |
|
| 86 |
-
accumulator = tl.zeros((BLOCK_SIZE_M,
|
| 87 |
-
for k in range(0, tl.cdiv(K,
|
| 88 |
# ---- fused fp8_act_quant ----
|
| 89 |
a_raw = tl.load(a_ptrs).to(tl.float32)
|
| 90 |
-
a_s = tl.max(tl.abs(a_raw)) / 448.0
|
| 91 |
a = (a_raw / tl.maximum(a_s, 1e-12)).to(tl.float8e4nv)
|
| 92 |
-
# ----
|
| 93 |
b = tl.load(b_ptrs)
|
| 94 |
-
|
| 95 |
-
offs_ks = k_start // block_k
|
| 96 |
-
b_s = tl.load(Bs_ptrs + offs_ks * stride_Bs_k)
|
| 97 |
accumulator += tl.dot(a, b) * a_s * b_s[None, :]
|
| 98 |
-
a_ptrs +=
|
| 99 |
-
b_ptrs +=
|
| 100 |
|
| 101 |
if C.dtype.element_ty == tl.bfloat16:
|
| 102 |
c = accumulator.to(tl.bfloat16)
|
|
@@ -106,7 +101,7 @@ def w8a8_block_fp8_matmul_batched_kernel(
|
|
| 106 |
c = accumulator.to(tl.float32)
|
| 107 |
|
| 108 |
offs_cm = tl.arange(0, BLOCK_SIZE_M)
|
| 109 |
-
offs_cn = pid_n *
|
| 110 |
c_ptrs = C + offs_cm[:, None] * 0 + stride_cn * offs_cn[None, :]
|
| 111 |
tl.store(c_ptrs, c)
|
| 112 |
|
|
@@ -130,17 +125,17 @@ def w8a8_tensor_fp8_matmul_batched_kernel(
|
|
| 130 |
S,
|
| 131 |
N,
|
| 132 |
K,
|
|
|
|
| 133 |
stride_ak,
|
|
|
|
| 134 |
stride_bk,
|
| 135 |
stride_bn,
|
|
|
|
| 136 |
stride_cn,
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
stride_Esb,
|
| 142 |
-
block_n: tl.constexpr,
|
| 143 |
-
block_k: tl.constexpr,
|
| 144 |
BLOCK_SIZE_M: tl.constexpr,
|
| 145 |
):
|
| 146 |
"""Tensor-scale batched FP8 expert matmul kernel.
|
|
@@ -153,27 +148,28 @@ def w8a8_tensor_fp8_matmul_batched_kernel(
|
|
| 153 |
|
| 154 |
expert_id = tl.load(ExpertIds + batch_id).to(tl.int64)
|
| 155 |
|
| 156 |
-
A = A + batch_id *
|
| 157 |
-
B = B + expert_id *
|
| 158 |
-
C = C + batch_id *
|
| 159 |
-
Bs = Bs + expert_id *
|
| 160 |
|
| 161 |
-
offs_bn = pid_n *
|
| 162 |
-
offs_k = tl.arange(0,
|
| 163 |
a_ptrs = A + tl.arange(0, BLOCK_SIZE_M)[:, None] * 0 + offs_k[None, :] * stride_ak
|
| 164 |
b_ptrs = B + (offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn)
|
| 165 |
|
| 166 |
b_s = tl.load(Bs)
|
| 167 |
-
a_s = tl.load(As + batch_id *
|
| 168 |
|
| 169 |
-
accumulator = tl.zeros((BLOCK_SIZE_M,
|
| 170 |
-
for _ in range(0, tl.cdiv(K,
|
| 171 |
a = tl.load(a_ptrs)
|
| 172 |
b = tl.load(b_ptrs)
|
|
|
|
|
|
|
|
|
|
| 173 |
|
| 174 |
-
|
| 175 |
-
a_ptrs += block_k * stride_ak
|
| 176 |
-
b_ptrs += block_k * stride_bk
|
| 177 |
|
| 178 |
if C.dtype.element_ty == tl.bfloat16:
|
| 179 |
c = accumulator.to(tl.bfloat16)
|
|
@@ -183,7 +179,7 @@ def w8a8_tensor_fp8_matmul_batched_kernel(
|
|
| 183 |
c = accumulator.to(tl.float32)
|
| 184 |
|
| 185 |
offs_cm = tl.arange(0, BLOCK_SIZE_M)
|
| 186 |
-
offs_cn = pid_n *
|
| 187 |
c_ptrs = C + offs_cm[:, None] * 0 + stride_cn * offs_cn[None, :]
|
| 188 |
tl.store(c_ptrs, c)
|
| 189 |
|
|
@@ -194,91 +190,70 @@ def _w8a8_block_fp8_matmul_batched(
|
|
| 194 |
B: torch.Tensor,
|
| 195 |
Bs: torch.Tensor,
|
| 196 |
expert_ids: torch.Tensor,
|
| 197 |
-
block_size: list[int]
|
| 198 |
) -> torch.Tensor:
|
| 199 |
-
"""
|
| 200 |
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
"""
|
| 205 |
-
assert A.ndim == 2, "A must be (S, K)"
|
| 206 |
assert A.is_contiguous(), "A must be contiguous"
|
| 207 |
-
|
| 208 |
-
assert B.ndim == 3, "B must be (E, N, K)"
|
| 209 |
assert B.is_contiguous(), "B must be contiguous"
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
assert Bs.is_contiguous(), "Bs must be contiguous"
|
| 214 |
|
| 215 |
S, K = A.shape
|
| 216 |
-
E, N,
|
| 217 |
|
| 218 |
-
|
| 219 |
-
block_n, block_k
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
# if we have per-tensor quantization, we use 128x128 block size for tiled matmul multiplication
|
| 224 |
-
if block_n == N and block_k == K:
|
| 225 |
-
block_n, block_k = 128, 128
|
| 226 |
-
|
| 227 |
-
# we specifically require block-aligned shapes to keep the kernel simpler
|
| 228 |
assert N % block_n == 0, f"N ({N}) must be divisible by block_n ({block_n})"
|
| 229 |
assert K % block_k == 0, f"K ({K}) must be divisible by block_k ({block_k})"
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
Bs
|
| 235 |
-
|
| 236 |
-
Bs = Bs.expand(E, N // block_n, K // block_k)
|
| 237 |
-
else:
|
| 238 |
-
assert Bs.ndim == 3, (
|
| 239 |
-
"Bs must be either (E,) / (E,1,1) for per-tensor scales or (E,N//block_n,K//block_k)"
|
| 240 |
-
)
|
| 241 |
-
assert Bs.shape[0] == E, (
|
| 242 |
-
f"Bs expert dim mismatch: expected {E}, got {Bs.shape[0]}"
|
| 243 |
-
)
|
| 244 |
-
assert Bs.shape[1] == N // block_n, (
|
| 245 |
-
f"Bs N-block dim mismatch: expected {N // block_n}, got {Bs.shape[1]}"
|
| 246 |
-
)
|
| 247 |
-
assert Bs.shape[2] == K // block_k, (
|
| 248 |
-
f"Bs K-block dim mismatch: expected {K // block_k}, got {Bs.shape[2]}"
|
| 249 |
-
)
|
| 250 |
|
| 251 |
C = A.new_empty(S, N)
|
| 252 |
-
grid = (S, triton.cdiv(N, block_n))
|
| 253 |
# Adaptive BLOCK_SIZE_M: smallest power-of-2 >= M, floored at 16, capped at 128.
|
| 254 |
# Matches the WGMMA tile to the actual row count — smaller tiles use less
|
| 255 |
# register pressure and a better-matched FP8 WGMMA instruction, improving
|
| 256 |
# both accuracy and performance for small M (decode).
|
| 257 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2((S + E - 1) // E), 16), 128)
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
|
|
|
| 282 |
|
| 283 |
return C
|
| 284 |
|
|
@@ -289,71 +264,68 @@ def _w8a8_tensor_fp8_matmul_batched(
|
|
| 289 |
B: torch.Tensor,
|
| 290 |
Bs: torch.Tensor,
|
| 291 |
expert_ids: torch.Tensor,
|
| 292 |
-
block_size: list[int] | None,
|
| 293 |
) -> torch.Tensor:
|
| 294 |
-
"""Tensor-scale batched FP8 matmul
|
| 295 |
-
|
| 296 |
-
Activations are quantized once with per-token tensor scales and multiplied
|
| 297 |
-
with expert-selected FP8 weights using per-expert tensor scales.
|
| 298 |
|
| 299 |
-
|
|
|
|
|
|
|
| 300 |
"""
|
| 301 |
-
assert A.ndim == 2, "A must be (S, K)"
|
| 302 |
assert A.is_contiguous(), "A must be contiguous"
|
| 303 |
-
|
| 304 |
-
assert B.ndim == 3, "B must be (E, N, K)"
|
| 305 |
assert B.is_contiguous(), "B must be contiguous"
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
assert Bs.is_contiguous(), "Bs must be contiguous"
|
| 310 |
|
| 311 |
S, K = A.shape
|
| 312 |
-
E, N,
|
| 313 |
|
|
|
|
| 314 |
if Bs.ndim == 1:
|
|
|
|
| 315 |
Bs = Bs.reshape(E, 1, 1)
|
| 316 |
-
elif Bs.ndim == 3 and Bs.shape[0] == E and Bs.shape[1] == 1 and Bs.shape[2] == 1:
|
| 317 |
-
pass
|
| 318 |
else:
|
| 319 |
-
assert Bs.
|
| 320 |
-
|
| 321 |
-
f"Tensor mode expects Bs shape (E,1,1), got {tuple(Bs.shape)}"
|
| 322 |
)
|
| 323 |
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
assert N % block_n == 0, f"N ({N}) must be divisible by block_n ({block_n})"
|
| 327 |
-
assert K % block_k == 0, f"K ({K}) must be divisible by block_k ({block_k})"
|
| 328 |
-
|
| 329 |
C = A.new_empty(S, N)
|
| 330 |
-
BLOCK_SIZE_M = min(max(triton.next_power_of_2((S + E - 1) // E), 16), 128)
|
| 331 |
qA, As = fp8_act_quant(A, K)
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 357 |
|
| 358 |
return C
|
| 359 |
|
|
@@ -363,25 +335,13 @@ def w8a8_block_fp8_matmul_batched(
|
|
| 363 |
B: torch.Tensor,
|
| 364 |
Bs: torch.Tensor,
|
| 365 |
expert_ids: torch.Tensor,
|
| 366 |
-
block_size: list[int]
|
| 367 |
) -> torch.Tensor:
|
| 368 |
-
"""
|
| 369 |
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
``(S, N, K)`` weight gather needed — and accumulates in float32.
|
| 374 |
-
|
| 375 |
-
Args:
|
| 376 |
-
A: Raw activation matrix ``[S, K]`` in bf16/fp16/fp32.
|
| 377 |
-
B: Stacked expert weight tensor ``[E, N, K]`` in ``float8_e4m3fn``.
|
| 378 |
-
Bs: Expert weight scales, accepted as ``[E, nb, kb]`` (block)
|
| 379 |
-
or ``[E]`` / ``[E,1,1]`` (per-tensor; expanded internally).
|
| 380 |
-
expert_ids: Expert index per token ``[S]``, values in ``[0, E)``.
|
| 381 |
-
block_size: ``[block_n, block_k]`` quantization block dimensions, e.g. ``[128, 128]``.
|
| 382 |
-
|
| 383 |
-
Returns:
|
| 384 |
-
Output tensor ``[S, N]`` in the same dtype as ``A``.
|
| 385 |
"""
|
| 386 |
return torch.ops.finegrained_fp8.w8a8_block_fp8_matmul_batched(
|
| 387 |
A, B, Bs, expert_ids, block_size
|
|
@@ -393,22 +353,15 @@ def w8a8_tensor_fp8_matmul_batched(
|
|
| 393 |
B: torch.Tensor,
|
| 394 |
Bs: torch.Tensor,
|
| 395 |
expert_ids: torch.Tensor,
|
| 396 |
-
block_size: list[int] | None,
|
| 397 |
) -> torch.Tensor:
|
| 398 |
-
"""Tensor-scale batched
|
| 399 |
-
|
| 400 |
-
Args:
|
| 401 |
-
A: Raw activation matrix ``[S, K]`` in bf16/fp16/fp32.
|
| 402 |
-
B: Stacked expert weight tensor ``[E, N, K]`` in ``float8_e4m3fn``.
|
| 403 |
-
Bs: Per-expert tensor scales ``[E]`` or ``[E,1,1]``.
|
| 404 |
-
expert_ids: Expert index per token ``[S]``, values in ``[0, E)``.
|
| 405 |
-
block_size: Kept for API consistency; tensor path derives tile sizes from ``N`` and ``K``.
|
| 406 |
|
| 407 |
-
|
| 408 |
-
|
|
|
|
| 409 |
"""
|
| 410 |
return torch.ops.finegrained_fp8.w8a8_tensor_fp8_matmul_batched(
|
| 411 |
-
A, B, Bs, expert_ids
|
| 412 |
)
|
| 413 |
|
| 414 |
|
|
@@ -432,6 +385,6 @@ def w8a8_fp8_matmul_batched(
|
|
| 432 |
if block_size is None or (
|
| 433 |
block_size[0] == B.size(1) and block_size[1] == B.size(2)
|
| 434 |
):
|
| 435 |
-
return w8a8_tensor_fp8_matmul_batched(A, B, Bs, expert_ids
|
| 436 |
|
| 437 |
return w8a8_block_fp8_matmul_batched(A, B, Bs, expert_ids, block_size)
|
|
|
|
| 18 |
from .act_quant import fp8_act_quant
|
| 19 |
from torch.library import triton_op, wrap_triton
|
| 20 |
|
| 21 |
+
from .utils import device_context
|
| 22 |
+
|
| 23 |
|
| 24 |
@triton.autotune(
|
| 25 |
configs=[
|
|
|
|
| 34 |
A, # (S, K) raw BF16/FP16 activations
|
| 35 |
B, # (E, N, K) FP8 weight matrices
|
| 36 |
C, # (S, N) output
|
| 37 |
+
Bs, # (E, N // BLOCK_SIZE_N, K // BLOCK_SIZE_K) weight scales
|
| 38 |
ExpertIds, # (S,) — which expert each batch element routes to
|
| 39 |
# Shape
|
| 40 |
S,
|
| 41 |
N,
|
| 42 |
K,
|
| 43 |
+
stride_am,
|
| 44 |
stride_ak,
|
| 45 |
+
stride_be,
|
| 46 |
stride_bk,
|
| 47 |
stride_bn,
|
| 48 |
+
stride_cm,
|
| 49 |
stride_cn,
|
| 50 |
+
stride_bs_e,
|
| 51 |
+
stride_bs_k,
|
| 52 |
+
stride_bs_n,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
# Meta-parameters
|
| 54 |
+
BLOCK_SIZE_N: tl.constexpr,
|
| 55 |
+
BLOCK_SIZE_K: tl.constexpr,
|
| 56 |
BLOCK_SIZE_M: tl.constexpr,
|
| 57 |
):
|
| 58 |
"""Block-scale batched FP8 expert matmul kernel.
|
|
|
|
| 63 |
batch_id = tl.program_id(axis=0)
|
| 64 |
pid_n = tl.program_id(axis=1)
|
| 65 |
|
|
|
|
|
|
|
| 66 |
# Cast expert_id to int64 to prevent int32 overflow when computing
|
| 67 |
# expert_id * stride_Eb (e.g. 255 * 9_437_184 > 2^31 for 256 experts of
|
| 68 |
# 3072×3072 FP8 weights).
|
| 69 |
expert_id = tl.load(ExpertIds + batch_id).to(tl.int64)
|
| 70 |
|
| 71 |
+
A = A + batch_id * stride_am
|
| 72 |
+
B = B + expert_id * stride_be
|
| 73 |
+
C = C + batch_id * stride_cm
|
| 74 |
+
Bs = Bs + expert_id * stride_bs_e
|
| 75 |
|
| 76 |
+
offs_bn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 77 |
+
offs_k = tl.arange(0, BLOCK_SIZE_K)
|
| 78 |
a_ptrs = A + tl.arange(0, BLOCK_SIZE_M)[:, None] * 0 + offs_k[None, :] * stride_ak
|
| 79 |
b_ptrs = B + (offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn)
|
| 80 |
|
| 81 |
+
bs_ptrs = Bs + pid_n * stride_bs_n
|
|
|
|
| 82 |
|
| 83 |
+
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 84 |
+
for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
|
| 85 |
# ---- fused fp8_act_quant ----
|
| 86 |
a_raw = tl.load(a_ptrs).to(tl.float32)
|
| 87 |
+
a_s = tl.max(tl.abs(a_raw)) / 448.0
|
| 88 |
a = (a_raw / tl.maximum(a_s, 1e-12)).to(tl.float8e4nv)
|
| 89 |
+
# ---- matmul ----
|
| 90 |
b = tl.load(b_ptrs)
|
| 91 |
+
b_s = tl.load(bs_ptrs + k * stride_bs_k)
|
|
|
|
|
|
|
| 92 |
accumulator += tl.dot(a, b) * a_s * b_s[None, :]
|
| 93 |
+
a_ptrs += BLOCK_SIZE_K * stride_ak
|
| 94 |
+
b_ptrs += BLOCK_SIZE_K * stride_bk
|
| 95 |
|
| 96 |
if C.dtype.element_ty == tl.bfloat16:
|
| 97 |
c = accumulator.to(tl.bfloat16)
|
|
|
|
| 101 |
c = accumulator.to(tl.float32)
|
| 102 |
|
| 103 |
offs_cm = tl.arange(0, BLOCK_SIZE_M)
|
| 104 |
+
offs_cn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 105 |
c_ptrs = C + offs_cm[:, None] * 0 + stride_cn * offs_cn[None, :]
|
| 106 |
tl.store(c_ptrs, c)
|
| 107 |
|
|
|
|
| 125 |
S,
|
| 126 |
N,
|
| 127 |
K,
|
| 128 |
+
stride_am,
|
| 129 |
stride_ak,
|
| 130 |
+
stride_be,
|
| 131 |
stride_bk,
|
| 132 |
stride_bn,
|
| 133 |
+
stride_cm,
|
| 134 |
stride_cn,
|
| 135 |
+
stride_as_m,
|
| 136 |
+
stride_bs_e,
|
| 137 |
+
BLOCK_SIZE_N: tl.constexpr,
|
| 138 |
+
BLOCK_SIZE_K: tl.constexpr,
|
|
|
|
|
|
|
|
|
|
| 139 |
BLOCK_SIZE_M: tl.constexpr,
|
| 140 |
):
|
| 141 |
"""Tensor-scale batched FP8 expert matmul kernel.
|
|
|
|
| 148 |
|
| 149 |
expert_id = tl.load(ExpertIds + batch_id).to(tl.int64)
|
| 150 |
|
| 151 |
+
A = A + batch_id * stride_am
|
| 152 |
+
B = B + expert_id * stride_be
|
| 153 |
+
C = C + batch_id * stride_cm
|
| 154 |
+
Bs = Bs + expert_id * stride_bs_e
|
| 155 |
|
| 156 |
+
offs_bn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 157 |
+
offs_k = tl.arange(0, BLOCK_SIZE_K)
|
| 158 |
a_ptrs = A + tl.arange(0, BLOCK_SIZE_M)[:, None] * 0 + offs_k[None, :] * stride_ak
|
| 159 |
b_ptrs = B + (offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn)
|
| 160 |
|
| 161 |
b_s = tl.load(Bs)
|
| 162 |
+
a_s = tl.load(As + batch_id * stride_as_m)
|
| 163 |
|
| 164 |
+
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 165 |
+
for _ in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
|
| 166 |
a = tl.load(a_ptrs)
|
| 167 |
b = tl.load(b_ptrs)
|
| 168 |
+
accumulator += tl.dot(a, b)
|
| 169 |
+
a_ptrs += BLOCK_SIZE_K * stride_ak
|
| 170 |
+
b_ptrs += BLOCK_SIZE_K * stride_bk
|
| 171 |
|
| 172 |
+
accumulator = accumulator * a_s * b_s
|
|
|
|
|
|
|
| 173 |
|
| 174 |
if C.dtype.element_ty == tl.bfloat16:
|
| 175 |
c = accumulator.to(tl.bfloat16)
|
|
|
|
| 179 |
c = accumulator.to(tl.float32)
|
| 180 |
|
| 181 |
offs_cm = tl.arange(0, BLOCK_SIZE_M)
|
| 182 |
+
offs_cn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 183 |
c_ptrs = C + offs_cm[:, None] * 0 + stride_cn * offs_cn[None, :]
|
| 184 |
tl.store(c_ptrs, c)
|
| 185 |
|
|
|
|
| 190 |
B: torch.Tensor,
|
| 191 |
Bs: torch.Tensor,
|
| 192 |
expert_ids: torch.Tensor,
|
| 193 |
+
block_size: list[int],
|
| 194 |
) -> torch.Tensor:
|
| 195 |
+
"""Block-scale batched FP8 matmul: C[s] = A[s] @ B[expert_ids[s]].T, with fused act quant.
|
| 196 |
|
| 197 |
+
A: (S, K) raw bf16/fp16 activations
|
| 198 |
+
B: (E, N, K) FP8 expert weights
|
| 199 |
+
Bs: (E, N // block_n, K // block_k) per-block weight scales
|
| 200 |
"""
|
| 201 |
+
assert A.ndim == 2, f"A must be 2D (S, K), got ndim={A.ndim}"
|
| 202 |
assert A.is_contiguous(), "A must be contiguous"
|
| 203 |
+
assert B.ndim == 3, f"B must be 3D (E, N, K), got ndim={B.ndim}"
|
|
|
|
| 204 |
assert B.is_contiguous(), "B must be contiguous"
|
| 205 |
+
assert A.shape[1] == B.shape[2], (
|
| 206 |
+
f"K mismatch: A has K={A.shape[1]}, B has K={B.shape[2]}"
|
| 207 |
+
)
|
|
|
|
| 208 |
|
| 209 |
S, K = A.shape
|
| 210 |
+
E, N, _ = B.shape
|
| 211 |
|
| 212 |
+
assert len(block_size) == 2, (
|
| 213 |
+
f"block_size must be [block_n, block_k], got {block_size}"
|
| 214 |
+
)
|
| 215 |
+
block_n, block_k = block_size[0], block_size[1]
|
| 216 |
+
# MoE expert dimensions must be block-aligned; non-aligned N/K is not supported.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
assert N % block_n == 0, f"N ({N}) must be divisible by block_n ({block_n})"
|
| 218 |
assert K % block_k == 0, f"K ({K}) must be divisible by block_k ({block_k})"
|
| 219 |
+
assert Bs.ndim == 3, (
|
| 220 |
+
f"Bs must be 3D (E, N//block_n, K//block_k), got ndim={Bs.ndim}"
|
| 221 |
+
)
|
| 222 |
+
assert Bs.shape == (E, N // block_n, K // block_k), (
|
| 223 |
+
f"Bs shape {tuple(Bs.shape)} != expected ({E}, {N // block_n}, {K // block_k})"
|
| 224 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
|
| 226 |
C = A.new_empty(S, N)
|
|
|
|
| 227 |
# Adaptive BLOCK_SIZE_M: smallest power-of-2 >= M, floored at 16, capped at 128.
|
| 228 |
# Matches the WGMMA tile to the actual row count — smaller tiles use less
|
| 229 |
# register pressure and a better-matched FP8 WGMMA instruction, improving
|
| 230 |
# both accuracy and performance for small M (decode).
|
| 231 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2((S + E - 1) // E), 16), 128)
|
| 232 |
+
grid = (S, triton.cdiv(N, block_n))
|
| 233 |
+
with device_context(A.device):
|
| 234 |
+
wrap_triton(w8a8_block_fp8_matmul_batched_kernel)[grid](
|
| 235 |
+
A,
|
| 236 |
+
B,
|
| 237 |
+
C,
|
| 238 |
+
Bs,
|
| 239 |
+
expert_ids,
|
| 240 |
+
S,
|
| 241 |
+
N,
|
| 242 |
+
K,
|
| 243 |
+
A.stride(0),
|
| 244 |
+
A.stride(1),
|
| 245 |
+
B.stride(0),
|
| 246 |
+
B.stride(2),
|
| 247 |
+
B.stride(1),
|
| 248 |
+
C.stride(0),
|
| 249 |
+
C.stride(1),
|
| 250 |
+
Bs.stride(0),
|
| 251 |
+
Bs.stride(2),
|
| 252 |
+
Bs.stride(1),
|
| 253 |
+
BLOCK_SIZE_N=block_n,
|
| 254 |
+
BLOCK_SIZE_K=block_k,
|
| 255 |
+
BLOCK_SIZE_M=BLOCK_SIZE_M,
|
| 256 |
+
)
|
| 257 |
|
| 258 |
return C
|
| 259 |
|
|
|
|
| 264 |
B: torch.Tensor,
|
| 265 |
Bs: torch.Tensor,
|
| 266 |
expert_ids: torch.Tensor,
|
|
|
|
| 267 |
) -> torch.Tensor:
|
| 268 |
+
"""Tensor-scale batched FP8 matmul: C[s] = A[s] @ B[expert_ids[s]].T, with fused act quant.
|
|
|
|
|
|
|
|
|
|
| 269 |
|
| 270 |
+
A: (S, K) raw bf16/fp16 activations
|
| 271 |
+
B: (E, N, K) FP8 expert weights
|
| 272 |
+
Bs: (E,) or (E, 1, 1) per-expert weight scales
|
| 273 |
"""
|
| 274 |
+
assert A.ndim == 2, f"A must be 2D (S, K), got ndim={A.ndim}"
|
| 275 |
assert A.is_contiguous(), "A must be contiguous"
|
| 276 |
+
assert B.ndim == 3, f"B must be 3D (E, N, K), got ndim={B.ndim}"
|
|
|
|
| 277 |
assert B.is_contiguous(), "B must be contiguous"
|
| 278 |
+
assert A.shape[1] == B.shape[2], (
|
| 279 |
+
f"K mismatch: A has K={A.shape[1]}, B has K={B.shape[2]}"
|
| 280 |
+
)
|
|
|
|
| 281 |
|
| 282 |
S, K = A.shape
|
| 283 |
+
E, N, _ = B.shape
|
| 284 |
|
| 285 |
+
# Normalize Bs to (E, 1, 1)
|
| 286 |
if Bs.ndim == 1:
|
| 287 |
+
assert Bs.shape[0] == E, f"Bs shape {tuple(Bs.shape)} != expected ({E},)"
|
| 288 |
Bs = Bs.reshape(E, 1, 1)
|
|
|
|
|
|
|
| 289 |
else:
|
| 290 |
+
assert Bs.shape == (E, 1, 1), (
|
| 291 |
+
f"Bs shape {tuple(Bs.shape)} != expected ({E}, 1, 1)"
|
|
|
|
| 292 |
)
|
| 293 |
|
| 294 |
+
BLOCK_SIZE_N = 128
|
| 295 |
+
BLOCK_SIZE_K = 128
|
|
|
|
|
|
|
|
|
|
| 296 |
C = A.new_empty(S, N)
|
|
|
|
| 297 |
qA, As = fp8_act_quant(A, K)
|
| 298 |
+
grid = (S, triton.cdiv(N, BLOCK_SIZE_N))
|
| 299 |
+
# Adaptive BLOCK_SIZE_M: smallest power-of-2 >= M, floored at 16, capped at 128.
|
| 300 |
+
# Matches the WGMMA tile to the actual row count — smaller tiles use less
|
| 301 |
+
# register pressure and a better-matched FP8 WGMMA instruction, improving
|
| 302 |
+
# both accuracy and performance for small M (decode).
|
| 303 |
+
BLOCK_SIZE_M = min(max(triton.next_power_of_2((S + E - 1) // E), 16), 128)
|
| 304 |
+
grid = (S, triton.cdiv(N, BLOCK_SIZE_N))
|
| 305 |
+
with device_context(A.device):
|
| 306 |
+
wrap_triton(w8a8_tensor_fp8_matmul_batched_kernel)[grid](
|
| 307 |
+
qA,
|
| 308 |
+
B,
|
| 309 |
+
C,
|
| 310 |
+
As,
|
| 311 |
+
Bs,
|
| 312 |
+
expert_ids,
|
| 313 |
+
S,
|
| 314 |
+
N,
|
| 315 |
+
K,
|
| 316 |
+
qA.stride(0),
|
| 317 |
+
qA.stride(1),
|
| 318 |
+
B.stride(0),
|
| 319 |
+
B.stride(2),
|
| 320 |
+
B.stride(1),
|
| 321 |
+
C.stride(0),
|
| 322 |
+
C.stride(1),
|
| 323 |
+
As.stride(0),
|
| 324 |
+
Bs.stride(0),
|
| 325 |
+
BLOCK_SIZE_N=BLOCK_SIZE_N,
|
| 326 |
+
BLOCK_SIZE_K=BLOCK_SIZE_K,
|
| 327 |
+
BLOCK_SIZE_M=BLOCK_SIZE_M,
|
| 328 |
+
)
|
| 329 |
|
| 330 |
return C
|
| 331 |
|
|
|
|
| 335 |
B: torch.Tensor,
|
| 336 |
Bs: torch.Tensor,
|
| 337 |
expert_ids: torch.Tensor,
|
| 338 |
+
block_size: list[int],
|
| 339 |
) -> torch.Tensor:
|
| 340 |
+
"""Block-scale batched FP8 matmul with fused activation quantization.
|
| 341 |
|
| 342 |
+
A: (S, K) raw activations, bf16/fp16/fp32
|
| 343 |
+
B: (E, N, K) FP8 expert weights
|
| 344 |
+
Bs: (E, N // block_n, K // block_k) per-block weight scales
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 345 |
"""
|
| 346 |
return torch.ops.finegrained_fp8.w8a8_block_fp8_matmul_batched(
|
| 347 |
A, B, Bs, expert_ids, block_size
|
|
|
|
| 353 |
B: torch.Tensor,
|
| 354 |
Bs: torch.Tensor,
|
| 355 |
expert_ids: torch.Tensor,
|
|
|
|
| 356 |
) -> torch.Tensor:
|
| 357 |
+
"""Tensor-scale batched FP8 matmul with fused activation quantization.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
|
| 359 |
+
A: (S, K) raw activations, bf16/fp16/fp32
|
| 360 |
+
B: (E, N, K) FP8 expert weights
|
| 361 |
+
Bs: (E,) or (E, 1, 1) per-expert weight scales
|
| 362 |
"""
|
| 363 |
return torch.ops.finegrained_fp8.w8a8_tensor_fp8_matmul_batched(
|
| 364 |
+
A, B, Bs, expert_ids
|
| 365 |
)
|
| 366 |
|
| 367 |
|
|
|
|
| 385 |
if block_size is None or (
|
| 386 |
block_size[0] == B.size(1) and block_size[1] == B.size(2)
|
| 387 |
):
|
| 388 |
+
return w8a8_tensor_fp8_matmul_batched(A, B, Bs, expert_ids)
|
| 389 |
|
| 390 |
return w8a8_block_fp8_matmul_batched(A, B, Bs, expert_ids, block_size)
|
build/torch-rocm/grouped.py
CHANGED
|
@@ -18,6 +18,8 @@ import triton.language as tl
|
|
| 18 |
from .act_quant import fp8_act_quant
|
| 19 |
from torch.library import triton_op, wrap_triton
|
| 20 |
|
|
|
|
|
|
|
| 21 |
|
| 22 |
@triton.autotune(
|
| 23 |
configs=[
|
|
@@ -25,14 +27,14 @@ from torch.library import triton_op, wrap_triton
|
|
| 25 |
for w in [2, 4, 8, 16]
|
| 26 |
for s in [2, 3, 4, 5]
|
| 27 |
],
|
| 28 |
-
key=["N", "K"],
|
| 29 |
)
|
| 30 |
@triton.jit
|
| 31 |
def w8a8_block_fp8_matmul_grouped_kernel(
|
| 32 |
A, # (S, K) raw BF16/FP16 activations, sorted/grouped by expert id
|
| 33 |
B, # (E, N, K) FP8 weight matrices
|
| 34 |
C, # (S, N) output
|
| 35 |
-
Bs, # (E, N //
|
| 36 |
Offsets, # (E,) int32 — cumulative row-end per expert
|
| 37 |
TileOffsets, # (E,) int32 — cumulative tile-end per expert
|
| 38 |
# Shape
|
|
@@ -42,19 +44,19 @@ def w8a8_block_fp8_matmul_grouped_kernel(
|
|
| 42 |
# Strides
|
| 43 |
stride_am,
|
| 44 |
stride_ak,
|
| 45 |
-
|
| 46 |
stride_bk,
|
| 47 |
stride_bn,
|
| 48 |
stride_cm,
|
| 49 |
stride_cn,
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
# Meta-parameters
|
| 54 |
-
block_n: tl.constexpr,
|
| 55 |
-
block_k: tl.constexpr,
|
| 56 |
-
BLOCK_SIZE_M: tl.constexpr,
|
| 57 |
NUM_EXPERTS: tl.constexpr,
|
|
|
|
|
|
|
|
|
|
| 58 |
NUM_EXPERTS_BIT_LENGTH: tl.constexpr,
|
| 59 |
):
|
| 60 |
"""Block-scale grouped FP8 expert matmul kernel.
|
|
@@ -87,12 +89,11 @@ def w8a8_block_fp8_matmul_grouped_kernel(
|
|
| 87 |
hi = tl.where(is_left, hi, mid)
|
| 88 |
|
| 89 |
# Cast expert_id to int64 to prevent int32 overflow when computing
|
| 90 |
-
# expert_id *
|
| 91 |
# 3072×3072 FP8 weights).
|
| 92 |
expert_id = lo.to(tl.int64)
|
| 93 |
|
| 94 |
prev_eid = tl.maximum(expert_id - 1, 0)
|
| 95 |
-
|
| 96 |
expert_start = tl.where(expert_id == 0, 0, tl.load(Offsets + prev_eid))
|
| 97 |
expert_end = tl.load(Offsets + expert_id)
|
| 98 |
M_expert = expert_end - expert_start
|
|
@@ -105,31 +106,30 @@ def w8a8_block_fp8_matmul_grouped_kernel(
|
|
| 105 |
row_mask = offs_am < M_expert
|
| 106 |
offs_global_m = expert_start + offs_am
|
| 107 |
|
| 108 |
-
offs_bn = pid_n *
|
| 109 |
-
offs_k = tl.arange(0,
|
| 110 |
|
| 111 |
a_ptrs = A + offs_global_m[:, None] * stride_am + offs_k[None, :] * stride_ak
|
| 112 |
b_ptrs = (
|
| 113 |
B
|
| 114 |
-
+ expert_id *
|
| 115 |
+ offs_k[:, None] * stride_bk
|
| 116 |
+ offs_bn[None, :] * stride_bn
|
| 117 |
)
|
| 118 |
-
|
| 119 |
-
Bs_ptrs = Bs + expert_id * stride_Esb + offs_bsn * stride_Bsn
|
| 120 |
|
| 121 |
-
accumulator = tl.zeros((BLOCK_SIZE_M,
|
| 122 |
-
for k in range(0, tl.cdiv(K,
|
| 123 |
# ---- fused fp8_act_quant ----
|
| 124 |
a_raw = tl.load(a_ptrs, mask=row_mask[:, None], other=0.0).to(tl.float32)
|
| 125 |
-
a_s = tl.max(tl.abs(a_raw), axis=1) / 448.0
|
| 126 |
a = (a_raw / tl.maximum(a_s[:, None], 1e-12)).to(tl.float8e4nv)
|
| 127 |
-
# ----
|
| 128 |
b = tl.load(b_ptrs)
|
| 129 |
-
b_s = tl.load(
|
| 130 |
accumulator += tl.dot(a, b) * a_s[:, None] * b_s[None, :]
|
| 131 |
-
a_ptrs +=
|
| 132 |
-
b_ptrs +=
|
| 133 |
|
| 134 |
if C.dtype.element_ty == tl.bfloat16:
|
| 135 |
c = accumulator.to(tl.bfloat16)
|
|
@@ -149,11 +149,11 @@ def w8a8_block_fp8_matmul_grouped_kernel(
|
|
| 149 |
for w in [2, 4, 8, 16]
|
| 150 |
for s in [2, 3, 4, 5]
|
| 151 |
],
|
| 152 |
-
key=["N", "K"],
|
| 153 |
)
|
| 154 |
@triton.jit
|
| 155 |
def w8a8_tensor_fp8_matmul_grouped_kernel(
|
| 156 |
-
A, # (S, K)
|
| 157 |
B, # (E, N, K) FP8 weight matrices
|
| 158 |
C, # (S, N) output
|
| 159 |
As, # (S, 1) activation scales
|
|
@@ -165,17 +165,17 @@ def w8a8_tensor_fp8_matmul_grouped_kernel(
|
|
| 165 |
K,
|
| 166 |
stride_am,
|
| 167 |
stride_ak,
|
| 168 |
-
|
| 169 |
stride_bk,
|
| 170 |
stride_bn,
|
| 171 |
stride_cm,
|
| 172 |
stride_cn,
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
block_n: tl.constexpr,
|
| 176 |
-
block_k: tl.constexpr,
|
| 177 |
-
BLOCK_SIZE_M: tl.constexpr,
|
| 178 |
NUM_EXPERTS: tl.constexpr,
|
|
|
|
|
|
|
|
|
|
| 179 |
NUM_EXPERTS_BIT_LENGTH: tl.constexpr,
|
| 180 |
):
|
| 181 |
"""Tensor-scale grouped FP8 expert matmul kernel.
|
|
@@ -213,28 +213,30 @@ def w8a8_tensor_fp8_matmul_grouped_kernel(
|
|
| 213 |
row_mask = offs_am < M_expert
|
| 214 |
offs_global_m = expert_start + offs_am
|
| 215 |
|
| 216 |
-
offs_bn = pid_n *
|
| 217 |
-
offs_k = tl.arange(0,
|
| 218 |
|
| 219 |
a_ptrs = A + offs_global_m[:, None] * stride_am + offs_k[None, :] * stride_ak
|
| 220 |
b_ptrs = (
|
| 221 |
B
|
| 222 |
-
+ expert_id *
|
| 223 |
+ offs_k[:, None] * stride_bk
|
| 224 |
+ offs_bn[None, :] * stride_bn
|
| 225 |
)
|
| 226 |
|
| 227 |
-
a_s = tl.load(As + offs_global_m *
|
| 228 |
-
b_s = tl.load(Bs + expert_id *
|
| 229 |
|
| 230 |
-
accumulator = tl.zeros((BLOCK_SIZE_M,
|
| 231 |
-
for _ in range(0, tl.cdiv(K,
|
| 232 |
a = tl.load(a_ptrs, mask=row_mask[:, None], other=0.0)
|
| 233 |
b = tl.load(b_ptrs)
|
| 234 |
|
| 235 |
-
accumulator += tl.dot(a, b)
|
| 236 |
-
a_ptrs +=
|
| 237 |
-
b_ptrs +=
|
|
|
|
|
|
|
| 238 |
|
| 239 |
if C.dtype.element_ty == tl.bfloat16:
|
| 240 |
c = accumulator.to(tl.bfloat16)
|
|
@@ -255,104 +257,78 @@ def _w8a8_block_fp8_matmul_grouped(
|
|
| 255 |
Bs: torch.Tensor,
|
| 256 |
offsets: torch.Tensor,
|
| 257 |
tokens_per_expert: torch.Tensor,
|
| 258 |
-
block_size: list[int]
|
| 259 |
-
allow_sync: bool = False,
|
| 260 |
) -> torch.Tensor:
|
| 261 |
-
"""
|
| 262 |
|
| 263 |
-
|
| 264 |
-
|
|
|
|
| 265 |
"""
|
| 266 |
-
assert A.ndim == 2, "A must be (S, K)"
|
| 267 |
assert A.is_contiguous(), "A must be contiguous"
|
| 268 |
-
|
| 269 |
-
assert B.ndim == 3, "B must be (E, N, K)"
|
| 270 |
assert B.is_contiguous(), "B must be contiguous"
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
assert offsets.is_contiguous(), "offsets must be contiguous"
|
| 275 |
-
assert Bs.is_contiguous(), "Bs must be contiguous"
|
| 276 |
|
| 277 |
S, K = A.shape
|
| 278 |
-
E, N,
|
| 279 |
-
|
| 280 |
-
if block_size is None:
|
| 281 |
-
block_n, block_k = 128, 128
|
| 282 |
-
else:
|
| 283 |
-
block_n, block_k = block_size[0], block_size[1]
|
| 284 |
-
|
| 285 |
-
if block_n == N and block_k == K:
|
| 286 |
-
block_n, block_k = 128, 128
|
| 287 |
|
| 288 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 289 |
assert N % block_n == 0, f"N ({N}) must be divisible by block_n ({block_n})"
|
| 290 |
assert K % block_k == 0, f"K ({K}) must be divisible by block_k ({block_k})"
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
Bs
|
| 296 |
-
|
| 297 |
-
Bs = Bs.expand(E, N // block_n, K // block_k)
|
| 298 |
-
else:
|
| 299 |
-
assert Bs.ndim == 3, (
|
| 300 |
-
"Bs must be either (E,) / (E,1,1) for per-tensor scales or (E,N//block_n,K//block_k)"
|
| 301 |
-
)
|
| 302 |
-
assert Bs.shape[0] == E, (
|
| 303 |
-
f"Bs expert dim mismatch: expected {E}, got {Bs.shape[0]}"
|
| 304 |
-
)
|
| 305 |
-
assert Bs.shape[1] == N // block_n, (
|
| 306 |
-
f"Bs N-block dim mismatch: expected {N // block_n}, got {Bs.shape[1]}"
|
| 307 |
-
)
|
| 308 |
-
assert Bs.shape[2] == K // block_k, (
|
| 309 |
-
f"Bs K-block dim mismatch: expected {K // block_k}, got {Bs.shape[2]}"
|
| 310 |
-
)
|
| 311 |
|
| 312 |
C = A.new_empty(S, N)
|
| 313 |
-
|
| 314 |
# Adaptive BLOCK_SIZE_M: match tile to average tokens per expert.
|
| 315 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2((S + E - 1) // E), 16), 128)
|
| 316 |
tiles_per_expert = (tokens_per_expert + BLOCK_SIZE_M - 1) // BLOCK_SIZE_M
|
| 317 |
tile_offsets = torch.cumsum(tiles_per_expert, dim=0).to(torch.int32)
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
# Using a static upper bound keeps the grid size data-independent, which is
|
| 324 |
-
# required for cuda-graph compatibility. Programs beyond the real tile count
|
| 325 |
-
# exit immediately via the early-return guard inside the kernel.
|
| 326 |
-
max_M_tiles = triton.cdiv(S, BLOCK_SIZE_M) + E
|
| 327 |
-
|
| 328 |
grid = (max_M_tiles, triton.cdiv(N, block_n))
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
|
|
|
| 356 |
|
| 357 |
return C
|
| 358 |
|
|
@@ -364,88 +340,74 @@ def _w8a8_tensor_fp8_matmul_grouped(
|
|
| 364 |
Bs: torch.Tensor,
|
| 365 |
offsets: torch.Tensor,
|
| 366 |
tokens_per_expert: torch.Tensor,
|
| 367 |
-
block_size: list[int] | None,
|
| 368 |
-
allow_sync: bool = False,
|
| 369 |
) -> torch.Tensor:
|
| 370 |
-
"""Tensor-scale grouped FP8 matmul
|
| 371 |
-
|
| 372 |
-
Uses the same grouped scheduling as block mode, but with per-token tensor
|
| 373 |
-
activation scales and per-expert tensor weight scales.
|
| 374 |
|
| 375 |
-
|
|
|
|
|
|
|
| 376 |
"""
|
| 377 |
-
assert A.ndim == 2, "A must be (S, K)"
|
| 378 |
assert A.is_contiguous(), "A must be contiguous"
|
| 379 |
-
|
| 380 |
-
assert B.ndim == 3, "B must be (E, N, K)"
|
| 381 |
assert B.is_contiguous(), "B must be contiguous"
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
assert offsets.is_contiguous(), "offsets must be contiguous"
|
| 386 |
-
assert Bs.is_contiguous(), "Bs must be contiguous"
|
| 387 |
|
| 388 |
S, K = A.shape
|
| 389 |
-
E, N,
|
| 390 |
|
|
|
|
| 391 |
if Bs.ndim == 1:
|
|
|
|
| 392 |
Bs = Bs.reshape(E, 1, 1)
|
| 393 |
-
elif Bs.ndim == 3 and Bs.shape[0] == E and Bs.shape[1] == 1 and Bs.shape[2] == 1:
|
| 394 |
-
pass
|
| 395 |
else:
|
| 396 |
-
assert Bs.
|
| 397 |
-
|
| 398 |
-
f"Tensor mode expects Bs shape (E,1,1), got {tuple(Bs.shape)}"
|
| 399 |
)
|
| 400 |
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
assert N % block_n == 0, f"N ({N}) must be divisible by block_n ({block_n})"
|
| 404 |
-
assert K % block_k == 0, f"K ({K}) must be divisible by block_k ({block_k})"
|
| 405 |
-
|
| 406 |
C = A.new_empty(S, N)
|
| 407 |
-
|
| 408 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2((S + E - 1) // E), 16), 128)
|
| 409 |
tiles_per_expert = (tokens_per_expert + BLOCK_SIZE_M - 1) // BLOCK_SIZE_M
|
| 410 |
tile_offsets = torch.cumsum(tiles_per_expert, dim=0).to(torch.int32)
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
BLOCK_SIZE_M=BLOCK_SIZE_M,
|
| 446 |
-
NUM_EXPERTS=E,
|
| 447 |
-
NUM_EXPERTS_BIT_LENGTH=E.bit_length(),
|
| 448 |
-
)
|
| 449 |
|
| 450 |
return C
|
| 451 |
|
|
@@ -456,33 +418,16 @@ def w8a8_block_fp8_matmul_grouped(
|
|
| 456 |
Bs: torch.Tensor,
|
| 457 |
offsets: torch.Tensor,
|
| 458 |
tokens_per_expert: torch.Tensor,
|
| 459 |
-
block_size: list[int]
|
| 460 |
-
allow_sync: bool = False,
|
| 461 |
) -> torch.Tensor:
|
| 462 |
-
"""
|
| 463 |
-
|
| 464 |
-
Tokens in ``A`` must be pre-sorted by expert id. The kernel quantizes ``A``
|
| 465 |
-
to FP8 on-the-fly (fused ``act_quant``), uses a static over-provisioned grid
|
| 466 |
-
for CUDA-graph compatibility, and resolves each tile's expert via an O(log E)
|
| 467 |
-
binary search over ``offsets``.
|
| 468 |
-
|
| 469 |
-
Args:
|
| 470 |
-
A: Raw activation matrix ``[S, K]`` sorted by expert, in bf16/fp16/fp32.
|
| 471 |
-
B: Stacked expert weight tensor ``[E, N, K]`` in ``float8_e4m3fn``.
|
| 472 |
-
Bs: Expert weight scales, accepted as ``[E, nb, kb]`` (block)
|
| 473 |
-
or ``[E]`` / ``[E,1,1]`` (per-tensor; expanded internally).
|
| 474 |
-
offsets: Cumulative token counts per expert ``[E]`` (i.e. ``cumsum(tokens_per_expert)``).
|
| 475 |
-
tokens_per_expert: Number of tokens routed to each expert ``[E]``.
|
| 476 |
-
block_size: ``[block_n, block_k]`` quantization block dimensions, e.g. ``[128, 128]``.
|
| 477 |
-
allow_sync: If True (default), read back the exact tile count from the GPU
|
| 478 |
-
(avoids wasted programs). If False, use a data-independent upper bound
|
| 479 |
-
(required for CUDA-graph / torch.compile compatibility).
|
| 480 |
|
| 481 |
-
|
| 482 |
-
|
|
|
|
| 483 |
"""
|
| 484 |
return torch.ops.finegrained_fp8.w8a8_block_fp8_matmul_grouped(
|
| 485 |
-
A, B, Bs, offsets, tokens_per_expert, block_size
|
| 486 |
)
|
| 487 |
|
| 488 |
|
|
@@ -492,25 +437,15 @@ def w8a8_tensor_fp8_matmul_grouped(
|
|
| 492 |
Bs: torch.Tensor,
|
| 493 |
offsets: torch.Tensor,
|
| 494 |
tokens_per_expert: torch.Tensor,
|
| 495 |
-
block_size: list[int] | None,
|
| 496 |
-
allow_sync: bool = False,
|
| 497 |
) -> torch.Tensor:
|
| 498 |
-
"""Tensor-scale grouped
|
| 499 |
-
|
| 500 |
-
Args:
|
| 501 |
-
A: Raw activation matrix ``[S, K]`` sorted by expert, in bf16/fp16/fp32.
|
| 502 |
-
B: Stacked expert weight tensor ``[E, N, K]`` in ``float8_e4m3fn``.
|
| 503 |
-
Bs: Per-expert tensor scales ``[E]`` or ``[E,1,1]``.
|
| 504 |
-
offsets: Cumulative token counts per expert ``[E]``.
|
| 505 |
-
tokens_per_expert: Number of tokens routed to each expert ``[E]``.
|
| 506 |
-
block_size: Kept for API consistency; tensor path derives tile sizes from ``N`` and ``K``.
|
| 507 |
-
allow_sync: If True, sync for exact grid; if False, use upper bound.
|
| 508 |
|
| 509 |
-
|
| 510 |
-
|
|
|
|
| 511 |
"""
|
| 512 |
return torch.ops.finegrained_fp8.w8a8_tensor_fp8_matmul_grouped(
|
| 513 |
-
A, B, Bs, offsets, tokens_per_expert
|
| 514 |
)
|
| 515 |
|
| 516 |
|
|
@@ -521,7 +456,6 @@ def w8a8_fp8_matmul_grouped(
|
|
| 521 |
offsets: torch.Tensor,
|
| 522 |
tokens_per_expert: torch.Tensor,
|
| 523 |
block_size: list[int] | None,
|
| 524 |
-
allow_sync: bool = False,
|
| 525 |
) -> torch.Tensor:
|
| 526 |
"""Unified grouped W8A8 FP8 matmul dispatcher.
|
| 527 |
|
|
@@ -536,10 +470,8 @@ def w8a8_fp8_matmul_grouped(
|
|
| 536 |
if block_size is None or (
|
| 537 |
block_size[0] == B.size(1) and block_size[1] == B.size(2)
|
| 538 |
):
|
| 539 |
-
return w8a8_tensor_fp8_matmul_grouped(
|
| 540 |
-
A, B, Bs, offsets, tokens_per_expert, block_size, allow_sync
|
| 541 |
-
)
|
| 542 |
|
| 543 |
return w8a8_block_fp8_matmul_grouped(
|
| 544 |
-
A, B, Bs, offsets, tokens_per_expert, block_size
|
| 545 |
)
|
|
|
|
| 18 |
from .act_quant import fp8_act_quant
|
| 19 |
from torch.library import triton_op, wrap_triton
|
| 20 |
|
| 21 |
+
from .utils import device_context
|
| 22 |
+
|
| 23 |
|
| 24 |
@triton.autotune(
|
| 25 |
configs=[
|
|
|
|
| 27 |
for w in [2, 4, 8, 16]
|
| 28 |
for s in [2, 3, 4, 5]
|
| 29 |
],
|
| 30 |
+
key=["N", "K", "BLOCK_SIZE_M"],
|
| 31 |
)
|
| 32 |
@triton.jit
|
| 33 |
def w8a8_block_fp8_matmul_grouped_kernel(
|
| 34 |
A, # (S, K) raw BF16/FP16 activations, sorted/grouped by expert id
|
| 35 |
B, # (E, N, K) FP8 weight matrices
|
| 36 |
C, # (S, N) output
|
| 37 |
+
Bs, # (E, N // BLOCK_SIZE_N, K // BLOCK_SIZE_K) weight scales
|
| 38 |
Offsets, # (E,) int32 — cumulative row-end per expert
|
| 39 |
TileOffsets, # (E,) int32 — cumulative tile-end per expert
|
| 40 |
# Shape
|
|
|
|
| 44 |
# Strides
|
| 45 |
stride_am,
|
| 46 |
stride_ak,
|
| 47 |
+
stride_be,
|
| 48 |
stride_bk,
|
| 49 |
stride_bn,
|
| 50 |
stride_cm,
|
| 51 |
stride_cn,
|
| 52 |
+
stride_bs_e,
|
| 53 |
+
stride_bs_k,
|
| 54 |
+
stride_bs_n,
|
| 55 |
# Meta-parameters
|
|
|
|
|
|
|
|
|
|
| 56 |
NUM_EXPERTS: tl.constexpr,
|
| 57 |
+
BLOCK_SIZE_N: tl.constexpr,
|
| 58 |
+
BLOCK_SIZE_K: tl.constexpr,
|
| 59 |
+
BLOCK_SIZE_M: tl.constexpr,
|
| 60 |
NUM_EXPERTS_BIT_LENGTH: tl.constexpr,
|
| 61 |
):
|
| 62 |
"""Block-scale grouped FP8 expert matmul kernel.
|
|
|
|
| 89 |
hi = tl.where(is_left, hi, mid)
|
| 90 |
|
| 91 |
# Cast expert_id to int64 to prevent int32 overflow when computing
|
| 92 |
+
# expert_id * stride_be (e.g. 255 * 9_437_184 > 2^31 for 256 experts of
|
| 93 |
# 3072×3072 FP8 weights).
|
| 94 |
expert_id = lo.to(tl.int64)
|
| 95 |
|
| 96 |
prev_eid = tl.maximum(expert_id - 1, 0)
|
|
|
|
| 97 |
expert_start = tl.where(expert_id == 0, 0, tl.load(Offsets + prev_eid))
|
| 98 |
expert_end = tl.load(Offsets + expert_id)
|
| 99 |
M_expert = expert_end - expert_start
|
|
|
|
| 106 |
row_mask = offs_am < M_expert
|
| 107 |
offs_global_m = expert_start + offs_am
|
| 108 |
|
| 109 |
+
offs_bn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 110 |
+
offs_k = tl.arange(0, BLOCK_SIZE_K)
|
| 111 |
|
| 112 |
a_ptrs = A + offs_global_m[:, None] * stride_am + offs_k[None, :] * stride_ak
|
| 113 |
b_ptrs = (
|
| 114 |
B
|
| 115 |
+
+ expert_id * stride_be
|
| 116 |
+ offs_k[:, None] * stride_bk
|
| 117 |
+ offs_bn[None, :] * stride_bn
|
| 118 |
)
|
| 119 |
+
bs_ptrs = Bs + expert_id * stride_bs_e + pid_n * stride_bs_n
|
|
|
|
| 120 |
|
| 121 |
+
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 122 |
+
for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
|
| 123 |
# ---- fused fp8_act_quant ----
|
| 124 |
a_raw = tl.load(a_ptrs, mask=row_mask[:, None], other=0.0).to(tl.float32)
|
| 125 |
+
a_s = tl.max(tl.abs(a_raw), axis=1) / 448.0
|
| 126 |
a = (a_raw / tl.maximum(a_s[:, None], 1e-12)).to(tl.float8e4nv)
|
| 127 |
+
# ---- matmul ----
|
| 128 |
b = tl.load(b_ptrs)
|
| 129 |
+
b_s = tl.load(bs_ptrs + k * stride_bs_k)
|
| 130 |
accumulator += tl.dot(a, b) * a_s[:, None] * b_s[None, :]
|
| 131 |
+
a_ptrs += BLOCK_SIZE_K * stride_ak
|
| 132 |
+
b_ptrs += BLOCK_SIZE_K * stride_bk
|
| 133 |
|
| 134 |
if C.dtype.element_ty == tl.bfloat16:
|
| 135 |
c = accumulator.to(tl.bfloat16)
|
|
|
|
| 149 |
for w in [2, 4, 8, 16]
|
| 150 |
for s in [2, 3, 4, 5]
|
| 151 |
],
|
| 152 |
+
key=["N", "K", "BLOCK_SIZE_M"],
|
| 153 |
)
|
| 154 |
@triton.jit
|
| 155 |
def w8a8_tensor_fp8_matmul_grouped_kernel(
|
| 156 |
+
A, # (S, K) raw BF16/FP16 activations, sorted/grouped by expert idc
|
| 157 |
B, # (E, N, K) FP8 weight matrices
|
| 158 |
C, # (S, N) output
|
| 159 |
As, # (S, 1) activation scales
|
|
|
|
| 165 |
K,
|
| 166 |
stride_am,
|
| 167 |
stride_ak,
|
| 168 |
+
stride_be,
|
| 169 |
stride_bk,
|
| 170 |
stride_bn,
|
| 171 |
stride_cm,
|
| 172 |
stride_cn,
|
| 173 |
+
stride_as_m,
|
| 174 |
+
stride_bs_e,
|
|
|
|
|
|
|
|
|
|
| 175 |
NUM_EXPERTS: tl.constexpr,
|
| 176 |
+
BLOCK_SIZE_N: tl.constexpr,
|
| 177 |
+
BLOCK_SIZE_K: tl.constexpr,
|
| 178 |
+
BLOCK_SIZE_M: tl.constexpr,
|
| 179 |
NUM_EXPERTS_BIT_LENGTH: tl.constexpr,
|
| 180 |
):
|
| 181 |
"""Tensor-scale grouped FP8 expert matmul kernel.
|
|
|
|
| 213 |
row_mask = offs_am < M_expert
|
| 214 |
offs_global_m = expert_start + offs_am
|
| 215 |
|
| 216 |
+
offs_bn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 217 |
+
offs_k = tl.arange(0, BLOCK_SIZE_K)
|
| 218 |
|
| 219 |
a_ptrs = A + offs_global_m[:, None] * stride_am + offs_k[None, :] * stride_ak
|
| 220 |
b_ptrs = (
|
| 221 |
B
|
| 222 |
+
+ expert_id * stride_be
|
| 223 |
+ offs_k[:, None] * stride_bk
|
| 224 |
+ offs_bn[None, :] * stride_bn
|
| 225 |
)
|
| 226 |
|
| 227 |
+
a_s = tl.load(As + offs_global_m * stride_as_m, mask=row_mask, other=0.0)
|
| 228 |
+
b_s = tl.load(Bs + expert_id * stride_bs_e)
|
| 229 |
|
| 230 |
+
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 231 |
+
for _ in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
|
| 232 |
a = tl.load(a_ptrs, mask=row_mask[:, None], other=0.0)
|
| 233 |
b = tl.load(b_ptrs)
|
| 234 |
|
| 235 |
+
accumulator += tl.dot(a, b)
|
| 236 |
+
a_ptrs += BLOCK_SIZE_K * stride_ak
|
| 237 |
+
b_ptrs += BLOCK_SIZE_K * stride_bk
|
| 238 |
+
|
| 239 |
+
accumulator = accumulator * a_s[:, None] * b_s
|
| 240 |
|
| 241 |
if C.dtype.element_ty == tl.bfloat16:
|
| 242 |
c = accumulator.to(tl.bfloat16)
|
|
|
|
| 257 |
Bs: torch.Tensor,
|
| 258 |
offsets: torch.Tensor,
|
| 259 |
tokens_per_expert: torch.Tensor,
|
| 260 |
+
block_size: list[int],
|
|
|
|
| 261 |
) -> torch.Tensor:
|
| 262 |
+
"""Block-scale grouped FP8 matmul: C = A @ B.T per expert, with fused act quant.
|
| 263 |
|
| 264 |
+
A: (S, K) raw bf16/fp16 activations, sorted by expert
|
| 265 |
+
B: (E, N, K) FP8 expert weights
|
| 266 |
+
Bs: (E, N // block_n, K // block_k) per-block weight scales
|
| 267 |
"""
|
| 268 |
+
assert A.ndim == 2, f"A must be 2D (S, K), got ndim={A.ndim}"
|
| 269 |
assert A.is_contiguous(), "A must be contiguous"
|
| 270 |
+
assert B.ndim == 3, f"B must be 3D (E, N, K), got ndim={B.ndim}"
|
|
|
|
| 271 |
assert B.is_contiguous(), "B must be contiguous"
|
| 272 |
+
assert A.shape[1] == B.shape[2], (
|
| 273 |
+
f"K mismatch: A has K={A.shape[1]}, B has K={B.shape[2]}"
|
| 274 |
+
)
|
|
|
|
|
|
|
| 275 |
|
| 276 |
S, K = A.shape
|
| 277 |
+
E, N, _ = B.shape
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
|
| 279 |
+
assert len(block_size) == 2, (
|
| 280 |
+
f"block_size must be [block_n, block_k], got {block_size}"
|
| 281 |
+
)
|
| 282 |
+
block_n, block_k = block_size[0], block_size[1]
|
| 283 |
+
# MoE expert dimensions must be block-aligned; non-aligned N/K is not supported.
|
| 284 |
assert N % block_n == 0, f"N ({N}) must be divisible by block_n ({block_n})"
|
| 285 |
assert K % block_k == 0, f"K ({K}) must be divisible by block_k ({block_k})"
|
| 286 |
+
assert Bs.ndim == 3, (
|
| 287 |
+
f"Bs must be 3D (E, N//block_n, K//block_k), got ndim={Bs.ndim}"
|
| 288 |
+
)
|
| 289 |
+
assert Bs.shape == (E, N // block_n, K // block_k), (
|
| 290 |
+
f"Bs shape {tuple(Bs.shape)} != expected ({E}, {N // block_n}, {K // block_k})"
|
| 291 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
|
| 293 |
C = A.new_empty(S, N)
|
|
|
|
| 294 |
# Adaptive BLOCK_SIZE_M: match tile to average tokens per expert.
|
| 295 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2((S + E - 1) // E), 16), 128)
|
| 296 |
tiles_per_expert = (tokens_per_expert + BLOCK_SIZE_M - 1) // BLOCK_SIZE_M
|
| 297 |
tile_offsets = torch.cumsum(tiles_per_expert, dim=0).to(torch.int32)
|
| 298 |
+
# Upper bound on M-tiles: sum_e ceil(M_e / BLOCK_M) <= ceil(S / BLOCK_M) + E.
|
| 299 |
+
# Programs beyond the real tile count exit immediately via the early-return
|
| 300 |
+
# guard inside the kernel. This is faster than syncing for the exact count
|
| 301 |
+
# and keeps the grid size data-independent (cuda-graph / torch.compile safe).
|
| 302 |
+
max_M_tiles = triton.cdiv(S, BLOCK_SIZE_M) + E
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 303 |
grid = (max_M_tiles, triton.cdiv(N, block_n))
|
| 304 |
+
with device_context(A.device):
|
| 305 |
+
wrap_triton(w8a8_block_fp8_matmul_grouped_kernel)[grid](
|
| 306 |
+
A,
|
| 307 |
+
B,
|
| 308 |
+
C,
|
| 309 |
+
Bs,
|
| 310 |
+
offsets,
|
| 311 |
+
tile_offsets,
|
| 312 |
+
S,
|
| 313 |
+
N,
|
| 314 |
+
K,
|
| 315 |
+
A.stride(0),
|
| 316 |
+
A.stride(1),
|
| 317 |
+
B.stride(0),
|
| 318 |
+
B.stride(2),
|
| 319 |
+
B.stride(1),
|
| 320 |
+
C.stride(0),
|
| 321 |
+
C.stride(1),
|
| 322 |
+
Bs.stride(0),
|
| 323 |
+
Bs.stride(2),
|
| 324 |
+
Bs.stride(1),
|
| 325 |
+
# Meta-parameters
|
| 326 |
+
NUM_EXPERTS=E,
|
| 327 |
+
BLOCK_SIZE_N=block_n,
|
| 328 |
+
BLOCK_SIZE_K=block_k,
|
| 329 |
+
BLOCK_SIZE_M=BLOCK_SIZE_M,
|
| 330 |
+
NUM_EXPERTS_BIT_LENGTH=E.bit_length(),
|
| 331 |
+
)
|
| 332 |
|
| 333 |
return C
|
| 334 |
|
|
|
|
| 340 |
Bs: torch.Tensor,
|
| 341 |
offsets: torch.Tensor,
|
| 342 |
tokens_per_expert: torch.Tensor,
|
|
|
|
|
|
|
| 343 |
) -> torch.Tensor:
|
| 344 |
+
"""Tensor-scale grouped FP8 matmul: C = A @ B.T per expert, with fused act quant.
|
|
|
|
|
|
|
|
|
|
| 345 |
|
| 346 |
+
A: (S, K) raw bf16/fp16 activations, sorted by expert
|
| 347 |
+
B: (E, N, K) FP8 expert weights
|
| 348 |
+
Bs: (E,) or (E, 1, 1) per-expert weight scales
|
| 349 |
"""
|
| 350 |
+
assert A.ndim == 2, f"A must be 2D (S, K), got ndim={A.ndim}"
|
| 351 |
assert A.is_contiguous(), "A must be contiguous"
|
| 352 |
+
assert B.ndim == 3, f"B must be 3D (E, N, K), got ndim={B.ndim}"
|
|
|
|
| 353 |
assert B.is_contiguous(), "B must be contiguous"
|
| 354 |
+
assert A.shape[1] == B.shape[2], (
|
| 355 |
+
f"K mismatch: A has K={A.shape[1]}, B has K={B.shape[2]}"
|
| 356 |
+
)
|
|
|
|
|
|
|
| 357 |
|
| 358 |
S, K = A.shape
|
| 359 |
+
E, N, _ = B.shape
|
| 360 |
|
| 361 |
+
# Normalize Bs to (E, 1, 1)
|
| 362 |
if Bs.ndim == 1:
|
| 363 |
+
assert Bs.shape[0] == E, f"Bs shape {tuple(Bs.shape)} != expected ({E},)"
|
| 364 |
Bs = Bs.reshape(E, 1, 1)
|
|
|
|
|
|
|
| 365 |
else:
|
| 366 |
+
assert Bs.shape == (E, 1, 1), (
|
| 367 |
+
f"Bs shape {tuple(Bs.shape)} != expected ({E}, 1, 1)"
|
|
|
|
| 368 |
)
|
| 369 |
|
| 370 |
+
BLOCK_SIZE_N = 128
|
| 371 |
+
BLOCK_SIZE_K = 128
|
|
|
|
|
|
|
|
|
|
| 372 |
C = A.new_empty(S, N)
|
| 373 |
+
qA, As = fp8_act_quant(A, K)
|
| 374 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2((S + E - 1) // E), 16), 128)
|
| 375 |
tiles_per_expert = (tokens_per_expert + BLOCK_SIZE_M - 1) // BLOCK_SIZE_M
|
| 376 |
tile_offsets = torch.cumsum(tiles_per_expert, dim=0).to(torch.int32)
|
| 377 |
+
# Upper bound on M-tiles: sum_e ceil(M_e / BLOCK_M) <= ceil(S / BLOCK_M) + E.
|
| 378 |
+
# Programs beyond the real tile count exit immediately via the early-return
|
| 379 |
+
# guard inside the kernel. This is faster than syncing for the exact count
|
| 380 |
+
# and keeps the grid size data-independent (cuda-graph / torch.compile safe).
|
| 381 |
+
max_M_tiles = triton.cdiv(S, BLOCK_SIZE_M) + E
|
| 382 |
+
grid = (max_M_tiles, triton.cdiv(N, BLOCK_SIZE_N))
|
| 383 |
+
with device_context(A.device):
|
| 384 |
+
wrap_triton(w8a8_tensor_fp8_matmul_grouped_kernel)[grid](
|
| 385 |
+
qA,
|
| 386 |
+
B,
|
| 387 |
+
C,
|
| 388 |
+
As,
|
| 389 |
+
Bs,
|
| 390 |
+
offsets,
|
| 391 |
+
tile_offsets,
|
| 392 |
+
S,
|
| 393 |
+
N,
|
| 394 |
+
K,
|
| 395 |
+
qA.stride(0),
|
| 396 |
+
qA.stride(1),
|
| 397 |
+
B.stride(0),
|
| 398 |
+
B.stride(2),
|
| 399 |
+
B.stride(1),
|
| 400 |
+
C.stride(0),
|
| 401 |
+
C.stride(1),
|
| 402 |
+
As.stride(0),
|
| 403 |
+
Bs.stride(0),
|
| 404 |
+
# Meta-parameters
|
| 405 |
+
NUM_EXPERTS=E,
|
| 406 |
+
BLOCK_SIZE_N=BLOCK_SIZE_N,
|
| 407 |
+
BLOCK_SIZE_K=BLOCK_SIZE_K,
|
| 408 |
+
BLOCK_SIZE_M=BLOCK_SIZE_M,
|
| 409 |
+
NUM_EXPERTS_BIT_LENGTH=E.bit_length(),
|
| 410 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 411 |
|
| 412 |
return C
|
| 413 |
|
|
|
|
| 418 |
Bs: torch.Tensor,
|
| 419 |
offsets: torch.Tensor,
|
| 420 |
tokens_per_expert: torch.Tensor,
|
| 421 |
+
block_size: list[int],
|
|
|
|
| 422 |
) -> torch.Tensor:
|
| 423 |
+
"""Block-scale grouped FP8 matmul with fused activation quantization.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 424 |
|
| 425 |
+
A: (S, K) raw activations sorted by expert, bf16/fp16/fp32
|
| 426 |
+
B: (E, N, K) FP8 expert weights
|
| 427 |
+
Bs: (E, N // block_n, K // block_k) per-block weight scales
|
| 428 |
"""
|
| 429 |
return torch.ops.finegrained_fp8.w8a8_block_fp8_matmul_grouped(
|
| 430 |
+
A, B, Bs, offsets, tokens_per_expert, block_size
|
| 431 |
)
|
| 432 |
|
| 433 |
|
|
|
|
| 437 |
Bs: torch.Tensor,
|
| 438 |
offsets: torch.Tensor,
|
| 439 |
tokens_per_expert: torch.Tensor,
|
|
|
|
|
|
|
| 440 |
) -> torch.Tensor:
|
| 441 |
+
"""Tensor-scale grouped FP8 matmul with fused activation quantization.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 442 |
|
| 443 |
+
A: (S, K) raw activations sorted by expert, bf16/fp16/fp32
|
| 444 |
+
B: (E, N, K) FP8 expert weights
|
| 445 |
+
Bs: (E,) or (E, 1, 1) per-expert weight scales
|
| 446 |
"""
|
| 447 |
return torch.ops.finegrained_fp8.w8a8_tensor_fp8_matmul_grouped(
|
| 448 |
+
A, B, Bs, offsets, tokens_per_expert
|
| 449 |
)
|
| 450 |
|
| 451 |
|
|
|
|
| 456 |
offsets: torch.Tensor,
|
| 457 |
tokens_per_expert: torch.Tensor,
|
| 458 |
block_size: list[int] | None,
|
|
|
|
| 459 |
) -> torch.Tensor:
|
| 460 |
"""Unified grouped W8A8 FP8 matmul dispatcher.
|
| 461 |
|
|
|
|
| 470 |
if block_size is None or (
|
| 471 |
block_size[0] == B.size(1) and block_size[1] == B.size(2)
|
| 472 |
):
|
| 473 |
+
return w8a8_tensor_fp8_matmul_grouped(A, B, Bs, offsets, tokens_per_expert)
|
|
|
|
|
|
|
| 474 |
|
| 475 |
return w8a8_block_fp8_matmul_grouped(
|
| 476 |
+
A, B, Bs, offsets, tokens_per_expert, block_size
|
| 477 |
)
|
build/torch-rocm/matmul.py
CHANGED
|
@@ -17,8 +17,18 @@ import triton
|
|
| 17 |
import triton.language as tl
|
| 18 |
from torch.library import triton_op, wrap_triton
|
| 19 |
|
|
|
|
|
|
|
| 20 |
|
| 21 |
# Adapted from https://github.com/sgl-project/sglang/blob/main/python/sglang/srt/layers/quantization/fp8_kernel.py
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
@triton.jit
|
| 23 |
def w8a8_block_fp8_matmul_kernel(
|
| 24 |
# Pointers to inputs and output
|
|
@@ -31,20 +41,16 @@ def w8a8_block_fp8_matmul_kernel(
|
|
| 31 |
M,
|
| 32 |
N,
|
| 33 |
K,
|
| 34 |
-
# Block size for block-wise quantization
|
| 35 |
-
group_n,
|
| 36 |
-
group_k,
|
| 37 |
-
# Stride for inputs and output
|
| 38 |
stride_am,
|
| 39 |
stride_ak,
|
| 40 |
stride_bk,
|
| 41 |
stride_bn,
|
| 42 |
stride_cm,
|
| 43 |
stride_cn,
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
# Meta-parameters
|
| 49 |
BLOCK_SIZE_M: tl.constexpr,
|
| 50 |
BLOCK_SIZE_N: tl.constexpr,
|
|
@@ -54,17 +60,13 @@ def w8a8_block_fp8_matmul_kernel(
|
|
| 54 |
"""Block-scale FP8 GEMM kernel.
|
| 55 |
|
| 56 |
Computes ``C = A @ B.T`` with block-wise activation/weight scales.
|
|
|
|
| 57 |
"""
|
| 58 |
-
|
| 59 |
-
|
| 60 |
num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
|
| 61 |
num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)
|
| 62 |
-
|
| 63 |
-
group_id = pid // num_pid_in_group
|
| 64 |
-
first_pid_m = group_id * GROUP_SIZE_M
|
| 65 |
-
group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M)
|
| 66 |
-
pid_m = first_pid_m + (pid % group_size_m)
|
| 67 |
-
pid_n = (pid % num_pid_in_group) // group_size_m
|
| 68 |
|
| 69 |
offs_am = (pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
|
| 70 |
offs_bn = (pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)) % N
|
|
@@ -72,19 +74,18 @@ def w8a8_block_fp8_matmul_kernel(
|
|
| 72 |
a_ptrs = A + (offs_am[:, None] * stride_am + offs_k[None, :] * stride_ak)
|
| 73 |
b_ptrs = B + (offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn)
|
| 74 |
|
| 75 |
-
|
| 76 |
-
offs_bsn = offs_bn //
|
| 77 |
-
|
| 78 |
|
| 79 |
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 80 |
for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
|
| 81 |
-
|
| 82 |
-
|
|
|
|
| 83 |
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
a_s = tl.load(As_ptrs + offs_ks * stride_As_k)
|
| 87 |
-
b_s = tl.load(Bs_ptrs + offs_ks * stride_Bs_k)
|
| 88 |
|
| 89 |
accumulator += tl.dot(a, b) * a_s[:, None] * b_s[None, :]
|
| 90 |
a_ptrs += BLOCK_SIZE_K * stride_ak
|
|
@@ -104,6 +105,14 @@ def w8a8_block_fp8_matmul_kernel(
|
|
| 104 |
tl.store(c_ptrs, c, mask=c_mask)
|
| 105 |
|
| 106 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
@triton.jit
|
| 108 |
def w8a8_tensor_fp8_matmul_kernel(
|
| 109 |
A,
|
|
@@ -120,7 +129,7 @@ def w8a8_tensor_fp8_matmul_kernel(
|
|
| 120 |
stride_bn,
|
| 121 |
stride_cm,
|
| 122 |
stride_cn,
|
| 123 |
-
|
| 124 |
BLOCK_SIZE_M: tl.constexpr,
|
| 125 |
BLOCK_SIZE_N: tl.constexpr,
|
| 126 |
BLOCK_SIZE_K: tl.constexpr,
|
|
@@ -130,40 +139,36 @@ def w8a8_tensor_fp8_matmul_kernel(
|
|
| 130 |
|
| 131 |
Computes ``C = A @ B.T`` with one activation scale per row and one
|
| 132 |
weight scale for the full matrix.
|
|
|
|
| 133 |
"""
|
| 134 |
-
|
|
|
|
| 135 |
num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
|
| 136 |
num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
pid_m = first_pid_m + (pid % group_size_m)
|
| 142 |
-
pid_n = (pid % num_pid_in_group) // group_size_m
|
| 143 |
-
|
| 144 |
-
offs_am = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
|
| 145 |
-
offs_bn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 146 |
offs_k = tl.arange(0, BLOCK_SIZE_K)
|
| 147 |
|
| 148 |
a_ptrs = A + offs_am[:, None] * stride_am + offs_k[None, :] * stride_ak
|
| 149 |
b_ptrs = B + offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn
|
| 150 |
|
| 151 |
-
a_s = tl.load(As + offs_am *
|
| 152 |
b_s = tl.load(Bs)
|
| 153 |
|
|
|
|
| 154 |
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 155 |
for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
|
| 156 |
-
|
| 157 |
-
a = tl.load(
|
| 158 |
-
|
| 159 |
-
)
|
| 160 |
-
b = tl.load(
|
| 161 |
-
b_ptrs, mask=(k_offs[:, None] < K) & (offs_bn[None, :] < N), other=0.0
|
| 162 |
-
)
|
| 163 |
-
accumulator += tl.dot(a, b) * a_s[:, None] * b_s
|
| 164 |
a_ptrs += BLOCK_SIZE_K * stride_ak
|
| 165 |
b_ptrs += BLOCK_SIZE_K * stride_bk
|
| 166 |
|
|
|
|
|
|
|
| 167 |
if C.dtype.element_ty == tl.bfloat16:
|
| 168 |
c = accumulator.to(tl.bfloat16)
|
| 169 |
elif C.dtype.element_ty == tl.float16:
|
|
@@ -184,82 +189,74 @@ def _w8a8_block_fp8_matmul(
|
|
| 184 |
B: torch.Tensor,
|
| 185 |
As: torch.Tensor,
|
| 186 |
Bs: torch.Tensor,
|
| 187 |
-
block_size: list[int]
|
| 188 |
output_dtype: torch.dtype = torch.float32,
|
| 189 |
) -> torch.Tensor:
|
| 190 |
-
"""
|
| 191 |
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
block-scale shapes.
|
| 195 |
"""
|
| 196 |
-
|
| 197 |
-
block_n, block_k
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
block_n, block_k = block_size[0], block_size[1]
|
| 201 |
-
|
| 202 |
-
assert A.shape[-1] == B.shape[-1]
|
| 203 |
-
assert A.is_contiguous()
|
| 204 |
|
| 205 |
-
assert
|
| 206 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
|
| 208 |
N, K = B.shape
|
| 209 |
M = A.numel() // A.shape[-1]
|
| 210 |
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
Bs = Bs.reshape(1, 1).expand(triton.cdiv(N, block_n), triton.cdiv(K, block_k))
|
| 220 |
-
else:
|
| 221 |
-
assert Bs.ndim == 2
|
| 222 |
-
assert triton.cdiv(N, block_n) == Bs.shape[0], f"{N}, {block_n}, {Bs.shape}"
|
| 223 |
-
assert triton.cdiv(K, block_k) == Bs.shape[1], f"{K}, {block_k}, {Bs.shape}"
|
| 224 |
|
|
|
|
|
|
|
| 225 |
C_shape = A.shape[:-1] + (N,)
|
| 226 |
C = A.new_empty(C_shape, dtype=output_dtype)
|
| 227 |
-
|
| 228 |
# Adaptive BLOCK_SIZE_M: smallest power-of-2 >= M, floored at 16, capped at 128.
|
| 229 |
# Matches the WGMMA tile to the actual row count — smaller tiles use less
|
| 230 |
# register pressure and a better-matched FP8 WGMMA instruction, improving
|
| 231 |
# both accuracy and performance for small M (decode).
|
| 232 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2(M), 16), 128)
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
BLOCK_SIZE_K=BLOCK_SIZE_K,
|
| 261 |
-
GROUP_SIZE_M=8,
|
| 262 |
-
)
|
| 263 |
|
| 264 |
return C
|
| 265 |
|
|
@@ -270,83 +267,65 @@ def _w8a8_tensor_fp8_matmul(
|
|
| 270 |
B: torch.Tensor,
|
| 271 |
As: torch.Tensor,
|
| 272 |
Bs: torch.Tensor,
|
| 273 |
-
block_size: list[int] | None,
|
| 274 |
output_dtype: torch.dtype = torch.float32,
|
| 275 |
) -> torch.Tensor:
|
| 276 |
-
"""Tensor-scale
|
| 277 |
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
- ``As``: scalar, ``[M]``, or ``[M,1]`` -> ``[M]``
|
| 281 |
-
- ``Bs``: scalar, ``[1]``, or ``[1,1]`` -> ``[1]``
|
| 282 |
"""
|
| 283 |
-
assert A.shape[-1] == B.shape[-1]
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
assert
|
| 287 |
-
assert B.
|
|
|
|
| 288 |
|
| 289 |
N, K = B.shape
|
| 290 |
M = A.numel() // A.shape[-1]
|
| 291 |
|
| 292 |
-
|
| 293 |
-
block_k = 128 if K % 128 == 0 else K
|
| 294 |
-
|
| 295 |
if As.numel() == 1:
|
| 296 |
As = As.reshape(1).expand(M).contiguous()
|
| 297 |
-
elif As.ndim ==
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
)
|
| 301 |
-
|
| 302 |
-
else:
|
| 303 |
-
assert As.ndim == 2 and As.shape[0] == M and As.shape[1] == 1, (
|
| 304 |
-
f"Tensor mode expects As shape [M,1], got {tuple(As.shape)}"
|
| 305 |
-
)
|
| 306 |
-
As = As.reshape(M).contiguous()
|
| 307 |
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
assert Bs.shape[0] == 1, (
|
| 312 |
-
f"Tensor mode expects Bs shape [1], got {tuple(Bs.shape)}"
|
| 313 |
-
)
|
| 314 |
-
Bs = Bs.contiguous()
|
| 315 |
-
else:
|
| 316 |
-
assert Bs.ndim == 2 and Bs.shape[0] == 1 and Bs.shape[1] == 1, (
|
| 317 |
-
f"Tensor mode expects Bs shape [1,1], got {tuple(Bs.shape)}"
|
| 318 |
-
)
|
| 319 |
-
Bs = Bs.reshape(1).contiguous()
|
| 320 |
|
|
|
|
|
|
|
| 321 |
C_shape = A.shape[:-1] + (N,)
|
| 322 |
C = A.new_empty(C_shape, dtype=output_dtype)
|
| 323 |
-
|
| 324 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2(M), 16), 128)
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
)
|
| 350 |
|
| 351 |
return C
|
| 352 |
|
|
@@ -356,7 +335,7 @@ def w8a8_block_fp8_matmul(
|
|
| 356 |
B: torch.Tensor,
|
| 357 |
As: torch.Tensor,
|
| 358 |
Bs: torch.Tensor,
|
| 359 |
-
block_size: list[int]
|
| 360 |
output_dtype: torch.dtype = torch.float32,
|
| 361 |
) -> torch.Tensor:
|
| 362 |
"""Block-wise W8A8 FP8 matrix multiplication.
|
|
@@ -386,7 +365,6 @@ def w8a8_tensor_fp8_matmul(
|
|
| 386 |
B: torch.Tensor,
|
| 387 |
As: torch.Tensor,
|
| 388 |
Bs: torch.Tensor,
|
| 389 |
-
block_size: list[int] | None,
|
| 390 |
output_dtype: torch.dtype = torch.float32,
|
| 391 |
) -> torch.Tensor:
|
| 392 |
"""Tensor-scale W8A8 FP8 matrix multiplication.
|
|
@@ -397,17 +375,14 @@ def w8a8_tensor_fp8_matmul(
|
|
| 397 |
Args:
|
| 398 |
A: Quantized activation tensor ``[M, K]`` in ``float8_e4m3fn``.
|
| 399 |
B: Quantized weight tensor ``[N, K]`` in ``float8_e4m3fn``.
|
| 400 |
-
As:
|
| 401 |
-
Bs:
|
| 402 |
-
block_size: Kept for API consistency; tensor path derives tile sizes from ``N`` and ``K``.
|
| 403 |
output_dtype: dtype of the returned tensor.
|
| 404 |
|
| 405 |
Returns:
|
| 406 |
Output tensor ``[M, N]`` in ``output_dtype``.
|
| 407 |
"""
|
| 408 |
-
return torch.ops.finegrained_fp8.w8a8_tensor_fp8_matmul(
|
| 409 |
-
A, B, As, Bs, block_size, output_dtype
|
| 410 |
-
)
|
| 411 |
|
| 412 |
|
| 413 |
def w8a8_fp8_matmul(
|
|
@@ -431,6 +406,6 @@ def w8a8_fp8_matmul(
|
|
| 431 |
if block_size is None or (
|
| 432 |
block_size[0] == B.size(0) and block_size[1] == B.size(1)
|
| 433 |
):
|
| 434 |
-
return w8a8_tensor_fp8_matmul(A, B, As, Bs,
|
| 435 |
|
| 436 |
return w8a8_block_fp8_matmul(A, B, As, Bs, block_size, output_dtype)
|
|
|
|
| 17 |
import triton.language as tl
|
| 18 |
from torch.library import triton_op, wrap_triton
|
| 19 |
|
| 20 |
+
from .utils import device_context
|
| 21 |
+
|
| 22 |
|
| 23 |
# Adapted from https://github.com/sgl-project/sglang/blob/main/python/sglang/srt/layers/quantization/fp8_kernel.py
|
| 24 |
+
@triton.autotune(
|
| 25 |
+
configs=[
|
| 26 |
+
triton.Config({}, num_warps=w, num_stages=s)
|
| 27 |
+
for w in [2, 4, 8, 16]
|
| 28 |
+
for s in [2, 3, 4]
|
| 29 |
+
],
|
| 30 |
+
key=["N", "K", "BLOCK_SIZE_M"],
|
| 31 |
+
)
|
| 32 |
@triton.jit
|
| 33 |
def w8a8_block_fp8_matmul_kernel(
|
| 34 |
# Pointers to inputs and output
|
|
|
|
| 41 |
M,
|
| 42 |
N,
|
| 43 |
K,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
stride_am,
|
| 45 |
stride_ak,
|
| 46 |
stride_bk,
|
| 47 |
stride_bn,
|
| 48 |
stride_cm,
|
| 49 |
stride_cn,
|
| 50 |
+
stride_as_m,
|
| 51 |
+
stride_as_k,
|
| 52 |
+
stride_bs_k,
|
| 53 |
+
stride_bs_n,
|
| 54 |
# Meta-parameters
|
| 55 |
BLOCK_SIZE_M: tl.constexpr,
|
| 56 |
BLOCK_SIZE_N: tl.constexpr,
|
|
|
|
| 60 |
"""Block-scale FP8 GEMM kernel.
|
| 61 |
|
| 62 |
Computes ``C = A @ B.T`` with block-wise activation/weight scales.
|
| 63 |
+
Uses a 2D grid with swizzle for L2 cache locality on B tiles.
|
| 64 |
"""
|
| 65 |
+
pid_m = tl.program_id(axis=0)
|
| 66 |
+
pid_n = tl.program_id(axis=1)
|
| 67 |
num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
|
| 68 |
num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)
|
| 69 |
+
pid_m, pid_n = tl.swizzle2d(pid_m, pid_n, num_pid_m, num_pid_n, GROUP_SIZE_M)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
offs_am = (pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
|
| 72 |
offs_bn = (pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)) % N
|
|
|
|
| 74 |
a_ptrs = A + (offs_am[:, None] * stride_am + offs_k[None, :] * stride_ak)
|
| 75 |
b_ptrs = B + (offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn)
|
| 76 |
|
| 77 |
+
as_ptrs = As + offs_am * stride_as_m
|
| 78 |
+
offs_bsn = offs_bn // BLOCK_SIZE_N
|
| 79 |
+
bs_ptrs = Bs + offs_bsn * stride_bs_n
|
| 80 |
|
| 81 |
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 82 |
for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
|
| 83 |
+
k_remaining = K - k * BLOCK_SIZE_K
|
| 84 |
+
a = tl.load(a_ptrs, mask=offs_k[None, :] < k_remaining, other=0.0)
|
| 85 |
+
b = tl.load(b_ptrs, mask=offs_k[:, None] < k_remaining, other=0.0)
|
| 86 |
|
| 87 |
+
a_s = tl.load(as_ptrs + k * stride_as_k)
|
| 88 |
+
b_s = tl.load(bs_ptrs + k * stride_bs_k)
|
|
|
|
|
|
|
| 89 |
|
| 90 |
accumulator += tl.dot(a, b) * a_s[:, None] * b_s[None, :]
|
| 91 |
a_ptrs += BLOCK_SIZE_K * stride_ak
|
|
|
|
| 105 |
tl.store(c_ptrs, c, mask=c_mask)
|
| 106 |
|
| 107 |
|
| 108 |
+
@triton.autotune(
|
| 109 |
+
configs=[
|
| 110 |
+
triton.Config({}, num_warps=w, num_stages=s)
|
| 111 |
+
for w in [2, 4, 8, 16]
|
| 112 |
+
for s in [2, 3, 4]
|
| 113 |
+
],
|
| 114 |
+
key=["N", "K", "BLOCK_SIZE_M"],
|
| 115 |
+
)
|
| 116 |
@triton.jit
|
| 117 |
def w8a8_tensor_fp8_matmul_kernel(
|
| 118 |
A,
|
|
|
|
| 129 |
stride_bn,
|
| 130 |
stride_cm,
|
| 131 |
stride_cn,
|
| 132 |
+
stride_as_m,
|
| 133 |
BLOCK_SIZE_M: tl.constexpr,
|
| 134 |
BLOCK_SIZE_N: tl.constexpr,
|
| 135 |
BLOCK_SIZE_K: tl.constexpr,
|
|
|
|
| 139 |
|
| 140 |
Computes ``C = A @ B.T`` with one activation scale per row and one
|
| 141 |
weight scale for the full matrix.
|
| 142 |
+
Uses a 2D grid with swizzle for L2 cache locality on B tiles.
|
| 143 |
"""
|
| 144 |
+
pid_m = tl.program_id(axis=0)
|
| 145 |
+
pid_n = tl.program_id(axis=1)
|
| 146 |
num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
|
| 147 |
num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)
|
| 148 |
+
pid_m, pid_n = tl.swizzle2d(pid_m, pid_n, num_pid_m, num_pid_n, GROUP_SIZE_M)
|
| 149 |
+
|
| 150 |
+
offs_am = (pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
|
| 151 |
+
offs_bn = (pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)) % N
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
offs_k = tl.arange(0, BLOCK_SIZE_K)
|
| 153 |
|
| 154 |
a_ptrs = A + offs_am[:, None] * stride_am + offs_k[None, :] * stride_ak
|
| 155 |
b_ptrs = B + offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn
|
| 156 |
|
| 157 |
+
a_s = tl.load(As + offs_am * stride_as_m)
|
| 158 |
b_s = tl.load(Bs)
|
| 159 |
|
| 160 |
+
# Accumulate raw dot products, apply scales once after the loop.
|
| 161 |
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 162 |
for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
|
| 163 |
+
k_remaining = K - k * BLOCK_SIZE_K
|
| 164 |
+
a = tl.load(a_ptrs, mask=offs_k[None, :] < k_remaining, other=0.0)
|
| 165 |
+
b = tl.load(b_ptrs, mask=offs_k[:, None] < k_remaining, other=0.0)
|
| 166 |
+
accumulator += tl.dot(a, b)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
a_ptrs += BLOCK_SIZE_K * stride_ak
|
| 168 |
b_ptrs += BLOCK_SIZE_K * stride_bk
|
| 169 |
|
| 170 |
+
accumulator = accumulator * a_s[:, None] * b_s
|
| 171 |
+
|
| 172 |
if C.dtype.element_ty == tl.bfloat16:
|
| 173 |
c = accumulator.to(tl.bfloat16)
|
| 174 |
elif C.dtype.element_ty == tl.float16:
|
|
|
|
| 189 |
B: torch.Tensor,
|
| 190 |
As: torch.Tensor,
|
| 191 |
Bs: torch.Tensor,
|
| 192 |
+
block_size: list[int],
|
| 193 |
output_dtype: torch.dtype = torch.float32,
|
| 194 |
) -> torch.Tensor:
|
| 195 |
+
"""Block-scale FP8 matmul: C = A @ B.T with per-block scales.
|
| 196 |
|
| 197 |
+
As: (M, K // block_k) — per-token-group activation scales
|
| 198 |
+
Bs: (N // block_n, K // block_k) — per-block weight scales
|
|
|
|
| 199 |
"""
|
| 200 |
+
assert len(block_size) == 2, (
|
| 201 |
+
f"block_size must be [block_n, block_k], got {block_size}"
|
| 202 |
+
)
|
| 203 |
+
block_n, block_k = block_size[0], block_size[1]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
|
| 205 |
+
assert A.shape[-1] == B.shape[-1], (
|
| 206 |
+
f"K mismatch: A has K={A.shape[-1]}, B has K={B.shape[-1]}"
|
| 207 |
+
)
|
| 208 |
+
assert A.is_contiguous(), "A must be contiguous"
|
| 209 |
+
assert B.ndim == 2, f"B must be 2D (N, K), got ndim={B.ndim}"
|
| 210 |
+
assert B.is_contiguous(), "B must be contiguous"
|
| 211 |
|
| 212 |
N, K = B.shape
|
| 213 |
M = A.numel() // A.shape[-1]
|
| 214 |
|
| 215 |
+
assert As.ndim >= 2, f"As must be at least 2D, got ndim={As.ndim}"
|
| 216 |
+
assert As.shape[-1] == triton.cdiv(K, block_k), (
|
| 217 |
+
f"As last dim {As.shape[-1]} != expected {triton.cdiv(K, block_k)} (cdiv(K={K}, block_k={block_k}))"
|
| 218 |
+
)
|
| 219 |
+
assert Bs.ndim == 2, f"Bs must be 2D (N//block_n, K//block_k), got ndim={Bs.ndim}"
|
| 220 |
+
assert Bs.shape == (triton.cdiv(N, block_n), triton.cdiv(K, block_k)), (
|
| 221 |
+
f"Bs shape {tuple(Bs.shape)} != expected ({triton.cdiv(N, block_n)}, {triton.cdiv(K, block_k)})"
|
| 222 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
|
| 224 |
+
BLOCK_SIZE_K = block_k
|
| 225 |
+
BLOCK_SIZE_N = block_n
|
| 226 |
C_shape = A.shape[:-1] + (N,)
|
| 227 |
C = A.new_empty(C_shape, dtype=output_dtype)
|
|
|
|
| 228 |
# Adaptive BLOCK_SIZE_M: smallest power-of-2 >= M, floored at 16, capped at 128.
|
| 229 |
# Matches the WGMMA tile to the actual row count — smaller tiles use less
|
| 230 |
# register pressure and a better-matched FP8 WGMMA instruction, improving
|
| 231 |
# both accuracy and performance for small M (decode).
|
| 232 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2(M), 16), 128)
|
| 233 |
+
grid = (triton.cdiv(M, BLOCK_SIZE_M), triton.cdiv(N, BLOCK_SIZE_N))
|
| 234 |
+
with device_context(A.device):
|
| 235 |
+
wrap_triton(w8a8_block_fp8_matmul_kernel)[grid](
|
| 236 |
+
A,
|
| 237 |
+
B,
|
| 238 |
+
C,
|
| 239 |
+
As,
|
| 240 |
+
Bs,
|
| 241 |
+
M,
|
| 242 |
+
N,
|
| 243 |
+
K,
|
| 244 |
+
A.stride(-2),
|
| 245 |
+
A.stride(-1),
|
| 246 |
+
B.stride(1),
|
| 247 |
+
B.stride(0),
|
| 248 |
+
C.stride(-2),
|
| 249 |
+
C.stride(-1),
|
| 250 |
+
As.stride(-2),
|
| 251 |
+
As.stride(-1),
|
| 252 |
+
Bs.stride(1),
|
| 253 |
+
Bs.stride(0),
|
| 254 |
+
# Meta-parameters
|
| 255 |
+
BLOCK_SIZE_M=BLOCK_SIZE_M,
|
| 256 |
+
BLOCK_SIZE_N=BLOCK_SIZE_N,
|
| 257 |
+
BLOCK_SIZE_K=BLOCK_SIZE_K,
|
| 258 |
+
GROUP_SIZE_M=8,
|
| 259 |
+
)
|
|
|
|
|
|
|
|
|
|
| 260 |
|
| 261 |
return C
|
| 262 |
|
|
|
|
| 267 |
B: torch.Tensor,
|
| 268 |
As: torch.Tensor,
|
| 269 |
Bs: torch.Tensor,
|
|
|
|
| 270 |
output_dtype: torch.dtype = torch.float32,
|
| 271 |
) -> torch.Tensor:
|
| 272 |
+
"""Tensor-scale FP8 matmul: C = A @ B.T with per-row / per-tensor scales.
|
| 273 |
|
| 274 |
+
As: scalar, (M,), or (M, 1) — per-row activation scales
|
| 275 |
+
Bs: scalar, (1,), or (1, 1) — single weight scale
|
|
|
|
|
|
|
| 276 |
"""
|
| 277 |
+
assert A.shape[-1] == B.shape[-1], (
|
| 278 |
+
f"K mismatch: A has K={A.shape[-1]}, B has K={B.shape[-1]}"
|
| 279 |
+
)
|
| 280 |
+
assert A.is_contiguous(), "A must be contiguous"
|
| 281 |
+
assert B.ndim == 2, f"B must be 2D (N, K), got ndim={B.ndim}"
|
| 282 |
+
assert B.is_contiguous(), "B must be contiguous"
|
| 283 |
|
| 284 |
N, K = B.shape
|
| 285 |
M = A.numel() // A.shape[-1]
|
| 286 |
|
| 287 |
+
# Normalize As to (M,)
|
|
|
|
|
|
|
| 288 |
if As.numel() == 1:
|
| 289 |
As = As.reshape(1).expand(M).contiguous()
|
| 290 |
+
elif As.ndim == 2:
|
| 291 |
+
As = As.reshape(M)
|
| 292 |
+
assert As.ndim == 1 and As.shape[0] == M, (
|
| 293 |
+
f"As must be scalar, (M,), or (M,1) with M={M}, got {tuple(As.shape)}"
|
| 294 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 295 |
|
| 296 |
+
# Normalize Bs to (1,)
|
| 297 |
+
assert Bs.numel() == 1, f"Bs must be scalar or (1,), got {tuple(Bs.shape)}"
|
| 298 |
+
Bs = Bs.reshape(1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
|
| 300 |
+
BLOCK_SIZE_N = 128
|
| 301 |
+
BLOCK_SIZE_K = 128
|
| 302 |
C_shape = A.shape[:-1] + (N,)
|
| 303 |
C = A.new_empty(C_shape, dtype=output_dtype)
|
|
|
|
| 304 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2(M), 16), 128)
|
| 305 |
+
grid = (triton.cdiv(M, BLOCK_SIZE_M), triton.cdiv(N, BLOCK_SIZE_N))
|
| 306 |
+
with device_context(A.device):
|
| 307 |
+
wrap_triton(w8a8_tensor_fp8_matmul_kernel)[grid](
|
| 308 |
+
A,
|
| 309 |
+
B,
|
| 310 |
+
C,
|
| 311 |
+
As,
|
| 312 |
+
Bs,
|
| 313 |
+
M,
|
| 314 |
+
N,
|
| 315 |
+
K,
|
| 316 |
+
A.stride(-2),
|
| 317 |
+
A.stride(-1),
|
| 318 |
+
B.stride(1),
|
| 319 |
+
B.stride(0),
|
| 320 |
+
C.stride(-2),
|
| 321 |
+
C.stride(-1),
|
| 322 |
+
As.stride(0),
|
| 323 |
+
# Meta-parameters
|
| 324 |
+
BLOCK_SIZE_M=BLOCK_SIZE_M,
|
| 325 |
+
BLOCK_SIZE_N=BLOCK_SIZE_N,
|
| 326 |
+
BLOCK_SIZE_K=BLOCK_SIZE_K,
|
| 327 |
+
GROUP_SIZE_M=8,
|
| 328 |
+
)
|
|
|
|
| 329 |
|
| 330 |
return C
|
| 331 |
|
|
|
|
| 335 |
B: torch.Tensor,
|
| 336 |
As: torch.Tensor,
|
| 337 |
Bs: torch.Tensor,
|
| 338 |
+
block_size: list[int],
|
| 339 |
output_dtype: torch.dtype = torch.float32,
|
| 340 |
) -> torch.Tensor:
|
| 341 |
"""Block-wise W8A8 FP8 matrix multiplication.
|
|
|
|
| 365 |
B: torch.Tensor,
|
| 366 |
As: torch.Tensor,
|
| 367 |
Bs: torch.Tensor,
|
|
|
|
| 368 |
output_dtype: torch.dtype = torch.float32,
|
| 369 |
) -> torch.Tensor:
|
| 370 |
"""Tensor-scale W8A8 FP8 matrix multiplication.
|
|
|
|
| 375 |
Args:
|
| 376 |
A: Quantized activation tensor ``[M, K]`` in ``float8_e4m3fn``.
|
| 377 |
B: Quantized weight tensor ``[N, K]`` in ``float8_e4m3fn``.
|
| 378 |
+
As: Per-row activation scales ``[M]``.
|
| 379 |
+
Bs: Single weight scale, scalar or ``[1]``.
|
|
|
|
| 380 |
output_dtype: dtype of the returned tensor.
|
| 381 |
|
| 382 |
Returns:
|
| 383 |
Output tensor ``[M, N]`` in ``output_dtype``.
|
| 384 |
"""
|
| 385 |
+
return torch.ops.finegrained_fp8.w8a8_tensor_fp8_matmul(A, B, As, Bs, output_dtype)
|
|
|
|
|
|
|
| 386 |
|
| 387 |
|
| 388 |
def w8a8_fp8_matmul(
|
|
|
|
| 406 |
if block_size is None or (
|
| 407 |
block_size[0] == B.size(0) and block_size[1] == B.size(1)
|
| 408 |
):
|
| 409 |
+
return w8a8_tensor_fp8_matmul(A, B, As, Bs, output_dtype)
|
| 410 |
|
| 411 |
return w8a8_block_fp8_matmul(A, B, As, Bs, block_size, output_dtype)
|
build/torch-rocm/utils.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from contextlib import contextmanager
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
@contextmanager
|
| 6 |
+
def device_context(device: torch.device):
|
| 7 |
+
"""Context manager that sets the active device for any backend (cuda, xpu, etc.)."""
|
| 8 |
+
backend = getattr(torch, device.type, None)
|
| 9 |
+
if backend is not None and hasattr(backend, "device"):
|
| 10 |
+
with backend.device(device):
|
| 11 |
+
yield
|
| 12 |
+
else:
|
| 13 |
+
yield
|
build/torch-xpu/_ops.py
CHANGED
|
@@ -1,8 +1,8 @@
|
|
| 1 |
import torch
|
| 2 |
-
ops = torch.ops.
|
| 3 |
|
| 4 |
def add_op_namespace_prefix(op_name: str):
|
| 5 |
"""
|
| 6 |
Prefix op by namespace.
|
| 7 |
"""
|
| 8 |
-
return f"
|
|
|
|
| 1 |
import torch
|
| 2 |
+
ops = torch.ops._finegrained_fp8_75cbe1b
|
| 3 |
|
| 4 |
def add_op_namespace_prefix(op_name: str):
|
| 5 |
"""
|
| 6 |
Prefix op by namespace.
|
| 7 |
"""
|
| 8 |
+
return f"_finegrained_fp8_75cbe1b::{op_name}"
|
build/torch-xpu/act_quant.py
CHANGED
|
@@ -17,6 +17,8 @@ import triton
|
|
| 17 |
import triton.language as tl
|
| 18 |
from torch.library import triton_op, wrap_triton
|
| 19 |
|
|
|
|
|
|
|
| 20 |
|
| 21 |
_FP8_DTYPE = torch.float8_e4m3fn
|
| 22 |
|
|
@@ -40,10 +42,12 @@ def _fp8_act_quant(
|
|
| 40 |
assert x.is_contiguous()
|
| 41 |
assert x.shape[-1] % block_size == 0
|
| 42 |
y = torch.empty_like(x, dtype=_FP8_DTYPE)
|
|
|
|
| 43 |
s = x.new_empty(*x.size()[:-1], x.size(-1) // block_size, dtype=torch.float32)
|
| 44 |
|
| 45 |
-
|
| 46 |
-
|
|
|
|
| 47 |
return y, s
|
| 48 |
|
| 49 |
|
|
|
|
| 17 |
import triton.language as tl
|
| 18 |
from torch.library import triton_op, wrap_triton
|
| 19 |
|
| 20 |
+
from .utils import device_context
|
| 21 |
+
|
| 22 |
|
| 23 |
_FP8_DTYPE = torch.float8_e4m3fn
|
| 24 |
|
|
|
|
| 42 |
assert x.is_contiguous()
|
| 43 |
assert x.shape[-1] % block_size == 0
|
| 44 |
y = torch.empty_like(x, dtype=_FP8_DTYPE)
|
| 45 |
+
grid = (triton.cdiv(x.numel(), block_size),)
|
| 46 |
s = x.new_empty(*x.size()[:-1], x.size(-1) // block_size, dtype=torch.float32)
|
| 47 |
|
| 48 |
+
with device_context(x.device):
|
| 49 |
+
wrap_triton(_fp8_act_quant_kernel)[grid](x, y, s, BLOCK_SIZE=block_size)
|
| 50 |
+
|
| 51 |
return y, s
|
| 52 |
|
| 53 |
|
build/torch-xpu/batched.py
CHANGED
|
@@ -18,6 +18,8 @@ import triton.language as tl
|
|
| 18 |
from .act_quant import fp8_act_quant
|
| 19 |
from torch.library import triton_op, wrap_triton
|
| 20 |
|
|
|
|
|
|
|
| 21 |
|
| 22 |
@triton.autotune(
|
| 23 |
configs=[
|
|
@@ -32,27 +34,25 @@ def w8a8_block_fp8_matmul_batched_kernel(
|
|
| 32 |
A, # (S, K) raw BF16/FP16 activations
|
| 33 |
B, # (E, N, K) FP8 weight matrices
|
| 34 |
C, # (S, N) output
|
| 35 |
-
Bs, # (E, N //
|
| 36 |
ExpertIds, # (S,) — which expert each batch element routes to
|
| 37 |
# Shape
|
| 38 |
S,
|
| 39 |
N,
|
| 40 |
K,
|
| 41 |
-
|
| 42 |
stride_ak,
|
|
|
|
| 43 |
stride_bk,
|
| 44 |
stride_bn,
|
|
|
|
| 45 |
stride_cn,
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
stride_Ab, # stride between rows in A (one token per program)
|
| 50 |
-
stride_Eb, # stride between experts in B
|
| 51 |
-
stride_Cb, # stride between rows in C (one token per program)
|
| 52 |
-
stride_Esb, # stride between experts in Bs
|
| 53 |
# Meta-parameters
|
| 54 |
-
|
| 55 |
-
|
| 56 |
BLOCK_SIZE_M: tl.constexpr,
|
| 57 |
):
|
| 58 |
"""Block-scale batched FP8 expert matmul kernel.
|
|
@@ -63,40 +63,35 @@ def w8a8_block_fp8_matmul_batched_kernel(
|
|
| 63 |
batch_id = tl.program_id(axis=0)
|
| 64 |
pid_n = tl.program_id(axis=1)
|
| 65 |
|
| 66 |
-
# Advance base pointers to this token's activation row and its expert's
|
| 67 |
-
# weight / scale slice. No pre-gather of weights needed (like in non-fp8 impls)
|
| 68 |
# Cast expert_id to int64 to prevent int32 overflow when computing
|
| 69 |
# expert_id * stride_Eb (e.g. 255 * 9_437_184 > 2^31 for 256 experts of
|
| 70 |
# 3072×3072 FP8 weights).
|
| 71 |
expert_id = tl.load(ExpertIds + batch_id).to(tl.int64)
|
| 72 |
|
| 73 |
-
A = A + batch_id *
|
| 74 |
-
B = B + expert_id *
|
| 75 |
-
C = C + batch_id *
|
| 76 |
-
Bs = Bs + expert_id *
|
| 77 |
|
| 78 |
-
offs_bn = pid_n *
|
| 79 |
-
offs_k = tl.arange(0,
|
| 80 |
a_ptrs = A + tl.arange(0, BLOCK_SIZE_M)[:, None] * 0 + offs_k[None, :] * stride_ak
|
| 81 |
b_ptrs = B + (offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn)
|
| 82 |
|
| 83 |
-
|
| 84 |
-
Bs_ptrs = Bs + offs_bsn * stride_Bs_n
|
| 85 |
|
| 86 |
-
accumulator = tl.zeros((BLOCK_SIZE_M,
|
| 87 |
-
for k in range(0, tl.cdiv(K,
|
| 88 |
# ---- fused fp8_act_quant ----
|
| 89 |
a_raw = tl.load(a_ptrs).to(tl.float32)
|
| 90 |
-
a_s = tl.max(tl.abs(a_raw)) / 448.0
|
| 91 |
a = (a_raw / tl.maximum(a_s, 1e-12)).to(tl.float8e4nv)
|
| 92 |
-
# ----
|
| 93 |
b = tl.load(b_ptrs)
|
| 94 |
-
|
| 95 |
-
offs_ks = k_start // block_k
|
| 96 |
-
b_s = tl.load(Bs_ptrs + offs_ks * stride_Bs_k)
|
| 97 |
accumulator += tl.dot(a, b) * a_s * b_s[None, :]
|
| 98 |
-
a_ptrs +=
|
| 99 |
-
b_ptrs +=
|
| 100 |
|
| 101 |
if C.dtype.element_ty == tl.bfloat16:
|
| 102 |
c = accumulator.to(tl.bfloat16)
|
|
@@ -106,7 +101,7 @@ def w8a8_block_fp8_matmul_batched_kernel(
|
|
| 106 |
c = accumulator.to(tl.float32)
|
| 107 |
|
| 108 |
offs_cm = tl.arange(0, BLOCK_SIZE_M)
|
| 109 |
-
offs_cn = pid_n *
|
| 110 |
c_ptrs = C + offs_cm[:, None] * 0 + stride_cn * offs_cn[None, :]
|
| 111 |
tl.store(c_ptrs, c)
|
| 112 |
|
|
@@ -130,17 +125,17 @@ def w8a8_tensor_fp8_matmul_batched_kernel(
|
|
| 130 |
S,
|
| 131 |
N,
|
| 132 |
K,
|
|
|
|
| 133 |
stride_ak,
|
|
|
|
| 134 |
stride_bk,
|
| 135 |
stride_bn,
|
|
|
|
| 136 |
stride_cn,
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
stride_Esb,
|
| 142 |
-
block_n: tl.constexpr,
|
| 143 |
-
block_k: tl.constexpr,
|
| 144 |
BLOCK_SIZE_M: tl.constexpr,
|
| 145 |
):
|
| 146 |
"""Tensor-scale batched FP8 expert matmul kernel.
|
|
@@ -153,27 +148,28 @@ def w8a8_tensor_fp8_matmul_batched_kernel(
|
|
| 153 |
|
| 154 |
expert_id = tl.load(ExpertIds + batch_id).to(tl.int64)
|
| 155 |
|
| 156 |
-
A = A + batch_id *
|
| 157 |
-
B = B + expert_id *
|
| 158 |
-
C = C + batch_id *
|
| 159 |
-
Bs = Bs + expert_id *
|
| 160 |
|
| 161 |
-
offs_bn = pid_n *
|
| 162 |
-
offs_k = tl.arange(0,
|
| 163 |
a_ptrs = A + tl.arange(0, BLOCK_SIZE_M)[:, None] * 0 + offs_k[None, :] * stride_ak
|
| 164 |
b_ptrs = B + (offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn)
|
| 165 |
|
| 166 |
b_s = tl.load(Bs)
|
| 167 |
-
a_s = tl.load(As + batch_id *
|
| 168 |
|
| 169 |
-
accumulator = tl.zeros((BLOCK_SIZE_M,
|
| 170 |
-
for _ in range(0, tl.cdiv(K,
|
| 171 |
a = tl.load(a_ptrs)
|
| 172 |
b = tl.load(b_ptrs)
|
|
|
|
|
|
|
|
|
|
| 173 |
|
| 174 |
-
|
| 175 |
-
a_ptrs += block_k * stride_ak
|
| 176 |
-
b_ptrs += block_k * stride_bk
|
| 177 |
|
| 178 |
if C.dtype.element_ty == tl.bfloat16:
|
| 179 |
c = accumulator.to(tl.bfloat16)
|
|
@@ -183,7 +179,7 @@ def w8a8_tensor_fp8_matmul_batched_kernel(
|
|
| 183 |
c = accumulator.to(tl.float32)
|
| 184 |
|
| 185 |
offs_cm = tl.arange(0, BLOCK_SIZE_M)
|
| 186 |
-
offs_cn = pid_n *
|
| 187 |
c_ptrs = C + offs_cm[:, None] * 0 + stride_cn * offs_cn[None, :]
|
| 188 |
tl.store(c_ptrs, c)
|
| 189 |
|
|
@@ -194,91 +190,70 @@ def _w8a8_block_fp8_matmul_batched(
|
|
| 194 |
B: torch.Tensor,
|
| 195 |
Bs: torch.Tensor,
|
| 196 |
expert_ids: torch.Tensor,
|
| 197 |
-
block_size: list[int]
|
| 198 |
) -> torch.Tensor:
|
| 199 |
-
"""
|
| 200 |
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
"""
|
| 205 |
-
assert A.ndim == 2, "A must be (S, K)"
|
| 206 |
assert A.is_contiguous(), "A must be contiguous"
|
| 207 |
-
|
| 208 |
-
assert B.ndim == 3, "B must be (E, N, K)"
|
| 209 |
assert B.is_contiguous(), "B must be contiguous"
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
assert Bs.is_contiguous(), "Bs must be contiguous"
|
| 214 |
|
| 215 |
S, K = A.shape
|
| 216 |
-
E, N,
|
| 217 |
|
| 218 |
-
|
| 219 |
-
block_n, block_k
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
# if we have per-tensor quantization, we use 128x128 block size for tiled matmul multiplication
|
| 224 |
-
if block_n == N and block_k == K:
|
| 225 |
-
block_n, block_k = 128, 128
|
| 226 |
-
|
| 227 |
-
# we specifically require block-aligned shapes to keep the kernel simpler
|
| 228 |
assert N % block_n == 0, f"N ({N}) must be divisible by block_n ({block_n})"
|
| 229 |
assert K % block_k == 0, f"K ({K}) must be divisible by block_k ({block_k})"
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
Bs
|
| 235 |
-
|
| 236 |
-
Bs = Bs.expand(E, N // block_n, K // block_k)
|
| 237 |
-
else:
|
| 238 |
-
assert Bs.ndim == 3, (
|
| 239 |
-
"Bs must be either (E,) / (E,1,1) for per-tensor scales or (E,N//block_n,K//block_k)"
|
| 240 |
-
)
|
| 241 |
-
assert Bs.shape[0] == E, (
|
| 242 |
-
f"Bs expert dim mismatch: expected {E}, got {Bs.shape[0]}"
|
| 243 |
-
)
|
| 244 |
-
assert Bs.shape[1] == N // block_n, (
|
| 245 |
-
f"Bs N-block dim mismatch: expected {N // block_n}, got {Bs.shape[1]}"
|
| 246 |
-
)
|
| 247 |
-
assert Bs.shape[2] == K // block_k, (
|
| 248 |
-
f"Bs K-block dim mismatch: expected {K // block_k}, got {Bs.shape[2]}"
|
| 249 |
-
)
|
| 250 |
|
| 251 |
C = A.new_empty(S, N)
|
| 252 |
-
grid = (S, triton.cdiv(N, block_n))
|
| 253 |
# Adaptive BLOCK_SIZE_M: smallest power-of-2 >= M, floored at 16, capped at 128.
|
| 254 |
# Matches the WGMMA tile to the actual row count — smaller tiles use less
|
| 255 |
# register pressure and a better-matched FP8 WGMMA instruction, improving
|
| 256 |
# both accuracy and performance for small M (decode).
|
| 257 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2((S + E - 1) // E), 16), 128)
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
|
|
|
| 282 |
|
| 283 |
return C
|
| 284 |
|
|
@@ -289,71 +264,68 @@ def _w8a8_tensor_fp8_matmul_batched(
|
|
| 289 |
B: torch.Tensor,
|
| 290 |
Bs: torch.Tensor,
|
| 291 |
expert_ids: torch.Tensor,
|
| 292 |
-
block_size: list[int] | None,
|
| 293 |
) -> torch.Tensor:
|
| 294 |
-
"""Tensor-scale batched FP8 matmul
|
| 295 |
-
|
| 296 |
-
Activations are quantized once with per-token tensor scales and multiplied
|
| 297 |
-
with expert-selected FP8 weights using per-expert tensor scales.
|
| 298 |
|
| 299 |
-
|
|
|
|
|
|
|
| 300 |
"""
|
| 301 |
-
assert A.ndim == 2, "A must be (S, K)"
|
| 302 |
assert A.is_contiguous(), "A must be contiguous"
|
| 303 |
-
|
| 304 |
-
assert B.ndim == 3, "B must be (E, N, K)"
|
| 305 |
assert B.is_contiguous(), "B must be contiguous"
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
assert Bs.is_contiguous(), "Bs must be contiguous"
|
| 310 |
|
| 311 |
S, K = A.shape
|
| 312 |
-
E, N,
|
| 313 |
|
|
|
|
| 314 |
if Bs.ndim == 1:
|
|
|
|
| 315 |
Bs = Bs.reshape(E, 1, 1)
|
| 316 |
-
elif Bs.ndim == 3 and Bs.shape[0] == E and Bs.shape[1] == 1 and Bs.shape[2] == 1:
|
| 317 |
-
pass
|
| 318 |
else:
|
| 319 |
-
assert Bs.
|
| 320 |
-
|
| 321 |
-
f"Tensor mode expects Bs shape (E,1,1), got {tuple(Bs.shape)}"
|
| 322 |
)
|
| 323 |
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
assert N % block_n == 0, f"N ({N}) must be divisible by block_n ({block_n})"
|
| 327 |
-
assert K % block_k == 0, f"K ({K}) must be divisible by block_k ({block_k})"
|
| 328 |
-
|
| 329 |
C = A.new_empty(S, N)
|
| 330 |
-
BLOCK_SIZE_M = min(max(triton.next_power_of_2((S + E - 1) // E), 16), 128)
|
| 331 |
qA, As = fp8_act_quant(A, K)
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 357 |
|
| 358 |
return C
|
| 359 |
|
|
@@ -363,25 +335,13 @@ def w8a8_block_fp8_matmul_batched(
|
|
| 363 |
B: torch.Tensor,
|
| 364 |
Bs: torch.Tensor,
|
| 365 |
expert_ids: torch.Tensor,
|
| 366 |
-
block_size: list[int]
|
| 367 |
) -> torch.Tensor:
|
| 368 |
-
"""
|
| 369 |
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
``(S, N, K)`` weight gather needed — and accumulates in float32.
|
| 374 |
-
|
| 375 |
-
Args:
|
| 376 |
-
A: Raw activation matrix ``[S, K]`` in bf16/fp16/fp32.
|
| 377 |
-
B: Stacked expert weight tensor ``[E, N, K]`` in ``float8_e4m3fn``.
|
| 378 |
-
Bs: Expert weight scales, accepted as ``[E, nb, kb]`` (block)
|
| 379 |
-
or ``[E]`` / ``[E,1,1]`` (per-tensor; expanded internally).
|
| 380 |
-
expert_ids: Expert index per token ``[S]``, values in ``[0, E)``.
|
| 381 |
-
block_size: ``[block_n, block_k]`` quantization block dimensions, e.g. ``[128, 128]``.
|
| 382 |
-
|
| 383 |
-
Returns:
|
| 384 |
-
Output tensor ``[S, N]`` in the same dtype as ``A``.
|
| 385 |
"""
|
| 386 |
return torch.ops.finegrained_fp8.w8a8_block_fp8_matmul_batched(
|
| 387 |
A, B, Bs, expert_ids, block_size
|
|
@@ -393,22 +353,15 @@ def w8a8_tensor_fp8_matmul_batched(
|
|
| 393 |
B: torch.Tensor,
|
| 394 |
Bs: torch.Tensor,
|
| 395 |
expert_ids: torch.Tensor,
|
| 396 |
-
block_size: list[int] | None,
|
| 397 |
) -> torch.Tensor:
|
| 398 |
-
"""Tensor-scale batched
|
| 399 |
-
|
| 400 |
-
Args:
|
| 401 |
-
A: Raw activation matrix ``[S, K]`` in bf16/fp16/fp32.
|
| 402 |
-
B: Stacked expert weight tensor ``[E, N, K]`` in ``float8_e4m3fn``.
|
| 403 |
-
Bs: Per-expert tensor scales ``[E]`` or ``[E,1,1]``.
|
| 404 |
-
expert_ids: Expert index per token ``[S]``, values in ``[0, E)``.
|
| 405 |
-
block_size: Kept for API consistency; tensor path derives tile sizes from ``N`` and ``K``.
|
| 406 |
|
| 407 |
-
|
| 408 |
-
|
|
|
|
| 409 |
"""
|
| 410 |
return torch.ops.finegrained_fp8.w8a8_tensor_fp8_matmul_batched(
|
| 411 |
-
A, B, Bs, expert_ids
|
| 412 |
)
|
| 413 |
|
| 414 |
|
|
@@ -432,6 +385,6 @@ def w8a8_fp8_matmul_batched(
|
|
| 432 |
if block_size is None or (
|
| 433 |
block_size[0] == B.size(1) and block_size[1] == B.size(2)
|
| 434 |
):
|
| 435 |
-
return w8a8_tensor_fp8_matmul_batched(A, B, Bs, expert_ids
|
| 436 |
|
| 437 |
return w8a8_block_fp8_matmul_batched(A, B, Bs, expert_ids, block_size)
|
|
|
|
| 18 |
from .act_quant import fp8_act_quant
|
| 19 |
from torch.library import triton_op, wrap_triton
|
| 20 |
|
| 21 |
+
from .utils import device_context
|
| 22 |
+
|
| 23 |
|
| 24 |
@triton.autotune(
|
| 25 |
configs=[
|
|
|
|
| 34 |
A, # (S, K) raw BF16/FP16 activations
|
| 35 |
B, # (E, N, K) FP8 weight matrices
|
| 36 |
C, # (S, N) output
|
| 37 |
+
Bs, # (E, N // BLOCK_SIZE_N, K // BLOCK_SIZE_K) weight scales
|
| 38 |
ExpertIds, # (S,) — which expert each batch element routes to
|
| 39 |
# Shape
|
| 40 |
S,
|
| 41 |
N,
|
| 42 |
K,
|
| 43 |
+
stride_am,
|
| 44 |
stride_ak,
|
| 45 |
+
stride_be,
|
| 46 |
stride_bk,
|
| 47 |
stride_bn,
|
| 48 |
+
stride_cm,
|
| 49 |
stride_cn,
|
| 50 |
+
stride_bs_e,
|
| 51 |
+
stride_bs_k,
|
| 52 |
+
stride_bs_n,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
# Meta-parameters
|
| 54 |
+
BLOCK_SIZE_N: tl.constexpr,
|
| 55 |
+
BLOCK_SIZE_K: tl.constexpr,
|
| 56 |
BLOCK_SIZE_M: tl.constexpr,
|
| 57 |
):
|
| 58 |
"""Block-scale batched FP8 expert matmul kernel.
|
|
|
|
| 63 |
batch_id = tl.program_id(axis=0)
|
| 64 |
pid_n = tl.program_id(axis=1)
|
| 65 |
|
|
|
|
|
|
|
| 66 |
# Cast expert_id to int64 to prevent int32 overflow when computing
|
| 67 |
# expert_id * stride_Eb (e.g. 255 * 9_437_184 > 2^31 for 256 experts of
|
| 68 |
# 3072×3072 FP8 weights).
|
| 69 |
expert_id = tl.load(ExpertIds + batch_id).to(tl.int64)
|
| 70 |
|
| 71 |
+
A = A + batch_id * stride_am
|
| 72 |
+
B = B + expert_id * stride_be
|
| 73 |
+
C = C + batch_id * stride_cm
|
| 74 |
+
Bs = Bs + expert_id * stride_bs_e
|
| 75 |
|
| 76 |
+
offs_bn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 77 |
+
offs_k = tl.arange(0, BLOCK_SIZE_K)
|
| 78 |
a_ptrs = A + tl.arange(0, BLOCK_SIZE_M)[:, None] * 0 + offs_k[None, :] * stride_ak
|
| 79 |
b_ptrs = B + (offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn)
|
| 80 |
|
| 81 |
+
bs_ptrs = Bs + pid_n * stride_bs_n
|
|
|
|
| 82 |
|
| 83 |
+
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 84 |
+
for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
|
| 85 |
# ---- fused fp8_act_quant ----
|
| 86 |
a_raw = tl.load(a_ptrs).to(tl.float32)
|
| 87 |
+
a_s = tl.max(tl.abs(a_raw)) / 448.0
|
| 88 |
a = (a_raw / tl.maximum(a_s, 1e-12)).to(tl.float8e4nv)
|
| 89 |
+
# ---- matmul ----
|
| 90 |
b = tl.load(b_ptrs)
|
| 91 |
+
b_s = tl.load(bs_ptrs + k * stride_bs_k)
|
|
|
|
|
|
|
| 92 |
accumulator += tl.dot(a, b) * a_s * b_s[None, :]
|
| 93 |
+
a_ptrs += BLOCK_SIZE_K * stride_ak
|
| 94 |
+
b_ptrs += BLOCK_SIZE_K * stride_bk
|
| 95 |
|
| 96 |
if C.dtype.element_ty == tl.bfloat16:
|
| 97 |
c = accumulator.to(tl.bfloat16)
|
|
|
|
| 101 |
c = accumulator.to(tl.float32)
|
| 102 |
|
| 103 |
offs_cm = tl.arange(0, BLOCK_SIZE_M)
|
| 104 |
+
offs_cn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 105 |
c_ptrs = C + offs_cm[:, None] * 0 + stride_cn * offs_cn[None, :]
|
| 106 |
tl.store(c_ptrs, c)
|
| 107 |
|
|
|
|
| 125 |
S,
|
| 126 |
N,
|
| 127 |
K,
|
| 128 |
+
stride_am,
|
| 129 |
stride_ak,
|
| 130 |
+
stride_be,
|
| 131 |
stride_bk,
|
| 132 |
stride_bn,
|
| 133 |
+
stride_cm,
|
| 134 |
stride_cn,
|
| 135 |
+
stride_as_m,
|
| 136 |
+
stride_bs_e,
|
| 137 |
+
BLOCK_SIZE_N: tl.constexpr,
|
| 138 |
+
BLOCK_SIZE_K: tl.constexpr,
|
|
|
|
|
|
|
|
|
|
| 139 |
BLOCK_SIZE_M: tl.constexpr,
|
| 140 |
):
|
| 141 |
"""Tensor-scale batched FP8 expert matmul kernel.
|
|
|
|
| 148 |
|
| 149 |
expert_id = tl.load(ExpertIds + batch_id).to(tl.int64)
|
| 150 |
|
| 151 |
+
A = A + batch_id * stride_am
|
| 152 |
+
B = B + expert_id * stride_be
|
| 153 |
+
C = C + batch_id * stride_cm
|
| 154 |
+
Bs = Bs + expert_id * stride_bs_e
|
| 155 |
|
| 156 |
+
offs_bn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 157 |
+
offs_k = tl.arange(0, BLOCK_SIZE_K)
|
| 158 |
a_ptrs = A + tl.arange(0, BLOCK_SIZE_M)[:, None] * 0 + offs_k[None, :] * stride_ak
|
| 159 |
b_ptrs = B + (offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn)
|
| 160 |
|
| 161 |
b_s = tl.load(Bs)
|
| 162 |
+
a_s = tl.load(As + batch_id * stride_as_m)
|
| 163 |
|
| 164 |
+
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 165 |
+
for _ in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
|
| 166 |
a = tl.load(a_ptrs)
|
| 167 |
b = tl.load(b_ptrs)
|
| 168 |
+
accumulator += tl.dot(a, b)
|
| 169 |
+
a_ptrs += BLOCK_SIZE_K * stride_ak
|
| 170 |
+
b_ptrs += BLOCK_SIZE_K * stride_bk
|
| 171 |
|
| 172 |
+
accumulator = accumulator * a_s * b_s
|
|
|
|
|
|
|
| 173 |
|
| 174 |
if C.dtype.element_ty == tl.bfloat16:
|
| 175 |
c = accumulator.to(tl.bfloat16)
|
|
|
|
| 179 |
c = accumulator.to(tl.float32)
|
| 180 |
|
| 181 |
offs_cm = tl.arange(0, BLOCK_SIZE_M)
|
| 182 |
+
offs_cn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 183 |
c_ptrs = C + offs_cm[:, None] * 0 + stride_cn * offs_cn[None, :]
|
| 184 |
tl.store(c_ptrs, c)
|
| 185 |
|
|
|
|
| 190 |
B: torch.Tensor,
|
| 191 |
Bs: torch.Tensor,
|
| 192 |
expert_ids: torch.Tensor,
|
| 193 |
+
block_size: list[int],
|
| 194 |
) -> torch.Tensor:
|
| 195 |
+
"""Block-scale batched FP8 matmul: C[s] = A[s] @ B[expert_ids[s]].T, with fused act quant.
|
| 196 |
|
| 197 |
+
A: (S, K) raw bf16/fp16 activations
|
| 198 |
+
B: (E, N, K) FP8 expert weights
|
| 199 |
+
Bs: (E, N // block_n, K // block_k) per-block weight scales
|
| 200 |
"""
|
| 201 |
+
assert A.ndim == 2, f"A must be 2D (S, K), got ndim={A.ndim}"
|
| 202 |
assert A.is_contiguous(), "A must be contiguous"
|
| 203 |
+
assert B.ndim == 3, f"B must be 3D (E, N, K), got ndim={B.ndim}"
|
|
|
|
| 204 |
assert B.is_contiguous(), "B must be contiguous"
|
| 205 |
+
assert A.shape[1] == B.shape[2], (
|
| 206 |
+
f"K mismatch: A has K={A.shape[1]}, B has K={B.shape[2]}"
|
| 207 |
+
)
|
|
|
|
| 208 |
|
| 209 |
S, K = A.shape
|
| 210 |
+
E, N, _ = B.shape
|
| 211 |
|
| 212 |
+
assert len(block_size) == 2, (
|
| 213 |
+
f"block_size must be [block_n, block_k], got {block_size}"
|
| 214 |
+
)
|
| 215 |
+
block_n, block_k = block_size[0], block_size[1]
|
| 216 |
+
# MoE expert dimensions must be block-aligned; non-aligned N/K is not supported.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
assert N % block_n == 0, f"N ({N}) must be divisible by block_n ({block_n})"
|
| 218 |
assert K % block_k == 0, f"K ({K}) must be divisible by block_k ({block_k})"
|
| 219 |
+
assert Bs.ndim == 3, (
|
| 220 |
+
f"Bs must be 3D (E, N//block_n, K//block_k), got ndim={Bs.ndim}"
|
| 221 |
+
)
|
| 222 |
+
assert Bs.shape == (E, N // block_n, K // block_k), (
|
| 223 |
+
f"Bs shape {tuple(Bs.shape)} != expected ({E}, {N // block_n}, {K // block_k})"
|
| 224 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
|
| 226 |
C = A.new_empty(S, N)
|
|
|
|
| 227 |
# Adaptive BLOCK_SIZE_M: smallest power-of-2 >= M, floored at 16, capped at 128.
|
| 228 |
# Matches the WGMMA tile to the actual row count — smaller tiles use less
|
| 229 |
# register pressure and a better-matched FP8 WGMMA instruction, improving
|
| 230 |
# both accuracy and performance for small M (decode).
|
| 231 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2((S + E - 1) // E), 16), 128)
|
| 232 |
+
grid = (S, triton.cdiv(N, block_n))
|
| 233 |
+
with device_context(A.device):
|
| 234 |
+
wrap_triton(w8a8_block_fp8_matmul_batched_kernel)[grid](
|
| 235 |
+
A,
|
| 236 |
+
B,
|
| 237 |
+
C,
|
| 238 |
+
Bs,
|
| 239 |
+
expert_ids,
|
| 240 |
+
S,
|
| 241 |
+
N,
|
| 242 |
+
K,
|
| 243 |
+
A.stride(0),
|
| 244 |
+
A.stride(1),
|
| 245 |
+
B.stride(0),
|
| 246 |
+
B.stride(2),
|
| 247 |
+
B.stride(1),
|
| 248 |
+
C.stride(0),
|
| 249 |
+
C.stride(1),
|
| 250 |
+
Bs.stride(0),
|
| 251 |
+
Bs.stride(2),
|
| 252 |
+
Bs.stride(1),
|
| 253 |
+
BLOCK_SIZE_N=block_n,
|
| 254 |
+
BLOCK_SIZE_K=block_k,
|
| 255 |
+
BLOCK_SIZE_M=BLOCK_SIZE_M,
|
| 256 |
+
)
|
| 257 |
|
| 258 |
return C
|
| 259 |
|
|
|
|
| 264 |
B: torch.Tensor,
|
| 265 |
Bs: torch.Tensor,
|
| 266 |
expert_ids: torch.Tensor,
|
|
|
|
| 267 |
) -> torch.Tensor:
|
| 268 |
+
"""Tensor-scale batched FP8 matmul: C[s] = A[s] @ B[expert_ids[s]].T, with fused act quant.
|
|
|
|
|
|
|
|
|
|
| 269 |
|
| 270 |
+
A: (S, K) raw bf16/fp16 activations
|
| 271 |
+
B: (E, N, K) FP8 expert weights
|
| 272 |
+
Bs: (E,) or (E, 1, 1) per-expert weight scales
|
| 273 |
"""
|
| 274 |
+
assert A.ndim == 2, f"A must be 2D (S, K), got ndim={A.ndim}"
|
| 275 |
assert A.is_contiguous(), "A must be contiguous"
|
| 276 |
+
assert B.ndim == 3, f"B must be 3D (E, N, K), got ndim={B.ndim}"
|
|
|
|
| 277 |
assert B.is_contiguous(), "B must be contiguous"
|
| 278 |
+
assert A.shape[1] == B.shape[2], (
|
| 279 |
+
f"K mismatch: A has K={A.shape[1]}, B has K={B.shape[2]}"
|
| 280 |
+
)
|
|
|
|
| 281 |
|
| 282 |
S, K = A.shape
|
| 283 |
+
E, N, _ = B.shape
|
| 284 |
|
| 285 |
+
# Normalize Bs to (E, 1, 1)
|
| 286 |
if Bs.ndim == 1:
|
| 287 |
+
assert Bs.shape[0] == E, f"Bs shape {tuple(Bs.shape)} != expected ({E},)"
|
| 288 |
Bs = Bs.reshape(E, 1, 1)
|
|
|
|
|
|
|
| 289 |
else:
|
| 290 |
+
assert Bs.shape == (E, 1, 1), (
|
| 291 |
+
f"Bs shape {tuple(Bs.shape)} != expected ({E}, 1, 1)"
|
|
|
|
| 292 |
)
|
| 293 |
|
| 294 |
+
BLOCK_SIZE_N = 128
|
| 295 |
+
BLOCK_SIZE_K = 128
|
|
|
|
|
|
|
|
|
|
| 296 |
C = A.new_empty(S, N)
|
|
|
|
| 297 |
qA, As = fp8_act_quant(A, K)
|
| 298 |
+
grid = (S, triton.cdiv(N, BLOCK_SIZE_N))
|
| 299 |
+
# Adaptive BLOCK_SIZE_M: smallest power-of-2 >= M, floored at 16, capped at 128.
|
| 300 |
+
# Matches the WGMMA tile to the actual row count — smaller tiles use less
|
| 301 |
+
# register pressure and a better-matched FP8 WGMMA instruction, improving
|
| 302 |
+
# both accuracy and performance for small M (decode).
|
| 303 |
+
BLOCK_SIZE_M = min(max(triton.next_power_of_2((S + E - 1) // E), 16), 128)
|
| 304 |
+
grid = (S, triton.cdiv(N, BLOCK_SIZE_N))
|
| 305 |
+
with device_context(A.device):
|
| 306 |
+
wrap_triton(w8a8_tensor_fp8_matmul_batched_kernel)[grid](
|
| 307 |
+
qA,
|
| 308 |
+
B,
|
| 309 |
+
C,
|
| 310 |
+
As,
|
| 311 |
+
Bs,
|
| 312 |
+
expert_ids,
|
| 313 |
+
S,
|
| 314 |
+
N,
|
| 315 |
+
K,
|
| 316 |
+
qA.stride(0),
|
| 317 |
+
qA.stride(1),
|
| 318 |
+
B.stride(0),
|
| 319 |
+
B.stride(2),
|
| 320 |
+
B.stride(1),
|
| 321 |
+
C.stride(0),
|
| 322 |
+
C.stride(1),
|
| 323 |
+
As.stride(0),
|
| 324 |
+
Bs.stride(0),
|
| 325 |
+
BLOCK_SIZE_N=BLOCK_SIZE_N,
|
| 326 |
+
BLOCK_SIZE_K=BLOCK_SIZE_K,
|
| 327 |
+
BLOCK_SIZE_M=BLOCK_SIZE_M,
|
| 328 |
+
)
|
| 329 |
|
| 330 |
return C
|
| 331 |
|
|
|
|
| 335 |
B: torch.Tensor,
|
| 336 |
Bs: torch.Tensor,
|
| 337 |
expert_ids: torch.Tensor,
|
| 338 |
+
block_size: list[int],
|
| 339 |
) -> torch.Tensor:
|
| 340 |
+
"""Block-scale batched FP8 matmul with fused activation quantization.
|
| 341 |
|
| 342 |
+
A: (S, K) raw activations, bf16/fp16/fp32
|
| 343 |
+
B: (E, N, K) FP8 expert weights
|
| 344 |
+
Bs: (E, N // block_n, K // block_k) per-block weight scales
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 345 |
"""
|
| 346 |
return torch.ops.finegrained_fp8.w8a8_block_fp8_matmul_batched(
|
| 347 |
A, B, Bs, expert_ids, block_size
|
|
|
|
| 353 |
B: torch.Tensor,
|
| 354 |
Bs: torch.Tensor,
|
| 355 |
expert_ids: torch.Tensor,
|
|
|
|
| 356 |
) -> torch.Tensor:
|
| 357 |
+
"""Tensor-scale batched FP8 matmul with fused activation quantization.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
|
| 359 |
+
A: (S, K) raw activations, bf16/fp16/fp32
|
| 360 |
+
B: (E, N, K) FP8 expert weights
|
| 361 |
+
Bs: (E,) or (E, 1, 1) per-expert weight scales
|
| 362 |
"""
|
| 363 |
return torch.ops.finegrained_fp8.w8a8_tensor_fp8_matmul_batched(
|
| 364 |
+
A, B, Bs, expert_ids
|
| 365 |
)
|
| 366 |
|
| 367 |
|
|
|
|
| 385 |
if block_size is None or (
|
| 386 |
block_size[0] == B.size(1) and block_size[1] == B.size(2)
|
| 387 |
):
|
| 388 |
+
return w8a8_tensor_fp8_matmul_batched(A, B, Bs, expert_ids)
|
| 389 |
|
| 390 |
return w8a8_block_fp8_matmul_batched(A, B, Bs, expert_ids, block_size)
|
build/torch-xpu/grouped.py
CHANGED
|
@@ -18,6 +18,8 @@ import triton.language as tl
|
|
| 18 |
from .act_quant import fp8_act_quant
|
| 19 |
from torch.library import triton_op, wrap_triton
|
| 20 |
|
|
|
|
|
|
|
| 21 |
|
| 22 |
@triton.autotune(
|
| 23 |
configs=[
|
|
@@ -25,14 +27,14 @@ from torch.library import triton_op, wrap_triton
|
|
| 25 |
for w in [2, 4, 8, 16]
|
| 26 |
for s in [2, 3, 4, 5]
|
| 27 |
],
|
| 28 |
-
key=["N", "K"],
|
| 29 |
)
|
| 30 |
@triton.jit
|
| 31 |
def w8a8_block_fp8_matmul_grouped_kernel(
|
| 32 |
A, # (S, K) raw BF16/FP16 activations, sorted/grouped by expert id
|
| 33 |
B, # (E, N, K) FP8 weight matrices
|
| 34 |
C, # (S, N) output
|
| 35 |
-
Bs, # (E, N //
|
| 36 |
Offsets, # (E,) int32 — cumulative row-end per expert
|
| 37 |
TileOffsets, # (E,) int32 — cumulative tile-end per expert
|
| 38 |
# Shape
|
|
@@ -42,19 +44,19 @@ def w8a8_block_fp8_matmul_grouped_kernel(
|
|
| 42 |
# Strides
|
| 43 |
stride_am,
|
| 44 |
stride_ak,
|
| 45 |
-
|
| 46 |
stride_bk,
|
| 47 |
stride_bn,
|
| 48 |
stride_cm,
|
| 49 |
stride_cn,
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
# Meta-parameters
|
| 54 |
-
block_n: tl.constexpr,
|
| 55 |
-
block_k: tl.constexpr,
|
| 56 |
-
BLOCK_SIZE_M: tl.constexpr,
|
| 57 |
NUM_EXPERTS: tl.constexpr,
|
|
|
|
|
|
|
|
|
|
| 58 |
NUM_EXPERTS_BIT_LENGTH: tl.constexpr,
|
| 59 |
):
|
| 60 |
"""Block-scale grouped FP8 expert matmul kernel.
|
|
@@ -87,12 +89,11 @@ def w8a8_block_fp8_matmul_grouped_kernel(
|
|
| 87 |
hi = tl.where(is_left, hi, mid)
|
| 88 |
|
| 89 |
# Cast expert_id to int64 to prevent int32 overflow when computing
|
| 90 |
-
# expert_id *
|
| 91 |
# 3072×3072 FP8 weights).
|
| 92 |
expert_id = lo.to(tl.int64)
|
| 93 |
|
| 94 |
prev_eid = tl.maximum(expert_id - 1, 0)
|
| 95 |
-
|
| 96 |
expert_start = tl.where(expert_id == 0, 0, tl.load(Offsets + prev_eid))
|
| 97 |
expert_end = tl.load(Offsets + expert_id)
|
| 98 |
M_expert = expert_end - expert_start
|
|
@@ -105,31 +106,30 @@ def w8a8_block_fp8_matmul_grouped_kernel(
|
|
| 105 |
row_mask = offs_am < M_expert
|
| 106 |
offs_global_m = expert_start + offs_am
|
| 107 |
|
| 108 |
-
offs_bn = pid_n *
|
| 109 |
-
offs_k = tl.arange(0,
|
| 110 |
|
| 111 |
a_ptrs = A + offs_global_m[:, None] * stride_am + offs_k[None, :] * stride_ak
|
| 112 |
b_ptrs = (
|
| 113 |
B
|
| 114 |
-
+ expert_id *
|
| 115 |
+ offs_k[:, None] * stride_bk
|
| 116 |
+ offs_bn[None, :] * stride_bn
|
| 117 |
)
|
| 118 |
-
|
| 119 |
-
Bs_ptrs = Bs + expert_id * stride_Esb + offs_bsn * stride_Bsn
|
| 120 |
|
| 121 |
-
accumulator = tl.zeros((BLOCK_SIZE_M,
|
| 122 |
-
for k in range(0, tl.cdiv(K,
|
| 123 |
# ---- fused fp8_act_quant ----
|
| 124 |
a_raw = tl.load(a_ptrs, mask=row_mask[:, None], other=0.0).to(tl.float32)
|
| 125 |
-
a_s = tl.max(tl.abs(a_raw), axis=1) / 448.0
|
| 126 |
a = (a_raw / tl.maximum(a_s[:, None], 1e-12)).to(tl.float8e4nv)
|
| 127 |
-
# ----
|
| 128 |
b = tl.load(b_ptrs)
|
| 129 |
-
b_s = tl.load(
|
| 130 |
accumulator += tl.dot(a, b) * a_s[:, None] * b_s[None, :]
|
| 131 |
-
a_ptrs +=
|
| 132 |
-
b_ptrs +=
|
| 133 |
|
| 134 |
if C.dtype.element_ty == tl.bfloat16:
|
| 135 |
c = accumulator.to(tl.bfloat16)
|
|
@@ -149,11 +149,11 @@ def w8a8_block_fp8_matmul_grouped_kernel(
|
|
| 149 |
for w in [2, 4, 8, 16]
|
| 150 |
for s in [2, 3, 4, 5]
|
| 151 |
],
|
| 152 |
-
key=["N", "K"],
|
| 153 |
)
|
| 154 |
@triton.jit
|
| 155 |
def w8a8_tensor_fp8_matmul_grouped_kernel(
|
| 156 |
-
A, # (S, K)
|
| 157 |
B, # (E, N, K) FP8 weight matrices
|
| 158 |
C, # (S, N) output
|
| 159 |
As, # (S, 1) activation scales
|
|
@@ -165,17 +165,17 @@ def w8a8_tensor_fp8_matmul_grouped_kernel(
|
|
| 165 |
K,
|
| 166 |
stride_am,
|
| 167 |
stride_ak,
|
| 168 |
-
|
| 169 |
stride_bk,
|
| 170 |
stride_bn,
|
| 171 |
stride_cm,
|
| 172 |
stride_cn,
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
block_n: tl.constexpr,
|
| 176 |
-
block_k: tl.constexpr,
|
| 177 |
-
BLOCK_SIZE_M: tl.constexpr,
|
| 178 |
NUM_EXPERTS: tl.constexpr,
|
|
|
|
|
|
|
|
|
|
| 179 |
NUM_EXPERTS_BIT_LENGTH: tl.constexpr,
|
| 180 |
):
|
| 181 |
"""Tensor-scale grouped FP8 expert matmul kernel.
|
|
@@ -213,28 +213,30 @@ def w8a8_tensor_fp8_matmul_grouped_kernel(
|
|
| 213 |
row_mask = offs_am < M_expert
|
| 214 |
offs_global_m = expert_start + offs_am
|
| 215 |
|
| 216 |
-
offs_bn = pid_n *
|
| 217 |
-
offs_k = tl.arange(0,
|
| 218 |
|
| 219 |
a_ptrs = A + offs_global_m[:, None] * stride_am + offs_k[None, :] * stride_ak
|
| 220 |
b_ptrs = (
|
| 221 |
B
|
| 222 |
-
+ expert_id *
|
| 223 |
+ offs_k[:, None] * stride_bk
|
| 224 |
+ offs_bn[None, :] * stride_bn
|
| 225 |
)
|
| 226 |
|
| 227 |
-
a_s = tl.load(As + offs_global_m *
|
| 228 |
-
b_s = tl.load(Bs + expert_id *
|
| 229 |
|
| 230 |
-
accumulator = tl.zeros((BLOCK_SIZE_M,
|
| 231 |
-
for _ in range(0, tl.cdiv(K,
|
| 232 |
a = tl.load(a_ptrs, mask=row_mask[:, None], other=0.0)
|
| 233 |
b = tl.load(b_ptrs)
|
| 234 |
|
| 235 |
-
accumulator += tl.dot(a, b)
|
| 236 |
-
a_ptrs +=
|
| 237 |
-
b_ptrs +=
|
|
|
|
|
|
|
| 238 |
|
| 239 |
if C.dtype.element_ty == tl.bfloat16:
|
| 240 |
c = accumulator.to(tl.bfloat16)
|
|
@@ -255,104 +257,78 @@ def _w8a8_block_fp8_matmul_grouped(
|
|
| 255 |
Bs: torch.Tensor,
|
| 256 |
offsets: torch.Tensor,
|
| 257 |
tokens_per_expert: torch.Tensor,
|
| 258 |
-
block_size: list[int]
|
| 259 |
-
allow_sync: bool = False,
|
| 260 |
) -> torch.Tensor:
|
| 261 |
-
"""
|
| 262 |
|
| 263 |
-
|
| 264 |
-
|
|
|
|
| 265 |
"""
|
| 266 |
-
assert A.ndim == 2, "A must be (S, K)"
|
| 267 |
assert A.is_contiguous(), "A must be contiguous"
|
| 268 |
-
|
| 269 |
-
assert B.ndim == 3, "B must be (E, N, K)"
|
| 270 |
assert B.is_contiguous(), "B must be contiguous"
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
assert offsets.is_contiguous(), "offsets must be contiguous"
|
| 275 |
-
assert Bs.is_contiguous(), "Bs must be contiguous"
|
| 276 |
|
| 277 |
S, K = A.shape
|
| 278 |
-
E, N,
|
| 279 |
-
|
| 280 |
-
if block_size is None:
|
| 281 |
-
block_n, block_k = 128, 128
|
| 282 |
-
else:
|
| 283 |
-
block_n, block_k = block_size[0], block_size[1]
|
| 284 |
-
|
| 285 |
-
if block_n == N and block_k == K:
|
| 286 |
-
block_n, block_k = 128, 128
|
| 287 |
|
| 288 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 289 |
assert N % block_n == 0, f"N ({N}) must be divisible by block_n ({block_n})"
|
| 290 |
assert K % block_k == 0, f"K ({K}) must be divisible by block_k ({block_k})"
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
Bs
|
| 296 |
-
|
| 297 |
-
Bs = Bs.expand(E, N // block_n, K // block_k)
|
| 298 |
-
else:
|
| 299 |
-
assert Bs.ndim == 3, (
|
| 300 |
-
"Bs must be either (E,) / (E,1,1) for per-tensor scales or (E,N//block_n,K//block_k)"
|
| 301 |
-
)
|
| 302 |
-
assert Bs.shape[0] == E, (
|
| 303 |
-
f"Bs expert dim mismatch: expected {E}, got {Bs.shape[0]}"
|
| 304 |
-
)
|
| 305 |
-
assert Bs.shape[1] == N // block_n, (
|
| 306 |
-
f"Bs N-block dim mismatch: expected {N // block_n}, got {Bs.shape[1]}"
|
| 307 |
-
)
|
| 308 |
-
assert Bs.shape[2] == K // block_k, (
|
| 309 |
-
f"Bs K-block dim mismatch: expected {K // block_k}, got {Bs.shape[2]}"
|
| 310 |
-
)
|
| 311 |
|
| 312 |
C = A.new_empty(S, N)
|
| 313 |
-
|
| 314 |
# Adaptive BLOCK_SIZE_M: match tile to average tokens per expert.
|
| 315 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2((S + E - 1) // E), 16), 128)
|
| 316 |
tiles_per_expert = (tokens_per_expert + BLOCK_SIZE_M - 1) // BLOCK_SIZE_M
|
| 317 |
tile_offsets = torch.cumsum(tiles_per_expert, dim=0).to(torch.int32)
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
# Using a static upper bound keeps the grid size data-independent, which is
|
| 324 |
-
# required for cuda-graph compatibility. Programs beyond the real tile count
|
| 325 |
-
# exit immediately via the early-return guard inside the kernel.
|
| 326 |
-
max_M_tiles = triton.cdiv(S, BLOCK_SIZE_M) + E
|
| 327 |
-
|
| 328 |
grid = (max_M_tiles, triton.cdiv(N, block_n))
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
|
|
|
| 356 |
|
| 357 |
return C
|
| 358 |
|
|
@@ -364,88 +340,74 @@ def _w8a8_tensor_fp8_matmul_grouped(
|
|
| 364 |
Bs: torch.Tensor,
|
| 365 |
offsets: torch.Tensor,
|
| 366 |
tokens_per_expert: torch.Tensor,
|
| 367 |
-
block_size: list[int] | None,
|
| 368 |
-
allow_sync: bool = False,
|
| 369 |
) -> torch.Tensor:
|
| 370 |
-
"""Tensor-scale grouped FP8 matmul
|
| 371 |
-
|
| 372 |
-
Uses the same grouped scheduling as block mode, but with per-token tensor
|
| 373 |
-
activation scales and per-expert tensor weight scales.
|
| 374 |
|
| 375 |
-
|
|
|
|
|
|
|
| 376 |
"""
|
| 377 |
-
assert A.ndim == 2, "A must be (S, K)"
|
| 378 |
assert A.is_contiguous(), "A must be contiguous"
|
| 379 |
-
|
| 380 |
-
assert B.ndim == 3, "B must be (E, N, K)"
|
| 381 |
assert B.is_contiguous(), "B must be contiguous"
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
assert offsets.is_contiguous(), "offsets must be contiguous"
|
| 386 |
-
assert Bs.is_contiguous(), "Bs must be contiguous"
|
| 387 |
|
| 388 |
S, K = A.shape
|
| 389 |
-
E, N,
|
| 390 |
|
|
|
|
| 391 |
if Bs.ndim == 1:
|
|
|
|
| 392 |
Bs = Bs.reshape(E, 1, 1)
|
| 393 |
-
elif Bs.ndim == 3 and Bs.shape[0] == E and Bs.shape[1] == 1 and Bs.shape[2] == 1:
|
| 394 |
-
pass
|
| 395 |
else:
|
| 396 |
-
assert Bs.
|
| 397 |
-
|
| 398 |
-
f"Tensor mode expects Bs shape (E,1,1), got {tuple(Bs.shape)}"
|
| 399 |
)
|
| 400 |
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
assert N % block_n == 0, f"N ({N}) must be divisible by block_n ({block_n})"
|
| 404 |
-
assert K % block_k == 0, f"K ({K}) must be divisible by block_k ({block_k})"
|
| 405 |
-
|
| 406 |
C = A.new_empty(S, N)
|
| 407 |
-
|
| 408 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2((S + E - 1) // E), 16), 128)
|
| 409 |
tiles_per_expert = (tokens_per_expert + BLOCK_SIZE_M - 1) // BLOCK_SIZE_M
|
| 410 |
tile_offsets = torch.cumsum(tiles_per_expert, dim=0).to(torch.int32)
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
BLOCK_SIZE_M=BLOCK_SIZE_M,
|
| 446 |
-
NUM_EXPERTS=E,
|
| 447 |
-
NUM_EXPERTS_BIT_LENGTH=E.bit_length(),
|
| 448 |
-
)
|
| 449 |
|
| 450 |
return C
|
| 451 |
|
|
@@ -456,33 +418,16 @@ def w8a8_block_fp8_matmul_grouped(
|
|
| 456 |
Bs: torch.Tensor,
|
| 457 |
offsets: torch.Tensor,
|
| 458 |
tokens_per_expert: torch.Tensor,
|
| 459 |
-
block_size: list[int]
|
| 460 |
-
allow_sync: bool = False,
|
| 461 |
) -> torch.Tensor:
|
| 462 |
-
"""
|
| 463 |
-
|
| 464 |
-
Tokens in ``A`` must be pre-sorted by expert id. The kernel quantizes ``A``
|
| 465 |
-
to FP8 on-the-fly (fused ``act_quant``), uses a static over-provisioned grid
|
| 466 |
-
for CUDA-graph compatibility, and resolves each tile's expert via an O(log E)
|
| 467 |
-
binary search over ``offsets``.
|
| 468 |
-
|
| 469 |
-
Args:
|
| 470 |
-
A: Raw activation matrix ``[S, K]`` sorted by expert, in bf16/fp16/fp32.
|
| 471 |
-
B: Stacked expert weight tensor ``[E, N, K]`` in ``float8_e4m3fn``.
|
| 472 |
-
Bs: Expert weight scales, accepted as ``[E, nb, kb]`` (block)
|
| 473 |
-
or ``[E]`` / ``[E,1,1]`` (per-tensor; expanded internally).
|
| 474 |
-
offsets: Cumulative token counts per expert ``[E]`` (i.e. ``cumsum(tokens_per_expert)``).
|
| 475 |
-
tokens_per_expert: Number of tokens routed to each expert ``[E]``.
|
| 476 |
-
block_size: ``[block_n, block_k]`` quantization block dimensions, e.g. ``[128, 128]``.
|
| 477 |
-
allow_sync: If True (default), read back the exact tile count from the GPU
|
| 478 |
-
(avoids wasted programs). If False, use a data-independent upper bound
|
| 479 |
-
(required for CUDA-graph / torch.compile compatibility).
|
| 480 |
|
| 481 |
-
|
| 482 |
-
|
|
|
|
| 483 |
"""
|
| 484 |
return torch.ops.finegrained_fp8.w8a8_block_fp8_matmul_grouped(
|
| 485 |
-
A, B, Bs, offsets, tokens_per_expert, block_size
|
| 486 |
)
|
| 487 |
|
| 488 |
|
|
@@ -492,25 +437,15 @@ def w8a8_tensor_fp8_matmul_grouped(
|
|
| 492 |
Bs: torch.Tensor,
|
| 493 |
offsets: torch.Tensor,
|
| 494 |
tokens_per_expert: torch.Tensor,
|
| 495 |
-
block_size: list[int] | None,
|
| 496 |
-
allow_sync: bool = False,
|
| 497 |
) -> torch.Tensor:
|
| 498 |
-
"""Tensor-scale grouped
|
| 499 |
-
|
| 500 |
-
Args:
|
| 501 |
-
A: Raw activation matrix ``[S, K]`` sorted by expert, in bf16/fp16/fp32.
|
| 502 |
-
B: Stacked expert weight tensor ``[E, N, K]`` in ``float8_e4m3fn``.
|
| 503 |
-
Bs: Per-expert tensor scales ``[E]`` or ``[E,1,1]``.
|
| 504 |
-
offsets: Cumulative token counts per expert ``[E]``.
|
| 505 |
-
tokens_per_expert: Number of tokens routed to each expert ``[E]``.
|
| 506 |
-
block_size: Kept for API consistency; tensor path derives tile sizes from ``N`` and ``K``.
|
| 507 |
-
allow_sync: If True, sync for exact grid; if False, use upper bound.
|
| 508 |
|
| 509 |
-
|
| 510 |
-
|
|
|
|
| 511 |
"""
|
| 512 |
return torch.ops.finegrained_fp8.w8a8_tensor_fp8_matmul_grouped(
|
| 513 |
-
A, B, Bs, offsets, tokens_per_expert
|
| 514 |
)
|
| 515 |
|
| 516 |
|
|
@@ -521,7 +456,6 @@ def w8a8_fp8_matmul_grouped(
|
|
| 521 |
offsets: torch.Tensor,
|
| 522 |
tokens_per_expert: torch.Tensor,
|
| 523 |
block_size: list[int] | None,
|
| 524 |
-
allow_sync: bool = False,
|
| 525 |
) -> torch.Tensor:
|
| 526 |
"""Unified grouped W8A8 FP8 matmul dispatcher.
|
| 527 |
|
|
@@ -536,10 +470,8 @@ def w8a8_fp8_matmul_grouped(
|
|
| 536 |
if block_size is None or (
|
| 537 |
block_size[0] == B.size(1) and block_size[1] == B.size(2)
|
| 538 |
):
|
| 539 |
-
return w8a8_tensor_fp8_matmul_grouped(
|
| 540 |
-
A, B, Bs, offsets, tokens_per_expert, block_size, allow_sync
|
| 541 |
-
)
|
| 542 |
|
| 543 |
return w8a8_block_fp8_matmul_grouped(
|
| 544 |
-
A, B, Bs, offsets, tokens_per_expert, block_size
|
| 545 |
)
|
|
|
|
| 18 |
from .act_quant import fp8_act_quant
|
| 19 |
from torch.library import triton_op, wrap_triton
|
| 20 |
|
| 21 |
+
from .utils import device_context
|
| 22 |
+
|
| 23 |
|
| 24 |
@triton.autotune(
|
| 25 |
configs=[
|
|
|
|
| 27 |
for w in [2, 4, 8, 16]
|
| 28 |
for s in [2, 3, 4, 5]
|
| 29 |
],
|
| 30 |
+
key=["N", "K", "BLOCK_SIZE_M"],
|
| 31 |
)
|
| 32 |
@triton.jit
|
| 33 |
def w8a8_block_fp8_matmul_grouped_kernel(
|
| 34 |
A, # (S, K) raw BF16/FP16 activations, sorted/grouped by expert id
|
| 35 |
B, # (E, N, K) FP8 weight matrices
|
| 36 |
C, # (S, N) output
|
| 37 |
+
Bs, # (E, N // BLOCK_SIZE_N, K // BLOCK_SIZE_K) weight scales
|
| 38 |
Offsets, # (E,) int32 — cumulative row-end per expert
|
| 39 |
TileOffsets, # (E,) int32 — cumulative tile-end per expert
|
| 40 |
# Shape
|
|
|
|
| 44 |
# Strides
|
| 45 |
stride_am,
|
| 46 |
stride_ak,
|
| 47 |
+
stride_be,
|
| 48 |
stride_bk,
|
| 49 |
stride_bn,
|
| 50 |
stride_cm,
|
| 51 |
stride_cn,
|
| 52 |
+
stride_bs_e,
|
| 53 |
+
stride_bs_k,
|
| 54 |
+
stride_bs_n,
|
| 55 |
# Meta-parameters
|
|
|
|
|
|
|
|
|
|
| 56 |
NUM_EXPERTS: tl.constexpr,
|
| 57 |
+
BLOCK_SIZE_N: tl.constexpr,
|
| 58 |
+
BLOCK_SIZE_K: tl.constexpr,
|
| 59 |
+
BLOCK_SIZE_M: tl.constexpr,
|
| 60 |
NUM_EXPERTS_BIT_LENGTH: tl.constexpr,
|
| 61 |
):
|
| 62 |
"""Block-scale grouped FP8 expert matmul kernel.
|
|
|
|
| 89 |
hi = tl.where(is_left, hi, mid)
|
| 90 |
|
| 91 |
# Cast expert_id to int64 to prevent int32 overflow when computing
|
| 92 |
+
# expert_id * stride_be (e.g. 255 * 9_437_184 > 2^31 for 256 experts of
|
| 93 |
# 3072×3072 FP8 weights).
|
| 94 |
expert_id = lo.to(tl.int64)
|
| 95 |
|
| 96 |
prev_eid = tl.maximum(expert_id - 1, 0)
|
|
|
|
| 97 |
expert_start = tl.where(expert_id == 0, 0, tl.load(Offsets + prev_eid))
|
| 98 |
expert_end = tl.load(Offsets + expert_id)
|
| 99 |
M_expert = expert_end - expert_start
|
|
|
|
| 106 |
row_mask = offs_am < M_expert
|
| 107 |
offs_global_m = expert_start + offs_am
|
| 108 |
|
| 109 |
+
offs_bn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 110 |
+
offs_k = tl.arange(0, BLOCK_SIZE_K)
|
| 111 |
|
| 112 |
a_ptrs = A + offs_global_m[:, None] * stride_am + offs_k[None, :] * stride_ak
|
| 113 |
b_ptrs = (
|
| 114 |
B
|
| 115 |
+
+ expert_id * stride_be
|
| 116 |
+ offs_k[:, None] * stride_bk
|
| 117 |
+ offs_bn[None, :] * stride_bn
|
| 118 |
)
|
| 119 |
+
bs_ptrs = Bs + expert_id * stride_bs_e + pid_n * stride_bs_n
|
|
|
|
| 120 |
|
| 121 |
+
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 122 |
+
for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
|
| 123 |
# ---- fused fp8_act_quant ----
|
| 124 |
a_raw = tl.load(a_ptrs, mask=row_mask[:, None], other=0.0).to(tl.float32)
|
| 125 |
+
a_s = tl.max(tl.abs(a_raw), axis=1) / 448.0
|
| 126 |
a = (a_raw / tl.maximum(a_s[:, None], 1e-12)).to(tl.float8e4nv)
|
| 127 |
+
# ---- matmul ----
|
| 128 |
b = tl.load(b_ptrs)
|
| 129 |
+
b_s = tl.load(bs_ptrs + k * stride_bs_k)
|
| 130 |
accumulator += tl.dot(a, b) * a_s[:, None] * b_s[None, :]
|
| 131 |
+
a_ptrs += BLOCK_SIZE_K * stride_ak
|
| 132 |
+
b_ptrs += BLOCK_SIZE_K * stride_bk
|
| 133 |
|
| 134 |
if C.dtype.element_ty == tl.bfloat16:
|
| 135 |
c = accumulator.to(tl.bfloat16)
|
|
|
|
| 149 |
for w in [2, 4, 8, 16]
|
| 150 |
for s in [2, 3, 4, 5]
|
| 151 |
],
|
| 152 |
+
key=["N", "K", "BLOCK_SIZE_M"],
|
| 153 |
)
|
| 154 |
@triton.jit
|
| 155 |
def w8a8_tensor_fp8_matmul_grouped_kernel(
|
| 156 |
+
A, # (S, K) raw BF16/FP16 activations, sorted/grouped by expert idc
|
| 157 |
B, # (E, N, K) FP8 weight matrices
|
| 158 |
C, # (S, N) output
|
| 159 |
As, # (S, 1) activation scales
|
|
|
|
| 165 |
K,
|
| 166 |
stride_am,
|
| 167 |
stride_ak,
|
| 168 |
+
stride_be,
|
| 169 |
stride_bk,
|
| 170 |
stride_bn,
|
| 171 |
stride_cm,
|
| 172 |
stride_cn,
|
| 173 |
+
stride_as_m,
|
| 174 |
+
stride_bs_e,
|
|
|
|
|
|
|
|
|
|
| 175 |
NUM_EXPERTS: tl.constexpr,
|
| 176 |
+
BLOCK_SIZE_N: tl.constexpr,
|
| 177 |
+
BLOCK_SIZE_K: tl.constexpr,
|
| 178 |
+
BLOCK_SIZE_M: tl.constexpr,
|
| 179 |
NUM_EXPERTS_BIT_LENGTH: tl.constexpr,
|
| 180 |
):
|
| 181 |
"""Tensor-scale grouped FP8 expert matmul kernel.
|
|
|
|
| 213 |
row_mask = offs_am < M_expert
|
| 214 |
offs_global_m = expert_start + offs_am
|
| 215 |
|
| 216 |
+
offs_bn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 217 |
+
offs_k = tl.arange(0, BLOCK_SIZE_K)
|
| 218 |
|
| 219 |
a_ptrs = A + offs_global_m[:, None] * stride_am + offs_k[None, :] * stride_ak
|
| 220 |
b_ptrs = (
|
| 221 |
B
|
| 222 |
+
+ expert_id * stride_be
|
| 223 |
+ offs_k[:, None] * stride_bk
|
| 224 |
+ offs_bn[None, :] * stride_bn
|
| 225 |
)
|
| 226 |
|
| 227 |
+
a_s = tl.load(As + offs_global_m * stride_as_m, mask=row_mask, other=0.0)
|
| 228 |
+
b_s = tl.load(Bs + expert_id * stride_bs_e)
|
| 229 |
|
| 230 |
+
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 231 |
+
for _ in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
|
| 232 |
a = tl.load(a_ptrs, mask=row_mask[:, None], other=0.0)
|
| 233 |
b = tl.load(b_ptrs)
|
| 234 |
|
| 235 |
+
accumulator += tl.dot(a, b)
|
| 236 |
+
a_ptrs += BLOCK_SIZE_K * stride_ak
|
| 237 |
+
b_ptrs += BLOCK_SIZE_K * stride_bk
|
| 238 |
+
|
| 239 |
+
accumulator = accumulator * a_s[:, None] * b_s
|
| 240 |
|
| 241 |
if C.dtype.element_ty == tl.bfloat16:
|
| 242 |
c = accumulator.to(tl.bfloat16)
|
|
|
|
| 257 |
Bs: torch.Tensor,
|
| 258 |
offsets: torch.Tensor,
|
| 259 |
tokens_per_expert: torch.Tensor,
|
| 260 |
+
block_size: list[int],
|
|
|
|
| 261 |
) -> torch.Tensor:
|
| 262 |
+
"""Block-scale grouped FP8 matmul: C = A @ B.T per expert, with fused act quant.
|
| 263 |
|
| 264 |
+
A: (S, K) raw bf16/fp16 activations, sorted by expert
|
| 265 |
+
B: (E, N, K) FP8 expert weights
|
| 266 |
+
Bs: (E, N // block_n, K // block_k) per-block weight scales
|
| 267 |
"""
|
| 268 |
+
assert A.ndim == 2, f"A must be 2D (S, K), got ndim={A.ndim}"
|
| 269 |
assert A.is_contiguous(), "A must be contiguous"
|
| 270 |
+
assert B.ndim == 3, f"B must be 3D (E, N, K), got ndim={B.ndim}"
|
|
|
|
| 271 |
assert B.is_contiguous(), "B must be contiguous"
|
| 272 |
+
assert A.shape[1] == B.shape[2], (
|
| 273 |
+
f"K mismatch: A has K={A.shape[1]}, B has K={B.shape[2]}"
|
| 274 |
+
)
|
|
|
|
|
|
|
| 275 |
|
| 276 |
S, K = A.shape
|
| 277 |
+
E, N, _ = B.shape
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
|
| 279 |
+
assert len(block_size) == 2, (
|
| 280 |
+
f"block_size must be [block_n, block_k], got {block_size}"
|
| 281 |
+
)
|
| 282 |
+
block_n, block_k = block_size[0], block_size[1]
|
| 283 |
+
# MoE expert dimensions must be block-aligned; non-aligned N/K is not supported.
|
| 284 |
assert N % block_n == 0, f"N ({N}) must be divisible by block_n ({block_n})"
|
| 285 |
assert K % block_k == 0, f"K ({K}) must be divisible by block_k ({block_k})"
|
| 286 |
+
assert Bs.ndim == 3, (
|
| 287 |
+
f"Bs must be 3D (E, N//block_n, K//block_k), got ndim={Bs.ndim}"
|
| 288 |
+
)
|
| 289 |
+
assert Bs.shape == (E, N // block_n, K // block_k), (
|
| 290 |
+
f"Bs shape {tuple(Bs.shape)} != expected ({E}, {N // block_n}, {K // block_k})"
|
| 291 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
|
| 293 |
C = A.new_empty(S, N)
|
|
|
|
| 294 |
# Adaptive BLOCK_SIZE_M: match tile to average tokens per expert.
|
| 295 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2((S + E - 1) // E), 16), 128)
|
| 296 |
tiles_per_expert = (tokens_per_expert + BLOCK_SIZE_M - 1) // BLOCK_SIZE_M
|
| 297 |
tile_offsets = torch.cumsum(tiles_per_expert, dim=0).to(torch.int32)
|
| 298 |
+
# Upper bound on M-tiles: sum_e ceil(M_e / BLOCK_M) <= ceil(S / BLOCK_M) + E.
|
| 299 |
+
# Programs beyond the real tile count exit immediately via the early-return
|
| 300 |
+
# guard inside the kernel. This is faster than syncing for the exact count
|
| 301 |
+
# and keeps the grid size data-independent (cuda-graph / torch.compile safe).
|
| 302 |
+
max_M_tiles = triton.cdiv(S, BLOCK_SIZE_M) + E
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 303 |
grid = (max_M_tiles, triton.cdiv(N, block_n))
|
| 304 |
+
with device_context(A.device):
|
| 305 |
+
wrap_triton(w8a8_block_fp8_matmul_grouped_kernel)[grid](
|
| 306 |
+
A,
|
| 307 |
+
B,
|
| 308 |
+
C,
|
| 309 |
+
Bs,
|
| 310 |
+
offsets,
|
| 311 |
+
tile_offsets,
|
| 312 |
+
S,
|
| 313 |
+
N,
|
| 314 |
+
K,
|
| 315 |
+
A.stride(0),
|
| 316 |
+
A.stride(1),
|
| 317 |
+
B.stride(0),
|
| 318 |
+
B.stride(2),
|
| 319 |
+
B.stride(1),
|
| 320 |
+
C.stride(0),
|
| 321 |
+
C.stride(1),
|
| 322 |
+
Bs.stride(0),
|
| 323 |
+
Bs.stride(2),
|
| 324 |
+
Bs.stride(1),
|
| 325 |
+
# Meta-parameters
|
| 326 |
+
NUM_EXPERTS=E,
|
| 327 |
+
BLOCK_SIZE_N=block_n,
|
| 328 |
+
BLOCK_SIZE_K=block_k,
|
| 329 |
+
BLOCK_SIZE_M=BLOCK_SIZE_M,
|
| 330 |
+
NUM_EXPERTS_BIT_LENGTH=E.bit_length(),
|
| 331 |
+
)
|
| 332 |
|
| 333 |
return C
|
| 334 |
|
|
|
|
| 340 |
Bs: torch.Tensor,
|
| 341 |
offsets: torch.Tensor,
|
| 342 |
tokens_per_expert: torch.Tensor,
|
|
|
|
|
|
|
| 343 |
) -> torch.Tensor:
|
| 344 |
+
"""Tensor-scale grouped FP8 matmul: C = A @ B.T per expert, with fused act quant.
|
|
|
|
|
|
|
|
|
|
| 345 |
|
| 346 |
+
A: (S, K) raw bf16/fp16 activations, sorted by expert
|
| 347 |
+
B: (E, N, K) FP8 expert weights
|
| 348 |
+
Bs: (E,) or (E, 1, 1) per-expert weight scales
|
| 349 |
"""
|
| 350 |
+
assert A.ndim == 2, f"A must be 2D (S, K), got ndim={A.ndim}"
|
| 351 |
assert A.is_contiguous(), "A must be contiguous"
|
| 352 |
+
assert B.ndim == 3, f"B must be 3D (E, N, K), got ndim={B.ndim}"
|
|
|
|
| 353 |
assert B.is_contiguous(), "B must be contiguous"
|
| 354 |
+
assert A.shape[1] == B.shape[2], (
|
| 355 |
+
f"K mismatch: A has K={A.shape[1]}, B has K={B.shape[2]}"
|
| 356 |
+
)
|
|
|
|
|
|
|
| 357 |
|
| 358 |
S, K = A.shape
|
| 359 |
+
E, N, _ = B.shape
|
| 360 |
|
| 361 |
+
# Normalize Bs to (E, 1, 1)
|
| 362 |
if Bs.ndim == 1:
|
| 363 |
+
assert Bs.shape[0] == E, f"Bs shape {tuple(Bs.shape)} != expected ({E},)"
|
| 364 |
Bs = Bs.reshape(E, 1, 1)
|
|
|
|
|
|
|
| 365 |
else:
|
| 366 |
+
assert Bs.shape == (E, 1, 1), (
|
| 367 |
+
f"Bs shape {tuple(Bs.shape)} != expected ({E}, 1, 1)"
|
|
|
|
| 368 |
)
|
| 369 |
|
| 370 |
+
BLOCK_SIZE_N = 128
|
| 371 |
+
BLOCK_SIZE_K = 128
|
|
|
|
|
|
|
|
|
|
| 372 |
C = A.new_empty(S, N)
|
| 373 |
+
qA, As = fp8_act_quant(A, K)
|
| 374 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2((S + E - 1) // E), 16), 128)
|
| 375 |
tiles_per_expert = (tokens_per_expert + BLOCK_SIZE_M - 1) // BLOCK_SIZE_M
|
| 376 |
tile_offsets = torch.cumsum(tiles_per_expert, dim=0).to(torch.int32)
|
| 377 |
+
# Upper bound on M-tiles: sum_e ceil(M_e / BLOCK_M) <= ceil(S / BLOCK_M) + E.
|
| 378 |
+
# Programs beyond the real tile count exit immediately via the early-return
|
| 379 |
+
# guard inside the kernel. This is faster than syncing for the exact count
|
| 380 |
+
# and keeps the grid size data-independent (cuda-graph / torch.compile safe).
|
| 381 |
+
max_M_tiles = triton.cdiv(S, BLOCK_SIZE_M) + E
|
| 382 |
+
grid = (max_M_tiles, triton.cdiv(N, BLOCK_SIZE_N))
|
| 383 |
+
with device_context(A.device):
|
| 384 |
+
wrap_triton(w8a8_tensor_fp8_matmul_grouped_kernel)[grid](
|
| 385 |
+
qA,
|
| 386 |
+
B,
|
| 387 |
+
C,
|
| 388 |
+
As,
|
| 389 |
+
Bs,
|
| 390 |
+
offsets,
|
| 391 |
+
tile_offsets,
|
| 392 |
+
S,
|
| 393 |
+
N,
|
| 394 |
+
K,
|
| 395 |
+
qA.stride(0),
|
| 396 |
+
qA.stride(1),
|
| 397 |
+
B.stride(0),
|
| 398 |
+
B.stride(2),
|
| 399 |
+
B.stride(1),
|
| 400 |
+
C.stride(0),
|
| 401 |
+
C.stride(1),
|
| 402 |
+
As.stride(0),
|
| 403 |
+
Bs.stride(0),
|
| 404 |
+
# Meta-parameters
|
| 405 |
+
NUM_EXPERTS=E,
|
| 406 |
+
BLOCK_SIZE_N=BLOCK_SIZE_N,
|
| 407 |
+
BLOCK_SIZE_K=BLOCK_SIZE_K,
|
| 408 |
+
BLOCK_SIZE_M=BLOCK_SIZE_M,
|
| 409 |
+
NUM_EXPERTS_BIT_LENGTH=E.bit_length(),
|
| 410 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 411 |
|
| 412 |
return C
|
| 413 |
|
|
|
|
| 418 |
Bs: torch.Tensor,
|
| 419 |
offsets: torch.Tensor,
|
| 420 |
tokens_per_expert: torch.Tensor,
|
| 421 |
+
block_size: list[int],
|
|
|
|
| 422 |
) -> torch.Tensor:
|
| 423 |
+
"""Block-scale grouped FP8 matmul with fused activation quantization.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 424 |
|
| 425 |
+
A: (S, K) raw activations sorted by expert, bf16/fp16/fp32
|
| 426 |
+
B: (E, N, K) FP8 expert weights
|
| 427 |
+
Bs: (E, N // block_n, K // block_k) per-block weight scales
|
| 428 |
"""
|
| 429 |
return torch.ops.finegrained_fp8.w8a8_block_fp8_matmul_grouped(
|
| 430 |
+
A, B, Bs, offsets, tokens_per_expert, block_size
|
| 431 |
)
|
| 432 |
|
| 433 |
|
|
|
|
| 437 |
Bs: torch.Tensor,
|
| 438 |
offsets: torch.Tensor,
|
| 439 |
tokens_per_expert: torch.Tensor,
|
|
|
|
|
|
|
| 440 |
) -> torch.Tensor:
|
| 441 |
+
"""Tensor-scale grouped FP8 matmul with fused activation quantization.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 442 |
|
| 443 |
+
A: (S, K) raw activations sorted by expert, bf16/fp16/fp32
|
| 444 |
+
B: (E, N, K) FP8 expert weights
|
| 445 |
+
Bs: (E,) or (E, 1, 1) per-expert weight scales
|
| 446 |
"""
|
| 447 |
return torch.ops.finegrained_fp8.w8a8_tensor_fp8_matmul_grouped(
|
| 448 |
+
A, B, Bs, offsets, tokens_per_expert
|
| 449 |
)
|
| 450 |
|
| 451 |
|
|
|
|
| 456 |
offsets: torch.Tensor,
|
| 457 |
tokens_per_expert: torch.Tensor,
|
| 458 |
block_size: list[int] | None,
|
|
|
|
| 459 |
) -> torch.Tensor:
|
| 460 |
"""Unified grouped W8A8 FP8 matmul dispatcher.
|
| 461 |
|
|
|
|
| 470 |
if block_size is None or (
|
| 471 |
block_size[0] == B.size(1) and block_size[1] == B.size(2)
|
| 472 |
):
|
| 473 |
+
return w8a8_tensor_fp8_matmul_grouped(A, B, Bs, offsets, tokens_per_expert)
|
|
|
|
|
|
|
| 474 |
|
| 475 |
return w8a8_block_fp8_matmul_grouped(
|
| 476 |
+
A, B, Bs, offsets, tokens_per_expert, block_size
|
| 477 |
)
|
build/torch-xpu/matmul.py
CHANGED
|
@@ -17,8 +17,18 @@ import triton
|
|
| 17 |
import triton.language as tl
|
| 18 |
from torch.library import triton_op, wrap_triton
|
| 19 |
|
|
|
|
|
|
|
| 20 |
|
| 21 |
# Adapted from https://github.com/sgl-project/sglang/blob/main/python/sglang/srt/layers/quantization/fp8_kernel.py
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
@triton.jit
|
| 23 |
def w8a8_block_fp8_matmul_kernel(
|
| 24 |
# Pointers to inputs and output
|
|
@@ -31,20 +41,16 @@ def w8a8_block_fp8_matmul_kernel(
|
|
| 31 |
M,
|
| 32 |
N,
|
| 33 |
K,
|
| 34 |
-
# Block size for block-wise quantization
|
| 35 |
-
group_n,
|
| 36 |
-
group_k,
|
| 37 |
-
# Stride for inputs and output
|
| 38 |
stride_am,
|
| 39 |
stride_ak,
|
| 40 |
stride_bk,
|
| 41 |
stride_bn,
|
| 42 |
stride_cm,
|
| 43 |
stride_cn,
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
# Meta-parameters
|
| 49 |
BLOCK_SIZE_M: tl.constexpr,
|
| 50 |
BLOCK_SIZE_N: tl.constexpr,
|
|
@@ -54,17 +60,13 @@ def w8a8_block_fp8_matmul_kernel(
|
|
| 54 |
"""Block-scale FP8 GEMM kernel.
|
| 55 |
|
| 56 |
Computes ``C = A @ B.T`` with block-wise activation/weight scales.
|
|
|
|
| 57 |
"""
|
| 58 |
-
|
| 59 |
-
|
| 60 |
num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
|
| 61 |
num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)
|
| 62 |
-
|
| 63 |
-
group_id = pid // num_pid_in_group
|
| 64 |
-
first_pid_m = group_id * GROUP_SIZE_M
|
| 65 |
-
group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M)
|
| 66 |
-
pid_m = first_pid_m + (pid % group_size_m)
|
| 67 |
-
pid_n = (pid % num_pid_in_group) // group_size_m
|
| 68 |
|
| 69 |
offs_am = (pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
|
| 70 |
offs_bn = (pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)) % N
|
|
@@ -72,19 +74,18 @@ def w8a8_block_fp8_matmul_kernel(
|
|
| 72 |
a_ptrs = A + (offs_am[:, None] * stride_am + offs_k[None, :] * stride_ak)
|
| 73 |
b_ptrs = B + (offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn)
|
| 74 |
|
| 75 |
-
|
| 76 |
-
offs_bsn = offs_bn //
|
| 77 |
-
|
| 78 |
|
| 79 |
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 80 |
for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
|
| 81 |
-
|
| 82 |
-
|
|
|
|
| 83 |
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
a_s = tl.load(As_ptrs + offs_ks * stride_As_k)
|
| 87 |
-
b_s = tl.load(Bs_ptrs + offs_ks * stride_Bs_k)
|
| 88 |
|
| 89 |
accumulator += tl.dot(a, b) * a_s[:, None] * b_s[None, :]
|
| 90 |
a_ptrs += BLOCK_SIZE_K * stride_ak
|
|
@@ -104,6 +105,14 @@ def w8a8_block_fp8_matmul_kernel(
|
|
| 104 |
tl.store(c_ptrs, c, mask=c_mask)
|
| 105 |
|
| 106 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
@triton.jit
|
| 108 |
def w8a8_tensor_fp8_matmul_kernel(
|
| 109 |
A,
|
|
@@ -120,7 +129,7 @@ def w8a8_tensor_fp8_matmul_kernel(
|
|
| 120 |
stride_bn,
|
| 121 |
stride_cm,
|
| 122 |
stride_cn,
|
| 123 |
-
|
| 124 |
BLOCK_SIZE_M: tl.constexpr,
|
| 125 |
BLOCK_SIZE_N: tl.constexpr,
|
| 126 |
BLOCK_SIZE_K: tl.constexpr,
|
|
@@ -130,40 +139,36 @@ def w8a8_tensor_fp8_matmul_kernel(
|
|
| 130 |
|
| 131 |
Computes ``C = A @ B.T`` with one activation scale per row and one
|
| 132 |
weight scale for the full matrix.
|
|
|
|
| 133 |
"""
|
| 134 |
-
|
|
|
|
| 135 |
num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
|
| 136 |
num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
pid_m = first_pid_m + (pid % group_size_m)
|
| 142 |
-
pid_n = (pid % num_pid_in_group) // group_size_m
|
| 143 |
-
|
| 144 |
-
offs_am = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
|
| 145 |
-
offs_bn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
| 146 |
offs_k = tl.arange(0, BLOCK_SIZE_K)
|
| 147 |
|
| 148 |
a_ptrs = A + offs_am[:, None] * stride_am + offs_k[None, :] * stride_ak
|
| 149 |
b_ptrs = B + offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn
|
| 150 |
|
| 151 |
-
a_s = tl.load(As + offs_am *
|
| 152 |
b_s = tl.load(Bs)
|
| 153 |
|
|
|
|
| 154 |
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 155 |
for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
|
| 156 |
-
|
| 157 |
-
a = tl.load(
|
| 158 |
-
|
| 159 |
-
)
|
| 160 |
-
b = tl.load(
|
| 161 |
-
b_ptrs, mask=(k_offs[:, None] < K) & (offs_bn[None, :] < N), other=0.0
|
| 162 |
-
)
|
| 163 |
-
accumulator += tl.dot(a, b) * a_s[:, None] * b_s
|
| 164 |
a_ptrs += BLOCK_SIZE_K * stride_ak
|
| 165 |
b_ptrs += BLOCK_SIZE_K * stride_bk
|
| 166 |
|
|
|
|
|
|
|
| 167 |
if C.dtype.element_ty == tl.bfloat16:
|
| 168 |
c = accumulator.to(tl.bfloat16)
|
| 169 |
elif C.dtype.element_ty == tl.float16:
|
|
@@ -184,82 +189,74 @@ def _w8a8_block_fp8_matmul(
|
|
| 184 |
B: torch.Tensor,
|
| 185 |
As: torch.Tensor,
|
| 186 |
Bs: torch.Tensor,
|
| 187 |
-
block_size: list[int]
|
| 188 |
output_dtype: torch.dtype = torch.float32,
|
| 189 |
) -> torch.Tensor:
|
| 190 |
-
"""
|
| 191 |
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
block-scale shapes.
|
| 195 |
"""
|
| 196 |
-
|
| 197 |
-
block_n, block_k
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
block_n, block_k = block_size[0], block_size[1]
|
| 201 |
-
|
| 202 |
-
assert A.shape[-1] == B.shape[-1]
|
| 203 |
-
assert A.is_contiguous()
|
| 204 |
|
| 205 |
-
assert
|
| 206 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
|
| 208 |
N, K = B.shape
|
| 209 |
M = A.numel() // A.shape[-1]
|
| 210 |
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
Bs = Bs.reshape(1, 1).expand(triton.cdiv(N, block_n), triton.cdiv(K, block_k))
|
| 220 |
-
else:
|
| 221 |
-
assert Bs.ndim == 2
|
| 222 |
-
assert triton.cdiv(N, block_n) == Bs.shape[0], f"{N}, {block_n}, {Bs.shape}"
|
| 223 |
-
assert triton.cdiv(K, block_k) == Bs.shape[1], f"{K}, {block_k}, {Bs.shape}"
|
| 224 |
|
|
|
|
|
|
|
| 225 |
C_shape = A.shape[:-1] + (N,)
|
| 226 |
C = A.new_empty(C_shape, dtype=output_dtype)
|
| 227 |
-
|
| 228 |
# Adaptive BLOCK_SIZE_M: smallest power-of-2 >= M, floored at 16, capped at 128.
|
| 229 |
# Matches the WGMMA tile to the actual row count — smaller tiles use less
|
| 230 |
# register pressure and a better-matched FP8 WGMMA instruction, improving
|
| 231 |
# both accuracy and performance for small M (decode).
|
| 232 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2(M), 16), 128)
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
BLOCK_SIZE_K=BLOCK_SIZE_K,
|
| 261 |
-
GROUP_SIZE_M=8,
|
| 262 |
-
)
|
| 263 |
|
| 264 |
return C
|
| 265 |
|
|
@@ -270,83 +267,65 @@ def _w8a8_tensor_fp8_matmul(
|
|
| 270 |
B: torch.Tensor,
|
| 271 |
As: torch.Tensor,
|
| 272 |
Bs: torch.Tensor,
|
| 273 |
-
block_size: list[int] | None,
|
| 274 |
output_dtype: torch.dtype = torch.float32,
|
| 275 |
) -> torch.Tensor:
|
| 276 |
-
"""Tensor-scale
|
| 277 |
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
- ``As``: scalar, ``[M]``, or ``[M,1]`` -> ``[M]``
|
| 281 |
-
- ``Bs``: scalar, ``[1]``, or ``[1,1]`` -> ``[1]``
|
| 282 |
"""
|
| 283 |
-
assert A.shape[-1] == B.shape[-1]
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
assert
|
| 287 |
-
assert B.
|
|
|
|
| 288 |
|
| 289 |
N, K = B.shape
|
| 290 |
M = A.numel() // A.shape[-1]
|
| 291 |
|
| 292 |
-
|
| 293 |
-
block_k = 128 if K % 128 == 0 else K
|
| 294 |
-
|
| 295 |
if As.numel() == 1:
|
| 296 |
As = As.reshape(1).expand(M).contiguous()
|
| 297 |
-
elif As.ndim ==
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
)
|
| 301 |
-
|
| 302 |
-
else:
|
| 303 |
-
assert As.ndim == 2 and As.shape[0] == M and As.shape[1] == 1, (
|
| 304 |
-
f"Tensor mode expects As shape [M,1], got {tuple(As.shape)}"
|
| 305 |
-
)
|
| 306 |
-
As = As.reshape(M).contiguous()
|
| 307 |
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
assert Bs.shape[0] == 1, (
|
| 312 |
-
f"Tensor mode expects Bs shape [1], got {tuple(Bs.shape)}"
|
| 313 |
-
)
|
| 314 |
-
Bs = Bs.contiguous()
|
| 315 |
-
else:
|
| 316 |
-
assert Bs.ndim == 2 and Bs.shape[0] == 1 and Bs.shape[1] == 1, (
|
| 317 |
-
f"Tensor mode expects Bs shape [1,1], got {tuple(Bs.shape)}"
|
| 318 |
-
)
|
| 319 |
-
Bs = Bs.reshape(1).contiguous()
|
| 320 |
|
|
|
|
|
|
|
| 321 |
C_shape = A.shape[:-1] + (N,)
|
| 322 |
C = A.new_empty(C_shape, dtype=output_dtype)
|
| 323 |
-
|
| 324 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2(M), 16), 128)
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
)
|
| 350 |
|
| 351 |
return C
|
| 352 |
|
|
@@ -356,7 +335,7 @@ def w8a8_block_fp8_matmul(
|
|
| 356 |
B: torch.Tensor,
|
| 357 |
As: torch.Tensor,
|
| 358 |
Bs: torch.Tensor,
|
| 359 |
-
block_size: list[int]
|
| 360 |
output_dtype: torch.dtype = torch.float32,
|
| 361 |
) -> torch.Tensor:
|
| 362 |
"""Block-wise W8A8 FP8 matrix multiplication.
|
|
@@ -386,7 +365,6 @@ def w8a8_tensor_fp8_matmul(
|
|
| 386 |
B: torch.Tensor,
|
| 387 |
As: torch.Tensor,
|
| 388 |
Bs: torch.Tensor,
|
| 389 |
-
block_size: list[int] | None,
|
| 390 |
output_dtype: torch.dtype = torch.float32,
|
| 391 |
) -> torch.Tensor:
|
| 392 |
"""Tensor-scale W8A8 FP8 matrix multiplication.
|
|
@@ -397,17 +375,14 @@ def w8a8_tensor_fp8_matmul(
|
|
| 397 |
Args:
|
| 398 |
A: Quantized activation tensor ``[M, K]`` in ``float8_e4m3fn``.
|
| 399 |
B: Quantized weight tensor ``[N, K]`` in ``float8_e4m3fn``.
|
| 400 |
-
As:
|
| 401 |
-
Bs:
|
| 402 |
-
block_size: Kept for API consistency; tensor path derives tile sizes from ``N`` and ``K``.
|
| 403 |
output_dtype: dtype of the returned tensor.
|
| 404 |
|
| 405 |
Returns:
|
| 406 |
Output tensor ``[M, N]`` in ``output_dtype``.
|
| 407 |
"""
|
| 408 |
-
return torch.ops.finegrained_fp8.w8a8_tensor_fp8_matmul(
|
| 409 |
-
A, B, As, Bs, block_size, output_dtype
|
| 410 |
-
)
|
| 411 |
|
| 412 |
|
| 413 |
def w8a8_fp8_matmul(
|
|
@@ -431,6 +406,6 @@ def w8a8_fp8_matmul(
|
|
| 431 |
if block_size is None or (
|
| 432 |
block_size[0] == B.size(0) and block_size[1] == B.size(1)
|
| 433 |
):
|
| 434 |
-
return w8a8_tensor_fp8_matmul(A, B, As, Bs,
|
| 435 |
|
| 436 |
return w8a8_block_fp8_matmul(A, B, As, Bs, block_size, output_dtype)
|
|
|
|
| 17 |
import triton.language as tl
|
| 18 |
from torch.library import triton_op, wrap_triton
|
| 19 |
|
| 20 |
+
from .utils import device_context
|
| 21 |
+
|
| 22 |
|
| 23 |
# Adapted from https://github.com/sgl-project/sglang/blob/main/python/sglang/srt/layers/quantization/fp8_kernel.py
|
| 24 |
+
@triton.autotune(
|
| 25 |
+
configs=[
|
| 26 |
+
triton.Config({}, num_warps=w, num_stages=s)
|
| 27 |
+
for w in [2, 4, 8, 16]
|
| 28 |
+
for s in [2, 3, 4]
|
| 29 |
+
],
|
| 30 |
+
key=["N", "K", "BLOCK_SIZE_M"],
|
| 31 |
+
)
|
| 32 |
@triton.jit
|
| 33 |
def w8a8_block_fp8_matmul_kernel(
|
| 34 |
# Pointers to inputs and output
|
|
|
|
| 41 |
M,
|
| 42 |
N,
|
| 43 |
K,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
stride_am,
|
| 45 |
stride_ak,
|
| 46 |
stride_bk,
|
| 47 |
stride_bn,
|
| 48 |
stride_cm,
|
| 49 |
stride_cn,
|
| 50 |
+
stride_as_m,
|
| 51 |
+
stride_as_k,
|
| 52 |
+
stride_bs_k,
|
| 53 |
+
stride_bs_n,
|
| 54 |
# Meta-parameters
|
| 55 |
BLOCK_SIZE_M: tl.constexpr,
|
| 56 |
BLOCK_SIZE_N: tl.constexpr,
|
|
|
|
| 60 |
"""Block-scale FP8 GEMM kernel.
|
| 61 |
|
| 62 |
Computes ``C = A @ B.T`` with block-wise activation/weight scales.
|
| 63 |
+
Uses a 2D grid with swizzle for L2 cache locality on B tiles.
|
| 64 |
"""
|
| 65 |
+
pid_m = tl.program_id(axis=0)
|
| 66 |
+
pid_n = tl.program_id(axis=1)
|
| 67 |
num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
|
| 68 |
num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)
|
| 69 |
+
pid_m, pid_n = tl.swizzle2d(pid_m, pid_n, num_pid_m, num_pid_n, GROUP_SIZE_M)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
offs_am = (pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
|
| 72 |
offs_bn = (pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)) % N
|
|
|
|
| 74 |
a_ptrs = A + (offs_am[:, None] * stride_am + offs_k[None, :] * stride_ak)
|
| 75 |
b_ptrs = B + (offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn)
|
| 76 |
|
| 77 |
+
as_ptrs = As + offs_am * stride_as_m
|
| 78 |
+
offs_bsn = offs_bn // BLOCK_SIZE_N
|
| 79 |
+
bs_ptrs = Bs + offs_bsn * stride_bs_n
|
| 80 |
|
| 81 |
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 82 |
for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
|
| 83 |
+
k_remaining = K - k * BLOCK_SIZE_K
|
| 84 |
+
a = tl.load(a_ptrs, mask=offs_k[None, :] < k_remaining, other=0.0)
|
| 85 |
+
b = tl.load(b_ptrs, mask=offs_k[:, None] < k_remaining, other=0.0)
|
| 86 |
|
| 87 |
+
a_s = tl.load(as_ptrs + k * stride_as_k)
|
| 88 |
+
b_s = tl.load(bs_ptrs + k * stride_bs_k)
|
|
|
|
|
|
|
| 89 |
|
| 90 |
accumulator += tl.dot(a, b) * a_s[:, None] * b_s[None, :]
|
| 91 |
a_ptrs += BLOCK_SIZE_K * stride_ak
|
|
|
|
| 105 |
tl.store(c_ptrs, c, mask=c_mask)
|
| 106 |
|
| 107 |
|
| 108 |
+
@triton.autotune(
|
| 109 |
+
configs=[
|
| 110 |
+
triton.Config({}, num_warps=w, num_stages=s)
|
| 111 |
+
for w in [2, 4, 8, 16]
|
| 112 |
+
for s in [2, 3, 4]
|
| 113 |
+
],
|
| 114 |
+
key=["N", "K", "BLOCK_SIZE_M"],
|
| 115 |
+
)
|
| 116 |
@triton.jit
|
| 117 |
def w8a8_tensor_fp8_matmul_kernel(
|
| 118 |
A,
|
|
|
|
| 129 |
stride_bn,
|
| 130 |
stride_cm,
|
| 131 |
stride_cn,
|
| 132 |
+
stride_as_m,
|
| 133 |
BLOCK_SIZE_M: tl.constexpr,
|
| 134 |
BLOCK_SIZE_N: tl.constexpr,
|
| 135 |
BLOCK_SIZE_K: tl.constexpr,
|
|
|
|
| 139 |
|
| 140 |
Computes ``C = A @ B.T`` with one activation scale per row and one
|
| 141 |
weight scale for the full matrix.
|
| 142 |
+
Uses a 2D grid with swizzle for L2 cache locality on B tiles.
|
| 143 |
"""
|
| 144 |
+
pid_m = tl.program_id(axis=0)
|
| 145 |
+
pid_n = tl.program_id(axis=1)
|
| 146 |
num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
|
| 147 |
num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)
|
| 148 |
+
pid_m, pid_n = tl.swizzle2d(pid_m, pid_n, num_pid_m, num_pid_n, GROUP_SIZE_M)
|
| 149 |
+
|
| 150 |
+
offs_am = (pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)) % M
|
| 151 |
+
offs_bn = (pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)) % N
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
offs_k = tl.arange(0, BLOCK_SIZE_K)
|
| 153 |
|
| 154 |
a_ptrs = A + offs_am[:, None] * stride_am + offs_k[None, :] * stride_ak
|
| 155 |
b_ptrs = B + offs_k[:, None] * stride_bk + offs_bn[None, :] * stride_bn
|
| 156 |
|
| 157 |
+
a_s = tl.load(As + offs_am * stride_as_m)
|
| 158 |
b_s = tl.load(Bs)
|
| 159 |
|
| 160 |
+
# Accumulate raw dot products, apply scales once after the loop.
|
| 161 |
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
| 162 |
for k in range(0, tl.cdiv(K, BLOCK_SIZE_K)):
|
| 163 |
+
k_remaining = K - k * BLOCK_SIZE_K
|
| 164 |
+
a = tl.load(a_ptrs, mask=offs_k[None, :] < k_remaining, other=0.0)
|
| 165 |
+
b = tl.load(b_ptrs, mask=offs_k[:, None] < k_remaining, other=0.0)
|
| 166 |
+
accumulator += tl.dot(a, b)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
a_ptrs += BLOCK_SIZE_K * stride_ak
|
| 168 |
b_ptrs += BLOCK_SIZE_K * stride_bk
|
| 169 |
|
| 170 |
+
accumulator = accumulator * a_s[:, None] * b_s
|
| 171 |
+
|
| 172 |
if C.dtype.element_ty == tl.bfloat16:
|
| 173 |
c = accumulator.to(tl.bfloat16)
|
| 174 |
elif C.dtype.element_ty == tl.float16:
|
|
|
|
| 189 |
B: torch.Tensor,
|
| 190 |
As: torch.Tensor,
|
| 191 |
Bs: torch.Tensor,
|
| 192 |
+
block_size: list[int],
|
| 193 |
output_dtype: torch.dtype = torch.float32,
|
| 194 |
) -> torch.Tensor:
|
| 195 |
+
"""Block-scale FP8 matmul: C = A @ B.T with per-block scales.
|
| 196 |
|
| 197 |
+
As: (M, K // block_k) — per-token-group activation scales
|
| 198 |
+
Bs: (N // block_n, K // block_k) — per-block weight scales
|
|
|
|
| 199 |
"""
|
| 200 |
+
assert len(block_size) == 2, (
|
| 201 |
+
f"block_size must be [block_n, block_k], got {block_size}"
|
| 202 |
+
)
|
| 203 |
+
block_n, block_k = block_size[0], block_size[1]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
|
| 205 |
+
assert A.shape[-1] == B.shape[-1], (
|
| 206 |
+
f"K mismatch: A has K={A.shape[-1]}, B has K={B.shape[-1]}"
|
| 207 |
+
)
|
| 208 |
+
assert A.is_contiguous(), "A must be contiguous"
|
| 209 |
+
assert B.ndim == 2, f"B must be 2D (N, K), got ndim={B.ndim}"
|
| 210 |
+
assert B.is_contiguous(), "B must be contiguous"
|
| 211 |
|
| 212 |
N, K = B.shape
|
| 213 |
M = A.numel() // A.shape[-1]
|
| 214 |
|
| 215 |
+
assert As.ndim >= 2, f"As must be at least 2D, got ndim={As.ndim}"
|
| 216 |
+
assert As.shape[-1] == triton.cdiv(K, block_k), (
|
| 217 |
+
f"As last dim {As.shape[-1]} != expected {triton.cdiv(K, block_k)} (cdiv(K={K}, block_k={block_k}))"
|
| 218 |
+
)
|
| 219 |
+
assert Bs.ndim == 2, f"Bs must be 2D (N//block_n, K//block_k), got ndim={Bs.ndim}"
|
| 220 |
+
assert Bs.shape == (triton.cdiv(N, block_n), triton.cdiv(K, block_k)), (
|
| 221 |
+
f"Bs shape {tuple(Bs.shape)} != expected ({triton.cdiv(N, block_n)}, {triton.cdiv(K, block_k)})"
|
| 222 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
|
| 224 |
+
BLOCK_SIZE_K = block_k
|
| 225 |
+
BLOCK_SIZE_N = block_n
|
| 226 |
C_shape = A.shape[:-1] + (N,)
|
| 227 |
C = A.new_empty(C_shape, dtype=output_dtype)
|
|
|
|
| 228 |
# Adaptive BLOCK_SIZE_M: smallest power-of-2 >= M, floored at 16, capped at 128.
|
| 229 |
# Matches the WGMMA tile to the actual row count — smaller tiles use less
|
| 230 |
# register pressure and a better-matched FP8 WGMMA instruction, improving
|
| 231 |
# both accuracy and performance for small M (decode).
|
| 232 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2(M), 16), 128)
|
| 233 |
+
grid = (triton.cdiv(M, BLOCK_SIZE_M), triton.cdiv(N, BLOCK_SIZE_N))
|
| 234 |
+
with device_context(A.device):
|
| 235 |
+
wrap_triton(w8a8_block_fp8_matmul_kernel)[grid](
|
| 236 |
+
A,
|
| 237 |
+
B,
|
| 238 |
+
C,
|
| 239 |
+
As,
|
| 240 |
+
Bs,
|
| 241 |
+
M,
|
| 242 |
+
N,
|
| 243 |
+
K,
|
| 244 |
+
A.stride(-2),
|
| 245 |
+
A.stride(-1),
|
| 246 |
+
B.stride(1),
|
| 247 |
+
B.stride(0),
|
| 248 |
+
C.stride(-2),
|
| 249 |
+
C.stride(-1),
|
| 250 |
+
As.stride(-2),
|
| 251 |
+
As.stride(-1),
|
| 252 |
+
Bs.stride(1),
|
| 253 |
+
Bs.stride(0),
|
| 254 |
+
# Meta-parameters
|
| 255 |
+
BLOCK_SIZE_M=BLOCK_SIZE_M,
|
| 256 |
+
BLOCK_SIZE_N=BLOCK_SIZE_N,
|
| 257 |
+
BLOCK_SIZE_K=BLOCK_SIZE_K,
|
| 258 |
+
GROUP_SIZE_M=8,
|
| 259 |
+
)
|
|
|
|
|
|
|
|
|
|
| 260 |
|
| 261 |
return C
|
| 262 |
|
|
|
|
| 267 |
B: torch.Tensor,
|
| 268 |
As: torch.Tensor,
|
| 269 |
Bs: torch.Tensor,
|
|
|
|
| 270 |
output_dtype: torch.dtype = torch.float32,
|
| 271 |
) -> torch.Tensor:
|
| 272 |
+
"""Tensor-scale FP8 matmul: C = A @ B.T with per-row / per-tensor scales.
|
| 273 |
|
| 274 |
+
As: scalar, (M,), or (M, 1) — per-row activation scales
|
| 275 |
+
Bs: scalar, (1,), or (1, 1) — single weight scale
|
|
|
|
|
|
|
| 276 |
"""
|
| 277 |
+
assert A.shape[-1] == B.shape[-1], (
|
| 278 |
+
f"K mismatch: A has K={A.shape[-1]}, B has K={B.shape[-1]}"
|
| 279 |
+
)
|
| 280 |
+
assert A.is_contiguous(), "A must be contiguous"
|
| 281 |
+
assert B.ndim == 2, f"B must be 2D (N, K), got ndim={B.ndim}"
|
| 282 |
+
assert B.is_contiguous(), "B must be contiguous"
|
| 283 |
|
| 284 |
N, K = B.shape
|
| 285 |
M = A.numel() // A.shape[-1]
|
| 286 |
|
| 287 |
+
# Normalize As to (M,)
|
|
|
|
|
|
|
| 288 |
if As.numel() == 1:
|
| 289 |
As = As.reshape(1).expand(M).contiguous()
|
| 290 |
+
elif As.ndim == 2:
|
| 291 |
+
As = As.reshape(M)
|
| 292 |
+
assert As.ndim == 1 and As.shape[0] == M, (
|
| 293 |
+
f"As must be scalar, (M,), or (M,1) with M={M}, got {tuple(As.shape)}"
|
| 294 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 295 |
|
| 296 |
+
# Normalize Bs to (1,)
|
| 297 |
+
assert Bs.numel() == 1, f"Bs must be scalar or (1,), got {tuple(Bs.shape)}"
|
| 298 |
+
Bs = Bs.reshape(1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
|
| 300 |
+
BLOCK_SIZE_N = 128
|
| 301 |
+
BLOCK_SIZE_K = 128
|
| 302 |
C_shape = A.shape[:-1] + (N,)
|
| 303 |
C = A.new_empty(C_shape, dtype=output_dtype)
|
|
|
|
| 304 |
BLOCK_SIZE_M = min(max(triton.next_power_of_2(M), 16), 128)
|
| 305 |
+
grid = (triton.cdiv(M, BLOCK_SIZE_M), triton.cdiv(N, BLOCK_SIZE_N))
|
| 306 |
+
with device_context(A.device):
|
| 307 |
+
wrap_triton(w8a8_tensor_fp8_matmul_kernel)[grid](
|
| 308 |
+
A,
|
| 309 |
+
B,
|
| 310 |
+
C,
|
| 311 |
+
As,
|
| 312 |
+
Bs,
|
| 313 |
+
M,
|
| 314 |
+
N,
|
| 315 |
+
K,
|
| 316 |
+
A.stride(-2),
|
| 317 |
+
A.stride(-1),
|
| 318 |
+
B.stride(1),
|
| 319 |
+
B.stride(0),
|
| 320 |
+
C.stride(-2),
|
| 321 |
+
C.stride(-1),
|
| 322 |
+
As.stride(0),
|
| 323 |
+
# Meta-parameters
|
| 324 |
+
BLOCK_SIZE_M=BLOCK_SIZE_M,
|
| 325 |
+
BLOCK_SIZE_N=BLOCK_SIZE_N,
|
| 326 |
+
BLOCK_SIZE_K=BLOCK_SIZE_K,
|
| 327 |
+
GROUP_SIZE_M=8,
|
| 328 |
+
)
|
|
|
|
| 329 |
|
| 330 |
return C
|
| 331 |
|
|
|
|
| 335 |
B: torch.Tensor,
|
| 336 |
As: torch.Tensor,
|
| 337 |
Bs: torch.Tensor,
|
| 338 |
+
block_size: list[int],
|
| 339 |
output_dtype: torch.dtype = torch.float32,
|
| 340 |
) -> torch.Tensor:
|
| 341 |
"""Block-wise W8A8 FP8 matrix multiplication.
|
|
|
|
| 365 |
B: torch.Tensor,
|
| 366 |
As: torch.Tensor,
|
| 367 |
Bs: torch.Tensor,
|
|
|
|
| 368 |
output_dtype: torch.dtype = torch.float32,
|
| 369 |
) -> torch.Tensor:
|
| 370 |
"""Tensor-scale W8A8 FP8 matrix multiplication.
|
|
|
|
| 375 |
Args:
|
| 376 |
A: Quantized activation tensor ``[M, K]`` in ``float8_e4m3fn``.
|
| 377 |
B: Quantized weight tensor ``[N, K]`` in ``float8_e4m3fn``.
|
| 378 |
+
As: Per-row activation scales ``[M]``.
|
| 379 |
+
Bs: Single weight scale, scalar or ``[1]``.
|
|
|
|
| 380 |
output_dtype: dtype of the returned tensor.
|
| 381 |
|
| 382 |
Returns:
|
| 383 |
Output tensor ``[M, N]`` in ``output_dtype``.
|
| 384 |
"""
|
| 385 |
+
return torch.ops.finegrained_fp8.w8a8_tensor_fp8_matmul(A, B, As, Bs, output_dtype)
|
|
|
|
|
|
|
| 386 |
|
| 387 |
|
| 388 |
def w8a8_fp8_matmul(
|
|
|
|
| 406 |
if block_size is None or (
|
| 407 |
block_size[0] == B.size(0) and block_size[1] == B.size(1)
|
| 408 |
):
|
| 409 |
+
return w8a8_tensor_fp8_matmul(A, B, As, Bs, output_dtype)
|
| 410 |
|
| 411 |
return w8a8_block_fp8_matmul(A, B, As, Bs, block_size, output_dtype)
|
build/torch-xpu/utils.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from contextlib import contextmanager
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
@contextmanager
|
| 6 |
+
def device_context(device: torch.device):
|
| 7 |
+
"""Context manager that sets the active device for any backend (cuda, xpu, etc.)."""
|
| 8 |
+
backend = getattr(torch, device.type, None)
|
| 9 |
+
if backend is not None and hasattr(backend, "device"):
|
| 10 |
+
with backend.device(device):
|
| 11 |
+
yield
|
| 12 |
+
else:
|
| 13 |
+
yield
|