diff --git a/zig/kernels/hip/quant/mlx_tiles.hpp b/zig/kernels/hip/quant/mlx_tiles.hpp index 7dacb30d3e7..2667746c3ef 100644 --- a/zig/kernels/hip/quant/mlx_tiles.hpp +++ b/zig/kernels/hip/quant/mlx_tiles.hpp @@ -23,6 +23,13 @@ __global__ void __launch_bounds__(256) affine_gemm_block(Affine a) { gemm_tile, IdentityAct, 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 +__global__ void __launch_bounds__(256) affine_gemm_rows(Affine a) { + gemm_tile, IdentityAct, T, F32Out, RT, M>(a); +} + // ---- the K-parallel tiles of a short prompt ---- template @@ -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 __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, StreamRound>; - stream_tile, IdentityAct, T, Epi, R, CB>(a, sides, lpc_log2, gshift); + stream_tile, IdentityAct, T, Epi, R, CB>(a, sides, lpc_log2, gshift, shared); } diff --git a/zig/kernels/hip/tiles/dot2_tiles.hip b/zig/kernels/hip/tiles/dot2_tiles.hip index bff70f5f72d..11ccf3c7550 100644 --- a/zig/kernels/hip/tiles/dot2_tiles.hip +++ b/zig/kernels/hip/tiles/dot2_tiles.hip @@ -343,8 +343,8 @@ using Dot = DotF16; template __global__ void affine_dot2_lanes(Affine); \ template __global__ void affine_dot2_lanes(Affine); #define TF_STREAM(BITS, R, CB) \ - template __global__ void affine_dot2_stream(Affine, StreamSides, int, int); \ - template __global__ void affine_dot2_stream(Affine, StreamSides, int, int); + template __global__ void affine_dot2_stream(Affine, StreamSides, int, int, int); \ + template __global__ void affine_dot2_stream(Affine, StreamSides, int, int, int); #if TF_MATRIX #define TF_WMMA(BITS) template __global__ void affine_wmma_gemm(Affine); #else @@ -353,6 +353,7 @@ using Dot = DotF16; #define TF_TILES(BITS) \ template __global__ void affine_dot2_block(Affine); \ template __global__ void affine_gemm_block::rt>(Affine); \ + template __global__ void affine_gemm_rows::rt, 64>(Affine); \ template __global__ void affine_gemm_kp(Affine); \ template __global__ void affine_gemm_kp(Affine); \ template __global__ void affine_gemm_kp(Affine); \ diff --git a/zig/kernels/hip/tiles/gemm.hpp b/zig/kernels/hip/tiles/gemm.hpp index de673cf5266..e30b05988e9 100644 --- a/zig/kernels/hip/tiles/gemm.hpp +++ b/zig/kernels/hip/tiles/gemm.hpp @@ -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 #include @@ -28,23 +28,23 @@ struct GemmShape { 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 +// 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 __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(a); const int groups = a.k / a.group; @@ -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(xrow_ptr); @@ -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 diff --git a/zig/kernels/hip/tiles/stream.hpp b/zig/kernels/hip/tiles/stream.hpp index d8544456771..cabc9e20825 100644 --- a/zig/kernels/hip/tiles/stream.hpp +++ b/zig/kernels/hip/tiles/stream.hpp @@ -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 #include @@ -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 +__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(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(xn, xp, std::make_integer_sequence{}); + // 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 +template __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; @@ -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(a, row0, stage, reinterpret_cast(stage + R * nch * 16)); + const uint32_t* xs = stage; + const float* sums = reinterpret_cast(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. @@ -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(xr[g * RG + r] + static_cast(q) * 32); @@ -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 -__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; @@ -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(blockIdx.y) * R >= a.m) return; - if constexpr (Dec::kWideBytes == 4) { - stream_body(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(a, lpc_log2, gshift, bx, sides.pair_cols, sides.limit); - } else { - stream_body(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(a, lpc_log2, gshift, bx, pc, sides.limit); } + if (shared) return stream_body(a, lpc_log2, gshift, bx, pc, sides.limit); + } + if constexpr (kWide) { + if (wide) return stream_body(a, lpc_log2, gshift, bx, pc, sides.limit); } + stream_body(a, lpc_log2, gshift, bx, pc, sides.limit); } } // namespace rocm diff --git a/zig/src/hip/kernel_tests.zig b/zig/src/hip/kernel_tests.zig index 27a95da9362..923a34778ed 100644 --- a/zig/src/hip/kernel_tests.zig +++ b/zig/src/hip/kernel_tests.zig @@ -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"); } diff --git a/zig/src/hip/kernel_tests/affine/stream.zig b/zig/src/hip/kernel_tests/affine/stream.zig new file mode 100644 index 00000000000..984f4a1c1ad --- /dev/null +++ b/zig/src/hip/kernel_tests/affine/stream.zig @@ -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 }); +} diff --git a/zig/src/hip/launches.zig b/zig/src/hip/launches.zig index 2ae4130f343..c79474fdcae 100644 --- a/zig/src/hip/launches.zig +++ b/zig/src/hip/launches.zig @@ -132,6 +132,17 @@ pub const Launcher = struct { /// Which kernels a run takes where two give the same bits; every one defaults on. pub const Choices = struct { fuse: bool = true, wide: bool = true, chunked: bool = true, products: affine.Choices = .{} }; + /// The current device's compute units (the HIP attribute), 0 when HIP does not say. + fn computeUnits(r: *const runtime.Runtime) u32 { + var lib = r.lib; + const current = lib.lookup(*const fn (*c_int) callconv(.c) c_int, "hipGetDevice") orelse return 0; + var device: c_int = 0; + var cus: c_int = 0; + runtime.check(current(&device)) catch return 0; + runtime.check(r.api.hipDeviceGetAttribute(&cus, .multiprocessor_count, device)) catch return 0; + return @intCast(@max(cus, 0)); + } + /// Loads the code objects on the current device and resolves every kernel the launchers use. pub fn load(r: *const runtime.Runtime, choices: Choices, images: [kernels.group_count][]align(8) const u8) Error!Launcher { var l: Launcher = undefined; @@ -252,7 +263,9 @@ pub const Launcher = struct { l.sum_partials = try att.function("tf_sum_partials"); const tiles = l.mods[@backingInt(kernels.Group.affine_tiles)]; const dot2 = l.mods[@backingInt(kernels.Group.affine_dot2)]; - l.affine = try affine.Kernels.load(tiles, dot2, caps.Caps.of(kernels.arch) orelse return error.Invalid, choices.products); + var products = choices.products; + if (products.cus == 0) products.cus = computeUnits(r); + l.affine = try affine.Kernels.load(tiles, dot2, caps.Caps.of(kernels.arch) orelse return error.Invalid, products); try l.affine.fillByteLut(r, dot2); return l; } diff --git a/zig/src/hip/launches/affine.zig b/zig/src/hip/launches/affine.zig index 7c2b8a0ccd2..5fc024b6700 100644 --- a/zig/src/hip/launches/affine.zig +++ b/zig/src/hip/launches/affine.zig @@ -20,8 +20,8 @@ const Error = runtime.Error; /// Matrix cores for products: `off` keeps every product on dot2 tiles; `auto` and `on` use them where a tile exists. pub const Matrix = enum { auto, on, off }; -/// Which product tiles a run takes where two give the same bits; every one defaults on. -pub const Choices = struct { matrix: Matrix = .auto, stream: bool = true, gemm: bool = true }; +/// Which product tiles a run takes where two give the same bits; every one defaults on. `cus`: the GPU's, 0 unknown. +pub const Choices = struct { matrix: Matrix = .auto, stream: bool = true, gemm: bool = true, cus: u32 = 0 }; /// quant/mlx.hpp's GroupTable, Routing and Affine as the kernels take them by value. pub const GroupTable = extern struct { p: u64, kind: c_int }; @@ -91,7 +91,9 @@ const fast_n = 256; const stream_cbs = [_]c_int{ 2, 4, 8 }; // columns a lane carries in the stream tile const stream_rows = [_]u8{ 1, 2, 4 }; // its row counts: columns * rows <= 16 const stream_waves = 4; // kStreamWaves -const streams_wanted = 3000; // kStreamWavesWanted +const streams_wanted = 3000; // the waves a stream launch fills a large GPU with +const stream_waves_cu = 96; // and a small one with, a compute unit +const stage_bytes_max = 32 << 10; // the most LDS the stream tile stages a block's x in (two blocks a CU still fit) const stream_code_words = 32; // kStreamCodeWords /// The K-parallel tiles of a short prompt: cb columns a lane set, r rows a pass over up to rb row blocks. @@ -106,8 +108,8 @@ pub const kp_tiles = [_]KpTile{ /// The GEMM tiles of the m >= 64 products: `gemm` (the default) or the reference `block`. pub const Tile = enum { gemm, block }; -/// Which GEMM tile of the 128-row family a launch runs: the matrix cores, the dot2 tile, or the reference tile. -pub const BlockKind = enum { matrix, gemm, block }; +/// The GEMM tile of the 128-row family a launch runs: matrix cores, dot2 on 128 or 64 rows a block, or reference. +pub const BlockKind = enum { matrix, gemm, gemm64, block }; pub const Kernels = struct { /// Whether block shape `tier` can take `m` rows: a tile that does not loop over its rows holds rb * r of them. @@ -131,8 +133,14 @@ pub const Kernels = struct { pairs: [bit_widths.len][stream_rows.len][stream_cbs.len]?Function, /// Off keeps the decode tiles before the stream tile (the policy's reference switch). stream_on: bool, + /// Off (the tests' comparison) keeps every lane of the stream tile loading its own x: the staged x's bits. + stage_on: bool, + /// The waves a stream launch wants: fewer columns a lane until it has them (a choice of speed, not of bits). + waves_wanted: u64, block: [bit_widths.len]Function, gemm: [bit_widths.len]Function, + /// The dot2 GEMM tile on 64 rows a block: the same bits as the 128-row one. + gemm64: [bit_widths.len]Function, wmma_gemm: [bit_widths.len]Function, kp: [bit_widths.len][kp_tiles.len]Function, span: [2]Function, @@ -153,6 +161,8 @@ pub const Kernels = struct { k.mode = choices.matrix; k.tile = if (choices.gemm) .gemm else .block; k.stream_on = choices.stream; + k.stage_on = true; + k.waves_wanted = wavesWanted(choices.cus); k.reg = Registry.init(tableFor(caps), &mlx_entries.all); k.reg.verify(k.env(), .mlx) catch return error.Invalid; // the GEMM tile's rows of x a lane keeps (tiles/gemm.hpp GemmShape): 8 for BF16, 16 for FP16 @@ -173,6 +183,7 @@ pub const Kernels = struct { k.block[b] = try m.function(std.fmt.comptimePrint("_ZN2tf4rocm17affine_dot2_blockINS0_{s}ELi{d}EEEvNS0_6AffineE", .{ dot, bits })); if (k.matrix) k.wmma_gemm[b] = try m.function(std.fmt.comptimePrint("_ZN2tf4rocm16affine_wmma_gemmILi{d}EEEvNS0_6AffineE", .{bits})); k.gemm[b] = try m.function(std.fmt.comptimePrint("_ZN2tf4rocm17affine_gemm_blockINS0_{s}ELi{d}E{s}EEvNS0_6AffineE", .{ dot, bits, shape })); + k.gemm64[b] = try m.function(std.fmt.comptimePrint("_ZN2tf4rocm16affine_gemm_rowsINS0_{s}ELi{d}E{s}Li64EEEvNS0_6AffineE", .{ dot, bits, shape })); inline for (kp_tiles, 0..) |t, i| { k.kp[b][i] = try m.function(std.fmt.comptimePrint("_ZN2tf4rocm14affine_gemm_kpINS0_{s}ELi{d}ELi{d}ELi{d}ELi{d}ELi{d}ELb{d}EEEvNS0_6AffineE", .{ dot, bits, t.cb, t.r, t.waves, t.rb, @intFromBool(t.loop) })); } @@ -185,11 +196,11 @@ pub const Kernels = struct { inline for (stream_rows, 0..) |rows, r| { inline for (stream_cbs, 0..) |cb, c| { k.stream[b][r][c] = if (cb * rows <= 16) - try m.function(std.fmt.comptimePrint("_ZN2tf4rocm18affine_dot2_streamINS0_{s}ELi{d}ELi{d}ELi{d}ELb0EEEvNS0_6AffineENS0_11StreamSidesEii", .{ dot, bits, rows, cb })) + try m.function(std.fmt.comptimePrint("_ZN2tf4rocm18affine_dot2_streamINS0_{s}ELi{d}ELi{d}ELi{d}ELb0EEEvNS0_6AffineENS0_11StreamSidesEiii", .{ dot, bits, rows, cb })) else null; k.pairs[b][r][c] = if (cb * rows <= 16) - try m.function(std.fmt.comptimePrint("_ZN2tf4rocm18affine_dot2_streamINS0_{s}ELi{d}ELi{d}ELi{d}ELb1EEEvNS0_6AffineENS0_11StreamSidesEii", .{ dot, bits, rows, cb })) + try m.function(std.fmt.comptimePrint("_ZN2tf4rocm18affine_dot2_streamINS0_{s}ELi{d}ELi{d}ELi{d}ELb1EEEvNS0_6AffineENS0_11StreamSidesEiii", .{ dot, bits, rows, cb })) else null; } @@ -209,8 +220,24 @@ pub const Kernels = struct { /// Launches on `s`; the counting stream runs nothing. fn go(r: *const runtime.Runtime, f: Function, grid: hl.Dim3, block: hl.Dim3, s: abi.Stream, args: *hl.Args) Error!void { + return goShared(r, f, grid, block, 0, s, args); + } + + fn goShared(r: *const runtime.Runtime, f: Function, grid: hl.Dim3, block: hl.Dim3, shared: u32, s: abi.Stream, args: *hl.Args) Error!void { if (s == util.counting) return; - try hl.launch(f, .{ .grid = grid, .block = block }, .{ .r = r, .handle = s }, args); + try hl.launch(f, .{ .grid = grid, .block = block, .shared = shared }, .{ .r = r, .handle = s }, args); + } + + /// The waves a stream launch wants on a GPU of `cus` compute units: a large GPU's 3000, fewer on a small one. + pub fn wavesWanted(cus: u32) u64 { + return if (cus == 0) streams_wanted else @min(streams_wanted, @as(u64, stream_waves_cu) * cus); + } + + /// LDS bytes a block stages its rows of x in, 0 for none: it repays one row at 4+ columns, two at 8 on a small GPU. + pub fn stageBytes(k: *const Kernels, rows: c_int, depth: c_int, cb: c_int) u32 { + const bytes = @as(i64, rows) * (2 * @as(i64, depth) + @divTrunc(depth, 32) * 4); + const repays = if (rows == 1) cb >= 4 else rows == 2 and cb == 8 and k.waves_wanted < streams_wanted; + return if (k.stage_on and repays and bytes <= stage_bytes_max) @intCast(bytes) else 0; } fn refuse(what: []const u8) Error { @@ -317,7 +344,7 @@ pub const Kernels = struct { if (stream_cbs[c] * stream_rows[ri] > 16 or stream_cbs[c] * a.bits > stream_code_words) continue; pick = c; const per_block: c_int = stream_waves * (@as(c_int, 32) >> lpc_log2) * @divExact(stream_cbs[c], pair_div); - if (@as(u64, cdiv(total_n, per_block)) * stream_waves * @as(u64, @intCast(items)) * cdiv(a.m, stream_rows[ri]) >= streams_wanted) break; + if (@as(u64, cdiv(total_n, per_block)) * stream_waves * @as(u64, @intCast(items)) * cdiv(a.m, stream_rows[ri]) >= k.waves_wanted) break; } const per_block: c_int = stream_waves * (@as(c_int, 32) >> lpc_log2) * @divExact(stream_cbs[pick], pair_div); var blocks: c_uint = cdiv(total_n, per_block); @@ -338,8 +365,10 @@ pub const Kernels = struct { 64 => 1, else => 2, })); + const stage = k.stageBytes(stream_rows[ri], a.k, stream_cbs[pick]); + try args.add(@as(c_int, @intFromBool(stage > 0))); const f = (if (sides.pair_cols > 0) k.pairs[b][ri][pick] else k.stream[b][ri][pick]).?; - try go(r, f, .{ .x = blocks, .y = cdiv(a.m, stream_rows[ri]), .z = @intCast(items) }, .{ .x = 32 * stream_waves }, s, &args); + try goShared(r, f, .{ .x = blocks, .y = cdiv(a.m, stream_rows[ri]), .z = @intCast(items) }, .{ .x = 32 * stream_waves }, stage, s, &args); } /// One row on the row tile: a lane owns a group, a wave reads a column's row in one run. @@ -400,7 +429,7 @@ pub const Kernels = struct { try go(r, k.fold, .{ .x = cdiv(a.n, fast_n), .y = @intCast(a.m) }, .{ .x = fast_n }, s, &fold); } - /// The 128 x 128 tile of a kind over every item of a plan (or the plain product). + /// The GEMM tile of a kind over every item of a plan (or the plain product): 128 (or 64) rows x 128 a block. pub fn blockGo(k: *const Kernels, r: *const runtime.Runtime, a: Arg, s: abi.Stream, items: c_int, kind: BlockKind) Error!void { const b = bitIndex(a.bits) orelse return refuse("bits"); var args: hl.Args = .{}; @@ -408,9 +437,11 @@ pub const Kernels = struct { const f = switch (kind) { .matrix => k.wmma_gemm[b], .gemm => k.gemm[b], + .gemm64 => k.gemm64[b], .block => k.block[b], }; - try go(r, f, .{ .x = cdiv(a.n, 128), .y = cdiv(a.m, 128), .z = @intCast(items) }, .{ .x = 256 }, s, &args); + const rows: c_int = if (kind == .gemm64) 64 else 128; + try go(r, f, .{ .x = cdiv(a.n, 128), .y = cdiv(a.m, rows), .z = @intCast(items) }, .{ .x = 256 }, s, &args); } /// K-parallel tile `tier` (an index of kp_tiles) of a short prompt. @@ -536,6 +567,12 @@ test "the split count follows the C rule" { try std.testing.expectEqual(@as(c_int, 8), Kernels.splitCount(1, 4096, 512, 64, 2)); } +test "a stream launch wants 3000 waves on a large GPU, 96 a compute unit on a small one" { + try std.testing.expectEqual(@as(u64, 3000), Kernels.wavesWanted(0)); + try std.testing.expectEqual(@as(u64, 3000), Kernels.wavesWanted(70)); + try std.testing.expectEqual(@as(u64, 768), Kernels.wavesWanted(8)); +} + test "the lane groups of a row tile" { try std.testing.expectEqual(@as(c_int, 0), Kernels.rowLanes(3)); try std.testing.expectEqual(@as(c_int, 4), Kernels.rowLanes(4)); diff --git a/zig/src/hip/launches/mlx_entries.zig b/zig/src/hip/launches/mlx_entries.zig index b9c8fe26c88..8365c0c4967 100644 --- a/zig/src/hip/launches/mlx_entries.zig +++ b/zig/src/hip/launches/mlx_entries.zig @@ -304,7 +304,7 @@ const other_decode = [_]Entry{ entry(.routed_act, .decode, "stream", .{ .family = .stream, .fits = &fitsPair, .launch = &launchPair, .policy = &streamOn }), }; -fn prefill(comptime op: Op) [7]Entry { +fn prefill(comptime op: Op) [8]Entry { return .{ entry(op, .prefill, "kp0", .{ .family = .gemm, .fits = kpFits(0), .launch = launchKp(0), .policy = &gemmOn }), entry(op, .prefill, "kp1", .{ .family = .gemm, .fits = kpFits(1), .launch = launchKp(1), .policy = &gemmOn }), @@ -312,6 +312,7 @@ fn prefill(comptime op: Op) [7]Entry { entry(op, .prefill, "kp3", .{ .family = .gemm, .fits = kpFits(3), .launch = launchKp(3), .policy = &gemmOn }), entry(op, .prefill, "matrix", .{ .family = .gemm, .fits = &fitsPrefillMatrix, .launch = launchBlock(.matrix), .caps = &matrixCores, .policy = &matrixOn }), entry(op, .prefill, "gemm", .{ .family = .gemm, .fits = &fitsPrefillGemm, .launch = launchBlock(.gemm), .policy = &gemmOn }), + entry(op, .prefill, "gemm64", .{ .family = .gemm, .fits = &fitsPrefillGemm, .launch = launchBlock(.gemm64), .policy = &gemmOn }), entry(op, .prefill, "block", .{ .family = .gemm, .fits = &fitsPrefillBlock, .launch = launchBlock(.block) }), }; } @@ -399,6 +400,13 @@ test "a prompt takes the K-parallel tiles by rows and by items, then the 128-row shape.items = 0; shape.m = 64; try std.testing.expect(std.mem.endsWith(u8, r.select(envOn("gfx1100", true, true, false), .mlx, .project, .prefill, shape).?.id, "gemm")); + // RDNA2 takes 33 to 64 rows on the 64-row GEMM tile + const dot2_env = envOn("gfx1030", true, true, false); + const short = [_]struct { u32, []const u8 }{ .{ 32, "kp2" }, .{ 33, "gemm64" }, .{ 64, "gemm64" }, .{ 65, "gemm" } }; + for (short) |p| { + shape.m = p[0]; + try std.testing.expect(std.mem.endsWith(u8, kernelsOn("gfx1030").select(dot2_env, .mlx, .project, .prefill, shape).?.id, p[1])); + } // RDNA2 takes a plan of up to 410 items on the second K-parallel tile const v = kernelsOn("gfx1030"); shape.fp16 = true; diff --git a/zig/src/hip/tuning/gfx1030.zon b/zig/src/hip/tuning/gfx1030.zon index a420e64cb4b..e585a855bf8 100644 --- a/zig/src/hip/tuning/gfx1030.zon +++ b/zig/src/hip/tuning/gfx1030.zon @@ -34,6 +34,8 @@ .{ .id = "mlx.project.prefill.kp3", .cost = 2, .items = 300, .plain = false }, .{ .id = "mlx.project.prefill.kp1", .cost = 3, .rows = 4, .items = 410 }, .{ .id = "mlx.project.prefill.kp2", .cost = 4, .rows = 32, .routed = false }, + // 33 to 64 rows: the GEMM tile on 64 rows a block keeps every wave busy (the 128-row one idles half) + .{ .id = "mlx.project.prefill.gemm64", .cost = 10, .rows = 64, .min_rows = 33 }, .{ .id = "mlx.project.prefill.gemm", .cost = 11 }, .{ .id = "mlx.project.prefill.block", .cost = 12 }, .{ .id = "mlx.routed.prefill.kp0", .cost = 1, .rows = 2, .routed = false },