refactor: reorganize CUDA kernels into per-family directories

- move attention kernels to csrc/kernels/attention/ and rotary to rotary/
- add shared common/mma.cuh (mma_sync, ldmatrix) and device.cuh (sm checks)
- split fp8_mm into three-layer fp8/common.h, gemm.cuh, mm.cu
- fix fused FP8 GEMM ldmatrix lane indexing to fix OOB shared reads
- update extension ops, loader, and kernel tests
This commit is contained in:
2026-08-22 20:40:31 +08:00
parent cb21af38ba
commit 16a55bb474
30 changed files with 1956 additions and 1235 deletions
+62
View File
@@ -0,0 +1,62 @@
#pragma once
#include <cuda_bf16.h>
#include <cuda_fp8.h>
#include <cuda_runtime.h>
#include <cstdint>
// Compile-time FP8 format: E4M3 (forward / high precision, max 448) or
// E5M2 (gradient / large dynamic range, max 57344).
enum class FP8Format : int {
E4M3 = 0,
E5M2 = 1,
};
// Compile-time tile configuration, mirroring KernelTraits<HEAD_DIM, BC,
// WARPS, STAGES> in the attention kernels. `Fmt` selects the FP8 conversion
// and the MMA PTX mnemonic; the remaining parameters shape the CTA tile and
// the cp.async pipeline depth.
template <FP8Format Fmt, int BlockM, int BlockN, int K, int Stages>
struct Fp8GemmTraits {
static constexpr FP8Format kFormat = Fmt;
static constexpr int kBlockM = BlockM;
static constexpr int kBlockN = BlockN;
static constexpr int kK = K;
static constexpr int kStages = Stages;
static constexpr bool kIsE5M2 = (Fmt == FP8Format::E5M2);
static constexpr __nv_fp8_interpretation_t kNvFormat =
kIsE5M2 ? __NV_E5M2 : __NV_E4M3;
static constexpr float kFp8Max = kIsE5M2 ? 57344.0f : 448.0f;
// Saturated float -> FP8 conversion for this format.
__device__ __forceinline__ static unsigned char cvt(float f) {
return static_cast<unsigned char>(
__nv_cvt_float_to_fp8(f, __NV_SATFINITE, kNvFormat));
}
};
// Unified GEMM parameter POD, mirroring AttentionParams: one struct flows
// through quantize / fused / pre-quantized kernels. Each kernel touches only
// the fields it needs; buffers are raw pointers packed by the torch binding.
struct FP8Params {
// Inputs: a/b are BF16 for the fused (quantize-in-GEMM) path, FP8 for
// the pre-quantized path. Scales are quantization steps (device scalars).
const void* __restrict__ a_ptr;
const void* __restrict__ b_ptr;
const float* __restrict__ scale_a;
const float* __restrict__ scale_b;
// Output: BF16 or FP8 (E4M3). out_scale is the output quantization step
// (FP8 output only).
void* __restrict__ out_ptr;
const float* __restrict__ out_scale;
// Fused forward extras: bias (may be null) and amax slots (may be null).
const __nv_bfloat16* __restrict__ bias;
float* __restrict__ amax_a;
float* __restrict__ amax_b;
// Shapes. total is only used by the elementwise quantize kernel.
int64_t m, n, k;
int64_t total;
};
+668
View File
@@ -0,0 +1,668 @@
#pragma once
// FP8 GEMM device code — pure CUDA, no torch. Mirrors the attention kernel
// layout (attn_*_mma.cuh): kernels take the FP8Params POD, tile shape and
// FP8 format ride on compile-time template parameters, and launchers are
// plain functions usable from both the torch binding and pure C tests.
#include <cuda_bf16.h>
#include <cuda_fp8.h>
#include <cuda_runtime.h>
#include <type_traits>
#include "common.h"
#include "../common/mma.cuh"
namespace fp8 {
// m16n8k32 (see astrai::mma_shape<fp8 type>::k in common/mma.cuh)
constexpr int kMmaK = 32;
constexpr int kWarps = 8; // 128x64 CTA = 8 warps
// Map the FP8Format enum to the CUDA fp8 element type consumed by mma_sync.
template <FP8Format Fmt>
struct fp8_input {
using type = __nv_fp8_e4m3;
};
template <>
struct fp8_input<FP8Format::E5M2> {
using type = __nv_fp8_e5m2;
};
// ---------------------------------------------------------------------------
// 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);
// instantiate it with fp8_input<Fmt>::type. Accumulates in-place: callers
// pass the same accumulator array as both `d` and `c`.
__device__ __forceinline__ void atomic_max_float(float* destination,
float value) {
if (destination)
atomicMax(reinterpret_cast<unsigned*>(destination),
__float_as_uint(value));
}
__device__ __forceinline__ float warp_reduce_max(float value) {
#pragma unroll
for (int offset = 16; offset; offset >>= 1) {
value = fmaxf(value, __shfl_xor_sync(0xffffffffu, value, offset));
}
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.
template <typename T>
__device__ __forceinline__ void cp_async_16b(T* destination,
const T* 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));
}
// 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.
// ---------------------------------------------------------------------------
template <FP8Format Fmt>
__global__ void fp8_quantize_kernel(FP8Params p) {
const float inv = 1.0f / *p.scale_a;
const auto* x = reinterpret_cast<const __nv_bfloat16*>(p.a_ptr);
void* x8 = p.out_ptr;
float* amax = p.amax_a;
float local_amax = 0.0f;
const int64_t stride = (int64_t)blockDim.x * gridDim.x;
for (int64_t i = blockIdx.x * blockDim.x + threadIdx.x; i < p.total;
i += stride) {
const float f = __bfloat162float(x[i]);
local_amax = fmaxf(local_amax, fabsf(f));
const float q = f * inv;
if constexpr (Fmt == FP8Format::E5M2) {
reinterpret_cast<__nv_fp8_e5m2*>(x8)[i] = __nv_fp8_e5m2(q);
} else {
reinterpret_cast<__nv_fp8_e4m3*>(x8)[i] = __nv_fp8_e4m3(q);
}
}
if (amax) {
local_amax = warp_reduce_max(local_amax);
__shared__ float slots[32];
if ((threadIdx.x & 31) == 0) slots[threadIdx.x >> 5] = local_amax;
__syncthreads();
if (threadIdx.x == 0) {
float v = 0.0f;
for (int w = 0; w < (blockDim.x >> 5); ++w) v = fmaxf(v, slots[w]);
atomic_max_float(amax, v);
}
}
}
// ---------------------------------------------------------------------------
// Fused kernel: BF16 A/B -> inline E4M3 quantize -> ldmatrix fragments ->
// 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
// tile is compact (row = kK bytes) so MMA fragments read directly.
// ---------------------------------------------------------------------------
template <typename Traits, bool OutFp8 = false>
__global__ void fp8_pq_gemm_kernel(FP8Params p) {
using T8 = std::conditional_t<Traits::kIsE5M2, __nv_fp8_e5m2, __nv_fp8_e4m3>;
constexpr int kBlockM = Traits::kBlockM;
constexpr int kBlockN = Traits::kBlockN;
constexpr int kK = Traits::kK;
constexpr int kStages = Traits::kStages;
__shared__ __align__(16) T8 a_tile[kStages][kBlockM][kK];
__shared__ __align__(16) T8 b_tile[kStages][kBlockN][kK];
const auto* a = reinterpret_cast<const T8*>(p.a_ptr);
const auto* b = reinterpret_cast<const T8*>(p.b_ptr);
auto* out_bf16 = reinterpret_cast<__nv_bfloat16*>(p.out_ptr);
auto* out_fp8 = reinterpret_cast<__nv_fp8_e4m3*>(p.out_ptr);
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 * 64 + group;
const int64_t output_col =
blockIdx.x * kBlockN + warp_n * 16 + thread_in_group * 2;
const float sa = *p.scale_a;
const float sb = *p.scale_b;
float acc[4 * 4 * 2] = {};
// One A chunk (16 FP8) per thread covers the 128x32 tile; the first 128
// threads issue the 64x32 B chunks.
auto load_tile = [&](int stage, int64_t k_base) {
const int r0 = tid >> 1;
const int c0 = (tid & 1) * 16;
const bool full_chunk = k_base + c0 + 15 < k;
const int64_t a_row = blockIdx.y * kBlockM + r0;
auto* a_dst = &a_tile[stage][r0][c0];
const auto* a_ptr = a + a_row * k + k_base + c0;
const bool full_a = a_row < m && full_chunk;
const bool aligned_a =
(reinterpret_cast<uintptr_t>(a_ptr) & 15) == 0;
if (full_a && aligned_a) {
cp_async_16b(a_dst, a_ptr, true);
} else {
#pragma unroll
for (int i = 0; i < 16; ++i) {
a_dst[i] = a_row < m && k_base + c0 + i < k
? a_ptr[i]
: T8(0.0f);
}
}
if (tid < 128) {
const int64_t b_row = blockIdx.x * kBlockN + r0;
auto* b_dst = &b_tile[stage][r0][c0];
const auto* b_ptr = b + b_row * k + k_base + c0;
const bool full_b = b_row < n && full_chunk;
const bool aligned_b =
(reinterpret_cast<uintptr_t>(b_ptr) & 15) == 0;
if (full_b && aligned_b) {
cp_async_16b(b_dst, b_ptr, true);
} else {
#pragma unroll
for (int i = 0; i < 16; ++i) {
b_dst[i] = b_row < n && k_base + c0 + i < k
? b_ptr[i]
: T8(0.0f);
}
}
}
};
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);
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;");
}
// Barrier 1: every thread's cp.async for this stage is complete
// before any thread reads tiles written by other threads.
__syncthreads();
#pragma unroll
for (int k_seg = 0; k_seg < kK / kMmaK; ++k_seg) {
const int frag_col = thread_in_group * 4 + k_seg * 32;
#pragma unroll
for (int nt = 0; nt < 2; ++nt) {
const int b_row = warp_n * 16 + nt * 8 + group;
unsigned b_frag[2];
b_frag[0] = *reinterpret_cast<const unsigned*>(
&b_tile[stage][b_row][frag_col]);
b_frag[1] = *reinterpret_cast<const unsigned*>(
&b_tile[stage][b_row][frag_col + 16]);
#pragma unroll
for (int mt = 0; mt < 4; ++mt) {
const int a_row0 = warp_m * 64 + mt * 16 + group;
unsigned a_frag[4];
a_frag[0] = *reinterpret_cast<const unsigned*>(
&a_tile[stage][a_row0][frag_col]);
a_frag[1] = *reinterpret_cast<const unsigned*>(
&a_tile[stage][a_row0 + 8][frag_col]);
a_frag[2] = *reinterpret_cast<const unsigned*>(
&a_tile[stage][a_row0][frag_col + 16]);
a_frag[3] = *reinterpret_cast<const unsigned*>(
&a_tile[stage][a_row0 + 8][frag_col + 16]);
astrai::mma_sync<typename fp8_input<Traits::kFormat>::type>(
acc + (nt * 4 + mt) * 4,
a_frag, b_frag, acc + (nt * 4 + mt) * 4);
}
}
}
// Barrier 2: every thread finished reading this stage's tiles before
// the prefetch for the (i+3)-th tile overwrites them.
__syncthreads();
if (tile_index + 3 < tile_count) {
load_tile(stage, (tile_index + 3) * kK);
asm volatile("cp.async.commit_group;");
}
}
const float output_scale = sa * sb;
const float o8_scale = OutFp8 ? output_scale * *p.out_scale : 0.0f;
#pragma unroll
for (int nt = 0; nt < 2; ++nt) {
const int64_t col = output_col + nt * 8;
// Per-row store: FP8 packs two adjacent columns into one 16-bit
// write; the BF16 path writes two scalars. Boundary columns fall
// back to a scalar convert so the pack never crosses the row edge.
auto store_out = [&](int64_t row, float v0, float v1) {
if (row >= m) return;
if constexpr (OutFp8) {
if (col + 1 < n) {
*reinterpret_cast<unsigned short*>(out_fp8 + row * n + col) =
static_cast<unsigned short>(__nv_cvt_float2_to_fp8x2(
make_float2(v0 * o8_scale, v1 * o8_scale),
__NV_SATFINITE, __NV_E4M3));
} else {
out_fp8[row * n + col] = __nv_fp8_e4m3(v0 * o8_scale);
}
} else {
out_bf16[row * n + col] = __float2bfloat16(v0 * output_scale);
if (col + 1 < n)
out_bf16[row * n + col + 1] =
__float2bfloat16(v1 * output_scale);
}
};
#pragma unroll
for (int mt = 0; mt < 4; ++mt) {
const int64_t row0 = row_base + mt * 16;
float* tile_acc = acc + (nt * 4 + mt) * 4;
if (col < n) {
store_out(row0, tile_acc[0], tile_acc[1]);
store_out(row0 + 8, tile_acc[2], tile_acc[3]);
}
}
}
}
// ---------------------------------------------------------------------------
// 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>
void launch_fp8_quantize(const FP8Params& p, cudaStream_t stream) {
constexpr int kThreads = 256;
const int64_t blocks = (p.total + kThreads - 1) / kThreads;
fp8_quantize_kernel<Fmt><<<blocks, kThreads, 0, stream>>>(p);
}
template <bool AddBias, bool TrackAmax>
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>
void launch_fp8_pq(const FP8Params& p, cudaStream_t stream) {
using Traits = PqTraits<Fmt>;
dim3 grid((p.n + Traits::kBlockN - 1) / Traits::kBlockN,
(p.m + Traits::kBlockM - 1) / Traits::kBlockM);
fp8_pq_gemm_kernel<Traits, OutFp8><<<grid, kWarps * 32, 0, stream>>>(p);
}
} // namespace fp8
+369
View File
@@ -0,0 +1,369 @@
// FP8 GEMM torch binding: tensor validation, FP8Params packing, template
// dispatch and pybind. Device code lives in gemm.cuh (pure CUDA) —
// mirroring the attn_*.cu / attn_*_mma.cuh split of the attention kernels.
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAGuard.h>
#include <cuda_bf16.h>
#include <cstdint>
#include <mutex>
#include <tuple>
#include <unordered_map>
#include "gemm.cuh"
#include "../common/device.cuh"
namespace {
// FP8Format / FP8Params live in the global namespace (common.h); the
// launchers live in fp8:: (gemm.cuh).
void check_fp8_device(const torch::Tensor& tensor) {
static std::mutex mutex;
static std::unordered_map<int, bool> supported;
const int device = tensor.device().index();
{
std::lock_guard<std::mutex> lock(mutex);
auto cached = supported.find(device);
if (cached != supported.end()) {
TORCH_CHECK(cached->second,
"fused FP8 MMA requires compute capability 8.9 or newer");
return;
}
}
const auto* properties = at::cuda::getDeviceProperties(device);
const bool is_supported =
astrai::sm_at_least(properties->major, properties->minor,
astrai::kMinSmForFp8Major,
astrai::kMinSmForFp8Minor);
{
std::lock_guard<std::mutex> lock(mutex);
supported.emplace(device, is_supported);
}
TORCH_CHECK(is_supported,
"fused FP8 MMA requires compute capability 8.9 or newer");
}
void check_scale(const torch::Tensor& scale, const torch::Tensor& input,
const char* name) {
TORCH_CHECK(scale.is_cuda() && scale.device() == input.device() &&
scale.scalar_type() == torch::kFloat32 && scale.numel() == 1,
name, " must be a CUDA float32 scalar on the input device");
}
// ---- FP8Params packing (mirrors attention/entry_utils.cuh pack_* helpers) ----
void pack_gemm_params(FP8Params& p, const void* a, const void* b, void* out,
const torch::Tensor& sa, const torch::Tensor& sb,
const torch::Tensor* out_scale, int64_t m, int64_t n,
int64_t k) {
p.a_ptr = a;
p.b_ptr = b;
p.out_ptr = out;
p.scale_a = sa.data_ptr<float>();
p.scale_b = sb.data_ptr<float>();
p.out_scale = out_scale ? out_scale->data_ptr<float>() : nullptr;
p.bias = nullptr;
p.amax_a = nullptr;
p.amax_b = nullptr;
p.m = m;
p.n = n;
p.k = k;
p.total = 0;
}
void pack_quantize_params(FP8Params& p, const void* x, void* x8,
const torch::Tensor& scale, torch::Tensor* amax,
int64_t total) {
p.a_ptr = x;
p.b_ptr = nullptr;
p.out_ptr = x8;
p.scale_a = scale.data_ptr<float>();
p.scale_b = nullptr;
p.out_scale = nullptr;
p.bias = nullptr;
p.amax_a = amax ? amax->data_ptr<float>() : nullptr;
p.amax_b = nullptr;
p.m = p.n = p.k = 0;
p.total = total;
}
} // namespace
// ---------------------------------------------------------------------------
// Entry points
// ---------------------------------------------------------------------------
std::tuple<torch::Tensor, torch::Tensor> quantize_bf16(torch::Tensor x,
torch::Tensor scale,
int64_t fmt) {
// BF16 -> FP8 quantize with fused amax. fmt: 0 = E4M3, 1 = E5M2.
// Returns (x8, amax); the caller never clears amax (zero-initialized here).
TORCH_CHECK(x.is_cuda() && scale.is_cuda(), "CUDA tensors required");
TORCH_CHECK(x.scalar_type() == torch::kBFloat16, "x must be bf16");
check_scale(scale, x, "scale");
check_fp8_device(x);
const at::cuda::OptionalCUDAGuard guard(x.device());
auto stream = at::cuda::getCurrentCUDAStream();
auto x_c = x.contiguous();
auto x8 = torch::empty_like(
x_c, x_c.options().dtype(fmt ? torch::kFloat8_e5m2
: torch::kFloat8_e4m3fn));
auto amax = torch::zeros({1}, x_c.options().dtype(torch::kFloat32));
FP8Params p;
pack_quantize_params(p, x_c.data_ptr(), x8.data_ptr(), scale, &amax,
x_c.numel());
if (fmt) {
fp8::launch_fp8_quantize<FP8Format::E5M2>(p, stream.stream());
} else {
fp8::launch_fp8_quantize<FP8Format::E4M3>(p, stream.stream());
}
C10_CUDA_CHECK(cudaGetLastError());
return {x8, amax};
}
torch::Tensor mm_fp8(torch::Tensor a, torch::Tensor b, torch::Tensor sa,
torch::Tensor sb, int64_t out_dtype,
c10::optional<torch::Tensor> out_scale) {
// Pre-quantized FP8 GEMM: out = a @ b^T * (sa * sb), FP32 accumulation.
// out_dtype: 0 = BF16 (default), 1 = FP8 E4M3 (requires out_scale, the
// quantization step for the output — mirrors torch._scaled_mm's
// out_dtype / scale_result). Both operands share the same FP8 format.
TORCH_CHECK(a.is_cuda() && b.is_cuda(), "CUDA tensors required");
TORCH_CHECK(a.scalar_type() == torch::kFloat8_e4m3fn ||
a.scalar_type() == torch::kFloat8_e5m2,
"a and b must be fp8 (e4m3fn or e5m2)");
TORCH_CHECK(a.scalar_type() == b.scalar_type(),
"a and b must share the same fp8 format");
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(sa, a, "sa");
check_scale(sb, a, "sb");
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), k = a_c.size(1), n = b_c.size(0);
const bool out_fp8 = (out_dtype == 1);
TORCH_CHECK(out_dtype == 0 || out_fp8,
"out_dtype must be 0 (bf16) or 1 (fp8 e4m3)");
torch::Tensor os;
if (out_fp8) {
TORCH_CHECK(out_scale.has_value(), "fp8 output requires out_scale");
os = out_scale.value();
check_scale(os, a, "out_scale");
}
auto out = torch::empty(
{m, n},
out_fp8 ? a_c.options().dtype(torch::kFloat8_e4m3fn)
: a_c.options().dtype(torch::kBFloat16));
FP8Params p;
pack_gemm_params(p, a_c.data_ptr(), b_c.data_ptr(), out.data_ptr(), sa, sb,
out_fp8 ? &os : nullptr, m, n, k);
if (a.scalar_type() == torch::kFloat8_e4m3fn) {
if (out_fp8) {
fp8::launch_fp8_pq<FP8Format::E4M3, true>(p, stream.stream());
} else {
fp8::launch_fp8_pq<FP8Format::E4M3>(p, stream.stream());
}
} else {
if (out_fp8) {
fp8::launch_fp8_pq<FP8Format::E5M2, true>(p, stream.stream());
} else {
fp8::launch_fp8_pq<FP8Format::E5M2>(p, stream.stream());
}
}
C10_CUDA_CHECK(cudaGetLastError());
return out;
}
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 sw) {
// Fused BF16 -> E4M3 -> MMA -> BF16 linear forward. amax_x / amax_w are
// zero-initialized here and returned (caller does not clear them).
TORCH_CHECK(x.is_cuda() && w.is_cuda(), "CUDA tensors required");
TORCH_CHECK(x.scalar_type() == torch::kBFloat16 &&
w.scalar_type() == torch::kBFloat16,
"x and w must be bf16");
TORCH_CHECK(x.device() == w.device(), "x and w must be on the same device");
check_scale(sx, x, "sx");
check_scale(sw, x, "sw");
check_fp8_device(x);
const at::cuda::OptionalCUDAGuard guard(x.device());
auto stream = at::cuda::getCurrentCUDAStream();
auto x_c = x.reshape({-1, w.size(1)}).contiguous();
auto w_c = w.contiguous();
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");
// 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;
if (has_bias) {
TORCH_CHECK(bias.is_cuda() && bias.device() == x.device() &&
bias.scalar_type() == torch::kBFloat16 &&
bias.numel() == n,
"bias must be CUDA bf16 with shape [N]");
}
FP8Params p;
pack_gemm_params(p, x_c.data_ptr(), w_c.data_ptr(), out.data_ptr(), sx, sw,
nullptr, m, n, k);
p.bias = has_bias ? reinterpret_cast<const __nv_bfloat16*>(bias.data_ptr())
: nullptr;
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 {
fp8::launch_fp8_fused<false, true>(p, stream.stream());
}
C10_CUDA_CHECK(cudaGetLastError());
std::vector<int64_t> shape(x.sizes().begin(), x.sizes().end() - 1);
shape.push_back(n);
return {out.reshape(shape), amax_x, amax_w};
}
std::tuple<torch::Tensor, torch::Tensor, torch::Tensor, torch::Tensor>
linear_backward_fp8(torch::Tensor g, torch::Tensor x, torch::Tensor w,
std::vector<int64_t> masks, torch::Tensor sg,
torch::Tensor sw, torch::Tensor sx, int64_t fmt) {
// Pre-quantized FP8 backward: grad is quantized once (E4M3 or E5M2 per
// `fmt`), then dX / dW run as FP8 tensor-core GEMMs sharing g8.
// Returns (grad_input, grad_weight, grad_bias, amax_g).
TORCH_CHECK(g.is_cuda() && x.is_cuda() && w.is_cuda(), "CUDA tensors required");
TORCH_CHECK(g.scalar_type() == torch::kBFloat16 &&
x.scalar_type() == torch::kBFloat16 &&
w.scalar_type() == torch::kBFloat16,
"g, x, and w must be bf16");
TORCH_CHECK(g.device() == x.device() && g.device() == w.device(),
"g, x, and w must be on the same device");
TORCH_CHECK(masks.size() == 3, "masks must contain three values");
check_fp8_device(g);
const at::cuda::OptionalCUDAGuard guard(g.device());
auto stream = at::cuda::getCurrentCUDAStream();
auto g_c = g.reshape({-1, w.size(0)}).contiguous(); // [M, N]
auto x_c = x.reshape({-1, x.size(-1)}).contiguous(); // [M, K]
auto w_c = w.contiguous(); // [N, K]
int64_t m = g_c.size(0), n = w_c.size(0), k = w_c.size(1);
TORCH_CHECK(x_c.size(0) == m && x_c.size(1) == k && g_c.size(1) == n,
"backward shape mismatch");
auto grad_input = torch::empty_like(x);
auto grad_weight = torch::empty_like(w);
auto grad_bias = torch::empty({0}, g.options());
auto amax_g = torch::zeros({1}, g.options().dtype(torch::kFloat32));
auto f8opt = fmt ? g.options().dtype(torch::kFloat8_e5m2)
: g.options().dtype(torch::kFloat8_e4m3fn);
const auto q_fmt = fmt ? FP8Format::E5M2 : FP8Format::E4M3;
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());
}
};
auto pq = [&](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;
pack_gemm_params(gp, a8.data_ptr(), b8.data_ptr(), out.data_ptr(), sa,
sb, nullptr, mm, nn, kk);
if (fmt) {
fp8::launch_fp8_pq<FP8Format::E5M2>(gp, stream.stream());
} else {
fp8::launch_fp8_pq<FP8Format::E4M3>(gp, stream.stream());
}
};
// dX = g @ W: quantize g once, then g8 @ w8^T.
if (masks[0]) {
auto g8 = torch::empty({m, n}, f8opt);
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.
if (masks[1]) {
auto g_t = g_c.transpose(0, 1).contiguous(); // [N, M]
auto x_t = x_c.transpose(0, 1).contiguous(); // [K, M]
auto g8_t = torch::empty({n, m}, f8opt);
auto x8_t = torch::empty({k, m}, f8opt);
quantize(g_t, g8_t, sg, nullptr);
quantize(x_t, x8_t, sx, nullptr);
pq(g8_t, x8_t, grad_weight, sg, sx, n, k, m);
}
if (!masks[0] && !masks[1]) {
amax_g.copy_(g_c.abs().amax().to(torch::kFloat32));
}
C10_CUDA_CHECK(cudaGetLastError());
if (masks[2]) grad_bias = g_c.sum(0).to(g.scalar_type());
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) {
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"),
py::arg("fmt"),
"BF16 to FP8 (E4M3/E5M2) quantize with fused amax; returns (x8, amax)");
m.def("mm_fp8", &mm_fp8, py::arg("a"), py::arg("b"), py::arg("sa"),
py::arg("sb"), py::arg("out_dtype") = 0,
py::arg("out_scale") = py::none(),
"Pre-quantized FP8 GEMM: a @ b^T * (sa * sb); out_dtype 0=bf16, "
"1=fp8 e4m3 (requires out_scale)");
m.def("linear_forward_fp8", &linear_forward_fp8, py::arg("x"),
py::arg("w"), py::arg("bias"), py::arg("sx"), py::arg("sw"),
"Fused BF16-to-FP8 linear forward; returns (out, amax_x, amax_w)");
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("sw"), py::arg("sx"), py::arg("fmt"),
"FP8 linear backward; returns (grad_input, grad_weight, grad_bias, amax_g)");
}