diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b5ae195e21..372300814a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- HIP: the gfx12 WMMA step pieces move from `tiles/wmma12_gemm.hpp` into a shared header, `tiles/wmma12_step.hpp`, for the coming gfx12 affine tile; it is only a move, so the kernels' bytes do not change (#3862, refs #2401). Thanks to @millaguie. + +- HIP on RDNA3.5: lane-round routed MoE plan buffers (`moe.planRows`) are sized to the exact window row count instead of the 16-row bucket, and rising added-row window costs are pooled within four-row tile steps (`costs.poolWindowRows`) so a tile step never prices an earlier draft step under a later one; no kernel or output token changes (#3774). Thanks to @gilby. + - Docs: the optimization ledger adds rows 30 to 32 (small-kernel fusion, stream-tile prefetch and the filled-item prompt grid), each `failed` for Flash Next on HIP with the measurements from #1603 (#3160, refs #1603). Thanks to @gilby. - Docs: the Qwen3.8-27B recipe says to serve with `--thinking-budget 4096` when thinking is on, and gives its GPQA Diamond result on TensorFold 1.2.7 and one GB10: replies cut at the limit from 78 of 198 to 0, and correct from 58.1% to 82.8% (#3373, fixes #3323). diff --git a/zig/build/hip.zig b/zig/build/hip.zig index 7d0da890b63..20d52a859b5 100644 --- a/zig/build/hip.zig +++ b/zig/build/hip.zig @@ -519,15 +519,14 @@ const groups = [_]Source{ }; /// What the group sources include, so an edit to one rebuilds them. const headers = [_][]const u8{ - "attention/attention_fa.hip", "attention/prefill.hpp", "decode/pages.hpp", "decode/plan.hpp", "ops/attention.hpp", - "ops/common.hpp", "ops/draw.hpp", "ops/tp.hpp", "ops/elementwise.hpp", "ops/linear.hpp", - "ops/moe.hpp", "ops/norms.hpp", "ops/rope.hpp", "common/arch.hpp", "common/dot2.hpp", - "common/vec.hpp", "common/wmma.hpp", "quant/act.hpp", "quant/mlx.hpp", "quant/mlx_decoder.hpp", - "quant/mlx_pieces.hpp", "quant/mlx_tiles.hpp", "tiles/dot2.hpp", "tiles/epilogue.hpp", "tiles/gemm.hpp", - "tiles/gemm_kp.hpp", "tiles/matrix_gemm.hpp", "tiles/matrix_item.hpp", "tiles/plan.hpp", "tiles/stream.hpp", - "flashnext/streams.hpp", "flashnext/ngram.hpp", "flashnext/indexer.hpp", "flashnext/sparse.hpp", "ops/nemotron_moe.hpp", - "quant/bf16_decoder.hpp", "quant/dense_tiles.hpp", "tiles/wmma12_gemm.hpp", "tiles/wmma12_gemm_k32_ref.hpp", "ops/columns.hpp", - "columns_controls.hpp", "ops/vision.hpp", "ops/dense_text.hpp", "ops/vl_position.hpp", "flashnext/sparse_lanes.hpp", + "attention/attention_fa.hip", "attention/prefill.hpp", "decode/pages.hpp", "decode/plan.hpp", "ops/attention.hpp", "ops/common.hpp", + "ops/draw.hpp", "ops/tp.hpp", "ops/elementwise.hpp", "ops/linear.hpp", "ops/moe.hpp", "ops/norms.hpp", + "ops/rope.hpp", "common/arch.hpp", "common/dot2.hpp", "common/vec.hpp", "common/wmma.hpp", "quant/act.hpp", + "quant/mlx.hpp", "quant/mlx_decoder.hpp", "quant/mlx_pieces.hpp", "quant/mlx_tiles.hpp", "tiles/dot2.hpp", "tiles/epilogue.hpp", + "tiles/gemm.hpp", "tiles/gemm_kp.hpp", "tiles/matrix_gemm.hpp", "tiles/matrix_item.hpp", "tiles/plan.hpp", "tiles/stream.hpp", + "flashnext/streams.hpp", "flashnext/ngram.hpp", "flashnext/indexer.hpp", "flashnext/sparse.hpp", "ops/nemotron_moe.hpp", "quant/bf16_decoder.hpp", + "quant/dense_tiles.hpp", "tiles/wmma12_gemm.hpp", "tiles/wmma12_gemm_k32_ref.hpp", "ops/columns.hpp", "columns_controls.hpp", "ops/vision.hpp", + "ops/dense_text.hpp", "ops/vl_position.hpp", "flashnext/sparse_lanes.hpp", "tiles/wmma12_step.hpp", }; /// The flags of the kernels' first build: no contraction, wave32 on RDNA, C++20. const flags = [_][]const u8{ "-D__HIP_PLATFORM_AMD__=1", "-DUSE_ROCM=1", "-DHIPBLAS_V2", "-fPIC", "-DCUDA_HAS_FP16=1", "-DHIP_ENABLE_WARP_SYNC_BUILTINS=1", "-std=c++20", "-fno-gpu-rdc", "-mno-wavefrontsize64", "-ffp-contract=off" }; diff --git a/zig/kernels/hip/tiles/wmma12_gemm.hpp b/zig/kernels/hip/tiles/wmma12_gemm.hpp index 22279860782..0a9bc6de912 100644 --- a/zig/kernels/hip/tiles/wmma12_gemm.hpp +++ b/zig/kernels/hip/tiles/wmma12_gemm.hpp @@ -1,31 +1,18 @@ #pragma once // gfx12 WMMA BF16 GEMM tile: y = x . W^T for BF16 x (m x k) and BF16 W (n x k, as stored), fp32 sums. -// Two block geometries (W12Geo), picked by the product's size; whatever the block, each output adds its k products in k -// order, 16 a WMMA step into one fp32 accumulator, so a row's bytes depend on neither m nor the geometry. +// Two block geometries (W12Geo, in tiles/wmma12_step.hpp), picked by the product's size; whatever the block, each +// output adds its k products in k order, 16 a WMMA step into one fp32 accumulator, so a row's bytes depend on neither m +// nor the geometry. // The K loop's barrier orders LDS only (no global data moves between waves), so it keeps the L0 cache. #include "common/vec.hpp" #include "common/wmma.hpp" +#include "tiles/wmma12_step.hpp" namespace tf { namespace rocm { -// A block of BM x BN outputs, WM x WN waves of (BM / WM) x (BN / WN), K steps of BK through double-buffered LDS. -// Staged rows are padded by 8 halves when that fits 64 KiB; past it they are unpadded with their 16-byte chunks -// XOR-swizzled by row (w12_at), which spreads the readers' banks without the pad. -template -struct W12Geo { - static constexpr int BM = BM_, BN = BN_, BK = BK_, WM = WM_, WN = WN_; - static constexpr bool Padded = 2 * (BM + BN) * (BK + 8) * 2 <= 64 * 1024; - static constexpr int Ld = Padded ? BK + 8 : BK; // halves a staged row, 16-byte aligned - static constexpr int Threads = 32 * WM * WN; - static_assert(BM % (16 * WM) == 0 && BN % (16 * WN) == 0, "a wave's sub-tile is whole 16 x 16 products"); - static_assert(BK % 16 == 0, "a K step is whole 16-deep products"); - static_assert(Padded || BK % 64 == 0, "an unpadded row holds whole groups of 8 chunks to swizzle"); - static_assert(2 * (BM + BN) * Ld * 2 <= 64 * 1024, "double-buffered x and W rows fit 64 KiB of LDS"); -}; - // Few rows or narrow outputs take the small block so the grid fills the GPU; launches/dense.zig mirrors both shapes. // The big block's 64-deep steps take 64 KiB unpadded (swizzled): half the barriers of 32-deep steps. using W12Small = W12Geo<16, 64, 64, 1, 4>; @@ -34,37 +21,6 @@ using W12Big = W12Geo<128, 128, 64, 2, 4>; using W12Pair = W12Geo<16, 64, 64, 1, 2>; constexpr int kW12Band = 4; // row blocks a band of the launch order walks the column blocks with -typedef __bf16 bf16x8 __attribute__((ext_vector_type(8))); - -// The half offset of 16-byte chunk c of staged row r: in place when padded, else at c ^ (r % 8). -template -__device__ __forceinline__ int w12_at(int r, int c) { - if constexpr (G::Padded) return r * G::Ld + 8 * c; - else return r * G::Ld + 8 * (c ^ (r % 8)); -} - -// The K loop's barrier: LDS stores before it are seen by LDS loads after it; global memory is not ordered (none moves). -__device__ __forceinline__ void w12_sync() { - __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local"); - __builtin_amdgcn_s_barrier(); - __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local"); -} - -// The served step, a 16-deep BF16 product into fp32 sums; the contract's control swaps in a less exact one. -struct W12Step { -#if TF_DEVICE_WMMA_GFX12 - __device__ static f32x8 mma(bf16x8 a, bf16x8 b, f32x8 c) { - return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(a, b, c); - } -#endif -}; - -// The served tile's staging: operand loads undo the stores' swizzle, and the K loop's barriers order LDS. The contract's -// controls each break one (a swizzle the loads ignore, a K loop without its barriers) and must go red. -struct W12Exact { - static constexpr bool swizzled_loads = true, ordered = true; -}; - // Block (x, y) in launch order takes tile (bx, by): bands of kW12Band row blocks share each column block's weights. __device__ __forceinline__ void w12_band(int& bx, int& by) { const int cols = gridDim.x, rows = gridDim.y; @@ -125,17 +81,15 @@ __device__ __forceinline__ void wmma12_gemm_tile(const Args& a) { #pragma unroll for (int q = 0; q < XPT; ++q) { const int p = tid + q * kW12Threads; - if (XP % kW12Threads == 0 || p < XP) *reinterpret_cast(&xs[buf][w12_at(p / PR, p % PR)]) = rx[q]; + if (XP % kW12Threads == 0 || p < XP) w12_store(xs[buf], p / PR, p % PR, rx[q]); } #pragma unroll for (int q = 0; q < WPT; ++q) { const int p = tid + q * kW12Threads; - if (WP % kW12Threads == 0 || p < WP) *reinterpret_cast(&ws[buf][w12_at(p / PR, p % PR)]) = rw[q]; + if (WP % kW12Threads == 0 || p < WP) w12_store(ws[buf], p / PR, p % PR, rw[q]); } }; - // an operand's chunk as the stores laid it out (a control's loads may ignore the swizzle) - const auto load_at = [](int r, int c) { return Fault::swizzled_loads ? w12_at(r, c) : r * G::Ld + 8 * c; }; f32x8 acc[TM][TN]; #pragma unroll for (int i = 0; i < TM; ++i) @@ -146,7 +100,7 @@ __device__ __forceinline__ void wmma12_gemm_tile(const Args& a) { const int koff = 8 * (lane >> 4); fetch(0); stash(0); - if constexpr (Fault::ordered) w12_sync(); + w12_sync(); for (int s = 0; s < steps; ++s) { const int buf = s & 1; if (s + 1 < steps) fetch(s + 1); @@ -154,16 +108,16 @@ __device__ __forceinline__ void wmma12_gemm_tile(const Args& a) { for (int kk = 0; kk < kW12K; kk += 16) { bf16x8 av[TM], bv[TN]; #pragma unroll - for (int i = 0; i < TM; ++i) av[i] = *reinterpret_cast(&xs[buf][load_at(arow + 16 * i, (kk + koff) / 8)]); + for (int i = 0; i < TM; ++i) av[i] = w12_load(xs[buf], arow + 16 * i, (kk + koff) / 8); #pragma unroll - for (int j = 0; j < TN; ++j) bv[j] = *reinterpret_cast(&ws[buf][load_at(bcol + 16 * j, (kk + koff) / 8)]); + for (int j = 0; j < TN; ++j) bv[j] = w12_load(ws[buf], bcol + 16 * j, (kk + koff) / 8); #pragma unroll for (int i = 0; i < TM; ++i) #pragma unroll for (int j = 0; j < TN; ++j) acc[i][j] = Step::mma(av[i], bv[j], acc[i][j]); } if (s + 1 < steps) stash(buf ^ 1); - if constexpr (Fault::ordered) w12_sync(); + w12_sync(); } if constexpr (requires { Epi::pairs; }) { // weights packed in 16-row groups (gate f..f+15, then up f..f+15) and a wave's columns whole 32-column groups: diff --git a/zig/kernels/hip/tiles/wmma12_step.hpp b/zig/kernels/hip/tiles/wmma12_step.hpp new file mode 100644 index 00000000000..19b4937817c --- /dev/null +++ b/zig/kernels/hip/tiles/wmma12_step.hpp @@ -0,0 +1,79 @@ +#pragma once + +// The gfx12 WMMA pieces below a tile's K loop, shared by the tiles that stage BF16 operands in LDS: the block +// geometry and its staging layout, the LDS-only barrier, the 16-deep BF16 step, the operand loads, and the staging +// the contract's controls break. A tile keeps its own K loop and epilogue (tiles/wmma12_gemm.hpp). +// tiles/wmma12_gemm_k32_ref.hpp does not include this header: it is a frozen copy that the served block must equal. + +#include "common/arch.hpp" +#include "common/vec.hpp" +#include "common/wmma.hpp" + +namespace tf { +namespace rocm { + +// A block of BM x BN outputs, WM x WN waves of (BM / WM) x (BN / WN), K steps of BK through double-buffered LDS. +// Staged rows are padded by 8 halves when that fits 64 KiB; past it they are unpadded with their 16-byte chunks +// XOR-swizzled by row (w12_at), which spreads the readers' banks without the pad. +template +struct W12Geo { + static constexpr int BM = BM_, BN = BN_, BK = BK_, WM = WM_, WN = WN_; + static constexpr bool Padded = 2 * (BM + BN) * (BK + 8) * 2 <= 64 * 1024; + static constexpr int Ld = Padded ? BK + 8 : BK; // halves a staged row, 16-byte aligned + static constexpr int Threads = 32 * WM * WN; + static_assert(BM % (16 * WM) == 0 && BN % (16 * WN) == 0, "a wave's sub-tile is whole 16 x 16 products"); + static_assert(BK % 16 == 0, "a K step is whole 16-deep products"); + static_assert(Padded || BK % 64 == 0, "an unpadded row holds whole groups of 8 chunks to swizzle"); + static_assert(2 * (BM + BN) * Ld * 2 <= 64 * 1024, "double-buffered x and W rows fit 64 KiB of LDS"); +}; + +typedef __bf16 bf16x8 __attribute__((ext_vector_type(8))); + +// The half offset of 16-byte chunk c of staged row r: in place when padded, else at c ^ (r % 8). +template +__device__ __forceinline__ int w12_at(int r, int c) { + if constexpr (G::Padded) return r * G::Ld + 8 * c; + else return r * G::Ld + 8 * (c ^ (r % 8)); +} + +// The served step, a 16-deep BF16 product into fp32 sums; the contract's control swaps in a less exact one. +struct W12Step { +#if TF_DEVICE_WMMA_GFX12 + __device__ static f32x8 mma(bf16x8 a, bf16x8 b, f32x8 c) { + return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(a, b, c); + } +#endif +}; + +// The served tile's staging: operand loads undo the stores' swizzle, and the K loop's barriers order LDS. The +// contract's controls each break one (a swizzle the loads ignore, a K loop without its barriers) and must go red. +struct W12Exact { + static constexpr bool swizzled_loads = true, ordered = true; +}; + +// The K loop's barrier: LDS stores before it are seen by LDS loads after it; global memory is not ordered (none moves). +// A control whose K loop is unordered gets no barrier. +template +__device__ __forceinline__ void w12_sync() { + if constexpr (Fault::ordered) { + __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local"); + __builtin_amdgcn_s_barrier(); + __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local"); + } +} + +// Stores an operand's chunk c of staged row r where w12_load reads it. +template +__device__ __forceinline__ void w12_store(unsigned short* stage, int r, int c, u32x4 v) { + *reinterpret_cast(&stage[w12_at(r, c)]) = v; +} + +// An operand's chunk c of staged row r as the stores laid it out (a control's loads may ignore the swizzle). +template +__device__ __forceinline__ bf16x8 w12_load(const unsigned short* stage, int r, int c) { + const int at = Fault::swizzled_loads ? w12_at(r, c) : r * G::Ld + 8 * c; + return *reinterpret_cast(&stage[at]); +} + +} // namespace rocm +} // namespace tf diff --git a/zig/src/hip/moe.zig b/zig/src/hip/moe.zig index 1f9166fa718..5ead1118201 100644 --- a/zig/src/hip/moe.zig +++ b/zig/src/hip/moe.zig @@ -55,6 +55,11 @@ pub fn bucket(rows: usize) usize { return @as(usize, 1) << @intCast(@max(4, bits)); } +/// Plan rows for `rows` real rows: exact on explicit exact plans or RDNA3.5 lane verify rounds, else bucket(rows). +pub fn planRows(o: Ops, exact: bool, rows: usize) usize { + return if (exact or (o.window and o.l.affine.caps.generation == .rdna3_5)) rows else bucket(rows); +} + /// max_items(pairs, experts, min(TILE, LANE_ROWS)): an item a used expert plus one a tile of pairs past its first. pub fn capacity(pairs: usize, experts: usize) usize { return @min(pairs, experts) + pairs / @min(TILE, LANE_ROWS); @@ -81,7 +86,7 @@ pub fn run(o: Ops, kind: Kind, r: Routed, x: Tensor, rows: usize, prefill: bool) _ = prefill; // the affine experts' arithmetic does not depend on it (the plan's tile comes from tile_for) const ex = r.experts; const slots = r.top_k + 1; - const size = if (r.exact) rows else bucket(rows); + const size = planRows(o, r.exact, rows); const pairs = rows * slots; const cap = capacity(size * slots, r.rows); const logits = try o.arena.of(f32, rows * r.rows); @@ -143,7 +148,7 @@ pub const Parts = struct { y: u64, wts: u64, slots: usize }; pub fn parts(o: Ops, kind: Kind, r: Routed, x: Tensor, rows: usize) ops.Error!Parts { std.debug.assert(r.experts.shared == null); const slots = r.top_k + 1; - const size = if (r.exact) rows else bucket(rows); + const size = planRows(o, r.exact, rows); const cap = capacity(size * slots, r.rows); const logits = try o.arena.of(f32, rows * r.rows); const pick = try o.arena.of(i32, size * slots); @@ -205,3 +210,20 @@ test "the routed products take the decode tile below 64 rows and in a lane round try std.testing.expectEqual(@as(usize, LANE_ROWS), tileFor(round, BLOCK_FROM)); try std.testing.expectEqual(@as(usize, LANE_ROWS), tileFor(round, 2048)); } + +test "planRows keeps RDNA3.5 lane rounds exact while leaving non-RDNA3.5 and non-window launches bucketed" { + const Caps = @import("caps.zig").Caps; + const Launcher = @import("launches.zig").Launcher; + for ([_][]const u8{ "gfx1030", "gfx1100", "gfx1151", "gfx1201" }) |name| { + var l: Launcher = undefined; + l.affine.caps = Caps.of(name).?; + const prefill: Ops = .{ .l = &l, .bf16 = true, .stream = undefined, .arena = undefined, .window = false }; + var window = prefill; + window.window = true; + try std.testing.expectEqual(@as(usize, 16), planRows(prefill, false, 3)); + try std.testing.expectEqual(@as(usize, 3), planRows(prefill, true, 3)); + const want: usize = if (l.affine.caps.generation == .rdna3_5) 3 else 16; + try std.testing.expectEqual(want, planRows(window, false, 3)); + try std.testing.expectEqual(@as(usize, 3), planRows(window, true, 3)); + } +} diff --git a/zig/src/hip_serve/costs.zig b/zig/src/hip_serve/costs.zig index 578d6bd4869..d24f8a061b5 100644 --- a/zig/src/hip_serve/costs.zig +++ b/zig/src/hip_serve/costs.zig @@ -62,7 +62,7 @@ pub fn forwards(r: anytype, widest: usize, streams: usize, batch_rows: usize, ou } } -/// `r.time(&.{w})` (one forward's mean ms) of a lone window of each width to `widest` rows. +/// `r.time(&.{w})` (one forward's mean ms) of a lone window of each width to `widest` rows, pooled across tile steps. pub fn windows(r: anytype, widest: usize, out: *Costs) !void { out.windows = 0; for (1..out.window.len + 1) |w| { @@ -70,6 +70,37 @@ pub fn windows(r: anytype, widest: usize, out: *Costs) !void { out.window[out.windows] = .{ .width = @intCast(w), .ms = try r.time(&.{w}) }; out.windows += 1; } + poolWindowRows(out.window[0..out.windows]); +} + +/// Pools rising added-row ms within each 4-row regime so a tile step never prices an earlier draft under a later one. +pub fn poolWindowRows(ws: []Cost) void { + if (ws.len <= 2) return; + std.debug.assert(ws.len <= 16); + var sums: [16]f64 = undefined; + var counts: [16]f64 = undefined; + var m: usize = 0; + var first: usize = 0; + for (ws[0 .. ws.len - 1], ws[1..], 2..) |a, b, r| { + if ((r - 1) % window == 0) first = m + 1; + sums[m] = b.ms - a.ms; + counts[m] = 1; + m += 1; + while (m > first + 1 and sums[m - 2] * counts[m - 1] < sums[m - 1] * counts[m - 2]) { + sums[m - 2] += sums[m - 1]; + counts[m - 2] += counts[m - 1]; + m -= 1; + } + } + var at: usize = 1; + for (sums[0..m], counts[0..m]) |s, k| { + const base = ws[at - 1].ms; + const n: usize = @intFromFloat(k); + for (0..n) |j| { + ws[at].ms = base + s / k * @as(f64, @floatFromInt(j + 1)); + at += 1; + } + } } /// Each row bucket shared rounds pad to, to `batch_rows`, timed at its rows over `streams` windows, prices its totals. @@ -130,3 +161,24 @@ test "lone widths to the widest, shared totals the streams can hold" { try std.testing.expectEqual(@as(u32, 12), c.shared[3].width); try std.testing.expectEqual(@as(usize, 3), f.calls.items[f.calls.items.len - 1]); } + +test "windows pools a rising added-row step across tile boundaries while leaving concave rows alone" { + const Script = struct { + ms: []const f64, + fn time(s: @This(), widths: []const usize) !f64 { + return s.ms[widths[0] - 1]; + } + }; + var c: Costs = .{}; + try windows(Script{ .ms = &.{ 10, 13, 15, 16 } }, 4, &c); + try std.testing.expectEqual(@as(usize, 4), c.windows); + for ([_]f64{ 10, 13, 15, 16 }, 0..) |want, i| try std.testing.expectApproxEqAbs(want, c.window[i].ms, 1e-12); + + try windows(Script{ .ms = &.{ 10, 11, 14, 15 } }, 4, &c); + try std.testing.expectEqual(@as(usize, 4), c.windows); + for ([_]f64{ 10, 12, 14, 15 }, 0..) |want, i| try std.testing.expectApproxEqAbs(want, c.window[i].ms, 1e-12); + + try windows(Script{ .ms = &.{ 10, 11, 14, 15, 21, 22, 25, 26 } }, 8, &c); + try std.testing.expectEqual(@as(usize, 8), c.windows); + for ([_]f64{ 10, 12, 14, 15, 21, 23, 25, 26 }, 0..) |want, i| try std.testing.expectApproxEqAbs(want, c.window[i].ms, 1e-12); +}