Add more GPU architectures support (#112)
* Add more GPU architectures support * Update layout.py * Optimize performance, Add SM90 support, Add 1D2D SM100 support * Add fmtlib submodule at commit 553ec11 --------- Co-authored-by: fzyzcjy <5236035+fzyzcjy@users.noreply.github.com>
This commit is contained in:
212
tests/generators.py
Normal file
212
tests/generators.py
Normal file
@@ -0,0 +1,212 @@
|
||||
import enum
|
||||
import random
|
||||
import torch
|
||||
from typing import Generator, Tuple, List
|
||||
|
||||
from deep_gemm.utils import (
|
||||
align, ceil_div,
|
||||
per_token_cast_to_fp8, per_channel_cast_to_fp8, per_block_cast_to_fp8,
|
||||
get_mk_alignment_for_contiguous_layout
|
||||
)
|
||||
|
||||
|
||||
class KernelType(enum.Enum):
|
||||
# For SM100 GEMMs
|
||||
Kernel1D1D = 0
|
||||
Kernel1D2D = 1
|
||||
|
||||
def is_1d1d(self):
|
||||
return self.value == 0
|
||||
|
||||
def is_1d2d(self):
|
||||
return self.value == 1
|
||||
|
||||
|
||||
class MajorTypeAB(enum.Enum):
|
||||
KMajor = 0
|
||||
MNMajor = 1
|
||||
|
||||
def is_k_major(self):
|
||||
return self.value == 0
|
||||
|
||||
def is_mn_major(self):
|
||||
return self.value == 1
|
||||
|
||||
|
||||
def get_arch_major() -> int:
|
||||
major, minor = torch.cuda.get_device_capability()
|
||||
return major
|
||||
|
||||
|
||||
def get_ue8m0_usage(kernel_type: KernelType) -> bool:
|
||||
if get_arch_major() == 9:
|
||||
return False
|
||||
return kernel_type.is_1d1d()
|
||||
|
||||
|
||||
def get_kernel_types() -> tuple:
|
||||
return (KernelType.Kernel1D2D, ) if get_arch_major() == 9 else (KernelType.Kernel1D1D, KernelType.Kernel1D2D)
|
||||
|
||||
|
||||
def get_out_dtype() -> tuple:
|
||||
return (torch.bfloat16, ) if get_arch_major() == 9 else (torch.bfloat16, torch.float)
|
||||
|
||||
|
||||
def get_major_ab(freeze_a: bool) -> tuple:
|
||||
if get_arch_major() == 9:
|
||||
return ((MajorTypeAB.KMajor, MajorTypeAB.KMajor), )
|
||||
if freeze_a:
|
||||
return (MajorTypeAB.KMajor, MajorTypeAB.KMajor), (MajorTypeAB.KMajor, MajorTypeAB.MNMajor)
|
||||
return (MajorTypeAB.KMajor, MajorTypeAB.KMajor), (MajorTypeAB.KMajor, MajorTypeAB.MNMajor), \
|
||||
(MajorTypeAB.MNMajor, MajorTypeAB.KMajor), (MajorTypeAB.MNMajor, MajorTypeAB.MNMajor)
|
||||
|
||||
|
||||
def enumerate_normal() -> Generator:
|
||||
for kernel_type in get_kernel_types():
|
||||
for m in (128, 4096):
|
||||
for n, k in [(2112, 7168), (24576, 1536), (32768, 512), (7168, 16384), (4096, 7168), (7168, 2048)]:
|
||||
for major_a, major_b in get_major_ab(False):
|
||||
for out_dtype in get_out_dtype():
|
||||
for accumulate in (False, ) if out_dtype == torch.bfloat16 or kernel_type.is_1d2d() else (False, True):
|
||||
yield kernel_type, m, n, k, major_a, major_b, accumulate, out_dtype
|
||||
|
||||
|
||||
def enumerate_m_grouped_contiguous() -> Generator:
|
||||
for kernel_type in get_kernel_types():
|
||||
for num_groups, expected_m_per_group, n, k in ((4, 8192, 4096, 7168), (4, 8192, 7168, 2048), (8, 4096, 4096, 7168), (8, 4096, 7168, 2048)):
|
||||
for major_a, major_b in get_major_ab(True):
|
||||
yield kernel_type, num_groups, expected_m_per_group, n, k, major_a, major_b
|
||||
|
||||
|
||||
def enumerate_m_grouped_masked() -> Generator:
|
||||
max_m = 4096
|
||||
for kernel_type in get_kernel_types():
|
||||
for num_groups, m in ((1, 1024), (2, 512), (4, 256)):
|
||||
for n, k in ((4096, 7168), (7168, 2048), ):
|
||||
yield kernel_type, num_groups, max_m, m, n, k
|
||||
|
||||
|
||||
def enumerate_k_grouped_contiguous():
|
||||
# TODO: support SM90 kernels
|
||||
if get_arch_major() == 9:
|
||||
return []
|
||||
|
||||
# Must with FP32 accumulation and 1D1D kernels
|
||||
for num_groups, m, n, expected_k_per_group in (( 4, 4096, 7168, 8192), ( 4, 7168, 2048, 8192), # EP64
|
||||
( 8, 4096, 7168, 4096), ( 8, 7168, 2048, 4096), # EP32
|
||||
(16, 4096, 7168, 2048), (16, 7168, 2048, 2048)): # EP16
|
||||
ks = [align(int(expected_k_per_group * random.uniform(0.7, 1.3)), get_mk_alignment_for_contiguous_layout()) for _ in range(num_groups)]
|
||||
yield num_groups, m, n, ks, expected_k_per_group
|
||||
|
||||
|
||||
def enumerate_sf_layout():
|
||||
for with_transpose in (True, False):
|
||||
for mn in (4096, 4097, 8192):
|
||||
for k in (128, 7168, 7296):
|
||||
for num_groups in (1, 2, 4) if with_transpose else (1, ):
|
||||
if num_groups > 1 and (mn * ceil_div(k, 128)) % 4 != 0:
|
||||
continue
|
||||
if not with_transpose and mn % 4 != 0:
|
||||
continue
|
||||
yield mn, k, with_transpose, num_groups
|
||||
|
||||
|
||||
def enumerate_k_grouped_sf_layout():
|
||||
alignment = get_mk_alignment_for_contiguous_layout()
|
||||
assert alignment % 128 == 0
|
||||
for mn in (4096, 7168):
|
||||
for num_groups, avg_k in ((16, 2048), (8, 4096), (72, 384), (128, 256)):
|
||||
ks = [align(int(random.uniform(0.7, 1.3) * avg_k), alignment) for _ in range(num_groups)]
|
||||
yield mn, ks, num_groups
|
||||
|
||||
|
||||
def generate_normal(m: int, n: int, k: int,
|
||||
major_a: MajorTypeAB, major_b: MajorTypeAB,
|
||||
accumulate: bool, out_dtype: torch.dtype,
|
||||
use_ue8m0: bool):
|
||||
a = torch.randn((m, k), device='cuda', dtype=torch.bfloat16)
|
||||
b = torch.randn((n, k), device='cuda', dtype=torch.bfloat16)
|
||||
d = torch.randn((m, n), device='cuda', dtype=out_dtype) * 32 if accumulate else \
|
||||
torch.empty((m, n), device='cuda', dtype=out_dtype)
|
||||
c = d if accumulate else None
|
||||
ref_d = (a.float() @ b.float().t() + (c if accumulate else 0)).to(out_dtype)
|
||||
|
||||
a_fp8, b_fp8 = per_token_cast_to_fp8(a, use_ue8m0=use_ue8m0), per_block_cast_to_fp8(b, use_ue8m0=use_ue8m0)
|
||||
a_fp8 = a_fp8 if major_a.is_k_major() else (a_fp8[0].T.contiguous().T, a_fp8[1])
|
||||
b_fp8 = b_fp8 if major_b.is_k_major() else (b_fp8[0].T.contiguous().T, b_fp8[1])
|
||||
return a_fp8, b_fp8, c, d, ref_d
|
||||
|
||||
|
||||
def generate_m_grouped_contiguous(num_groups: int, expected_m_per_group: int, n: int, k: int,
|
||||
major_a: MajorTypeAB, major_b: MajorTypeAB, use_ue8m0: bool) -> \
|
||||
Tuple[int, Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor, torch.Tensor], torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
actual_ms = [int(expected_m_per_group * random.uniform(0.7, 1.3)) for _ in range(num_groups)]
|
||||
aligned_ms = [align(actual_m, get_mk_alignment_for_contiguous_layout()) for actual_m in actual_ms]
|
||||
m = sum(aligned_ms)
|
||||
|
||||
a = torch.randn((m, k), device='cuda', dtype=torch.bfloat16)
|
||||
b = torch.randn((num_groups, n, k), device='cuda', dtype=torch.bfloat16)
|
||||
m_indices = torch.empty(m, device='cuda', dtype=torch.int32)
|
||||
d = torch.empty((m, n), device='cuda', dtype=torch.bfloat16)
|
||||
ref_d = torch.randn((m, n), device='cuda', dtype=torch.bfloat16)
|
||||
|
||||
start = 0
|
||||
for i, (actual_m, aligned_m) in enumerate(zip(actual_ms, aligned_ms)):
|
||||
actual_end = start + actual_m
|
||||
aligned_end = start + aligned_m
|
||||
m_indices[start:actual_end] = i
|
||||
m_indices[actual_end:aligned_end] = -1
|
||||
ref_d[start:aligned_end] = a[start:aligned_end] @ b[i].t()
|
||||
start = aligned_end
|
||||
ref_d = torch.where((m_indices == -1).unsqueeze(1), torch.zeros_like(ref_d), ref_d)
|
||||
|
||||
assert major_a.is_k_major()
|
||||
a_fp8 = per_token_cast_to_fp8(a, use_ue8m0=use_ue8m0)
|
||||
b_fp8 = (torch.empty_like(b, dtype=torch.float8_e4m3fn),
|
||||
torch.empty((num_groups, ceil_div(n, 128), ceil_div(k, 128)), device='cuda', dtype=torch.float))
|
||||
for i in range(num_groups):
|
||||
b_fp8[0][i], b_fp8[1][i] = per_block_cast_to_fp8(b[i], use_ue8m0=use_ue8m0)
|
||||
b_fp8 = b_fp8 if major_b.is_k_major() else (b_fp8[0].mT.contiguous().mT, b_fp8[1])
|
||||
return m, a_fp8, b_fp8, m_indices, d, ref_d
|
||||
|
||||
|
||||
def generate_m_grouped_masked(num_groups: int, max_m: int, expected_m_per_group: int, n: int, k: int, use_ue8m0: bool) -> \
|
||||
Tuple[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor, torch.Tensor], torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
a = torch.randn((num_groups, max_m, k), device='cuda', dtype=torch.bfloat16)
|
||||
b = torch.randn((num_groups, n, k), device='cuda', dtype=torch.bfloat16)
|
||||
d = torch.empty((num_groups, max_m, n), device='cuda', dtype=torch.bfloat16)
|
||||
ref_d = torch.einsum('gmk,gnk->gmn', a, b)
|
||||
|
||||
a_fp8 = (torch.empty_like(a, dtype=torch.float8_e4m3fn), torch.empty((num_groups, max_m, ceil_div(k, 128)), device='cuda', dtype=torch.float))
|
||||
b_fp8 = (torch.empty_like(b, dtype=torch.float8_e4m3fn), torch.empty((num_groups, ceil_div(n, 128), ceil_div(k, 128)), device='cuda', dtype=torch.float))
|
||||
for i in range(num_groups):
|
||||
a_fp8[0][i], a_fp8[1][i] = per_token_cast_to_fp8(a[i], use_ue8m0=use_ue8m0)
|
||||
b_fp8[0][i], b_fp8[1][i] = per_block_cast_to_fp8(b[i], use_ue8m0=use_ue8m0)
|
||||
|
||||
masked_m = torch.empty((num_groups, ), device='cuda', dtype=torch.int)
|
||||
for j in range(num_groups):
|
||||
masked_m[j] = int(expected_m_per_group * random.uniform(0.7, 1.3))
|
||||
assert masked_m.amax().item() <= max_m
|
||||
|
||||
return a_fp8, b_fp8, masked_m, d, ref_d
|
||||
|
||||
|
||||
def generate_k_grouped_contiguous(num_groups: int, m: int, n: int, ks: List[int], use_ue8m0: bool):
|
||||
assert get_mk_alignment_for_contiguous_layout() % 128 == 0
|
||||
k = sum(ks)
|
||||
|
||||
a = torch.randn((k, m), device='cuda', dtype=torch.bfloat16)
|
||||
b = torch.randn((k, n), device='cuda', dtype=torch.bfloat16)
|
||||
c = torch.randn((num_groups, m, n), device='cuda', dtype=torch.float) * 32
|
||||
d = c
|
||||
ref_d = torch.empty_like(c)
|
||||
|
||||
start = 0
|
||||
for i, group_k in enumerate(ks):
|
||||
end = start + group_k
|
||||
ref_d[i] = c[i] + (a[start:end].T @ b[start:end])
|
||||
start = end
|
||||
|
||||
a_fp8 = per_channel_cast_to_fp8(a, use_ue8m0=use_ue8m0)
|
||||
b_fp8 = per_channel_cast_to_fp8(b, use_ue8m0=use_ue8m0)
|
||||
return k, a_fp8, b_fp8, c, d, ref_d
|
||||
@@ -1,297 +1,161 @@
|
||||
# PyTorch has its own NVRTC, which may have a lower version than the system
|
||||
# So try to disable PyTorch's NVRTC, or import NVRTC before PyTorch
|
||||
import cuda.bindings.nvrtc as nvrtc
|
||||
print(f'NVRTC version: {nvrtc.nvrtcVersion()[1:]}')
|
||||
|
||||
import copy
|
||||
import random
|
||||
import time
|
||||
import torch
|
||||
from typing import List, Tuple
|
||||
|
||||
import deep_gemm
|
||||
from deep_gemm import bench_kineto, calc_diff, ceil_div, get_col_major_tma_aligned_tensor
|
||||
from deep_gemm.jit_kernels.utils import get_m_alignment_for_contiguous_layout
|
||||
from deep_gemm.testing import (
|
||||
bench, bench_kineto,
|
||||
calc_diff, count_bytes
|
||||
)
|
||||
|
||||
|
||||
def per_token_cast_to_fp8(x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
|
||||
assert x.dim() == 2
|
||||
m, n = x.shape
|
||||
pad_size = (128 - (n % 128)) % 128
|
||||
x = torch.nn.functional.pad(x, (0, pad_size), value=0) if pad_size > 0 else x
|
||||
x_view = x.view(m, -1, 128)
|
||||
x_amax = x_view.abs().float().amax(dim=2).view(m, -1).clamp(1e-4)
|
||||
fp8_data = (x_view * (448.0 / x_amax.unsqueeze(2))).to(torch.float8_e4m3fn)
|
||||
return fp8_data.view(m, n + pad_size)[:, :n], (x_amax / 448.0).view(m, -1)
|
||||
|
||||
|
||||
def per_block_cast_to_fp8(x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
|
||||
assert x.dim() == 2
|
||||
m, n = x.shape
|
||||
x_padded = torch.zeros((ceil_div(m, 128) * 128, ceil_div(n, 128) * 128), dtype=x.dtype, device=x.device)
|
||||
x_padded[:m, :n] = x
|
||||
x_view = x_padded.view(-1, 128, x_padded.size(1) // 128, 128)
|
||||
x_amax = x_view.abs().float().amax(dim=(1, 3), keepdim=True).clamp(1e-4)
|
||||
x_scaled = (x_view * (448.0 / x_amax)).to(torch.float8_e4m3fn)
|
||||
return x_scaled.view_as(x_padded)[:m, :n].contiguous(), (x_amax / 448.0).view(x_view.size(0), x_view.size(2))
|
||||
|
||||
|
||||
def construct(m: int, k: int, n: int) -> \
|
||||
Tuple[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor, torch.Tensor], torch.Tensor, torch.Tensor]:
|
||||
x = torch.randn((m, k), device='cuda', dtype=torch.bfloat16)
|
||||
y = torch.randn((n, k), device='cuda', dtype=torch.bfloat16)
|
||||
out = torch.empty((m, n), device='cuda', dtype=torch.bfloat16)
|
||||
ref_out = x @ y.t()
|
||||
|
||||
x_fp8, y_fp8 = per_token_cast_to_fp8(x), per_block_cast_to_fp8(y)
|
||||
# Transpose earlier so that the testing will not trigger transposing kernels
|
||||
x_fp8 = (x_fp8[0], get_col_major_tma_aligned_tensor(x_fp8[1]))
|
||||
return x_fp8, y_fp8, out, ref_out
|
||||
|
||||
|
||||
def construct_contiguous_grouped(num_groups: int, expected_m_per_group: int, k: int, n: int) -> \
|
||||
Tuple[int, Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor, torch.Tensor], torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
alignment = get_m_alignment_for_contiguous_layout()
|
||||
group_ms = [int(expected_m_per_group * random.uniform(0.7, 1.3)) for _ in range(num_groups)]
|
||||
m = sum([ceil_div(x, alignment) * alignment for x in group_ms])
|
||||
|
||||
x = torch.randn((m, k), device='cuda', dtype=torch.bfloat16)
|
||||
y = torch.randn((num_groups, n, k), device='cuda', dtype=torch.bfloat16)
|
||||
m_indices = torch.empty(m, device='cuda', dtype=torch.int32)
|
||||
out = torch.empty((m, n), device='cuda', dtype=torch.bfloat16)
|
||||
ref_out = torch.randn((m, n), device='cuda', dtype=torch.bfloat16)
|
||||
|
||||
start = 0
|
||||
for i, group_m in enumerate(group_ms):
|
||||
actual_end = start + group_m
|
||||
aligned_end = start + ceil_div(group_m, alignment) * alignment
|
||||
m_indices[start:actual_end] = i
|
||||
m_indices[actual_end:aligned_end] = -1
|
||||
ref_out[start:aligned_end] = x[start:aligned_end] @ y[i].t()
|
||||
start = aligned_end
|
||||
ref_out = torch.where((m_indices == -1).unsqueeze(1), torch.zeros_like(ref_out), ref_out)
|
||||
|
||||
assert m % 4 == 0, f'TMA alignment error: {m}'
|
||||
x_fp8 = per_token_cast_to_fp8(x)
|
||||
y_fp8 = (torch.empty_like(y, dtype=torch.float8_e4m3fn), torch.empty((num_groups, ceil_div(n, 128), k // 128), device='cuda', dtype=torch.float))
|
||||
for i in range(num_groups):
|
||||
y_fp8[0][i], y_fp8[1][i] = per_block_cast_to_fp8(y[i])
|
||||
|
||||
return m, x_fp8, y_fp8, m_indices, out, ref_out
|
||||
|
||||
|
||||
def construct_masked_grouped(num_groups: int, max_m: int, expected_m_per_group: int, k: int, n: int) -> \
|
||||
Tuple[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor, torch.Tensor], torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
x = torch.randn((num_groups, max_m, k), device='cuda', dtype=torch.bfloat16)
|
||||
y = torch.randn((num_groups, n, k), device='cuda', dtype=torch.bfloat16)
|
||||
out = torch.empty((num_groups, max_m, n), device='cuda', dtype=torch.bfloat16)
|
||||
ref_out = torch.einsum('gmk,gnk->gmn', x, y)
|
||||
|
||||
assert max_m % 4 == 0, f'TMA alignment error: {max_m}'
|
||||
x_fp8 = (torch.empty_like(x, dtype=torch.float8_e4m3fn), torch.empty((num_groups, max_m, k // 128), device='cuda', dtype=torch.float))
|
||||
y_fp8 = (torch.empty_like(y, dtype=torch.float8_e4m3fn), torch.empty((num_groups, ceil_div(n, 128), k // 128), device='cuda', dtype=torch.float))
|
||||
for i in range(num_groups):
|
||||
x_fp8[0][i], x_fp8[1][i] = per_token_cast_to_fp8(x[i])
|
||||
y_fp8[0][i], y_fp8[1][i] = per_block_cast_to_fp8(y[i])
|
||||
|
||||
# Transpose earlier so that the testing will not trigger transposing kernels
|
||||
x_fp8 = (x_fp8[0], get_col_major_tma_aligned_tensor(x_fp8[1]))
|
||||
|
||||
# Construct mask
|
||||
masked_m = torch.empty((num_groups, ), device='cuda', dtype=torch.int)
|
||||
for j in range(num_groups):
|
||||
masked_m[j] = int(expected_m_per_group * random.uniform(0.7, 1.3))
|
||||
assert masked_m.amax().item() <= max_m
|
||||
return x_fp8, y_fp8, masked_m, out, ref_out
|
||||
|
||||
|
||||
def construct_wgrad(m: int, k: int, n: int) -> \
|
||||
Tuple[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor, torch.Tensor], torch.Tensor, torch.Tensor, torch.Tensor]:
|
||||
x = torch.randn((m, k), device='cuda', dtype=torch.bfloat16)
|
||||
y = torch.randn((n, k), device='cuda', dtype=torch.bfloat16)
|
||||
residual = torch.randn((m, n), device='cuda', dtype=torch.float) * 10
|
||||
out = residual.clone()
|
||||
ref_out = residual + (x.float() @ y.float().t())
|
||||
|
||||
x_fp8 = per_token_cast_to_fp8(x)
|
||||
y_fp8 = per_token_cast_to_fp8(y)
|
||||
|
||||
# NOTES: please do inplace add on the `out` later
|
||||
return x_fp8, y_fp8, residual, out, ref_out
|
||||
|
||||
|
||||
def construct_k_grouped_wgrad(m: int, n: int, k_sizes: List[int]) -> \
|
||||
Tuple[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor, torch.Tensor], torch.Tensor, torch.Tensor, List[int]]:
|
||||
num_groups, total_k = len(k_sizes), sum(k_sizes)
|
||||
|
||||
x_flat = torch.empty((m * total_k,), device='cuda', dtype=torch.bfloat16)
|
||||
y_flat = torch.empty((n * total_k,), device='cuda', dtype=torch.bfloat16)
|
||||
out = torch.zeros((num_groups, m, n), device='cuda', dtype=torch.float)
|
||||
ref_out = torch.zeros((num_groups, m, n), device='cuda', dtype=torch.float)
|
||||
|
||||
# Fill tensors with data and compute reference output
|
||||
x_offset, y_offset = 0, 0
|
||||
for idx, k in enumerate(k_sizes):
|
||||
x_chunk = torch.randn((m, k), device='cuda', dtype=torch.bfloat16)
|
||||
y_chunk = torch.randn((n, k), device='cuda', dtype=torch.bfloat16)
|
||||
|
||||
x_flat[x_offset:x_offset + m * k].copy_(x_chunk.flatten())
|
||||
y_flat[y_offset:y_offset + n * k].copy_(y_chunk.flatten())
|
||||
ref_out[idx] = x_chunk.float() @ y_chunk.float().t()
|
||||
|
||||
x_offset += m * k
|
||||
y_offset += n * k
|
||||
|
||||
x_fp8_flat = torch.empty_like(x_flat, dtype=torch.float8_e4m3fn)
|
||||
y_fp8_flat = torch.empty_like(y_flat, dtype=torch.float8_e4m3fn)
|
||||
|
||||
total_scale_factors = sum(ceil_div(k, 128) for k in k_sizes)
|
||||
x_scales = torch.empty((total_scale_factors, m), device='cuda', dtype=torch.float)
|
||||
y_scales = torch.empty((total_scale_factors, n), device='cuda', dtype=torch.float)
|
||||
|
||||
# Cast to FP8 and prepare scale factors
|
||||
x_offset, y_offset, scale_offset = 0, 0, 0
|
||||
for k in k_sizes:
|
||||
x_fp8_chunk, x_scale_chunk = per_token_cast_to_fp8(x_flat[x_offset:x_offset + m * k].view(m, k))
|
||||
y_fp8_chunk, y_scale_chunk = per_token_cast_to_fp8(y_flat[y_offset:y_offset + n * k].view(n, k))
|
||||
|
||||
x_fp8_flat[x_offset:x_offset + m * k].copy_(x_fp8_chunk.flatten())
|
||||
y_fp8_flat[y_offset:y_offset + n * k].copy_(y_fp8_chunk.flatten())
|
||||
|
||||
num_scales = ceil_div(k, 128)
|
||||
x_scales[scale_offset:scale_offset + num_scales].copy_(x_scale_chunk.T)
|
||||
y_scales[scale_offset:scale_offset + num_scales].copy_(y_scale_chunk.T)
|
||||
|
||||
x_offset += m * k
|
||||
y_offset += n * k
|
||||
scale_offset += num_scales
|
||||
|
||||
return (x_fp8_flat, x_scales), (y_fp8_flat, y_scales), out, ref_out, k_sizes
|
||||
from generators import (
|
||||
KernelType, get_ue8m0_usage,
|
||||
enumerate_normal, enumerate_m_grouped_contiguous, enumerate_m_grouped_masked, enumerate_k_grouped_contiguous,
|
||||
generate_normal, generate_m_grouped_contiguous, generate_m_grouped_masked, generate_k_grouped_contiguous
|
||||
)
|
||||
|
||||
|
||||
def test_gemm() -> None:
|
||||
print('Testing GEMM:')
|
||||
for m in (64, 128, 4096):
|
||||
for k, n in [(576, 7168), (7168, 2112), (1536, 24576), (512, 32768), (16384, 7168), (7168, 4096), (2048, 7168)]:
|
||||
x_fp8, y_fp8, out, ref_out = construct(m, k, n)
|
||||
deep_gemm.gemm_fp8_fp8_bf16_nt(x_fp8, y_fp8, out)
|
||||
diff = calc_diff(out, ref_out)
|
||||
assert diff < 0.001, f'{m=}, {k=}, {n=}, {diff:.5f}'
|
||||
for kernel_type, m, n, k, major_a, major_b, accumulate, out_dtype in enumerate_normal():
|
||||
major_opt = 'N' if major_a.is_k_major() else 'T'
|
||||
major_opt += 'T' if major_b.is_k_major() else 'N'
|
||||
out_opt = 'FP32' if out_dtype == torch.float else 'BF16'
|
||||
acc_opt = f'acc={int(accumulate)}'
|
||||
kernel_opt = f'1D1D' if kernel_type.is_1d1d() else '1D2D'
|
||||
use_ue8m0 = get_ue8m0_usage(kernel_type)
|
||||
disable_ue8m0_cast = not use_ue8m0
|
||||
|
||||
# noinspection PyShadowingNames
|
||||
def test_func():
|
||||
deep_gemm.gemm_fp8_fp8_bf16_nt(x_fp8, y_fp8, out)
|
||||
for test_alias in (False, True):
|
||||
a, b, c, d, ref_d = generate_normal(m, n, k, major_a, major_b, accumulate, out_dtype, use_ue8m0=use_ue8m0)
|
||||
func_name = f'fp8_gemm_{major_opt.lower() if test_alias else "nt"}'
|
||||
if test_alias:
|
||||
a = a if major_a.is_k_major() else (a[0].T, a[1].T)
|
||||
b = b if major_b.is_k_major() else (b[0].T, b[1].T)
|
||||
assert a[0].is_contiguous() and b[0].is_contiguous()
|
||||
getattr(deep_gemm, func_name)(a, b, d, c=c, disable_ue8m0_cast=disable_ue8m0_cast)
|
||||
diff = calc_diff(d, ref_d)
|
||||
assert diff < 0.001, (f'{m=}, {n=}, {k=}, {kernel_opt}, {major_opt=}, {accumulate=}, {out_dtype=}, '
|
||||
f'{diff:.5f}, alias={test_alias}')
|
||||
a, b, c, d, ref_d = generate_normal(m, n, k, major_a, major_b, accumulate, out_dtype, use_ue8m0=use_ue8m0)
|
||||
|
||||
t = bench_kineto(test_func, 'fp8_gemm', suppress_kineto_output=True)
|
||||
print(f' > Perf (m={m:5}, n={n:5}, k={k:5}): {t * 1e6:4.0f} us | '
|
||||
f'throughput: {2 * m * n * k / t / 1e12:4.0f} TFLOPS, '
|
||||
f'{(m * k + k * n + m * n * 2) / 1e9 / t:4.0f} GB/s')
|
||||
# Test launch overhead
|
||||
launch_start_t = time.time_ns()
|
||||
deep_gemm.fp8_gemm_nt(a, b, d, c=c, disable_ue8m0_cast=disable_ue8m0_cast)
|
||||
launch_end_t = time.time_ns()
|
||||
torch.cuda.synchronize()
|
||||
|
||||
# noinspection PyShadowingNames
|
||||
def test_func():
|
||||
deep_gemm.fp8_gemm_nt(a, b, d, c=c, disable_ue8m0_cast=disable_ue8m0_cast)
|
||||
|
||||
t = bench_kineto(test_func, 'fp8_gemm', suppress_kineto_output=True)
|
||||
print(f' > Perf (m={m:5}, n={n:5}, k={k:5}, {kernel_opt}, layout={major_opt}, {out_opt}, {acc_opt}):'
|
||||
f' launch {(launch_end_t - launch_start_t) / 1e3:4.0f} us | {t * 1e6:4.0f} us | '
|
||||
f'{2 * m * n * k / t / 1e12:4.0f} TFLOPS | '
|
||||
f'{count_bytes(a, b, c, d) / 1e9 / t:4.0f} GB/s')
|
||||
print()
|
||||
|
||||
|
||||
def test_m_grouped_gemm_contiguous() -> None:
|
||||
print('Testing grouped contiguous GEMM:')
|
||||
print('Testing m-grouped contiguous GEMM:')
|
||||
|
||||
for num_groups, expected_m_per_group, k, n in ((4, 8192, 7168, 4096), (4, 8192, 2048, 7168),
|
||||
(8, 4096, 7168, 4096), (8, 4096, 2048, 7168),
|
||||
(32, 256, 7168, 4096), (32, 256, 2048, 7168)):
|
||||
# NOTES: we should mask the unfilled part before calculating difference
|
||||
m, x_fp8, y_fp8, m_indices, out, ref_out = construct_contiguous_grouped(num_groups, expected_m_per_group, k, n)
|
||||
deep_gemm.m_grouped_gemm_fp8_fp8_bf16_nt_contiguous(x_fp8, y_fp8, out, m_indices)
|
||||
out = torch.where((m_indices == -1).unsqueeze(1), torch.zeros_like(out), out)
|
||||
diff = calc_diff(out, ref_out)
|
||||
assert diff < 0.001, f'{m=}, {k=}, {n=}, {diff:.5f}'
|
||||
for kernel_type, num_groups, expected_m_per_group, n, k, major_a, major_b in enumerate_m_grouped_contiguous():
|
||||
major_opt = 'N' if major_a.is_k_major() else 'T'
|
||||
major_opt += 'T' if major_b.is_k_major() else 'N'
|
||||
kernel_opt = f'1D1D' if kernel_type.is_1d1d() else '1D2D'
|
||||
use_ue8m0 = get_ue8m0_usage(kernel_type)
|
||||
disable_ue8m0_cast = not use_ue8m0
|
||||
|
||||
for test_alias in (False, True):
|
||||
m, a, b, m_indices, d, ref_d = generate_m_grouped_contiguous(num_groups, expected_m_per_group, n, k, major_a, major_b, use_ue8m0=use_ue8m0)
|
||||
func_name = f"m_grouped_fp8_gemm_{(major_opt.lower() if test_alias else 'nt')}_contiguous"
|
||||
if test_alias:
|
||||
assert major_a.is_k_major()
|
||||
b = b if major_b.is_k_major() else (b[0].mT, b[1].mT)
|
||||
assert a[0].is_contiguous() and b[0].is_contiguous()
|
||||
getattr(deep_gemm, func_name)(a, b, d, m_indices, disable_ue8m0_cast=disable_ue8m0_cast)
|
||||
d = torch.where((m_indices == -1).unsqueeze(1), torch.zeros_like(d), d)
|
||||
diff = calc_diff(d, ref_d)
|
||||
assert diff < 0.001, f'{m=}, {n=}, {k=}, {major_opt}, {kernel_opt}, {diff:.5f}, alias={test_alias}'
|
||||
m, a, b, m_indices, d, ref_d = generate_m_grouped_contiguous(num_groups, expected_m_per_group, n, k, major_a, major_b, use_ue8m0=use_ue8m0)
|
||||
|
||||
# noinspection PyShadowingNames
|
||||
def test_func():
|
||||
deep_gemm.m_grouped_gemm_fp8_fp8_bf16_nt_contiguous(x_fp8, y_fp8, out, m_indices)
|
||||
deep_gemm.m_grouped_fp8_gemm_nt_contiguous(a, b, d, m_indices, disable_ue8m0_cast=disable_ue8m0_cast)
|
||||
|
||||
t = bench_kineto(test_func, 'fp8_gemm', suppress_kineto_output=True)
|
||||
valid_m = (m_indices != -1).sum().item()
|
||||
print(f' > Perf ({num_groups=:2}, {expected_m_per_group=:4}, n={n:4}, k={k:4}): {t * 1e6:4.0f} us | '
|
||||
f'throughput: {2 * valid_m * n * k / t / 1e12:4.0f} TFLOPS, '
|
||||
f'{(valid_m * k + num_groups * k * n + valid_m * n * 2) / 1e9 / t:4.0f} GB/s')
|
||||
print(f' > Perf ({num_groups=}, m={m:5}, n={n:5}, k={k:5}, {kernel_opt}, layout={major_opt}): '
|
||||
f'{t * 1e6:4.0f} us | '
|
||||
f'{2 * m * n * k / t / 1e12:4.0f} TFLOPS | '
|
||||
f'{count_bytes(a, b, d) / 1e9 / t:4.0f} GB/s')
|
||||
print()
|
||||
|
||||
|
||||
def test_m_grouped_gemm_masked() -> None:
|
||||
print('Testing grouped masked GEMM:')
|
||||
print('Testing m-grouped masked GEMM:')
|
||||
|
||||
for num_groups, expected_m_per_group in ((1, 1024), (2, 512), (4, 256)):
|
||||
for k, n in ((7168, 4096), (2048, 7168), ):
|
||||
# Test correctness
|
||||
for i in range(10):
|
||||
x_fp8, y_fp8, masked_m, out, ref_out = construct_masked_grouped(num_groups, 4096, expected_m_per_group, k, n)
|
||||
deep_gemm.m_grouped_gemm_fp8_fp8_bf16_nt_masked(x_fp8, y_fp8, out, masked_m, expected_m_per_group)
|
||||
for j in range(num_groups):
|
||||
diff = calc_diff(out[j, :masked_m[j].item()], ref_out[j, :masked_m[j].item()])
|
||||
assert diff < 0.001, f'{expected_m_per_group=}, {k=}, {n=}, {j=}, masked_m={masked_m[j]}, {num_groups=}, {diff:.5f}'
|
||||
# TODO: when the actual `m` is greater than `expected_m_per_group`, efficiency may significantly decrease.
|
||||
for kernel_type, num_groups, max_m, expected_m_per_group, n, k in enumerate_m_grouped_masked():
|
||||
kernel_opt = f'1D1D' if kernel_type.is_1d1d() else '1D2D'
|
||||
use_ue8m0 = get_ue8m0_usage(kernel_type)
|
||||
disable_ue8m0_cast = not use_ue8m0
|
||||
|
||||
# noinspection PyShadowingNames
|
||||
def test_func():
|
||||
deep_gemm.m_grouped_gemm_fp8_fp8_bf16_nt_masked(x_fp8, y_fp8, out, masked_m, expected_m_per_group)
|
||||
# Test correctness
|
||||
for i in range(10):
|
||||
a, b, masked_m, d, ref_d = generate_m_grouped_masked(num_groups, max_m, expected_m_per_group, n, k, use_ue8m0=use_ue8m0)
|
||||
deep_gemm.fp8_m_grouped_gemm_nt_masked(a, b, d, masked_m, expected_m_per_group, disable_ue8m0_cast=disable_ue8m0_cast)
|
||||
for j in range(num_groups):
|
||||
diff = calc_diff(d[j, :masked_m[j].item()], ref_d[j, :masked_m[j].item()])
|
||||
assert diff < 0.001, f'{m=}, {n=}, {k=}, {j=}, masked_m={masked_m[j]}, {kernel_opt}, {num_groups=}, {diff:.5f}'
|
||||
|
||||
# Test performance with fixed shapes
|
||||
# noinspection PyUnboundLocalVariable
|
||||
valid_m = masked_m.sum().item()
|
||||
t = bench_kineto(test_func, 'fp8_gemm', suppress_kineto_output=True)
|
||||
print(f' > Perf ({num_groups=}, expected_m_per_group={expected_m_per_group:4}, n={n:4}, k={k:4}): {t * 1e6:4.0f} us | '
|
||||
f'throughput: {2 * valid_m * n * k / t / 1e12:4.0f} TFLOPS, '
|
||||
f'{(valid_m * k + num_groups * k * n + valid_m * n * 2) / 1e9 / t:4.0f} GB/s')
|
||||
# Construct full cases
|
||||
a, b, masked_m, d, ref_d = generate_m_grouped_masked(num_groups, max_m, expected_m_per_group, n, k, use_ue8m0=use_ue8m0)
|
||||
|
||||
# noinspection PyShadowingNames
|
||||
def test_func():
|
||||
deep_gemm.fp8_m_grouped_gemm_nt_masked(a, b, d, masked_m, expected_m_per_group, disable_ue8m0_cast=disable_ue8m0_cast)
|
||||
|
||||
# Test performance with fixed shapes
|
||||
valid_m = masked_m.sum().item()
|
||||
t = bench_kineto(test_func, 'fp8_gemm', suppress_kineto_output=True)
|
||||
print(f' > Perf ({num_groups=}, expected_m_per_group={expected_m_per_group:4}, n={n:4}, k={k:4}, {kernel_opt}): '
|
||||
f'{t * 1e6:4.0f} us | '
|
||||
f'{2 * valid_m * n * k / t / 1e12:4.0f} TFLOPS | '
|
||||
f'{(count_bytes(a, d) * valid_m / (max_m * num_groups) + count_bytes(b)) / 1e9 / t:4.0f} GB/s')
|
||||
print()
|
||||
|
||||
|
||||
def test_wgrad_gemm():
|
||||
print('Testing weight gradient GEMM:')
|
||||
def test_k_grouped_gemm_contiguous() -> None:
|
||||
print('Testing k-grouped contiguous GEMM:')
|
||||
|
||||
for k in (4096, 8192):
|
||||
for m, n in ((7168, 2112), (1536, 24576), (512, 32768), (16384, 7168), (7168, 4096), (2048, 7168)):
|
||||
# Test correctness
|
||||
x_fp8, y_fp8, residual, out, ref_out = construct_wgrad(m, k, n)
|
||||
deep_gemm.wgrad_gemm_fp8_fp8_fp32_nt(x_fp8, y_fp8, out)
|
||||
diff = calc_diff(out, ref_out)
|
||||
assert diff < 0.001, f'{m=}, {k=}, {n=}, {diff:.5f}'
|
||||
for num_groups, m, n, ks, expected_k_per_group in enumerate_k_grouped_contiguous():
|
||||
use_ue8m0 = get_ue8m0_usage(KernelType.Kernel1D1D)
|
||||
|
||||
# Construct new tensors only once to avoid L2 cache acceleration (creating them puts them in L2)
|
||||
x_fp8, y_fp8, residual, out, ref_out = construct_wgrad(m, k, n)
|
||||
for test_empty_groups in (False, True):
|
||||
new_ks = copy.deepcopy(ks)
|
||||
if test_empty_groups:
|
||||
new_ks[random.randint(0, num_groups - 1)] = 0
|
||||
k, a, b, c, d, ref_d = generate_k_grouped_contiguous(num_groups, m, n, new_ks, use_ue8m0=use_ue8m0)
|
||||
new_ks_tensor = torch.tensor(new_ks, dtype=torch.int, device='cuda')
|
||||
deep_gemm.k_grouped_fp8_gemm_tn_contiguous(a, b, d, new_ks, new_ks_tensor, c=c)
|
||||
diff = calc_diff(d, ref_d)
|
||||
assert diff < 0.001, f'{m=}, {n=}, {k=}, {i=}, {diff:.5f}'
|
||||
|
||||
# noinspection PyShadowingNames
|
||||
def test_func():
|
||||
deep_gemm.wgrad_gemm_fp8_fp8_fp32_nt(x_fp8, y_fp8, out)
|
||||
# Test performance
|
||||
k, a, b, c, d, ref_d = generate_k_grouped_contiguous(num_groups, m, n, ks, use_ue8m0=use_ue8m0)
|
||||
ks_tensor = torch.tensor(ks, dtype=torch.int, device='cuda')
|
||||
|
||||
t = bench_kineto(test_func, 'fp8_wgrad_gemm', suppress_kineto_output=True)
|
||||
print(f' > Performance (m={m:5}, n={n:5}, k={k:5}): {t * 1e6:4.0f} us | '
|
||||
f'throughput: {2 * m * n * k / t / 1e12:4.0f} TFLOPS, '
|
||||
f'{(m * k + k * n + m * n * 2) / 1e9 / t:4.0f} GB/s')
|
||||
print()
|
||||
# noinspection PyShadowingNames
|
||||
def test_func():
|
||||
deep_gemm.k_grouped_fp8_gemm_tn_contiguous(a, b, d, ks, ks_tensor, c=c)
|
||||
|
||||
|
||||
def test_k_grouped_wgrad_gemm():
|
||||
print('Testing grouped weight gradient GEMM:')
|
||||
|
||||
for num_groups, base_k in ((4, 4096), (4, 8192), (8, 4096)):
|
||||
for m, n in ((7168, 4096), (2048, 7168)):
|
||||
# Vary k sizes around base_k
|
||||
k_sizes = [base_k + random.randint(-1, 1) * 128 for _ in range(num_groups - 1)]
|
||||
k_sizes.append(base_k * num_groups - sum(k_sizes))
|
||||
|
||||
# Test correctness
|
||||
x_fp8, y_fp8, out, ref_out, k_sizes = construct_k_grouped_wgrad(m, n, k_sizes)
|
||||
deep_gemm.k_grouped_wgrad_gemm_fp8_fp8_fp32_nt(x_fp8, y_fp8, out, k_sizes)
|
||||
|
||||
for idx in range(num_groups):
|
||||
diff = calc_diff(out[idx], ref_out[idx])
|
||||
assert diff < 0.001, f'{num_groups=}, {m=}, {n=}, k={k_sizes[idx]}, batch={idx}, {diff:.5f}'
|
||||
|
||||
# Construct new tensors to avoid L2 cache acceleration
|
||||
x_fp8, y_fp8, out, ref_out, k_sizes = construct_k_grouped_wgrad(m, n, k_sizes)
|
||||
total_k = sum(k_sizes)
|
||||
|
||||
def test_func():
|
||||
deep_gemm.k_grouped_wgrad_gemm_fp8_fp8_fp32_nt(x_fp8, y_fp8, out, k_sizes)
|
||||
|
||||
t = bench_kineto(test_func, 'fp8_wgrad_gemm', suppress_kineto_output=True, with_multiple_kernels=True) * num_groups
|
||||
print(f' > Performance ({num_groups=}, m={m:5}, n={n:5}, avg_k={total_k//num_groups:5}): {t * 1e6:4.0f} us | '
|
||||
f'throughput: {2 * num_groups * m * n * (total_k/num_groups) / t / 1e12:4.0f} TFLOPS, '
|
||||
f'{(m * total_k + n * total_k + num_groups * m * n * 2) / 1e9 / t:4.0f} GB/s')
|
||||
t = bench_kineto(test_func, 'fp8_gemm', suppress_kineto_output=True)
|
||||
print(f' > Perf ({num_groups=:2}, m={m:5}, n={n:5}, k={k:5}): '
|
||||
f'{t * 1e6:4.0f} us | '
|
||||
f'{2 * m * n * k / t / 1e12:4.0f} TFLOPS | '
|
||||
f'{count_bytes(a, b, c, d) / 1e9 / t:4.0f} GB/s')
|
||||
print()
|
||||
|
||||
|
||||
@@ -307,6 +171,4 @@ if __name__ == '__main__':
|
||||
test_gemm()
|
||||
test_m_grouped_gemm_contiguous()
|
||||
test_m_grouped_gemm_masked()
|
||||
|
||||
test_wgrad_gemm()
|
||||
test_k_grouped_wgrad_gemm()
|
||||
test_k_grouped_gemm_contiguous()
|
||||
|
||||
@@ -1,98 +0,0 @@
|
||||
import ctypes
|
||||
import os
|
||||
import torch
|
||||
import cuda.bindings.driver as cbd
|
||||
from typing import Any, Dict
|
||||
|
||||
from deep_gemm import jit
|
||||
|
||||
# Essential debugging staffs
|
||||
os.environ['DG_JIT_DEBUG'] = os.getenv('DG_JIT_DEBUG', '1')
|
||||
os.environ['DG_JIT_DISABLE_CACHE'] = os.getenv('DG_JIT_DISABLE_CACHE', '1')
|
||||
|
||||
|
||||
class VectorAddRuntime(jit.Runtime):
|
||||
def __init__(self, path: str) -> None:
|
||||
super().__init__(path)
|
||||
|
||||
@staticmethod
|
||||
def generate(kwargs: Dict[str, Any]) -> str:
|
||||
return f"""
|
||||
#ifdef __CUDACC_RTC__
|
||||
#include <deep_gemm/nvrtc_std.cuh>
|
||||
#else
|
||||
#include <cuda.h>
|
||||
#endif
|
||||
|
||||
#include <cuda_fp8.h>
|
||||
#include <cuda_bf16.h>
|
||||
|
||||
template <typename T>
|
||||
__global__ void vector_add(T* a, T* b, T* c, uint32_t n) {{
|
||||
uint32_t i = blockDim.x * blockIdx.x + threadIdx.x;
|
||||
if (i < n) {{
|
||||
c[i] = a[i] + b[i];
|
||||
}}
|
||||
}}
|
||||
|
||||
static void __instantiate_kernel() {{
|
||||
auto ptr = reinterpret_cast<void*>(&vector_add<{kwargs['T']}>);
|
||||
}}
|
||||
"""
|
||||
|
||||
# noinspection PyShadowingNames,PyMethodOverriding
|
||||
@staticmethod
|
||||
def launch(kernel: cbd.CUkernel, kwargs: Dict[str, Any]) -> cbd.CUresult:
|
||||
assert kwargs['A'].shape == kwargs['B'].shape == kwargs['C'].shape
|
||||
assert kwargs['A'].device == kwargs['B'].device == kwargs['C'].device
|
||||
assert kwargs['A'].dim() == 1
|
||||
|
||||
config = cbd.CUlaunchConfig()
|
||||
config.gridDimX = (kwargs['A'].numel() + 127) // 128
|
||||
config.gridDimY = 1
|
||||
config.gridDimZ = 1
|
||||
config.blockDimX = 128
|
||||
config.blockDimY = 1
|
||||
config.blockDimZ = 1
|
||||
config.hStream = kwargs['STREAM']
|
||||
|
||||
arg_values = (
|
||||
kwargs['A'].data_ptr(),
|
||||
kwargs['B'].data_ptr(),
|
||||
kwargs['C'].data_ptr(),
|
||||
kwargs['A'].numel(),
|
||||
)
|
||||
arg_types = (
|
||||
ctypes.c_void_p,
|
||||
ctypes.c_void_p,
|
||||
ctypes.c_void_p,
|
||||
ctypes.c_uint32,
|
||||
)
|
||||
|
||||
return cbd.cuLaunchKernelEx(config, kernel, (arg_values, arg_types), 0)[0]
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print('Generated code:')
|
||||
kwargs = {'T': 'float'}
|
||||
code = VectorAddRuntime.generate(kwargs)
|
||||
print(code)
|
||||
print()
|
||||
|
||||
for compiler_name in ('NVCC', 'NVRTC'):
|
||||
# Get compiler
|
||||
compiler_cls = getattr(jit, f'{compiler_name}Compiler')
|
||||
print(f'Compiler: {compiler_name}, version: {compiler_cls.__version__()}')
|
||||
|
||||
# Build
|
||||
print('Building ...')
|
||||
func = compiler_cls.build('test_func', code, VectorAddRuntime, kwargs)
|
||||
|
||||
# Run and check
|
||||
a = torch.randn((1024, ), dtype=torch.float32, device='cuda')
|
||||
b = torch.randn((1024, ), dtype=torch.float32, device='cuda')
|
||||
c = torch.empty_like(a)
|
||||
ret = func(A=a, B=b, C=c, STREAM=torch.cuda.current_stream().cuda_stream)
|
||||
assert ret == cbd.CUresult.CUDA_SUCCESS, ret
|
||||
torch.testing.assert_close(c, a + b)
|
||||
print(f'JIT test for {compiler_name} passed\n')
|
||||
104
tests/test_layout.py
Normal file
104
tests/test_layout.py
Normal file
@@ -0,0 +1,104 @@
|
||||
import time
|
||||
import torch
|
||||
import random
|
||||
from deep_gemm.testing import bench_kineto, count_bytes
|
||||
from deep_gemm.utils import (
|
||||
align, ceil_div,
|
||||
per_token_cast_to_fp8, per_channel_cast_to_fp8,
|
||||
get_tma_aligned_size,
|
||||
get_mn_major_tma_aligned_packed_ue8m0_tensor,
|
||||
get_k_grouped_mn_major_tma_aligned_packed_ue8m0_tensor
|
||||
)
|
||||
|
||||
from generators import (
|
||||
enumerate_sf_layout,
|
||||
enumerate_k_grouped_sf_layout
|
||||
)
|
||||
|
||||
|
||||
def get_mn_major_tma_aligned_packed_ue8m0_tensor_torch_impl(x: torch.Tensor) -> torch.Tensor:
|
||||
assert x.dtype == torch.float and x.dim() in (2, 3)
|
||||
|
||||
# First, convert into UE8M0 `uint8_t`
|
||||
ue8m0_tensor = (x.view(torch.int) >> 23).to(torch.uint8)
|
||||
|
||||
# Second, make padded packed tensors
|
||||
mn, k = x.shape[-2], x.shape[-1]
|
||||
remove_dim = False
|
||||
if x.dim() == 2:
|
||||
x, remove_dim = x.unsqueeze(0), True
|
||||
b = x.shape[0]
|
||||
aligned_mn = get_tma_aligned_size(mn, 4)
|
||||
aligned_k = align(k, 4)
|
||||
padded = torch.zeros((b, aligned_mn, aligned_k), device=x.device, dtype=torch.uint8)
|
||||
padded[:, :mn, :k] = ue8m0_tensor
|
||||
padded = padded.view(-1).view(dtype=torch.int).view(b, aligned_mn, aligned_k // 4)
|
||||
|
||||
# Finally, transpose
|
||||
transposed = torch.zeros((b, aligned_k // 4, aligned_mn), device=x.device, dtype=torch.int).mT
|
||||
transposed[:, :, :] = padded
|
||||
aligned_x = transposed[:, :mn, :]
|
||||
return aligned_x.squeeze(0) if remove_dim else aligned_x
|
||||
|
||||
|
||||
def test_sf_layout_kernels() -> None:
|
||||
print('Testing SF layout kernels:')
|
||||
for mn, k, with_transpose, num_groups in enumerate_sf_layout():
|
||||
x = torch.randn((num_groups * mn, k), dtype=torch.bfloat16, device='cuda')
|
||||
x, fp32_sf = per_token_cast_to_fp8(x, use_ue8m0=True)
|
||||
fp32_sf = fp32_sf if num_groups == 1 else fp32_sf.view(num_groups, mn, -1)
|
||||
fp32_sf = fp32_sf if with_transpose else fp32_sf.transpose(-1, -2).contiguous().transpose(-1, -2)
|
||||
|
||||
# Correctness
|
||||
packed_sf = get_mn_major_tma_aligned_packed_ue8m0_tensor(fp32_sf)
|
||||
ref_packed_sf = get_mn_major_tma_aligned_packed_ue8m0_tensor_torch_impl(fp32_sf)
|
||||
assert torch.equal(packed_sf, ref_packed_sf), f'{mn=}, {k=}, {with_transpose=}, {num_groups=}'
|
||||
assert packed_sf.shape == ref_packed_sf.shape
|
||||
assert all([packed_sf.stride(i) == ref_packed_sf.stride(i) for i in range(packed_sf.dim())])
|
||||
|
||||
# Test launch overhead
|
||||
launch_start_t = time.time_ns()
|
||||
get_mn_major_tma_aligned_packed_ue8m0_tensor(fp32_sf)
|
||||
launch_end_t = time.time_ns()
|
||||
|
||||
# Performance
|
||||
t = bench_kineto(lambda: get_mn_major_tma_aligned_packed_ue8m0_tensor(fp32_sf), 'pack_fp32_into_ue8m0')
|
||||
print(f' > Perf ({num_groups=:2}, {mn=:5}, {k=:5}, transpose={int(with_transpose)}): '
|
||||
f'launch {(launch_end_t - launch_start_t) / 1e3:3.0f} us | {t * 1e6:4.0f} us | '
|
||||
f'{count_bytes(fp32_sf, packed_sf) / 1e9 / t:4.0f} GB/s')
|
||||
print()
|
||||
|
||||
|
||||
def test_k_grouped_sf_layout_kernels() -> None:
|
||||
print('Testing k-grouped SF layout kernels:')
|
||||
for mn, ks, num_groups in enumerate_k_grouped_sf_layout():
|
||||
sf_ks = [k // 128 for k in ks]
|
||||
packed_sf_ks = [ceil_div(k, 512) for k in ks]
|
||||
ks_tensor = torch.tensor(ks, dtype=torch.int, device='cuda')
|
||||
x = torch.randn((sum(ks), mn), dtype=torch.bfloat16, device='cuda')
|
||||
x, fp32_sf = per_channel_cast_to_fp8(x, use_ue8m0=True)
|
||||
|
||||
# Correctness
|
||||
packed_sf = get_k_grouped_mn_major_tma_aligned_packed_ue8m0_tensor(fp32_sf, ks_tensor, ks)
|
||||
split_packed_sf = packed_sf.split(packed_sf_ks)
|
||||
split_fp32_sf = fp32_sf.split(sf_ks)
|
||||
for i in range(num_groups):
|
||||
ref_packed_sf = get_mn_major_tma_aligned_packed_ue8m0_tensor_torch_impl(split_fp32_sf[i].T).T
|
||||
assert torch.equal(split_packed_sf[i], ref_packed_sf), f'{i=}'
|
||||
|
||||
# Performance
|
||||
t = bench_kineto(lambda: get_k_grouped_mn_major_tma_aligned_packed_ue8m0_tensor(fp32_sf, ks_tensor, ks), 'pack_fp32_into_ue8m0')
|
||||
print(f' > Perf ({num_groups=:3}, {mn=:5}, sum_k={sum(ks):5}):'
|
||||
f'{t * 1e6:4.0f} us | '
|
||||
f'{count_bytes(fp32_sf, packed_sf, ks_tensor) / 1e9 / t:4.0f} GB/s')
|
||||
print()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
torch.backends.cuda.matmul.allow_tf32 = True
|
||||
torch.backends.cudnn.allow_tf32 = True
|
||||
torch.manual_seed(1)
|
||||
random.seed(1)
|
||||
|
||||
test_sf_layout_kernels()
|
||||
test_k_grouped_sf_layout_kernels()
|
||||
Reference in New Issue
Block a user