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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions zig/kernels/hip/quant/mlx_tiles.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@ __global__ void __launch_bounds__(256) affine_gemm_block(Affine a) {
gemm_tile<MlxDecoder<BITS>, IdentityAct<T>, T, F32Out, RT>(a);
}

// ---- the same tile on 64 rows a block: a short prompt's rows without the 128-row block's idle waves ----

template <typename T, int BITS, int RT, int M>
__global__ void __launch_bounds__(256) affine_gemm_rows(Affine a) {
gemm_tile<MlxDecoder<BITS>, IdentityAct<T>, T, F32Out, RT, M>(a);
}

// ---- the K-parallel tiles of a short prompt ----

template <typename T, int BITS, int CB, int R, int WAVES, int RB, bool LOOP>
Expand Down Expand Up @@ -58,9 +65,9 @@ struct StreamSides {
// Item z of the plan (or the plain product, or a group's side) at CB columns a lane, R rows; PAIR fuses the activation.
template <typename T, int BITS, int R, int CB, bool PAIR>
__global__ void __launch_bounds__(32 * kStreamWaves) affine_dot2_stream(Affine a, StreamSides sides, int lpc_log2,
int gshift) {
int gshift, int shared) {
using Epi = std::conditional_t<PAIR, StreamSwiglu<T>, StreamRound<T>>;
stream_tile<MlxDecoder<BITS>, IdentityAct<T>, T, Epi, R, CB>(a, sides, lpc_log2, gshift);
stream_tile<MlxDecoder<BITS>, IdentityAct<T>, T, Epi, R, CB>(a, sides, lpc_log2, gshift, shared);
}


Expand Down
5 changes: 3 additions & 2 deletions zig/kernels/hip/tiles/dot2_tiles.hip
Original file line number Diff line number Diff line change
Expand Up @@ -343,8 +343,8 @@ using Dot = DotF16;
template __global__ void affine_dot2_lanes<Dot, BITS, ROWS, 2>(Affine); \
template __global__ void affine_dot2_lanes<Dot, BITS, ROWS, 4>(Affine);
#define TF_STREAM(BITS, R, CB) \
template __global__ void affine_dot2_stream<Dot, BITS, R, CB, false>(Affine, StreamSides, int, int); \
template __global__ void affine_dot2_stream<Dot, BITS, R, CB, true>(Affine, StreamSides, int, int);
template __global__ void affine_dot2_stream<Dot, BITS, R, CB, false>(Affine, StreamSides, int, int, int); \
template __global__ void affine_dot2_stream<Dot, BITS, R, CB, true>(Affine, StreamSides, int, int, int);
#if TF_MATRIX
#define TF_WMMA(BITS) template __global__ void affine_wmma_gemm<BITS>(Affine);
#else
Expand All @@ -353,6 +353,7 @@ using Dot = DotF16;
#define TF_TILES(BITS) \
template __global__ void affine_dot2_block<Dot, BITS>(Affine); \
template __global__ void affine_gemm_block<Dot, BITS, GemmShape<Dot>::rt>(Affine); \
template __global__ void affine_gemm_rows<Dot, BITS, GemmShape<Dot>::rt, 64>(Affine); \
template __global__ void affine_gemm_kp<Dot, BITS, 8, 1, 2, 2, false>(Affine); \
template __global__ void affine_gemm_kp<Dot, BITS, 4, 4, 2, 4, true>(Affine); \
template __global__ void affine_gemm_kp<Dot, BITS, 4, 8, 2, 4, false>(Affine); \
Expand Down
31 changes: 17 additions & 14 deletions zig/kernels/hip/tiles/gemm.hpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#pragma once

// Dot2 prefill GEMM (m >= 64), 128 x 128 a block: bit for bit affine_dot2_block's per-group dot2 chain and fma fold.
// Dot2 prefill GEMM, 128 or 64 rows x 128 a block: bit for bit affine_dot2_block's dot2 chains and fma fold.

#include <type_traits>
#include <utility>
Expand Down Expand Up @@ -28,23 +28,23 @@ struct GemmShape<DotBF16> {
static constexpr int rt = 8;
};

// One 128 x 128 block of y = x . W^T: Dec reads weights and group terms, Act the rows of x, T multiplies, Epi stores.
template <class Dec, class Act, class T, class Epi, int RT>
// One M x 128 block of y = x . W^T: Dec reads weights and group terms, Act the rows of x, T multiplies, Epi stores.
template <class Dec, class Act, class T, class Epi, int RT, int M = kGemmM>
__device__ __forceinline__ void gemm_tile(typename Dec::Args& a) {
if (!Dec::take_item(a, blockIdx.z)) return;
const int bx = blockIdx.x, by = blockIdx.y;
if (by * kGemmM >= a.m) return;
if (by * M >= a.m) return;
using pair = typename T::pair;
constexpr int kLdw = kGemmLd / 2;
__shared__ __attribute__((aligned(16))) uint32_t xs[2][kGemmM * kLdw];
__shared__ __attribute__((aligned(16))) uint32_t xs[2][M * kLdw];
__shared__ __attribute__((aligned(16))) uint32_t ws[2][kGemmN * kLdw];
__shared__ float sx[2][kGemmM];
__shared__ float sx[2][M];
// The last three groups' scales and biases: bias lags scale a stage, so a slow wave reads an older group.
__shared__ float sc[3][kGemmN];
__shared__ float bi[3][kGemmN];

const int tid = threadIdx.x;
const int m0 = by * kGemmM;
const int m0 = by * M;
const int n0 = bx * kGemmN;
const int words_row = Dec::template row_words<int>(a);
const int groups = a.k / a.group;
Expand All @@ -60,9 +60,9 @@ __device__ __forceinline__ void gemm_tile(typename Dec::Args& a) {
const int xhalf = tid & 1;
// Rows past the end are not loaded, stored or summed: a stager wave has 16 rows, a summer 32: whole waves skip.
const int wave = __builtin_amdgcn_readfirstlane(tid >> 5);
const bool xlive = wave * 16 < a.m - m0;
const bool sxlive = (line & ~31) < a.m - m0;
const int row_s = m0 + xrow < a.m ? m0 + xrow : 0;
const bool xlive = wave * 16 < a.m - m0 && wave * 16 < M;
const bool sxlive = (line & ~31) < a.m - m0 && line < M;
const int row_s = m0 + xrow < a.m && xrow < M ? m0 + xrow : 0;
const typename Act::elem* xrow_ptr = Act::row(a, row_s);
const u32x4* xsrc = reinterpret_cast<const u32x4*>(xrow_ptr);

Expand Down Expand Up @@ -131,15 +131,18 @@ __device__ __forceinline__ void gemm_tile(typename Dec::Args& a) {
if (st % per == per - 1) sx[(st / per) & 1][line] = run;
};

// A wave owns 16 rows, 128 columns; at RT = 8 lanes 0-15 take rows 0-7, 16-31 rows 8-15; x rows come by quad DPP.
constexpr int CT = 64 / RT;
// A wave owns 16 rows, M columns; at RT = 8 lanes 0-15 take rows 0-7, 16-31 rows 8-15; x rows come by quad DPP.
constexpr int CT = 64 / RT * M / kGemmM;
const int lane = tid & 31;
constexpr int RG = M / 16; // row groups; under 128 rows the waves of a row group split its 128 columns
constexpr int CW = 16 * RG; // columns a wave
// With 3 groups or fewer live, odd blocks rotate groups by 2 waves so a WGP's two blocks keep all four SIMDs busy.
const int rg = (wave + ((a.m - m0 <= 48 && (bx & 1)) ? 6 : 0)) & 7;
const int rg = M == kGemmM ? (wave + ((a.m - m0 <= 48 && (bx & 1)) ? 6 : 0)) & 7 : wave % RG;
const int cpart = M == kGemmM ? 0 : wave / RG;
const bool live = rg * 16 < a.m - m0;
const int hrow = RT == 8 ? (lane >> 4) * 8 : 0;
constexpr int kCStride = RT == 8 ? 16 : 32;
const int cbase = RT == 8 ? lane & 15 : lane;
const int cbase = cpart * CW + (RT == 8 ? lane & 15 : lane);
float acc[RT][CT];
float dot[RT][CT];
#pragma unroll
Expand Down
74 changes: 62 additions & 12 deletions zig/kernels/hip/tiles/stream.hpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#pragma once

// Streaming decode tile for 1 to 8 rows: a lane owns a 32-code chunk of a column; no LDS, lanes fold by shuffle.
// Streaming decode tile for 1 to 16 rows: a lane owns a 32-code chunk of a column; lanes fold by shuffle.

#include <type_traits>
#include <utility>
Expand Down Expand Up @@ -51,8 +51,40 @@ __device__ inline void stream_dots(const typename T::pair (&xp)[RG][16], const u
...);
}

// The block's R rows of x into LDS (R * (2k + k / 8) bytes): chunk q of row r as pairs at [r][v][q][4], sums after.
template <class Dec, class Act, class T, int R>
__device__ inline void stream_stage(const typename Dec::Args& a, int row0, uint32_t* pairs, float* sums) {
using pair = typename T::pair;
const int nch = a.k >> 5;
for (int at = threadIdx.x; at < R * nch; at += 32 * kStreamWaves) {
const int r = at / nch;
const int q = at - r * nch;
const u32x4* src = reinterpret_cast<const u32x4*>(Act::row(a, row0 + r < a.m ? row0 + r : 0) + q * 32LL);
uint32_t xn[16];
#pragma unroll
for (int v = 0; v < 4; ++v) {
const u32x4 t = src[v];
xn[4 * v] = t.x;
xn[4 * v + 1] = t.y;
xn[4 * v + 2] = t.z;
xn[4 * v + 3] = t.w;
}
float s = 0.f;
#pragma unroll
for (int i = 0; i < 16; ++i) s = T::dot(__builtin_bit_cast(pair, xn[i]), __builtin_bit_cast(pair, T::ones), s);
sums[at] = s;
pair xp[16];
stream_x_pairs<Dec, T>(xn, xp, std::make_integer_sequence<int, 16>{});
// word by word: a u32x4 built from the pairs' bit casts lost a lane on gfx1100 (hipcc 7.14)
#pragma unroll
for (int i = 0; i < 16; ++i)
pairs[((r * 4 + (i >> 2)) * nch + q) * 4 + (i & 3)] = __builtin_bit_cast(uint32_t, xp[i]);
}
__syncthreads();
}

// Epi::kPair: a lane's CB columns are CB / 2 gate columns and the same up columns; out is silu(gate) * up.
template <class Dec, class Act, class T, class Epi, int R, int CB, bool WIDE>
template <class Dec, class Act, class T, class Epi, int R, int CB, bool WIDE, bool SHARED>
__device__ inline void stream_body(const typename Dec::Args& a, int lpc_log2, int gshift, int bx, int pair_cols, float limit) {
using pair = typename T::pair;
constexpr bool PAIR = Epi::kPair;
Expand Down Expand Up @@ -90,6 +122,11 @@ __device__ inline void stream_body(const typename Dec::Args& a, int lpc_log2, in
for (int c = 0; c < CB; ++c) acc[r][c] = 0.f;
}

// SHARED: the lanes read x pairs and sums of x from the block's stage instead of loading x (same values, same bits)
extern __shared__ uint32_t stage[];
if constexpr (SHARED) stream_stage<Dec, Act, T, R>(a, row0, stage, reinterpret_cast<float*>(stage + R * nch * 16));
const uint32_t* xs = stage;
const float* sums = reinterpret_cast<const float*>(stage + R * nch * 16);
const typename Dec::StreamTerms terms(a);

// The loads of one round: every column's chunk and its scale and bias, none waited for before the dots.
Expand Down Expand Up @@ -122,6 +159,14 @@ __device__ inline void stream_body(const typename Dec::Args& a, int lpc_log2, in
float sx[RG];
#pragma unroll
for (int r = 0; r < RG; ++r) {
if constexpr (SHARED) {
const int row = g * RG + r;
#pragma unroll
for (int i = 0; i < 16; ++i)
xp[r][i] = __builtin_bit_cast(pair, xs[((row * 4 + (i >> 2)) * nch + q) * 4 + (i & 3)]);
sx[r] = sums[row * nch + q];
continue;
}
uint32_t xn[16];
const u32x4* src =
reinterpret_cast<const u32x4*>(xr[g * RG + r] + static_cast<long long>(q) * 32);
Expand Down Expand Up @@ -202,9 +247,9 @@ __device__ inline void stream_body(const typename Dec::Args& a, int lpc_log2, in
}
}

// Item z of the plan (or plain product, or a group's side) at CB columns a lane, R rows; chunk group is q >> gshift.
// Item z of a plan (or product, or group side), CB columns a lane, R rows, chunk group q >> gshift; `shared` stages x.
template <class Dec, class Act, class T, class Epi, int R, int CB, class Sides>
__device__ inline void stream_tile(typename Dec::Args& a, const Sides& sides, int lpc_log2, int gshift) {
__device__ inline void stream_tile(typename Dec::Args& a, const Sides& sides, int lpc_log2, int gshift, int shared) {
int bx = blockIdx.x;
if (sides.count > 0) {
int s = 0;
Expand All @@ -219,16 +264,21 @@ __device__ inline void stream_tile(typename Dec::Args& a, const Sides& sides, in
}
}
if (!Dec::take_item(a, blockIdx.z) || static_cast<int>(blockIdx.y) * R >= a.m) return;
if constexpr (Dec::kWideBytes == 4) {
stream_body<Dec, Act, T, Epi, R, CB, false>(a, lpc_log2, gshift, bx, sides.pair_cols, sides.limit);
} else {
// every chunk is wide-aligned when the words and the row stride are
if (Dec::wide_aligned(a)) {
stream_body<Dec, Act, T, Epi, R, CB, true>(a, lpc_log2, gshift, bx, sides.pair_cols, sides.limit);
} else {
stream_body<Dec, Act, T, Epi, R, CB, false>(a, lpc_log2, gshift, bx, sides.pair_cols, sides.limit);
// every chunk is wide-aligned when the words and the row stride are
constexpr bool kWide = Dec::kWideBytes != 4;
const bool wide = kWide && Dec::wide_aligned(a);
const int pc = sides.pair_cols;
if constexpr (R <= 2) {
if constexpr (kWide) {
if (shared && wide)
return stream_body<Dec, Act, T, Epi, R, CB, true, true>(a, lpc_log2, gshift, bx, pc, sides.limit);
}
if (shared) return stream_body<Dec, Act, T, Epi, R, CB, false, true>(a, lpc_log2, gshift, bx, pc, sides.limit);
}
if constexpr (kWide) {
if (wide) return stream_body<Dec, Act, T, Epi, R, CB, true, false>(a, lpc_log2, gshift, bx, pc, sides.limit);
}
stream_body<Dec, Act, T, Epi, R, CB, false, false>(a, lpc_log2, gshift, bx, pc, sides.limit);
}

} // namespace rocm
Expand Down
1 change: 1 addition & 0 deletions zig/src/hip/kernel_tests.zig
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,5 @@ test {
_ = @import("kernel_tests/ops.zig");
_ = @import("kernel_tests/affine/affine.zig");
_ = @import("kernel_tests/affine/rows.zig");
_ = @import("kernel_tests/affine/stream.zig");
}
145 changes: 145 additions & 0 deletions zig/src/hip/kernel_tests/affine/stream.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
//! The stream tile's staged x against each lane's own loads, at every width, group, row count and columns a lane.

const std = @import("std");
const base = @import("../rig.zig");
const affine = @import("../../launches/affine.zig");
const Buffer = base.Buffer;
const gpa = base.gpa;
const data = @import("data.zig");
const cases = @import("cases.zig");
const prod = @import("product.zig");

/// The bytes every launch below writes, hashed in order, as the stream tile before the stage wrote them.
const pinned_f16: u64 = 0x36ef53355d892c81;
const pinned_bf16: u64 = 0x6b703ab847138aad;

/// Row counts: one and two rows a block (the staged tiles), a partial block of four, and the y blocks above.
const row_counts = [_]usize{ 1, 2, 3, 5, 16 };

/// How a launch writes: fp32, the activation type, silu(gate) * up of a stacked pair, or fp32 of a two-expert plan.
const Out = enum { f32, act, pair, routed };

const Shape = struct { n: usize, k: usize, bits: u8, group: u16 };

/// The waves a launch of `cb` columns a lane makes, as streamGo counts them: the target that picks that width.
fn wavesOf(s: Shape, m: usize, cb: usize, out: Out) u64 {
var lpc_log2: u6 = 0;
while ((@as(usize, 1) << lpc_log2) < s.k / 32 and lpc_log2 < 5) lpc_log2 += 1;
const rows: usize = if (m == 1) 1 else if (m == 2) 2 else 4;
const cols = if (out == .pair) s.n / 2 else s.n;
const per_block = 4 * (@as(usize, 32) >> lpc_log2) * (if (out == .pair) cb / 2 else cb);
return (cols + per_block - 1) / per_block * 4 * ((m + rows - 1) / rows);
}

/// One product at `m` rows through every width of the tile, staged and not: the differing bytes; the hash of the rest.
fn product(t: *prod.Rig, rng: *data.Rng, s: Shape, out: Out, hash: *u64) !usize {
const most = row_counts[row_counts.len - 1];
const words_row = s.k * s.bits / 32;
const groups = s.k / s.group;
const hx = try data.fill(gpa, u16, most * s.k, rng, if (t.fp16) data.makeX16 else data.makeXB);
defer gpa.free(hx);
const experts: usize = if (out == .routed) 2 else 1;
const hw = try data.fill(gpa, u32, experts * s.n * words_row, rng, data.makeWord);
defer gpa.free(hw);
const hs = try data.fill(gpa, u16, experts * s.n * groups, rng, data.makeScale);
defer gpa.free(hs);
const hb = try data.fill(gpa, u16, experts * s.n * groups, rng, data.makeBias);
defer gpa.free(hb);
var x = try Buffer.fromHost(t.base, hx);
defer x.free();
var words = try Buffer.fromHost(t.base, hw);
defer words.free();
var scale = try Buffer.fromHost(t.base, hs);
defer scale.free();
var bias = try Buffer.fromHost(t.base, hb);
defer bias.free();
// a plan's rows reversed: item 0 (expert 0) takes the first half of the members, item 1 the rest
var members: [most]c_int = undefined;
for (&members, 0..) |*mb, i| mb.* = @intCast(most - 1 - i);
var member_buf = try Buffer.fromHost(t.base, @as([]const c_int, &members));
defer member_buf.free();
var plan = try Buffer.alloc(t.base, 6 * @sizeOf(c_int));
defer plan.free();
const cols = if (out == .pair) s.n / 2 else s.n;
const size: usize = if (out == .f32 or out == .routed) 4 else 2;
const bytes = most * cols * size;
var outs: [2]Buffer = .{ try Buffer.alloc(t.base, bytes), try Buffer.alloc(t.base, bytes) };
defer for (&outs) |*o| o.free();
const got = try gpa.alloc(u8, 2 * bytes);
defer gpa.free(got);
var k = t.kernels.*;
var bad: usize = 0;
for (row_counts) |m| for ([_]usize{ 8, 4, 2 }) |cb| {
const block_rows: usize = if (m <= 2) m else 4;
if (cb * block_rows > 16 or cb * s.bits > 32) continue;
const arg: affine.Arg = .{
.x = x.ptr,
.words = words.ptr,
.scale = .{ .p = scale.ptr, .kind = 1 },
.bias = .{ .p = bias.ptr, .kind = 1 },
.out = 0,
.m = @intCast(m),
.n = @intCast(s.n),
.k = @intCast(s.k),
.bits = s.bits,
.group = s.group,
.fp16 = @intFromBool(t.fp16),
};
var a0 = arg;
var items: c_int = 1;
if (out == .routed) {
const first = (m + 1) / 2;
const item = [6]c_int{ 0, 0, @intCast(first), 1, @intCast(first), @intCast(m - first) };
try plan.upload(0, std.mem.sliceAsBytes(&item));
items = if (m > first) 2 else 1;
a0.m = @intCast(first);
a0.route = .{ .items = plan.ptr, .members = member_buf.ptr, .x_div = 1 };
}
// the widest width meets a target of one wave; a narrower one the waves it makes itself
k.waves_wanted = if (cb == 8) 1 else wavesOf(s, @intCast(a0.m), cb, out) * @as(u64, @intCast(items));
for (outs, [_]bool{ false, true }) |o, staged| {
k.stage_on = staged;
var a = a0;
if (size == 4) a.out = o.ptr else a.out16 = o.ptr;
try o.fill8(0xA5, null);
const sides: affine.StreamSides = if (out == .pair) .{ .pair_cols = @intCast(cols) } else .{};
try k.streamGo(&t.base.r, a, sides, @intCast(cols), items, t.base.stream.handle);
}
try t.base.stream.synchronize();
const n_bytes = if (out == .routed) most * cols * size else m * cols * size;
try outs[0].download(0, got[0..n_bytes]);
try outs[1].download(0, got[bytes..][0..n_bytes]);
hash.* = std.hash.Wyhash.hash(hash.*, got[0..n_bytes]);
if (!std.mem.eql(u8, got[0..n_bytes], got[bytes..][0..n_bytes])) {
if (bad < 6) std.debug.print(" stream n{d} k{d} b{d} g{d} {s} m{d} cb{d}: staged x writes other bytes\n", .{ s.n, s.k, s.bits, s.group, @tagName(out), m, cb });
bad += 1;
}
};
return bad;
}

/// Every width and group at a few stages, an odd stage count or 4096, and a long run, through every output.
pub fn sweep(t: *prod.Rig) !u64 {
var rng: data.Rng = .{ .state = 0x51ED270B27C1F5E3 };
var hash: u64 = 0;
var bad: usize = 0;
for (cases.widths) |bits| for (cases.groups) |group| {
// two rows staged up to k 7680, one to 15360
const ks = [_]usize{ 3 * @as(usize, group), if (group == 32) 2080 else 4096, 9216 };
for (ks, 0..) |k, j| for (std.enums.values(Out)) |out| {
const n: usize = if (j == 0) 202 else if (j == 1) 1006 else 4100;
bad += try product(t, &rng, .{ .n = n, .k = k, .bits = bits, .group = group }, out, &hash);
};
};
try base.expect(bad == 0, "stream: {d} launches with staged x differ from the lanes' own loads", .{bad});
return hash;
}

test "the stream tile writes the same bytes with x staged in LDS as with each lane's loads, and as before the stage" {
const b = try base.Rig.open(1 << 20);
defer b.close();
var rig = prod.Rig.open(b);
const hash = try sweep(&rig);
const pinned = if (rig.fp16) pinned_f16 else pinned_bf16;
try base.expect(hash == pinned, "stream: the bytes hash to 0x{x}, the tile before the stage wrote 0x{x}", .{ hash, pinned });
}
Loading
Loading