Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions aiter/ops/opus/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,24 @@ def gemm_a16w16_opus(
)


def gemm_a8w8_blockscale_bpreshuffle_opus(
XQ: Tensor,
WQ: Tensor,
x_scale: Tensor,
w_scale: Tensor,
dtype: torch.dtype = torch.bfloat16,
*,
kernelId: int | None = None,
out: Tensor | None = None,
) -> Tensor:
"""Run the gfx950 MXFP8 NN / TT / TN blockscale GEMM (kid picked by shape)."""
from .gemm_op_a8w8 import gemm_a8w8_blockscale_bpreshuffle_opus as _impl

return _impl(XQ, WQ, x_scale, w_scale, dtype, kernelId=kernelId, out=out)


__all__ = [
"gemm_a8w8_blockscale_bpreshuffle_opus",
"gemm_a16w16_opus",
"opus_bmm",
"opus_gemm",
Expand Down
115 changes: 115 additions & 0 deletions aiter/ops/opus/gemm_op_a8w8.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,13 @@
# make it add a dummy CUDA Tensor to every raw launch, which is observable host
# overhead on short BMM kernels.

import re

import torch
from torch import Tensor

from csrc.opus_gemm.opus_gemm_common import (
MXFP8_DIRECTION_PATTERN,
a8w8_mxscale_bpreshuffle_supports_shape,
bpreshuffle_workspace_bytes,
get_registry,
Expand Down Expand Up @@ -397,6 +400,117 @@ def _launch_a8w8_blockscale_bpreshuffle_gemm(
return Y


# ---- MXFP8 NN / TT / TN (gfx950 CO kids) ------------------------------------


def _mxfp8_direction(XQ: Tensor, WQ: Tensor) -> str | None:
"""Storage of logical XQ [M, K] / WQ [N, K] as the kernel names spell it.

First letter A, second B. A "N" is stored [M, K] (strides (K, 1)), A "T"
[K, M] (strides (1, M)); B "T" is stored [N, K] (strides (K, 1)), B "N"
[K, N] (strides (1, N)). Returns "NN", "TT", "TN", "NT" or None.
"""
(M, K), N = XQ.shape, WQ.shape[0]
if XQ.stride() == (K, 1):
a = "N"
elif XQ.stride() == (1, M):
a = "T"
else:
return None
if WQ.stride() == (K, 1):
b = "T"
elif WQ.stride() == (1, N):
b = "N"
else:
return None
return a + b


def _select_mxfp8_direction_kid(
direction: str, M: int, N: int, K: int, arch: str, cu_num: int
) -> int | None:
"""Pick a supported NN / TT / TN kid for the shape.

256x128 tiles for N not a multiple of 256 or up to 2048 x 2048 outputs
(more tiles to fill the CUs), else 256x256; GroupM 16 from M = 16384;
PadM only when M is not a multiple of 256.
"""
want_bn = 256 if N % 256 == 0 and M * N > 2048 * 2048 else 128
want_group_m = 16 if M >= 16384 else 0
best = None
for kid, instance in get_registry(_A8W8_BPRESHUFFLE_FAMILY, arch, cu_num).items():
match = MXFP8_DIRECTION_PATTERN.search(instance.name)
if match is None or match[1].upper() != direction:
continue
if not a8w8_mxscale_bpreshuffle_supports_shape(instance, M, N, K):
continue
group_m = re.search(r"_gm(\d+)", instance.name)
rank = (
instance.B_N != want_bn,
(int(group_m[1]) if group_m else 0) != want_group_m,
instance.m_align != instance.B_M,
kid,
)
if best is None or rank < best[0]:
best = (rank, kid)
return None if best is None else best[1]


def gemm_a8w8_blockscale_bpreshuffle_opus(
XQ: Tensor,
WQ: Tensor,
x_scale: Tensor,
w_scale: Tensor,
dtype: torch.dtype = torch.bfloat16,
*,
kernelId: int | None = None,
out: Tensor | None = None,
) -> Tensor:
"""gfx950 MXFP8 1x128 blockscale GEMM for NN / TT / TN operand storage.

Computes Y[M, N] = XQ[M, K] @ WQ[N, K]^T on logical shapes; the storage is
read from the strides (see ``_mxfp8_direction``), so pass the transposed
view of a [K, M] A or of a [K, N] B, never a copy. WQ is the
``shuffle_weight(layout=(16, 16))`` of its own storage. x_scale is the
E8M0 [M, K/128] scale with column-major bytes; w_scale the E8M0
[N/128, K/128] scale stored like WQ ([N/128, K/128] for B "T",
[K/128, N/128] for B "N"). Output is BF16.

``kernelId`` runs that kid (56-85); otherwise one is picked by shape.
NT operands belong to ``gemm_a8w8_blockscale_bpreshuffle``.
"""
if XQ.dim() != 2 or WQ.dim() != 2:
raise ValueError("gemm_a8w8_blockscale_bpreshuffle_opus expects 2D XQ / WQ")
if dtype != torch.bfloat16:
raise ValueError("gemm_a8w8_blockscale_bpreshuffle_opus writes BF16 only")
direction = _mxfp8_direction(XQ, WQ)
if direction is None or direction == "NT":
raise ValueError(
f"gemm_a8w8_blockscale_bpreshuffle_opus serves NN / TT / TN storage; got "
f"XQ strides {tuple(XQ.stride())}, WQ strides {tuple(WQ.stride())}"
+ (" (NT: use gemm_a8w8_blockscale_bpreshuffle)" if direction else "")
)
M, K = map(int, XQ.shape)
N = int(WQ.shape[0])
if out is None:
out = torch.empty((M, N), dtype=dtype, device=XQ.device)
elif tuple(out.shape) != (M, N) or out.dtype != dtype:
raise ValueError(
f"out must be {dtype} [{M}, {N}], got {out.dtype} {tuple(out.shape)}"
)
if kernelId is None:
arch, cu_num = _device_arch_and_cu(XQ.device)
kernelId = _select_mxfp8_direction_kid(direction, M, N, K, arch, cu_num)
if kernelId is None:
raise ValueError(
f"no {direction} MXFP8 kernel supports M={M}, N={N}, K={K} on {arch} "
"(M % 16, N % 128 and K % 128 must be 0)"
)
return _launch_a8w8_blockscale_bpreshuffle_gemm(
XQ, WQ, x_scale, w_scale, out, kid=int(kernelId)
)


def _validate_a8w8_mxscale_bmm_tensors(
XQ: Tensor,
WQ: Tensor,
Expand Down Expand Up @@ -779,5 +893,6 @@ def _mxscale_bmm_workspace(
__all__ = [
"bmm_a8w8_mxscale_opus",
"bmm_a8w8_mxscale_opus_bpreshuffle",
"gemm_a8w8_blockscale_bpreshuffle_opus",
"opus_gemm_a8w8_blockscale_bpreshuffle_tune",
]
53 changes: 43 additions & 10 deletions csrc/opus_gemm/codegen/gen_instances_gfx950.py
Original file line number Diff line number Diff line change
Expand Up @@ -3191,27 +3191,57 @@ def gen_bmm_mxscale_fused_instance(
)


_BPRESHUFFLE_ARGUMENTS = r"""
def _bpreshuffle_arguments(direction="NT"):
"""Host checks / kargs of a bpreshuffle kernel for an "NT", "NN", "TT" or "TN" layout.

The first letter is A, the second B (BLAS op): A T = stored [K,M] (M-contiguous),
B T = stored [N,K] (K-contiguous), B N = stored [K,N] (N-contiguous)."""
if direction == "NT":
matrix_check = 'XQ.is_contiguous() && WQ.is_contiguous() && Y.is_contiguous(), "matrix layout differs"'
sfa_stride_check = "x_scale.stride(1) == m"
sfb_check = ' && w_scale.is_contiguous(), "scale layout differs"'
stride_a, stride_b, stride_sfb = "k", "k", "k / 128"
else:
a_strides = ("1", "m") if direction[0] == "T" else ("k", "1")
b_strides = ("k", "1") if direction[1] == "T" else ("1", "n")
sfb_strides = ("k / 128", "1") if direction[1] == "T" else ("1", "n / 128")
stride_a = "m" if direction[0] == "T" else "k"
stride_b = "k" if direction[1] == "T" else "n"
stride_sfb = "k / 128" if direction[1] == "T" else "n / 128"
matrix_check = (
'Y.is_contiguous(), "matrix shape/output layout differs");\n'
f" AITER_CHECK(XQ.stride(-2) == {a_strides[0]} && XQ.stride(-1) == {a_strides[1]} &&\n"
f" WQ.stride(-2) == {b_strides[0]} && WQ.stride(-1) == {b_strides[1]},\n"
f' "{direction} CO expects XQ strides ({a_strides[0]}, {a_strides[1]}) and WQ strides ({b_strides[0]}, {b_strides[1]}); got (",\n'
' XQ.stride(-2), ", ", XQ.stride(-1), ") and (", WQ.stride(-2), ", ", WQ.stride(-1), ")"'
)
sfa_stride_check = "(k == 128 || x_scale.stride(1) == m)"
sfb_check = (
" &&\n"
f" (n == 128 || w_scale.stride(0) == {sfb_strides[0]}) && (k == 128 || w_scale.stride(1) == {sfb_strides[1]}),\n"
f' "{direction} CO expects E8M0 scales: x_scale [M,K/128] with column-major bytes (contiguous, as per_group_quant_hip(transpose_scale=True) emits, or a strides (1,M) view), w_scale [N/128,K/128] strides ({sfb_strides[0]}, {sfb_strides[1]})"'
)
return f"""
AITER_CHECK((XQ.dim() == 2 || XQ.dim() == 3) && WQ.dim() == XQ.dim() && Y.dim() == XQ.dim() &&
(XQ.dim() == 2 || (XQ.size(0) == 1 && WQ.size(0) == 1 && Y.size(0) == 1)), "requires GEMM batch=1");
const int64_t m = XQ.size(-2), n = WQ.size(-2), k = XQ.size(-1);
AITER_CHECK(m > 0 && n > 0 && k > 0 && m <= INT32_MAX && n <= INT32_MAX && k <= INT32_MAX &&
WQ.size(-1) == k && Y.size(-2) == m && Y.size(-1) == n &&
XQ.is_contiguous() && WQ.is_contiguous() && Y.is_contiguous(), "matrix layout differs");
const auto e8m0 = [](const aiter_tensor_t& tensor) {
{matrix_check});
const auto e8m0 = [](const aiter_tensor_t& tensor) {{
return tensor.dtype() == AITER_DTYPE_fp8_e8m0 || tensor.dtype() == AITER_DTYPE_u8;
};
}};
AITER_CHECK(e8m0(x_scale) && e8m0(w_scale) && x_scale.dim() == 2 && w_scale.dim() == 2 &&
x_scale.size(0) == m && x_scale.size(1) == k / 128 &&
(x_scale.is_contiguous() || (x_scale.stride(0) == 1 && x_scale.stride(1) == m)) &&
w_scale.size(0) == n / 128 && w_scale.size(1) == k / 128 && w_scale.is_contiguous(), "scale layout differs");
opus_gemm_blockscale_mxscale_bpreshuffle_kargs_gfx950 args{};
(x_scale.is_contiguous() || (x_scale.stride(0) == 1 && {sfa_stride_check})) &&
w_scale.size(0) == n / 128 && w_scale.size(1) == k / 128{sfb_check});
opus_gemm_blockscale_mxscale_bpreshuffle_kargs_gfx950 args{{}};
args.ptr_a = XQ.data_ptr(); args.ptr_b = WQ.data_ptr(); args.ptr_c = Y.data_ptr();
args.m = m; args.n = n; args.k = k; args.batch = 1;
args.stride_a = k; args.stride_b = k; args.stride_c = n;
args.stride_a = {stride_a}; args.stride_b = {stride_b}; args.stride_c = n;
args.stride_a_batch = m * k; args.stride_b_batch = n * k; args.stride_c_batch = int(uint64_t(m) * n);
args.ptr_sfa = x_scale.data_ptr(); args.ptr_sfb = w_scale.data_ptr();
args.stride_sfa = m; args.stride_sfb = k / 128;
args.stride_sfa = m; args.stride_sfb = {stride_sfb};
args.stride_sfa_batch = m * (k / 128); args.stride_sfb_batch = (n / 128) * (k / 128);
"""

Expand Down Expand Up @@ -3239,11 +3269,14 @@ def gen_mxscale_bpreshuffle_instance(
):
workspace_extra = ""
split_k = 1
direction = "NT"
if k.bpreshuffle_co is not None:
if any(row["kid_name"] == k.name for row in cg._host_instantiations):
return
entry = k.bpreshuffle_co
symbol = entry["symbol"]
if entry["pipeline"] in ("mxfp8_nn", "mxfp8_tt", "mxfp8_tn"):
direction = entry["pipeline"][-2:].upper()
grid_setup = f'AITER_CHECK(m % {k.m_align} == 0 && n % {k.B_N} == 0 && k % {k.B_K} == 0, "shape is unsupported by this CO");\n'
# Some COs bake shape-dependent strides into the device code. Enforce
# their manifest contract here, including for direct exact-kid callers.
Expand Down Expand Up @@ -3444,7 +3477,7 @@ def gen_mxscale_bpreshuffle_instance(
host_header=host_header,
name=k.name,
workspace_extra=workspace_extra,
arguments=_BPRESHUFFLE_ARGUMENTS,
arguments=_bpreshuffle_arguments(direction),
body=body,
)
write_if_changed(os.path.join(cg.impl_path, f"{k.name}.cuh"), source)
Expand Down
53 changes: 41 additions & 12 deletions csrc/opus_gemm/gen_co/build_co.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@
# whose .co is not on disk (so nothing downstream can register an unlaunchable
# kid), and this script exists to create exactly those files.
from opus_gemm_common import (
MXFP8_DIRECTION_PATTERN,
gfx950_co_kernels_declared,
gfx1250_4wave_co_kernels_declared,
)
Expand Down Expand Up @@ -353,18 +354,46 @@ def _check_gfx950_pin(
path,
]
).stdout
reads = {int(x) for x in re.findall(r"ds_read_b128\s+a\[(\d+):", asm)}
bm, bn, bk = entry["tile"]
wm, wn = entry["wave_layout"]
a_regs = bm // (wm * 16) * (bk // 128) * 8
if entry["pipeline"] == "pingpong_lds":
a_regs = min(bm // (wm * 16), 3) * 8
b_regs = bn // (wn * 16) * 8
for bit, first, size in ((1, 0, a_regs), (2, 64, b_regs)):
if mask & bit and not set(range(first, first + size, 4)).issubset(reads):
raise ValueError(
f"pin mask {mask}: LDS reads did not reach AGPR range {first}:{first + size}"
)
if MXFP8_DIRECTION_PATTERN.search(entry["name"]):
# NN / TT / TN pin A / B anywhere in the AGPRs, loaded by plain or TR8 reads:
# every MFMA A / B operand must be an AGPR range that an LDS read filled.
reads = {
reg
for first, last in re.findall(r"\bds_read\w*\s+a\[(\d+):(\d+)\]", asm)
for reg in range(int(first), int(last) + 1)
}
mmas = [
re.split(r",\s*", line.split("//", 1)[0].strip().split(None, 1)[1])
for line in asm.splitlines()
if "v_mfma_scale_" in line
]
if not mmas:
raise ValueError("pin A/B: no MFMA instructions")
for bit, index, operand in ((1, 1, "A"), (2, 2, "B")):
if not mask & bit:
continue
for op in mmas:
match = re.fullmatch(r"a\[(\d+):(\d+)\]", op[index])
if match is None:
raise ValueError(f"pin {operand}: MFMA operand is not in AGPRs")
first, last = map(int, match.groups())
if not set(range(first, last + 1)).issubset(reads):
raise ValueError(
f"pin {operand}: MFMA AGPRs were not loaded from LDS"
)
else:
reads = {int(x) for x in re.findall(r"ds_read_b128\s+a\[(\d+):", asm)}
bm, bn, bk = entry["tile"]
wm, wn = entry["wave_layout"]
a_regs = bm // (wm * 16) * (bk // 128) * 8
if entry["pipeline"] == "pingpong_lds":
a_regs = min(bm // (wm * 16), 3) * 8
b_regs = bn // (wn * 16) * 8
for bit, first, size in ((1, 0, a_regs), (2, 64, b_regs)):
if mask & bit and not set(range(first, first + size, 4)).issubset(reads):
raise ValueError(
f"pin mask {mask}: LDS reads did not reach AGPR range {first}:{first + size}"
)
if mask & 4:
mmas = [
line.split("//", 1)[0].strip().split(None, 1)[1].split(", ")
Expand Down
Loading
Loading