perf: pure FP8 fwd/bwd and lean non-transposed GEMM

- drop the fused kernel; forward/backward are quantize + a pre-quantized GEMM
- rename module fp8_mm -> fp8_ops (mm.cu -> ops.cu)
- kernels/launchers fp8_gemm_kernel / launch_fp8_gemm; drop PqTraits/gather_trans/pack_fp8x4_vector
- remove the in-kernel transposed-operand branches (TransA/TransB)
- backward: quantize g once (amax_g here), explicit fp8 transposes, fast non-transposed GEMMs (dX = g@w^T, dW = g^T@x^T)
- each pass uses a single FP8 format (E4M3 fwd / E5M2 bwd)
This commit is contained in:
2026-08-23 15:38:30 +08:00
parent a29bdfae46
commit 4244df2785
8 changed files with 160 additions and 519 deletions
+28 -27
View File
@@ -35,8 +35,6 @@ from torch.library import Library
from astrai.extension.ops.fp8 import ( from astrai.extension.ops.fp8 import (
linear_backward_fp8, linear_backward_fp8,
linear_forward_fp8, linear_forward_fp8,
mm_fp8,
quantize_bf16,
) )
# Max representable value per FP8 format (E4M3: 448, E5M2: 57344). # Max representable value per FP8 format (E4M3: 448, E5M2: 57344).
@@ -275,9 +273,9 @@ def _dynamic_scale(t: torch.Tensor, recipe: FP8Recipe, fmt: str) -> torch.Tensor
def fp8_linear_forward(x: torch.Tensor, w: torch.Tensor, bias=None): def fp8_linear_forward(x: torch.Tensor, w: torch.Tensor, bias=None):
"""Scaled fp8 linear forward (called from the aten::linear impl). """Scaled fp8 linear forward (called from the aten::linear impl).
Delayed scaling uses the fused BF16->E4M3 GEMM (quantize + amax inside the Pure FP8 path for both recipes: quantize x/w with the active scales, run
kernel); dynamic scaling measures the current amax first and runs the the pre-quantized GEMM, and feed the freshly measured amax back into the
pre-quantized path. delayed-scaling ring (dynamic scaling measures the current amax itself).
""" """
if bias is None: if bias is None:
bias = torch.empty(0, device=x.device, dtype=x.dtype) bias = torch.empty(0, device=x.device, dtype=x.dtype)
@@ -287,21 +285,16 @@ def fp8_linear_forward(x: torch.Tensor, w: torch.Tensor, bias=None):
if not meta.w_init: if not meta.w_init:
meta.init_w(w, fmt) meta.init_w(w, fmt)
if isinstance(state.recipe, DynamicScaling): if isinstance(state.recipe, DynamicScaling):
x_2d = x.reshape(-1, w.size(1)) sx = _dynamic_scale(x.reshape(-1, w.size(1)), state.recipe, fmt)
sx = _dynamic_scale(x_2d, state.recipe, fmt)
sw = _dynamic_scale(w, state.recipe, fmt) sw = _dynamic_scale(w, state.recipe, fmt)
x8, _ = quantize_bf16(x_2d, sx, fmt) else:
w8, _ = quantize_bf16(w, sw, fmt) if not meta.x_init:
out = mm_fp8(x8, w8, sx, sw) meta.init_x(x, fmt)
out = out.reshape(*x.shape[:-1], w.size(0)) sx, sw = meta.x_scale, meta.w_scale
if bias.numel(): out, amax_x, amax_w = linear_forward_fp8(x, w, bias, sx, sw, fmt)
out = out + bias if not isinstance(state.recipe, DynamicScaling):
return out meta.update_x(amax_x, fmt)
if not meta.x_init: meta.update_w(amax_w, fmt)
meta.init_x(x, fmt)
out, amax_x, amax_w = linear_forward_fp8(x, w, bias, meta.x_scale, meta.w_scale)
meta.update_x(amax_x, fmt)
meta.update_w(amax_w, fmt)
return out return out
@@ -373,32 +366,40 @@ def _linear_cuda_impl(x: torch.Tensor, w: torch.Tensor, bias=None):
def _linear_backward_cuda_impl(input_tensor, grad_output, weight, output_mask): def _linear_backward_cuda_impl(input_tensor, grad_output, weight, output_mask):
# Backward dim contract: grad_output is [..., N], weight is [N, K], so
# the contraction check is grad_output.size(-1) == weight.size(0) (not the
# forward's x.size(-1) == w.size(1) — that would silently skip fp8 for
# every non-square layer).
if ( if (
fp8_linear_enabled() fp8_linear_enabled()
and weight.dtype == torch.bfloat16 and weight.dtype == torch.bfloat16
and _fp8_supported(grad_output, weight) and grad_output.dim() >= 2
and weight.dim() == 2
and grad_output.size(-1) == weight.size(0)
and input_tensor.dim() >= 2
and input_tensor.size(-1) == weight.size(1)
): ):
return fp8_linear_backward(grad_output, input_tensor, weight, list(output_mask)) return fp8_linear_backward(grad_output, input_tensor, weight, list(output_mask))
compute_dtype = weight.dtype compute_dtype = weight.dtype
grad = grad_output.to(compute_dtype) grad = grad_output.to(compute_dtype)
grad_2d = grad.reshape(-1, weight.size(0)) grad_2d = grad.reshape(-1, weight.size(0))
input_2d = input_tensor.reshape(-1, input_tensor.size(-1)).to(compute_dtype) input_2d = input_tensor.reshape(-1, input_tensor.size(-1)).to(compute_dtype)
# Unneeded grads come back full-shape-but-uninitialized (mirroring the
# fp8 binding), so reshape_as can never hit an empty tensor.
grad_input = ( grad_input = (
torch.mm(grad_2d, weight) torch.mm(grad_2d, weight).reshape_as(input_tensor)
if output_mask[0] if output_mask[0]
else torch.empty(0, device=input_tensor.device, dtype=input_tensor.dtype) else torch.empty_like(input_tensor)
) )
grad_weight = ( grad_weight = (
torch.mm(grad_2d.t(), input_2d) torch.mm(grad_2d.t(), input_2d) if output_mask[1] else torch.empty_like(weight)
if output_mask[1]
else torch.empty(0, device=input_tensor.device, dtype=input_tensor.dtype)
) )
grad_bias = ( grad_bias = (
grad.sum(dim=0) grad.sum(dim=0)
if output_mask[2] if output_mask[2]
else torch.empty(0, device=input_tensor.device, dtype=input_tensor.dtype) else torch.empty(0, device=grad.device, dtype=grad.dtype)
) )
return grad_input.reshape_as(input_tensor), grad_weight, grad_bias return grad_input, grad_weight, grad_bias
_lib = Library("aten", "IMPL", "CUDA") _lib = Library("aten", "IMPL", "CUDA")
+10 -8
View File
@@ -1,6 +1,6 @@
"""FP8 CUDA kernel interface adapter (the only module touching the pybind). """FP8 CUDA kernel interface adapter (the only module touching the pybind).
Isolates the ``fp8_mm`` CUDA extension behind stable Python primitives: Isolates the ``fp8_ops`` CUDA extension behind stable Python primitives:
- ``quantize_bf16(x, scale, fmt) -> (x8, amax)`` — BF16 → FP8 with fused amax - ``quantize_bf16(x, scale, fmt) -> (x8, amax)`` — BF16 → FP8 with fused amax
- ``mm_fp8(a8, b8, sa, sb) -> out`` — pre-quantized FP8 GEMM (BF16 output) - ``mm_fp8(a8, b8, sa, sb) -> out`` — pre-quantized FP8 GEMM (BF16 output)
@@ -33,11 +33,11 @@ _MOD: object | None = None
def _mod() -> object: def _mod() -> object:
global _MOD global _MOD
if _MOD is None: if _MOD is None:
if not is_available("fp8_mm"): if not is_available("fp8_ops"):
raise RuntimeError( raise RuntimeError(
"CUDA kernel 'fp8_mm' is not available. Build with CSRC_KERNELS=true." "CUDA kernel 'fp8_ops' is not available. Build with CSRC_KERNELS=true."
) )
_MOD = get_module("fp8_mm") _MOD = get_module("fp8_ops")
return _MOD return _MOD
@@ -154,16 +154,18 @@ def mm_fp8(
return fp8_gemm(a, b, sa, sb, int(out_dtype == "e4m3"), out_scale) return fp8_gemm(a, b, sa, sb, int(out_dtype == "e4m3"), out_scale)
def linear_forward_fp8(x, w, bias, sx, sw): def linear_forward_fp8(x, w, bias, sx, sw, fmt: str = "e4m3"):
"""BF16 linear forward, quantizing x/w to E4M3 inside the GEMM. """Pure FP8 linear forward: quantize x/w to ``fmt``, pre-quantized GEMM.
Returns ``(out, amax_x, amax_w)``. ``bias`` may be ``None``. Returns ``(out, amax_x, amax_w)``. ``bias`` may be ``None``. Both
operands share the same FP8 format (E4M3 by default; E5M2 for a
range-first configuration).
""" """
if not (x.dtype == torch.bfloat16 and w.dtype == torch.bfloat16): if not (x.dtype == torch.bfloat16 and w.dtype == torch.bfloat16):
raise TypeError(f"fp8 forward requires bf16 inputs, got {x.dtype}/{w.dtype}") raise TypeError(f"fp8 forward requires bf16 inputs, got {x.dtype}/{w.dtype}")
if bias is None: if bias is None:
bias = torch.empty(0, device=x.device, dtype=x.dtype) bias = torch.empty(0, device=x.device, dtype=x.dtype)
return _mod().linear_forward_fp8(x, w, bias, sx, sw) return _mod().linear_forward_fp8(x, w, bias, sx, sw, _fmt_int(fmt))
def linear_backward_fp8(g, x, w, masks, sg, sw, sx, fmt: str = "e5m2"): def linear_backward_fp8(g, x, w, masks, sg, sw, sx, fmt: str = "e5m2"):
+2 -2
View File
@@ -58,7 +58,7 @@ set(KERNEL_NAMES
attn_paged_decode attn_paged_decode
attn_paged_prefill attn_paged_prefill
rotary_emb rotary_emb
fp8_mm fp8_ops
) )
set(KERNEL_SRCS set(KERNEL_SRCS
attention/decode.cu attention/decode.cu
@@ -66,7 +66,7 @@ set(KERNEL_SRCS
attention/paged_decode.cu attention/paged_decode.cu
attention/paged_prefill.cu attention/paged_prefill.cu
rotary/rotary_emb.cu rotary/rotary_emb.cu
fp8/mm.cu fp8/ops.cu
) )
list(LENGTH KERNEL_NAMES _kernel_count) list(LENGTH KERNEL_NAMES _kernel_count)
+28 -390
View File
@@ -32,16 +32,6 @@ struct fp8_input<FP8Format::E5M2> {
// Shared device helpers // Shared device helpers
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
__device__ __forceinline__ unsigned pack_fp8x4_vector(
float x0, float x1, float x2, float x3,
__nv_fp8_interpretation_t fmt = __NV_E4M3) {
const auto low = __nv_cvt_float2_to_fp8x2(make_float2(x0, x1),
__NV_SATFINITE, fmt);
const auto high = __nv_cvt_float2_to_fp8x2(make_float2(x2, x3),
__NV_SATFINITE, fmt);
return static_cast<unsigned>(low) | (static_cast<unsigned>(high) << 16);
}
// FP8 MMA lives in the shared astrai::mma_sync template (common/mma.cuh); // FP8 MMA lives in the shared astrai::mma_sync template (common/mma.cuh);
// instantiate it with fp8_input<Fmt>::type. Accumulates in-place: callers // instantiate it with fp8_input<Fmt>::type. Accumulates in-place: callers
// pass the same accumulator array as both `d` and `c`. // pass the same accumulator array as both `d` and `c`.
@@ -61,33 +51,6 @@ __device__ __forceinline__ float warp_reduce_max(float value) {
return value; return value;
} }
// Block-wide max reduction of a per-warp tracked value, then an atomic
// update of the global amax slot when `track` is set.
template <int NWarps>
__device__ __forceinline__ void block_reduce_amax(float& local, float* slots,
int warp, int lane,
bool track, float* global) {
local = warp_reduce_max(local);
if (lane == 0) slots[warp] = local;
__syncthreads();
if (warp == 0) {
float value = lane < NWarps ? slots[lane] : 0.0f;
value = warp_reduce_max(value);
if (lane == 0 && track && global) atomic_max_float(global, value);
}
}
// One thread moves eight BF16 values (16 bytes) via cp.async; the uint4
// shape keeps source and destination naturally 128-bit aligned.
__device__ __forceinline__ void cp_async_bf16_8(
__nv_bfloat16* destination, const __nv_bfloat16* source, bool valid) {
const unsigned shared_address = __cvta_generic_to_shared(destination);
const uint4* source_vec = reinterpret_cast<const uint4*>(source);
asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;"
:: "r"(shared_address), "l"(source_vec),
"r"(valid ? 16 : 0));
}
// One thread moves sixteen FP8 values (16 bytes) via cp.async. // One thread moves sixteen FP8 values (16 bytes) via cp.async.
template <typename T> template <typename T>
__device__ __forceinline__ void cp_async_16b(T* destination, __device__ __forceinline__ void cp_async_16b(T* destination,
@@ -99,28 +62,6 @@ __device__ __forceinline__ void cp_async_16b(T* destination,
"r"(valid ? 16 : 0)); "r"(valid ? 16 : 0));
} }
// Convert four BF16 values to one 4xFP8 pack, tracking the raw (pre-scale)
// amax — scaling first would saturate amax at the FP8 max and collapse the
// scale. Format comes from Traits.
template <typename Traits, bool TrackAmax = true>
__device__ __forceinline__ unsigned load_fp8x4_from_bf16(
const __nv_bfloat16* source, float scale_inv, float& amax,
bool track_amax = true) {
float x0 = __bfloat162float(source[0]);
float x1 = __bfloat162float(source[1]);
float x2 = __bfloat162float(source[2]);
float x3 = __bfloat162float(source[3]);
if constexpr (TrackAmax) {
if (track_amax) {
amax = fmaxf(amax, fmaxf(fabsf(x0), fmaxf(fabsf(x1),
fmaxf(fabsf(x2), fabsf(x3)))));
}
}
return pack_fp8x4_vector(x0 * scale_inv, x1 * scale_inv,
x2 * scale_inv, x3 * scale_inv,
Traits::kNvFormat);
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Quantize kernel: BF16 -> FP8 (E4M3 or E5M2), fused amax over raw values. // Quantize kernel: BF16 -> FP8 (E4M3 or E5M2), fused amax over raw values.
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
@@ -158,301 +99,24 @@ __global__ void fp8_quantize_kernel(FP8Params p) {
} }
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Fused kernel: BF16 A/B -> inline E4M3 quantize -> ldmatrix fragments -> // Pre-quantized GEMM kernel: FP8 A/B read straight into shared memory, FP32
// MMA -> BF16 out. 128x64 CTA / 64x16 warp tile / cp.async pipeline.
// The quantized FP8 tiles live in a separate smem region laid out around
// ldmatrix's single-address, 128-byte-strided matrices (16-byte rows):
// A8: [M/16 block][4 sub-blocks of 8 rows x 16 fp8][...] where sub-block
// order is (h0,m0-7), (h0,m8-15), (h1,m0-7), (h1,m8-15) — one
// ldmatrix.x4 emits the whole m16n8k32 A fragment (regs 0..3 match).
// B8: [N/8 block][2 sub-blocks of 8 rows x 16 fp8][...] with h0 then h1 —
// one ldmatrix.x2 emits the m16n8k32 B fragment (regs 0,1).
// ---------------------------------------------------------------------------
template <typename Traits, bool AddBias, bool TrackAmax>
__global__ void fp8_fused_gemm_kernel(FP8Params p) {
using T8 = __nv_fp8_e4m3; // fused forward always quantizes to E4M3
constexpr int kBlockM = Traits::kBlockM;
constexpr int kBlockN = Traits::kBlockN;
constexpr int kK = Traits::kK;
constexpr int kStages = Traits::kStages;
constexpr int kWarpM = 64; // warp tile rows (BlockM / 2)
constexpr int kWarpN = 16; // warp tile cols (BlockN / 4)
constexpr int a_stride = kBlockM * kK; // bf16 elements per A stage
constexpr int b_stride = kBlockN * kK; // bf16 elements per B stage
// A8 block layout: (M/16) blocks x 4 sub-blocks x 128 B = BlockM*32 B.
// B8 block layout: (N/8) blocks x 2 sub-blocks x 128 B = BlockN*32 B.
constexpr int a8_bytes = kBlockM * 32;
constexpr int b8_bytes = kBlockN * 32;
// smem layout: [A bf16 stages][B bf16 stages][A8 fp8 tiles][B8 fp8 tiles]
constexpr int bf16_bytes = kStages * (a_stride + b_stride) * 2;
extern __shared__ char smem[];
auto* a_bf16 = reinterpret_cast<__nv_bfloat16*>(smem);
auto* b_bf16 = reinterpret_cast<__nv_bfloat16*>(smem + kStages * a_stride * 2);
auto* a8 = reinterpret_cast<T8*>(smem + bf16_bytes);
auto* b8 = reinterpret_cast<T8*>(smem + bf16_bytes + a8_bytes);
__shared__ float warp_amax_a[kWarps];
__shared__ float warp_amax_b[kWarps];
const auto* a = reinterpret_cast<const __nv_bfloat16*>(p.a_ptr);
const auto* b = reinterpret_cast<const __nv_bfloat16*>(p.b_ptr);
auto* out = reinterpret_cast<__nv_bfloat16*>(p.out_ptr);
const auto* bias = p.bias;
const float* scale_a = p.scale_a;
const float* scale_b = p.scale_b;
float* amax_a = p.amax_a;
float* amax_b = p.amax_b;
const int64_t m = p.m, n = p.n, k = p.k;
const int tid = threadIdx.x;
const int warp = tid >> 5;
const int lane = tid & 31;
const int group = lane >> 2;
const int thread_in_group = lane & 3;
constexpr int warps_n = kBlockN / 16;
const int warp_m = warp / warps_n;
const int warp_n = warp % warps_n;
const int64_t row_base = blockIdx.y * kBlockM + warp_m * kWarpM + group;
const int64_t output_col =
blockIdx.x * kBlockN + warp_n * 16 + thread_in_group * 2;
const float sa = *scale_a;
const float sb = *scale_b;
const float inv_a = 1.0f / sa;
const float inv_b = 1.0f / sb;
float local_amax_a = 0.0f;
float local_amax_b = 0.0f;
float acc[4 * 4 * 2] = {};
const bool track_amax_a = TrackAmax && blockIdx.x == 0;
const bool track_amax_b = TrackAmax && blockIdx.y == 0;
// Each thread issues 8 A chunks and 4 B chunks of 8 BF16 (16B) per stage.
auto load_tile = [&](int stage, int64_t k_base) {
const int r0 = tid >> 2;
const int c0 = (tid & 3) * 8;
#pragma unroll
for (int j = 0; j < kK / 32; ++j) {
const int col = c0 + 32 * j;
const bool full_chunk = k_base + col + 7 < k;
const int64_t a_row = blockIdx.y * kBlockM + r0;
const int64_t b_row = blockIdx.x * kBlockN + r0;
auto* a_dst = &a_bf16[stage * a_stride + r0 * kK + col];
auto* b_dst = &b_bf16[stage * b_stride + r0 * kK + col];
const auto* a_ptr = a + a_row * k + k_base + col;
const auto* b_ptr = b + b_row * k + k_base + col;
const bool full_a = a_row < m && full_chunk;
const bool full_b = b_row < n && full_chunk;
const bool aligned_a =
(reinterpret_cast<uintptr_t>(a_ptr) & 15) == 0;
const bool aligned_b =
(reinterpret_cast<uintptr_t>(b_ptr) & 15) == 0;
if (full_a && aligned_a) {
cp_async_bf16_8(a_dst, a_ptr, true);
} else {
#pragma unroll
for (int i = 0; i < 8; ++i) {
a_dst[i] = a_row < m && k_base + col + i < k
? a_ptr[i]
: __float2bfloat16(0.0f);
}
}
if (full_b && aligned_b) {
cp_async_bf16_8(b_dst, b_ptr, true);
} else {
#pragma unroll
for (int i = 0; i < 8; ++i) {
b_dst[i] = b_row < n && k_base + col + i < k
? b_ptr[i]
: __float2bfloat16(0.0f);
}
}
if (r0 + kWarpM < kBlockM) {
const int64_t a_row_hi = blockIdx.y * kBlockM + r0 + kWarpM;
auto* a_dst_hi =
&a_bf16[stage * a_stride + (r0 + kWarpM) * kK + col];
const auto* a_ptr_hi = a + a_row_hi * k + k_base + col;
const bool full_a_hi = a_row_hi < m && full_chunk;
const bool aligned_a_hi =
(reinterpret_cast<uintptr_t>(a_ptr_hi) & 15) == 0;
if (full_a_hi && aligned_a_hi) {
cp_async_bf16_8(a_dst_hi, a_ptr_hi, true);
} else {
#pragma unroll
for (int i = 0; i < 8; ++i) {
a_dst_hi[i] = a_row_hi < m && k_base + col + i < k
? a_ptr_hi[i]
: __float2bfloat16(0.0f);
}
}
}
}
};
// Quantize the BF16 staging area into the ldmatrix-friendly FP8 tiles.
// A8 sub-block for global row `row` and K half `h`:
// (row>>4)*512 + ((h<<1)|((row>>3)&1))*128 + (row&7)*16
// B8 sub-block: (row>>3)*256 + h*128 + (row&7)*16.
// Each thread emits one 4-FP8 pack at a time (256 threads, kK/4 = 8 packs
// per row).
auto quantize_tile = [&](int stage) {
constexpr int kA_packs = kBlockM * kK / 4;
constexpr int kB_packs = kBlockN * kK / 4;
#pragma unroll
for (int i = tid; i < kA_packs; i += 256) {
const int row = i >> 3; // 8 packs per row
const int k4 = (i & 7) * 4;
const int half = k4 >> 4; // 0: k 0-15, 1: k 16-31
const int k16 = k4 & 15;
const int a8_idx =
(row >> 4) * 512 + (((half << 1) | ((row >> 3) & 1)) * 128) +
(row & 7) * 16 + k16;
auto* src = &a_bf16[stage * a_stride + row * kK + k4];
auto* dst = reinterpret_cast<unsigned*>(&a8[a8_idx]);
*dst = load_fp8x4_from_bf16<Traits, TrackAmax>(
src, inv_a, local_amax_a, track_amax_a);
}
#pragma unroll
for (int i = tid; i < kB_packs; i += 256) {
const int row = i >> 3;
const int k4 = (i & 7) * 4;
const int half = k4 >> 4;
const int k16 = k4 & 15;
const int b8_idx =
(row >> 3) * 256 + half * 128 + (row & 7) * 16 + k16;
auto* src = &b_bf16[stage * b_stride + row * kK + k4];
auto* dst = reinterpret_cast<unsigned*>(&b8[b8_idx]);
*dst = load_fp8x4_from_bf16<Traits, TrackAmax>(
src, inv_b, local_amax_b, track_amax_b);
}
};
const int64_t tile_count = (k + kK - 1) / kK;
load_tile(0, 0);
asm volatile("cp.async.commit_group;");
if (tile_count > 1) {
load_tile(1, kK);
asm volatile("cp.async.commit_group;");
}
if (tile_count > 2) {
load_tile(2, 2 * kK);
asm volatile("cp.async.commit_group;");
}
for (int64_t tile_index = 0; tile_index < tile_count; ++tile_index) {
const int stage = static_cast<int>(tile_index % kStages);
// 3-stage pipeline: at most 2 groups in flight; the tail of the K
// loop waits for everything.
const int64_t remaining = tile_count - tile_index - 1;
if (remaining >= 2) {
asm volatile("cp.async.wait_group 2;");
} else if (remaining == 1) {
asm volatile("cp.async.wait_group 1;");
} else {
asm volatile("cp.async.wait_group 0;");
}
// wait_group only waits for this thread's async copies. All threads
// must finish loading before the tile is read by the CTA.
__syncthreads();
quantize_tile(stage);
__syncthreads();
// kK == kMmaK, so one m16n8k32 MMA segment per K stage; fragments
// come from the fp8 tiles via ldmatrix.
#pragma unroll
for (int k_seg = 0; k_seg < kK / kMmaK; ++k_seg) {
#pragma unroll
for (int nt = 0; nt < 2; ++nt) {
const int b_row0 = warp_n * 16 + nt * 8;
unsigned b_frag[2];
// B8 block = (b_row0>>3), sub-blocks h0 then h1 at +0/+128.
// ldmatrix: each thread supplies one matrix-row address —
// threads 0-7 feed matrix 0 (h0) rows, 8-15 matrix 1 (h1);
// the remaining threads' addresses are ignored.
const int b8_base = (b_row0 >> 3) * 256;
astrai::ldmatrix_x2<T8>(
b_frag,
&b8[b8_base + ((lane / 8) & 1) * 128 + (lane % 8) * 16]);
#pragma unroll
for (int mt = 0; mt < 4; ++mt) {
const int a_row0 = warp_m * kWarpM + mt * 16;
unsigned a_frag[4];
// A8 block = (a_row0>>4); one x4 emits regs 0..3 in the
// exact mma A-operand order: h0m0-7, h0m8-15, h1m0-7,
// h1m8-15. Each thread supplies matrix (tid/8) row
// (tid%8) — all 32 addresses are used by x4.
const int a8_base = (a_row0 >> 4) * 512;
astrai::ldmatrix_x4<T8>(
a_frag,
&a8[a8_base + (lane / 8) * 128 + (lane % 8) * 16]);
astrai::mma_sync<typename fp8_input<Traits::kFormat>::type>(
acc + (nt * 4 + mt) * 4,
a_frag, b_frag, acc + (nt * 4 + mt) * 4);
}
}
}
__syncthreads();
if (tile_index + 3 < tile_count) {
load_tile(stage, (tile_index + 3) * kK);
asm volatile("cp.async.commit_group;");
}
}
if constexpr (TrackAmax) {
block_reduce_amax<kWarps>(local_amax_a, warp_amax_a, warp, lane,
track_amax_a, amax_a);
block_reduce_amax<kWarps>(local_amax_b, warp_amax_b, warp, lane,
track_amax_b, amax_b);
}
const float output_scale = sa * sb;
#pragma unroll
for (int nt = 0; nt < 2; ++nt) {
const int64_t col = output_col + nt * 8;
#pragma unroll
for (int mt = 0; mt < 4; ++mt) {
const int64_t row0 = row_base + mt * 16;
const int64_t row1 = row0 + 8;
float* tile_acc = acc + (nt * 4 + mt) * 4;
if (col < n) {
float bias0 = 0.0f;
float bias1 = 0.0f;
if constexpr (AddBias) {
bias0 = __bfloat162float(bias[col]);
if (col + 1 < n)
bias1 = __bfloat162float(bias[col + 1]);
}
if (row0 < m) {
out[row0 * n + col] =
__float2bfloat16(tile_acc[0] * output_scale + bias0);
if (col + 1 < n)
out[row0 * n + col + 1] = __float2bfloat16(
tile_acc[1] * output_scale + bias1);
}
if (row1 < m) {
out[row1 * n + col] =
__float2bfloat16(tile_acc[2] * output_scale + bias0);
if (col + 1 < n)
out[row1 * n + col + 1] = __float2bfloat16(
tile_acc[3] * output_scale + bias1);
}
}
}
}
}
// ---------------------------------------------------------------------------
// Pre-quantized kernel: FP8 A/B read straight into shared memory, FP32
// accumulation, BF16 or FP8 output. The input format follows Traits; the // accumulation, BF16 or FP8 output. The input format follows Traits; the
// tile is compact (row = kK bytes) so MMA fragments read directly. // tile is compact (row = kK bytes) so MMA fragments read directly — no
// in-kernel transpose of the operands (the binding handles transposes).
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
template <typename Traits, bool OutFp8 = false> template <typename Traits, bool OutFp8 = false>
__global__ void fp8_pq_gemm_kernel(FP8Params p) { __global__ void fp8_gemm_kernel(FP8Params p) {
using T8 = std::conditional_t<Traits::kIsE5M2, __nv_fp8_e5m2, __nv_fp8_e4m3>; using T8 = std::conditional_t<Traits::kIsE5M2, __nv_fp8_e5m2, __nv_fp8_e4m3>;
constexpr int kBlockM = Traits::kBlockM; constexpr int kBlockM = Traits::kBlockM;
constexpr int kBlockN = Traits::kBlockN; constexpr int kBlockN = Traits::kBlockN;
constexpr int kK = Traits::kK; constexpr int kK = Traits::kK;
constexpr int kStages = Traits::kStages; constexpr int kStages = Traits::kStages;
__shared__ __align__(16) T8 a_tile[kStages][kBlockM][kK]; // Tiles are [M][kK] / [N][kK]: each row is kK bytes (16B-aligned for
__shared__ __align__(16) T8 b_tile[kStages][kBlockN][kK]; // cp.async), and the MMA fragments read 4-byte-aligned K-contiguous
// chunks directly from them.
__shared__ __align__(16) T8 a_smem[kStages][kBlockM][kK];
__shared__ __align__(16) T8 b_smem[kStages][kBlockN][kK];
const auto* a = reinterpret_cast<const T8*>(p.a_ptr); const auto* a = reinterpret_cast<const T8*>(p.a_ptr);
const auto* b = reinterpret_cast<const T8*>(p.b_ptr); const auto* b = reinterpret_cast<const T8*>(p.b_ptr);
@@ -476,13 +140,15 @@ __global__ void fp8_pq_gemm_kernel(FP8Params p) {
float acc[4 * 4 * 2] = {}; float acc[4 * 4 * 2] = {};
// One A chunk (16 FP8) per thread covers the 128x32 tile; the first 128 // One A chunk (16 FP8) per thread covers the 128x32 tile; the first 128
// threads issue the 64x32 B chunks. // threads issue the 64x32 B chunks. Both operands are already in the MMA
// row-major / col-major layout ([M][K] with K contiguous), so each thread
// copies a 16-byte-aligned run straight into the tile via cp.async.
auto load_tile = [&](int stage, int64_t k_base) { auto load_tile = [&](int stage, int64_t k_base) {
const int r0 = tid >> 1; const int r0 = tid >> 1;
const int c0 = (tid & 1) * 16; const int c0 = (tid & 1) * 16;
const bool full_chunk = k_base + c0 + 15 < k; const bool full_chunk = k_base + c0 + 15 < k;
const int64_t a_row = blockIdx.y * kBlockM + r0; const int64_t a_row = blockIdx.y * kBlockM + r0;
auto* a_dst = &a_tile[stage][r0][c0]; auto* a_dst = &a_smem[stage][r0][c0];
const auto* a_ptr = a + a_row * k + k_base + c0; const auto* a_ptr = a + a_row * k + k_base + c0;
const bool full_a = a_row < m && full_chunk; const bool full_a = a_row < m && full_chunk;
const bool aligned_a = const bool aligned_a =
@@ -491,15 +157,14 @@ __global__ void fp8_pq_gemm_kernel(FP8Params p) {
cp_async_16b(a_dst, a_ptr, true); cp_async_16b(a_dst, a_ptr, true);
} else { } else {
#pragma unroll #pragma unroll
for (int i = 0; i < 16; ++i) { for (int i = 0; i < 16; ++i)
a_dst[i] = a_row < m && k_base + c0 + i < k a_dst[i] = a_row < m && k_base + c0 + i < k
? a_ptr[i] ? a_ptr[i]
: T8(0.0f); : T8(0.0f);
}
} }
if (tid < 128) { if (tid < 128) {
const int64_t b_row = blockIdx.x * kBlockN + r0; const int b_row = blockIdx.x * kBlockN + r0;
auto* b_dst = &b_tile[stage][r0][c0]; auto* b_dst = &b_smem[stage][r0][c0];
const auto* b_ptr = b + b_row * k + k_base + c0; const auto* b_ptr = b + b_row * k + k_base + c0;
const bool full_b = b_row < n && full_chunk; const bool full_b = b_row < n && full_chunk;
const bool aligned_b = const bool aligned_b =
@@ -508,11 +173,10 @@ __global__ void fp8_pq_gemm_kernel(FP8Params p) {
cp_async_16b(b_dst, b_ptr, true); cp_async_16b(b_dst, b_ptr, true);
} else { } else {
#pragma unroll #pragma unroll
for (int i = 0; i < 16; ++i) { for (int i = 0; i < 16; ++i)
b_dst[i] = b_row < n && k_base + c0 + i < k b_dst[i] = b_row < n && k_base + c0 + i < k
? b_ptr[i] ? b_ptr[i]
: T8(0.0f); : T8(0.0f);
}
} }
} }
}; };
@@ -548,23 +212,24 @@ __global__ void fp8_pq_gemm_kernel(FP8Params p) {
#pragma unroll #pragma unroll
for (int nt = 0; nt < 2; ++nt) { for (int nt = 0; nt < 2; ++nt) {
const int b_row = warp_n * 16 + nt * 8 + group; const int b_row = warp_n * 16 + nt * 8 + group;
// B fragment: two 4-FP8 chunks (K-contiguous) at output row.
unsigned b_frag[2]; unsigned b_frag[2];
b_frag[0] = *reinterpret_cast<const unsigned*>( b_frag[0] = *reinterpret_cast<const unsigned*>(
&b_tile[stage][b_row][frag_col]); &b_smem[stage][b_row][frag_col]);
b_frag[1] = *reinterpret_cast<const unsigned*>( b_frag[1] = *reinterpret_cast<const unsigned*>(
&b_tile[stage][b_row][frag_col + 16]); &b_smem[stage][b_row][frag_col + 16]);
#pragma unroll #pragma unroll
for (int mt = 0; mt < 4; ++mt) { for (int mt = 0; mt < 4; ++mt) {
const int a_row0 = warp_m * 64 + mt * 16 + group; const int a_row0 = warp_m * 64 + mt * 16 + group;
unsigned a_frag[4]; unsigned a_frag[4];
a_frag[0] = *reinterpret_cast<const unsigned*>( a_frag[0] = *reinterpret_cast<const unsigned*>(
&a_tile[stage][a_row0][frag_col]); &a_smem[stage][a_row0][frag_col]);
a_frag[1] = *reinterpret_cast<const unsigned*>( a_frag[1] = *reinterpret_cast<const unsigned*>(
&a_tile[stage][a_row0 + 8][frag_col]); &a_smem[stage][a_row0 + 8][frag_col]);
a_frag[2] = *reinterpret_cast<const unsigned*>( a_frag[2] = *reinterpret_cast<const unsigned*>(
&a_tile[stage][a_row0][frag_col + 16]); &a_smem[stage][a_row0][frag_col + 16]);
a_frag[3] = *reinterpret_cast<const unsigned*>( a_frag[3] = *reinterpret_cast<const unsigned*>(
&a_tile[stage][a_row0 + 8][frag_col + 16]); &a_smem[stage][a_row0 + 8][frag_col + 16]);
astrai::mma_sync<typename fp8_input<Traits::kFormat>::type>( astrai::mma_sync<typename fp8_input<Traits::kFormat>::type>(
acc + (nt * 4 + mt) * 4, acc + (nt * 4 + mt) * 4,
a_frag, b_frag, acc + (nt * 4 + mt) * 4); a_frag, b_frag, acc + (nt * 4 + mt) * 4);
@@ -622,13 +287,6 @@ __global__ void fp8_pq_gemm_kernel(FP8Params p) {
// Launchers — pure CUDA (no torch), usable from the binding and pure C tests. // Launchers — pure CUDA (no torch), usable from the binding and pure C tests.
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// Fused forward tile config: 128x64 CTA, K=32, 3-stage cp.async pipeline,
// plus the fp8 ldmatrix tile region (A8[2][BlockM][16] + B8[2][BlockN][16]).
using FusedTraits = Fp8GemmTraits<FP8Format::E4M3, 128, 64, 32, 3>;
// Pre-quantized tile config: 128x64 CTA, K=32, 3-stage pipeline.
template <FP8Format Fmt>
using PqTraits = Fp8GemmTraits<Fmt, 128, 64, 32, 3>;
template <FP8Format Fmt> template <FP8Format Fmt>
void launch_fp8_quantize(const FP8Params& p, cudaStream_t stream) { void launch_fp8_quantize(const FP8Params& p, cudaStream_t stream) {
constexpr int kThreads = 256; constexpr int kThreads = 256;
@@ -636,33 +294,13 @@ void launch_fp8_quantize(const FP8Params& p, cudaStream_t stream) {
fp8_quantize_kernel<Fmt><<<blocks, kThreads, 0, stream>>>(p); fp8_quantize_kernel<Fmt><<<blocks, kThreads, 0, stream>>>(p);
} }
template <bool AddBias, bool TrackAmax> // Pre-quantized GEMM tile config: 128x64 CTA, K=32, 3-stage pipeline.
void launch_fp8_fused(const FP8Params& p, cudaStream_t stream) {
// bf16 staging (3 stages) + fp8 ldmatrix tiles (A8[2][M][16] + B8[2][N][16])
constexpr int kSmemBytes =
FusedTraits::kStages *
(FusedTraits::kBlockM * FusedTraits::kK +
FusedTraits::kBlockN * FusedTraits::kK) *
2 +
2 * FusedTraits::kBlockM * 16 + 2 * FusedTraits::kBlockN * 16;
dim3 grid((p.n + FusedTraits::kBlockN - 1) / FusedTraits::kBlockN,
(p.m + FusedTraits::kBlockM - 1) / FusedTraits::kBlockM);
auto kernel = fp8_fused_gemm_kernel<FusedTraits, AddBias, TrackAmax>;
static bool attribute_set = false;
if (!attribute_set) {
cudaFuncSetAttribute(
kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, kSmemBytes);
attribute_set = true;
}
kernel<<<grid, kWarps * 32, kSmemBytes, stream>>>(p);
}
template <FP8Format Fmt, bool OutFp8 = false> template <FP8Format Fmt, bool OutFp8 = false>
void launch_fp8_pq(const FP8Params& p, cudaStream_t stream) { void launch_fp8_gemm(const FP8Params& p, cudaStream_t stream) {
using Traits = PqTraits<Fmt>; using Traits = Fp8GemmTraits<Fmt, 128, 64, 32, 3>;
dim3 grid((p.n + Traits::kBlockN - 1) / Traits::kBlockN, dim3 grid((p.n + Traits::kBlockN - 1) / Traits::kBlockN,
(p.m + Traits::kBlockM - 1) / Traits::kBlockM); (p.m + Traits::kBlockM - 1) / Traits::kBlockM);
fp8_pq_gemm_kernel<Traits, OutFp8><<<grid, kWarps * 32, 0, stream>>>(p); fp8_gemm_kernel<Traits, OutFp8><<<grid, kWarps * 32, 0, stream>>>(p);
} }
} // namespace fp8 } // namespace fp8
@@ -168,15 +168,15 @@ torch::Tensor mm_fp8(torch::Tensor a, torch::Tensor b, torch::Tensor sa,
out_fp8 ? &os : nullptr, m, n, k); out_fp8 ? &os : nullptr, m, n, k);
if (a.scalar_type() == torch::kFloat8_e4m3fn) { if (a.scalar_type() == torch::kFloat8_e4m3fn) {
if (out_fp8) { if (out_fp8) {
fp8::launch_fp8_pq<FP8Format::E4M3, true>(p, stream.stream()); fp8::launch_fp8_gemm<FP8Format::E4M3, true>(p, stream.stream());
} else { } else {
fp8::launch_fp8_pq<FP8Format::E4M3>(p, stream.stream()); fp8::launch_fp8_gemm<FP8Format::E4M3>(p, stream.stream());
} }
} else { } else {
if (out_fp8) { if (out_fp8) {
fp8::launch_fp8_pq<FP8Format::E5M2, true>(p, stream.stream()); fp8::launch_fp8_gemm<FP8Format::E5M2, true>(p, stream.stream());
} else { } else {
fp8::launch_fp8_pq<FP8Format::E5M2>(p, stream.stream()); fp8::launch_fp8_gemm<FP8Format::E5M2>(p, stream.stream());
} }
} }
C10_CUDA_CHECK(cudaGetLastError()); C10_CUDA_CHECK(cudaGetLastError());
@@ -185,9 +185,10 @@ torch::Tensor mm_fp8(torch::Tensor a, torch::Tensor b, torch::Tensor sa,
std::tuple<torch::Tensor, torch::Tensor, torch::Tensor> linear_forward_fp8( std::tuple<torch::Tensor, torch::Tensor, torch::Tensor> linear_forward_fp8(
torch::Tensor x, torch::Tensor w, torch::Tensor bias, torch::Tensor sx, torch::Tensor x, torch::Tensor w, torch::Tensor bias, torch::Tensor sx,
torch::Tensor sw) { torch::Tensor sw, int64_t fmt) {
// Fused BF16 -> E4M3 -> MMA -> BF16 linear forward. amax_x / amax_w are // Pure FP8 forward: quantize x/w (fmt: 0 = E4M3, 1 = E5M2), then the
// zero-initialized here and returned (caller does not clear them). // pre-quantized GEMM; the dequantized BF16 output gets the bias added.
// amax_x / amax_w come from the quantize kernels (zero-initialized here).
TORCH_CHECK(x.is_cuda() && w.is_cuda(), "CUDA tensors required"); TORCH_CHECK(x.is_cuda() && w.is_cuda(), "CUDA tensors required");
TORCH_CHECK(x.scalar_type() == torch::kBFloat16 && TORCH_CHECK(x.scalar_type() == torch::kBFloat16 &&
w.scalar_type() == torch::kBFloat16, w.scalar_type() == torch::kBFloat16,
@@ -199,14 +200,10 @@ std::tuple<torch::Tensor, torch::Tensor, torch::Tensor> linear_forward_fp8(
const at::cuda::OptionalCUDAGuard guard(x.device()); const at::cuda::OptionalCUDAGuard guard(x.device());
auto stream = at::cuda::getCurrentCUDAStream(); auto stream = at::cuda::getCurrentCUDAStream();
auto x_c = x.reshape({-1, w.size(1)}).contiguous(); auto x_c = x.reshape({-1, w.size(1)}).contiguous(); // [M, K]
auto w_c = w.contiguous(); auto w_c = w.contiguous(); // [N, K]
int64_t m = x_c.size(0), k = x_c.size(1), n = w_c.size(0); int64_t m = x_c.size(0), k = x_c.size(1), n = w_c.size(0);
TORCH_CHECK(w_c.dim() == 2 && w_c.size(1) == k, "inner dim mismatch"); TORCH_CHECK(w_c.dim() == 2 && w_c.size(1) == k, "inner dim mismatch");
// amax slots are zero-initialized here; the kernel atomically maxes in.
auto amax_x = torch::zeros({1}, x.options().dtype(torch::kFloat32));
auto amax_w = torch::zeros({1}, x.options().dtype(torch::kFloat32));
auto out = torch::empty({m, n}, x_c.options());
const bool has_bias = bias.defined() && bias.numel() > 0; const bool has_bias = bias.defined() && bias.numel() > 0;
if (has_bias) { if (has_bias) {
TORCH_CHECK(bias.is_cuda() && bias.device() == x.device() && TORCH_CHECK(bias.is_cuda() && bias.device() == x.device() &&
@@ -214,23 +211,42 @@ std::tuple<torch::Tensor, torch::Tensor, torch::Tensor> linear_forward_fp8(
bias.numel() == n, bias.numel() == n,
"bias must be CUDA bf16 with shape [N]"); "bias must be CUDA bf16 with shape [N]");
} }
const auto f8opt = fmt ? torch::kFloat8_e5m2 : torch::kFloat8_e4m3fn;
auto x8 = torch::empty({m, k}, x_c.options().dtype(f8opt));
auto w8 = torch::empty({n, k}, x_c.options().dtype(f8opt));
auto amax_x = torch::zeros({1}, x.options().dtype(torch::kFloat32));
auto amax_w = torch::zeros({1}, x.options().dtype(torch::kFloat32));
auto out = torch::empty({m, n}, x_c.options());
auto quantize = [&](const torch::Tensor& src, torch::Tensor& dst,
const torch::Tensor& scale, torch::Tensor* amax) {
FP8Params qp;
pack_quantize_params(qp, src.data_ptr(), dst.data_ptr(), scale, amax,
src.numel());
if (fmt) {
fp8::launch_fp8_quantize<FP8Format::E5M2>(qp, stream.stream());
} else {
fp8::launch_fp8_quantize<FP8Format::E4M3>(qp, stream.stream());
}
};
quantize(x_c, x8, sx, &amax_x);
quantize(w_c, w8, sw, &amax_w);
FP8Params p; FP8Params p;
pack_gemm_params(p, x_c.data_ptr(), w_c.data_ptr(), out.data_ptr(), sx, sw, pack_gemm_params(p, x8.data_ptr(), w8.data_ptr(), out.data_ptr(), sx, sw,
nullptr, m, n, k); nullptr, m, n, k);
p.bias = has_bias ? reinterpret_cast<const __nv_bfloat16*>(bias.data_ptr()) if (fmt) {
: nullptr; fp8::launch_fp8_gemm<FP8Format::E5M2>(p, stream.stream());
p.amax_a = amax_x.data_ptr<float>();
p.amax_b = amax_w.data_ptr<float>();
if (has_bias) {
fp8::launch_fp8_fused<true, true>(p, stream.stream());
} else { } else {
fp8::launch_fp8_fused<false, true>(p, stream.stream()); fp8::launch_fp8_gemm<FP8Format::E4M3>(p, stream.stream());
} }
C10_CUDA_CHECK(cudaGetLastError()); C10_CUDA_CHECK(cudaGetLastError());
std::vector<int64_t> shape(x.sizes().begin(), x.sizes().end() - 1); std::vector<int64_t> shape(x.sizes().begin(), x.sizes().end() - 1);
shape.push_back(n); shape.push_back(n);
return {out.reshape(shape), amax_x, amax_w}; auto out_r = out.reshape(shape);
if (has_bias) out_r = out_r + bias;
return {out_r, amax_x, amax_w};
} }
std::tuple<torch::Tensor, torch::Tensor, torch::Tensor, torch::Tensor> std::tuple<torch::Tensor, torch::Tensor, torch::Tensor, torch::Tensor>
@@ -265,7 +281,6 @@ linear_backward_fp8(torch::Tensor g, torch::Tensor x, torch::Tensor w,
auto amax_g = torch::zeros({1}, g.options().dtype(torch::kFloat32)); auto amax_g = torch::zeros({1}, g.options().dtype(torch::kFloat32));
auto f8opt = fmt ? g.options().dtype(torch::kFloat8_e5m2) auto f8opt = fmt ? g.options().dtype(torch::kFloat8_e5m2)
: g.options().dtype(torch::kFloat8_e4m3fn); : g.options().dtype(torch::kFloat8_e4m3fn);
const auto q_fmt = fmt ? FP8Format::E5M2 : FP8Format::E4M3;
auto quantize = [&](const torch::Tensor& src, torch::Tensor& dst, auto quantize = [&](const torch::Tensor& src, torch::Tensor& dst,
const torch::Tensor& scale, torch::Tensor* amax) { const torch::Tensor& scale, torch::Tensor* amax) {
@@ -278,38 +293,46 @@ linear_backward_fp8(torch::Tensor g, torch::Tensor x, torch::Tensor w,
fp8::launch_fp8_quantize<FP8Format::E4M3>(qp, stream.stream()); fp8::launch_fp8_quantize<FP8Format::E4M3>(qp, stream.stream());
} }
}; };
auto pq = [&](const torch::Tensor& a8, const torch::Tensor& b8, // Explicit-transpose backward: the gradient/activation tensors keep their
torch::Tensor& out, const torch::Tensor& sa, // natural row-major layout, which the GEMM consumes transposed (W is
const torch::Tensor& sb, int64_t mm, int64_t nn, int64_t kk) { // [N,K] but dX contracts over N; x is [M,K] and g is [M,N] for dW), so
// the fp8 operands are transposed once and run through the fast non-trans
// pre-quantized GEMM. g is quantized once (amax_g measured here); its
// transpose is derived from the same g8 so both GEMMs share the value.
auto pq_n = [&](const torch::Tensor& a8, const torch::Tensor& b8,
torch::Tensor& out, const torch::Tensor& sa,
const torch::Tensor& sb, int64_t mm, int64_t nn,
int64_t kk) {
FP8Params gp; FP8Params gp;
pack_gemm_params(gp, a8.data_ptr(), b8.data_ptr(), out.data_ptr(), sa, pack_gemm_params(gp, a8.data_ptr(), b8.data_ptr(), out.data_ptr(), sa,
sb, nullptr, mm, nn, kk); sb, nullptr, mm, nn, kk);
if (fmt) { if (fmt) {
fp8::launch_fp8_pq<FP8Format::E5M2>(gp, stream.stream()); fp8::launch_fp8_gemm<FP8Format::E5M2>(gp, stream.stream());
} else { } else {
fp8::launch_fp8_pq<FP8Format::E4M3>(gp, stream.stream()); fp8::launch_fp8_gemm<FP8Format::E4M3>(gp, stream.stream());
} }
}; };
// dX = g @ W: quantize g once, then g8 @ w8^T. torch::Tensor g8;
if (masks[0]) { if (masks[0] || masks[1]) {
auto g8 = torch::empty({m, n}, f8opt); g8 = torch::empty({m, n}, f8opt);
quantize(g_c, g8, sg, &amax_g); quantize(g_c, g8, sg, &amax_g);
auto w_t = w_c.transpose(0, 1).contiguous(); // [K, N]
auto w8_t = torch::empty({k, n}, f8opt);
quantize(w_t, w8_t, sw, nullptr);
auto grad_input_2d = grad_input.reshape({m, k});
pq(g8, w8_t, grad_input_2d, sg, sw, m, k, n);
} }
// dW = g^T @ x: transposed layouts for both operands. // dX = g @ W: A = g8 [M,N] natural; B = W^T [K,N] (w8 transposed in fp8).
if (masks[0]) {
auto w8 = torch::empty({n, k}, f8opt);
quantize(w_c, w8, sw, nullptr);
auto w8T = w8.transpose(0, 1).contiguous(); // [K, N]
auto grad_input_2d = grad_input.reshape({m, k});
pq_n(g8, w8T, grad_input_2d, sg, sw, m, k, n);
}
// dW = g^T @ x: A = g^T [N,M] (g8 transposed); B = x^T [K,M].
if (masks[1]) { if (masks[1]) {
auto g_t = g_c.transpose(0, 1).contiguous(); // [N, M] auto g8T = g8.transpose(0, 1).contiguous(); // [N, M]
auto x_t = x_c.transpose(0, 1).contiguous(); // [K, M] auto x8 = torch::empty({m, k}, f8opt);
auto g8_t = torch::empty({n, m}, f8opt); quantize(x_c, x8, sx, nullptr);
auto x8_t = torch::empty({k, m}, f8opt); auto x8T = x8.transpose(0, 1).contiguous(); // [K, M]
quantize(g_t, g8_t, sg, nullptr); pq_n(g8T, x8T, grad_weight, sg, sx, n, k, m);
quantize(x_t, x8_t, sx, nullptr);
pq(g8_t, x8_t, grad_weight, sg, sx, n, k, m);
} }
if (!masks[0] && !masks[1]) { if (!masks[0] && !masks[1]) {
amax_g.copy_(g_c.abs().amax().to(torch::kFloat32)); amax_g.copy_(g_c.abs().amax().to(torch::kFloat32));
@@ -319,38 +342,7 @@ linear_backward_fp8(torch::Tensor g, torch::Tensor x, torch::Tensor w,
return {grad_input, grad_weight, grad_bias, amax_g}; return {grad_input, grad_weight, grad_bias, amax_g};
} }
torch::Tensor fp8_mm(torch::Tensor a, torch::Tensor b, torch::Tensor sx,
torch::Tensor sw) {
// BF16-in fused FP8 GEMM primitive (no bias, no amax): a @ b^T.
TORCH_CHECK(a.is_cuda() && b.is_cuda(), "CUDA tensors required");
TORCH_CHECK(a.scalar_type() == torch::kBFloat16 &&
b.scalar_type() == torch::kBFloat16,
"a and b must be bf16");
TORCH_CHECK(a.dim() == 2 && b.dim() == 2, "a and b must be 2D");
TORCH_CHECK(a.device() == b.device(), "a and b must be on the same device");
TORCH_CHECK(a.size(1) == b.size(1), "inner dim mismatch");
check_scale(sx, a, "sx");
check_scale(sw, a, "sw");
check_fp8_device(a);
const at::cuda::OptionalCUDAGuard guard(a.device());
auto stream = at::cuda::getCurrentCUDAStream();
auto a_c = a.contiguous();
auto b_c = b.contiguous();
int64_t m = a_c.size(0), n = b_c.size(0), k = a_c.size(1);
auto out = torch::empty({m, n}, a_c.options());
FP8Params p;
pack_gemm_params(p, a_c.data_ptr(), b_c.data_ptr(), out.data_ptr(), sx, sw,
nullptr, m, n, k);
fp8::launch_fp8_fused<false, false>(p, stream.stream());
C10_CUDA_CHECK(cudaGetLastError());
return out;
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def("fp8_mm", &fp8_mm, py::arg("a"), py::arg("b"), py::arg("sx"),
py::arg("sw"),
"Fused BF16 input, E4M3 MMA, FP32 accumulation, BF16 output GEMM");
m.def("quantize_bf16", &quantize_bf16, py::arg("x"), py::arg("scale"), m.def("quantize_bf16", &quantize_bf16, py::arg("x"), py::arg("scale"),
py::arg("fmt"), py::arg("fmt"),
"BF16 to FP8 (E4M3/E5M2) quantize with fused amax; returns (x8, amax)"); "BF16 to FP8 (E4M3/E5M2) quantize with fused amax; returns (x8, amax)");
@@ -361,7 +353,9 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
"1=fp8 e4m3 (requires out_scale)"); "1=fp8 e4m3 (requires out_scale)");
m.def("linear_forward_fp8", &linear_forward_fp8, py::arg("x"), m.def("linear_forward_fp8", &linear_forward_fp8, py::arg("x"),
py::arg("w"), py::arg("bias"), py::arg("sx"), py::arg("sw"), py::arg("w"), py::arg("bias"), py::arg("sx"), py::arg("sw"),
"Fused BF16-to-FP8 linear forward; returns (out, amax_x, amax_w)"); py::arg("fmt") = 0,
"Pure FP8 linear forward: quantize x/w, pre-quantized GEMM; "
"returns (out, amax_x, amax_w)");
m.def("linear_backward_fp8", &linear_backward_fp8, py::arg("g"), m.def("linear_backward_fp8", &linear_backward_fp8, py::arg("g"),
py::arg("x"), py::arg("w"), py::arg("masks"), py::arg("sg"), py::arg("x"), py::arg("w"), py::arg("masks"), py::arg("sg"),
py::arg("sw"), py::arg("sx"), py::arg("fmt"), py::arg("sw"), py::arg("sx"), py::arg("fmt"),
+14 -9
View File
@@ -11,7 +11,7 @@ AstrAI includes optional custom CUDA kernels for attention, rotary embedding, an
| `attn_paged_decode` | `attention/paged_decode.cu` | Paged KV cache decode attention | | `attn_paged_decode` | `attention/paged_decode.cu` | Paged KV cache decode attention |
| `attn_paged_prefill` | `attention/paged_prefill.cu` | Paged KV cache prefill attention (ragged batch) | | `attn_paged_prefill` | `attention/paged_prefill.cu` | Paged KV cache prefill attention (ragged batch) |
| `rotary_emb` | `rotary/rotary_emb.cu` | Fused rotary embedding (cos/sin lookup + rotation) | | `rotary_emb` | `rotary/rotary_emb.cu` | Fused rotary embedding (cos/sin lookup + rotation) |
| `fp8_mm` | `fp8/mm.cu` | FP8 quantization + tensor-core GEMM (sm_89+) | | `fp8_ops` | `fp8/ops.cu` | FP8 quantization + tensor-core GEMM (sm_89+) |
Additionally, optimized `.cuh` variants with tensor-core MMA (Matrix Multiply-Accumulate) exist: Additionally, optimized `.cuh` variants with tensor-core MMA (Matrix Multiply-Accumulate) exist:
@@ -39,7 +39,7 @@ Standalone benchmark vs torch complex-multiply (48 calls = 24 layers × q+k): 6-
### FP8 GEMM / Linear Kernel ### FP8 GEMM / Linear Kernel
The `fp8_mm` family (`csrc/kernels/fp8/`) accelerates bf16 linear layers by The `fp8_ops` family (`csrc/kernels/fp8/`) accelerates bf16 linear layers by
quantizing to FP8 and running tensor-core GEMMs (**requires sm_89+**; fp8 quantizing to FP8 and running tensor-core GEMMs (**requires sm_89+**; fp8
`mma.sync.m16n8k32` only exists on Ada/Hopper). It follows the same three-layer `mma.sync.m16n8k32` only exists on Ada/Hopper). It follows the same three-layer
style as attention, but split into **three** files: style as attention, but split into **three** files:
@@ -47,8 +47,8 @@ style as attention, but split into **three** files:
| File | Role | | File | Role |
|------|------| |------|------|
| `fp8/common.h` | `FP8Format` enum (E4M3/E5M2), `Fp8GemmTraits<Fmt, BlockM, BlockN, K, Stages>`, `FP8Params` POD — no torch | | `fp8/common.h` | `FP8Format` enum (E4M3/E5M2), `Fp8GemmTraits<Fmt, BlockM, BlockN, K, Stages>`, `FP8Params` POD — no torch |
| `fp8/gemm.cuh` | pure-CUDA device code: `fp8_quantize_kernel` (BF16→FP8 + amax), `fp8_pq_gemm_kernel` (pre-quantized GEMM, 128×64 CTA / 64×16 warp / 3-stage cp.async) — no torch | | `fp8/gemm.cuh` | pure-CUDA device code: `fp8_quantize_kernel` (BF16→FP8 + amax), `fp8_gemm_kernel` (pre-quantized GEMM, 128×64 CTA / 64×16 warp / 3-stage cp.async) — no torch |
| `fp8/mm.cu` | binding only: `check_fp8_device` (sm_89+), param packing, launch dispatch, pybind → module `fp8_mm` | | `fp8/ops.cu` | binding only: `check_fp8_device` (sm_89+), param packing, launch dispatch, pybind → module `fp8_ops` |
Scale semantics follow `torch._scaled_mm` (quantization step size: divide by Scale semantics follow `torch._scaled_mm` (quantization step size: divide by
`scale`; the kernel computes the reciprocal internally — the interface never `scale`; the kernel computes the reciprocal internally — the interface never
@@ -97,7 +97,7 @@ unset, `setup.py` auto-detects the real GPU capability through
- **sm_80+** (Ampere and later): enables the tensor-core MMA path - **sm_80+** (Ampere and later): enables the tensor-core MMA path
(`mma.sync.m16n8k16.bf16` for bf16 attention, `mma.sync.m16n8k32` for FP8). (`mma.sync.m16n8k16.bf16` for bf16 attention, `mma.sync.m16n8k32` for FP8).
- **sm_89+**: required for the FP8 family (`fp8_mm`) — FP8 tensor-core - **sm_89+**: required for the FP8 family (`fp8_ops`) — FP8 tensor-core
instructions only exist on Ada/Hopper and newer. instructions only exist on Ada/Hopper and newer.
- **`-DASTRAI_NO_MMA`** is a manual escape hatch only — the build never defines - **`-DASTRAI_NO_MMA`** is a manual escape hatch only — the build never defines
it automatically. To disable the MMA path, add it to `NVCC_FLAGS` yourself; it automatically. To disable the MMA path, add it to `NVCC_FLAGS` yourself;
@@ -246,9 +246,14 @@ with attn_backend(ATTN_BACKEND.CUDA):
The `attention(...)` policy entry point falls back to `FlashAttnBackend` (when The `attention(...)` policy entry point falls back to `FlashAttnBackend` (when
flash-attn is installed and supports the call) or `TorchNativeBackend` when the flash-attn is installed and supports the call) or `TorchNativeBackend` when the
automatically selected CUDA backend cannot handle an input. An explicit automatically selected CUDA backend cannot handle an input. Resolution
`ASTR_BACKEND` or `attn_backend(...)` selection is strict and raises instead of precedence is: explicit `attn_backend(...)` context > `ASTR_BACKEND` env >
silently switching implementations. default. An explicit `attn_backend(...)` selection is strict and raises instead
of silently switching implementations; the env override (and the implicit
default) fall back to the first compatible backend when incapable. Training
calls (`fwd=None`, no KV cache) resolve by capability: the CUDA cache kernels
cannot run without a cache, so they fall back to flash (mask-free/causal calls
only) and finally to torch SDPA.
### Rotary Backend ### Rotary Backend
@@ -372,7 +377,7 @@ csrc/
│ │ └── paged_prefill.cu # → module attn_paged_prefill │ │ └── paged_prefill.cu # → module attn_paged_prefill
│ ├── rotary/ │ ├── rotary/
│ │ └── rotary_emb.cu # rotary embedding (kernel + binding in one file) → module rotary_emb │ │ └── rotary_emb.cu # rotary embedding (kernel + binding in one file) → module rotary_emb
│ └── fp8/ # FP8 family (module name fp8_mm) │ └── fp8/ # FP8 family (module name fp8_ops)
│ ├── common.h # FP8Format enum, Fp8GemmTraits, FP8Params POD (no torch) │ ├── common.h # FP8Format enum, Fp8GemmTraits, FP8Params POD (no torch)
│ ├── gemm.cuh # FP8 device code: quantize + pre-quantized GEMM kernels (no torch) │ ├── gemm.cuh # FP8 device code: quantize + pre-quantized GEMM kernels (no torch)
│ └── mm.cu # binding only: validation, param packing, launch dispatch, pybind │ └── mm.cu # binding only: validation, param packing, launch dispatch, pybind
+1 -1
View File
@@ -17,7 +17,7 @@ CUDA_AVAIL = torch.cuda.is_available()
KERNEL_AVAIL = CUDA_AVAIL and all(is_available(k) for k in KERNEL_NAMES) KERNEL_AVAIL = CUDA_AVAIL and all(is_available(k) for k in KERNEL_NAMES)
FP8_AVAIL = ( FP8_AVAIL = (
CUDA_AVAIL CUDA_AVAIL
and is_available("fp8_mm") and is_available("fp8_ops")
and torch.cuda.get_device_capability() >= (8, 9) and torch.cuda.get_device_capability() >= (8, 9)
) )
skip_no_cuda = pytest.mark.skipif(not CUDA_AVAIL, reason="CUDA not available") skip_no_cuda = pytest.mark.skipif(not CUDA_AVAIL, reason="CUDA not available")
+7 -6
View File
@@ -1,6 +1,7 @@
"""FP8 primitives: kernel-level (CUDA) and policy-level (CPU-verifiable) tests. """FP8 primitives: kernel-level (CUDA) and policy-level (CPU-verifiable) tests.
The kernel-level tests exercise the fused and pre-quantized CUDA paths; the The kernel-level tests exercise the pure FP8 path (quantize_bf16 + mm_fp8 for
the forward GEMM, quantize + pre-quantized GEMMs for the backward); the
policy-level tests (recipes, autocast context, per-tensor meta, CPU fallbacks policy-level tests (recipes, autocast context, per-tensor meta, CPU fallbacks
of the custom ops) run without a GPU. of the custom ops) run without a GPU.
""" """
@@ -16,7 +17,6 @@ from astrai.extension.fp8 import (
fp8_autocast, fp8_autocast,
fp8_state, fp8_state,
) )
from astrai.extension.loader import get_module
from astrai.extension.ops.fp8 import ( from astrai.extension.ops.fp8 import (
linear_backward_fp8, linear_backward_fp8,
linear_forward_fp8, linear_forward_fp8,
@@ -44,14 +44,15 @@ def _quantize(tensor, scale):
("m", "n", "k"), ("m", "n", "k"),
[(16, 8, 32), (17, 9, 33), (31, 15, 64), (32, 48, 96)], [(16, 8, 32), (17, 9, 33), (31, 15, 64), (32, 48, 96)],
) )
def test_fused_fp8_mma_matches_explicit_quantization(m, n, k): def test_fp8_mm_matches_explicit_quantization(m, n, k):
torch.manual_seed(m + n + k) torch.manual_seed(m + n + k)
a = torch.randn(m, k, device="cuda", dtype=torch.bfloat16) a = torch.randn(m, k, device="cuda", dtype=torch.bfloat16)
b = torch.randn(n, k, device="cuda", dtype=torch.bfloat16) b = torch.randn(n, k, device="cuda", dtype=torch.bfloat16)
scale_a = _scale(a) scale_a = _scale(a)
scale_b = _scale(b) scale_b = _scale(b)
a8, _ = quantize_bf16(a, scale_a, "e4m3")
out = get_module("fp8_mm").fp8_mm(a, b, scale_a, scale_b) b8, _ = quantize_bf16(b, scale_b, "e4m3")
out = mm_fp8(a8, b8, scale_a, scale_b)
expected = ( expected = (
_quantize(a, scale_a) @ _quantize(b, scale_b).t() * scale_a * scale_b _quantize(a, scale_a) @ _quantize(b, scale_b).t() * scale_a * scale_b
).to(torch.bfloat16) ).to(torch.bfloat16)
@@ -86,7 +87,7 @@ def test_quantize_bf16_e5m2_format():
@skip_no_fp8 @skip_no_fp8
def test_fused_fp8_linear_forward_and_backward(): def test_fp8_linear_forward_and_backward():
torch.manual_seed(7) torch.manual_seed(7)
m, n, k = 19, 13, 37 m, n, k = 19, 13, 37
x = torch.randn(m, k, device="cuda", dtype=torch.bfloat16) x = torch.randn(m, k, device="cuda", dtype=torch.bfloat16)