diff --git a/CHANGELOG.md b/CHANGELOG.md index 00472b8589e..ae204227c93 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,9 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Qwen3.8-Flash-Next on HIP fills prompts faster: its sparse attention runs a new kernel with the same sums as before (a lane holds a key and several heads, keys and values staged in the cache type), so replies are unchanged. On a Radeon 8060S (gfx1151), cold prompts of 2,048 to 63,728 tokens finish 29 to 41% sooner; other HIP chips take the kernel but weren't run (#1877). Thanks to @gilby. +- HIP on gfx12 under `--policy matrix=on`: Qwen3 dense checkpoints load each layer's gate and up weights interleaved as one weight, and one WMMA product writes silu(gate) x up in its epilogue instead of two products and `tf_silu_mul`, with the same output bytes: Qwen3-Reranker-8B ranks 16 documents in 0.657 to 0.661 s instead of 0.687 to 0.697 s and Qwen3-Embedding-8B embeds 100 short inputs in 0.901 to 0.911 s instead of 0.940 to 0.948 s on a Radeon AI PRO R9700. The kernel contract checks both fused blocks byte for byte against the unfused launches (part of #2245). Thanks to @laudney. +- Nemotron on Macs: the masked prompt shader calls the shared `tf_paged_row` page helper again, so its prompt sources compile; #2322 had used the name #2283 retired the same day (#2548). - Server: control bytes in a request line (C0, DEL and C1) appear in the access log as `\xNN`, so a request cannot write terminal escapes into the log; ordinary lines are unchanged (#2542). Thanks to @chadhurley25075-png. - Conversation states on disk (`--learn-conversations`): a row block or state file whose trailer sizes add up to the file only by wrapping past 2^64 is refused at open, where a safe build used to panic on the addition (#2544). Thanks to @chadhurley25075-png. diff --git a/zig/build/hip.zig b/zig/build/hip.zig index a919f2c3c92..a74e584fa7e 100644 --- a/zig/build/hip.zig +++ b/zig/build/hip.zig @@ -513,15 +513,15 @@ 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/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", + "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/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", }; /// 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/flashnext/flashnext.hip b/zig/kernels/hip/flashnext/flashnext.hip index 19260651c6c..3195bf10c93 100644 --- a/zig/kernels/hip/flashnext/flashnext.hip +++ b/zig/kernels/hip/flashnext/flashnext.hip @@ -4,3 +4,4 @@ #include "ngram.hpp" #include "indexer.hpp" #include "sparse.hpp" +#include "sparse_lanes.hpp" diff --git a/zig/kernels/hip/flashnext/sparse_lanes.hpp b/zig/kernels/hip/flashnext/sparse_lanes.hpp new file mode 100644 index 00000000000..a983d535f7c --- /dev/null +++ b/zig/kernels/hip/flashnext/sparse_lanes.hpp @@ -0,0 +1,209 @@ +#pragma once + +#include "../ops/common.hpp" + +// sparse_parts with the same fp32 operations in the same order: 16-bit staging, a lane a key and several heads. + +namespace { + +constexpr int kLanesTiles = 1; +constexpr int kLanesRow = kSparseMostDims + 8; + +template +__device__ __forceinline__ float lanes_widen(uint32_t h) { + if constexpr (kKind == 1) return __half2float(__ushort_as_half(static_cast(h))); + return bf16_to_float(static_cast(h)); +} + +// Block (g, r, p) as sparse_parts over a kKind cache (1 fp16, 2 bf16): a lane a key and kHeads heads, 2 dims a thread. +template +__device__ void sparse_lanes(const float* q, const void* k, const void* v, const int* ids, long long id_stride, + const int* count, const int* sparse, float* parts_o, float* parts_ms, int heads, + int kv_heads, int dims, long long cap, float scale, int parts) { + constexpr int kWavesTile = kSparseWaves / kLanesTiles; + constexpr int kHeads = (kSparseGroup + kWavesTile - 1) / kWavesTile; + constexpr int kHalf = (kSparseGroup + 1) / 2; + __shared__ __attribute__((aligned(16))) float qs[kSparseGroup][kSparseMostDims]; + __shared__ __attribute__((aligned(16))) uint16_t kv[kLanesTiles][kSparseTile][kLanesRow]; + __shared__ __attribute__((aligned(16))) float ps[kLanesTiles][kSparseGroup][kSparseTile]; + __shared__ float tree[kLanesTiles][kSparseGroup], tops[kLanesTiles][kSparseGroup], sums[kLanesTiles][kSparseGroup]; + __shared__ float fs[kLanesTiles][kSparseGroup], m[kSparseGroup], l[kSparseGroup]; + __shared__ long long keys[kLanesTiles][kSparseTile]; + const int g = blockIdx.x, r = blockIdx.y, part = blockIdx.z; + const int group = heads / kv_heads; + const int t = threadIdx.x, lane = t & 31, wave = t >> 5; + const int n = count[r]; + const bool listed = ids != nullptr && sparse != nullptr && sparse[r] != 0; + const int lo = static_cast(static_cast(part) * n / parts); + const int hi = static_cast(static_cast(part + 1) * n / parts); + const long long head_base = static_cast(g) * cap * dims; + const uint16_t* k16 = static_cast(k); + const uint16_t* v16 = static_cast(v); + for (int i = t; i < group * dims; i += kSparseWaves * 32) { + const int h = i / dims, d = i % dims; + qs[h][d] = q[(static_cast(r) * heads + g * group + h) * dims + d] * scale; + } + if (t < kSparseGroup) { + m[t] = -INFINITY; + l[t] = 0.f; + } + // scores: this wave's tile and first head; values: this thread's dim pair and first head + const int slot = wave / kWavesTile, h0 = (wave % kWavesTile) * kHeads; + const int dp = (t & 127) * 2, hv0 = (t >> 7) * kHalf; + float o[kHalf][2]; +#pragma unroll + for (int h = 0; h < kHalf; ++h) o[h][0] = o[h][1] = 0.f; + const int chunks = dims / 8; + for (int t0 = lo; t0 < hi; t0 += kLanesTiles * kSparseTile) { + int tn[kLanesTiles]; +#pragma unroll + for (int s = 0; s < kLanesTiles; ++s) tn[s] = max(0, min(kSparseTile, hi - t0 - s * kSparseTile)); + __syncthreads(); + if (t < kLanesTiles * kSparseTile) { + const int s = t / kSparseTile, j = t % kSparseTile, at = t0 + s * kSparseTile + j; + if (j < tn[s]) keys[s][j] = listed ? ids[r * id_stride + at] : at; + } + __syncthreads(); + for (int i = t; i < kLanesTiles * kSparseTile * chunks; i += kSparseWaves * 32) { + const int s = i / (kSparseTile * chunks), j = (i / chunks) % kSparseTile, c = i % chunks; + if (j < tn[s]) + *reinterpret_cast(&kv[s][j][c * 8]) = + *reinterpret_cast(k16 + head_base + keys[s][j] * dims + c * 8); + } + __syncthreads(); + float sc[kHeads]; +#pragma unroll + for (int a = 0; a < kHeads; ++a) sc[a] = 0.f; + const bool live = lane < tn[slot]; + if (tn[slot] > 0) { +#pragma unroll 4 + for (int d = 0; d < dims; d += 4) { + const uint2 w = *reinterpret_cast(&kv[slot][lane][d]); + const float k0 = lanes_widen(w.x & 0xffff), k1 = lanes_widen(w.x >> 16); + const float k2 = lanes_widen(w.y & 0xffff), k3 = lanes_widen(w.y >> 16); +#pragma unroll + for (int a = 0; a < kHeads; ++a) { + const float4 x = *reinterpret_cast(&qs[min(h0 + a, kSparseGroup - 1)][d]); + sc[a] += x.x * k0; + sc[a] += x.y * k1; + sc[a] += x.z * k2; + sc[a] += x.w * k3; + } + } +#pragma unroll + for (int a = 0; a < kHeads; ++a) { + float top = live ? sc[a] : -INFINITY; +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) top = fmaxf(top, __shfl_xor(top, mask, 32)); + if (lane == 0 && h0 + a < group) tree[slot][h0 + a] = top; + } + } + __syncthreads(); + // values replace the keys; each tile's top is folded into the running max in tile order + for (int i = t; i < kLanesTiles * kSparseTile * chunks; i += kSparseWaves * 32) { + const int s = i / (kSparseTile * chunks), j = (i / chunks) % kSparseTile, c = i % chunks; + if (j < tn[s]) + *reinterpret_cast(&kv[s][j][c * 8]) = + *reinterpret_cast(v16 + head_base + keys[s][j] * dims + c * 8); + } + if (tn[slot] > 0) { +#pragma unroll + for (int a = 0; a < kHeads; ++a) { + const int h = h0 + a; + if (h >= group) continue; + float top = fmaxf(tree[0][h], m[h]); + for (int s = 1; s <= slot; ++s) top = fmaxf(tree[s][h], top); + const float e = live ? expf(sc[a] - top) : 0.f; + float sum = e; +#pragma unroll + for (int mask = 16; mask > 0; mask >>= 1) sum += __shfl_xor(sum, mask, 32); + ps[slot][h][lane] = e; + if (lane == 0) { + tops[slot][h] = top; + sums[slot][h] = sum; + } + } + } + __syncthreads(); + if (t < group) { +#pragma unroll + for (int s = 0; s < kLanesTiles; ++s) { + if (tn[s] == 0) break; + const float top = tops[s][t]; + const float f = expf(m[t] - top); + fs[s][t] = f; + l[t] = l[t] * f + sums[s][t]; + m[t] = top; + } + } + __syncthreads(); + if (dp < dims) { +#pragma unroll + for (int s = 0; s < kLanesTiles; ++s) { + if (tn[s] == 0) break; +#pragma unroll + for (int h = 0; h < kHalf; ++h) { + const float f = fs[s][hv0 + h]; + o[h][0] *= f; + o[h][1] *= f; + } + for (int j = 0; j < tn[s]; ++j) { + const uint32_t w = *reinterpret_cast(&kv[s][j][dp]); + const float v0 = lanes_widen(w & 0xffff), v1 = lanes_widen(w >> 16); +#pragma unroll + for (int h = 0; h < kHalf; ++h) { + const float p = ps[s][hv0 + h][j]; + o[h][0] += p * v0; + o[h][1] += p * v1; + } + } + } + } + } + __syncthreads(); + for (int h = 0; h < kHalf; ++h) { + if (hv0 + h >= group || dp >= dims) continue; + const long long out = (static_cast(r) * heads + g * group + hv0 + h) * parts + part; + parts_o[out * dims + dp] = o[h][0]; + parts_o[out * dims + dp + 1] = o[h][1]; + } + if (t < group) { + const long long out = (static_cast(r) * heads + g * group + t) * parts + part; + parts_ms[out * 2] = m[t]; + parts_ms[out * 2 + 1] = l[t]; + } +} + +extern "C" __global__ void __launch_bounds__(kSparseWaves * 32, 2) +tf_fn_sparse_lanes6_f16(const float* q, const void* k, const void* v, const int* ids, long long id_stride, + const int* count, const int* sparse, float* parts_o, float* parts_ms, int heads, + int kv_heads, int dims, long long cap, float scale, int parts) { + sparse_lanes<6, 1>(q, k, v, ids, id_stride, count, sparse, parts_o, parts_ms, heads, kv_heads, dims, cap, scale, + parts); +} + +extern "C" __global__ void __launch_bounds__(kSparseWaves * 32, 2) +tf_fn_sparse_lanes6_bf16(const float* q, const void* k, const void* v, const int* ids, long long id_stride, + const int* count, const int* sparse, float* parts_o, float* parts_ms, int heads, + int kv_heads, int dims, long long cap, float scale, int parts) { + sparse_lanes<6, 2>(q, k, v, ids, id_stride, count, sparse, parts_o, parts_ms, heads, kv_heads, dims, cap, scale, + parts); +} + +extern "C" __global__ void __launch_bounds__(kSparseWaves * 32, 2) +tf_fn_sparse_lanes12_f16(const float* q, const void* k, const void* v, const int* ids, long long id_stride, + const int* count, const int* sparse, float* parts_o, float* parts_ms, int heads, + int kv_heads, int dims, long long cap, float scale, int parts) { + sparse_lanes<12, 1>(q, k, v, ids, id_stride, count, sparse, parts_o, parts_ms, heads, kv_heads, dims, cap, scale, + parts); +} + +extern "C" __global__ void __launch_bounds__(kSparseWaves * 32, 2) +tf_fn_sparse_lanes12_bf16(const float* q, const void* k, const void* v, const int* ids, long long id_stride, + const int* count, const int* sparse, float* parts_o, float* parts_ms, int heads, + int kv_heads, int dims, long long cap, float scale, int parts) { + sparse_lanes<12, 2>(q, k, v, ids, id_stride, count, sparse, parts_o, parts_ms, heads, kv_heads, dims, cap, scale, + parts); +} + +} // namespace diff --git a/zig/src/core/contract/hip_records.zig b/zig/src/core/contract/hip_records.zig index 300d33ea28d..26d5834ad24 100644 --- a/zig/src/core/contract/hip_records.zig +++ b/zig/src/core/contract/hip_records.zig @@ -494,7 +494,7 @@ const own_records = [own_count]Record{ }, }, } ++ @import("hip_records_pair.zig").records ++ @import("hip_records_prompt.zig").records ++ - @import("hip_records_score.zig").records ++ @import("hip_records_embed.zig").records ++ @import("hip_records_tail.zig").records ++ @import("hip_records_tap.zig").records; + @import("hip_records_score.zig").records ++ @import("hip_records_embed.zig").records ++ @import("hip_records_tail.zig").records ++ @import("hip_records_tap.zig").records ++ @import("hip_records_sparse.zig").records; pub const records = own_records ++ @import("hip_records_stream.zig").records ++ @import("hip_records_router.zig").records ++ @import("hip_records_item.zig").records ++ @import("hip_records_qwen3.zig").records ++ @import("hip_records_columns.zig").records ++ diff --git a/zig/src/core/contract/hip_records_families.zig b/zig/src/core/contract/hip_records_families.zig index fe6d2369b2e..d7a7c340df7 100644 --- a/zig/src/core/contract/hip_records_families.zig +++ b/zig/src/core/contract/hip_records_families.zig @@ -32,6 +32,7 @@ test "HIP record counts stay pinned in their owning files" { @import("hip_records_qwen_vision.zig").records.len, @import("hip_records_router.zig").records.len, @import("hip_records_score.zig").records.len, + @import("hip_records_sparse.zig").records.len, @import("hip_records_stream_plain.zig").records.len, @import("hip_records_stream_swiglu.zig").records.len, @import("hip_records_tail.zig").records.len, diff --git a/zig/src/core/contract/hip_records_sparse.zig b/zig/src/core/contract/hip_records_sparse.zig new file mode 100644 index 00000000000..5f3ad18bb0e --- /dev/null +++ b/zig/src/core/contract/hip_records_sparse.zig @@ -0,0 +1,21 @@ +//! Gate 5's records of Flash Next's lanes sparse attention (tf_fn_sparse_lanes12_*). +const Record = @import("hip_records.zig").Record; + +/// Flash Next's lanes sparse attention, 12 query heads a kv head, one cache kind (`early` VGPRs: gfx1030, gfx1100). +fn sparseLanes(comptime kind: []const u8, comptime early: u32, comptime late: u32) Record { + const symbol = "tf_fn_sparse_lanes12_" ++ kind; + return .{ + .launch = .{ .name = "flashnext " ++ symbol, .symbol = symbol, .image = "flashnext", .threads = 256 }, + .usage = .{ + .{ .vgprs = early, .sgprs = 55, .lds = 31264, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = early, .sgprs = 55, .lds = 31264, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = late, .sgprs = 57, .lds = 31264, .private = 0, .bound = 256, .wave = 32 }, + .{ .vgprs = late, .sgprs = 59, .lds = 31264, .private = 0, .bound = 256, .wave = 32 }, + }, + }; +} + +pub const records = [_]Record{ + sparseLanes("f16", 74, 72), + sparseLanes("bf16", 84, 83), +}; diff --git a/zig/src/hip/kernel_tests.zig b/zig/src/hip/kernel_tests.zig index 378cf0d3861..40d901ad6ab 100644 --- a/zig/src/hip/kernel_tests.zig +++ b/zig/src/hip/kernel_tests.zig @@ -45,6 +45,7 @@ test { _ = @import("kernel_tests/flashnext.zig"); _ = @import("kernel_tests/flashnext_attn.zig"); _ = @import("kernel_tests/moe_gate.zig"); + _ = @import("kernel_tests/flashnext_sparse.zig"); _ = @import("kernel_tests/nemotron/moe.zig"); _ = @import("kernel_tests/nemotron/pick.zig"); _ = @import("kernel_tests/nemotron/attention.zig"); diff --git a/zig/src/hip/kernel_tests/flashnext_sparse.zig b/zig/src/hip/kernel_tests/flashnext_sparse.zig new file mode 100644 index 00000000000..73d875976f0 --- /dev/null +++ b/zig/src/hip/kernel_tests/flashnext_sparse.zig @@ -0,0 +1,110 @@ +//! Flash Next's two sparse attention kernels on the same rows: the lanes kernel's parts equal the scalar kernel's bits. +const std = @import("std"); +const rig = @import("rig.zig"); +const fx = @import("flashnext.zig"); +const Rig = rig.Rig; +const gpa = rig.gpa; +const ptr = fx.ptr; +const DeviceBuffer = @import("../memory.zig").DeviceBuffer; +const Launcher = @import("../launches.zig").Launcher; + +const Shape = struct { heads: c_int, kv_heads: c_int, dims: c_int, parts: c_int }; + +test "sparse attention: the lanes kernel gives the scalar kernel's bits at every count, part and cache kind" { + const t = try Rig.open(1 << 22); + defer t.close(); + const shapes = [_]Shape{ + .{ .heads = 24, .kv_heads = 2, .dims = 256, .parts = 16 }, + .{ .heads = 24, .kv_heads = 2, .dims = 256, .parts = 1 }, + .{ .heads = 6, .kv_heads = 1, .dims = 256, .parts = 3 }, + .{ .heads = 6, .kv_heads = 2, .dims = 128, .parts = 16 }, + .{ .heads = 12, .kv_heads = 1, .dims = 128, .parts = 5 }, + }; + for ([_]c_int{ 2, 1 }) |kind| for (shapes, 0..) |s, i| try same(t, s, kind, 0x5A11 + i); +} + +fn same(t: *Rig, s: Shape, kind: c_int, seed: u64) !void { + var rng: rig.Rng = .{ .state = seed }; + const heads: usize = @intCast(s.heads); + const kvh: usize = @intCast(s.kv_heads); + const dims: usize = @intCast(s.dims); + const parts: usize = @intCast(s.parts); + const cap = 2100; + const stride = 2048; + // counts across tile seams, a part shorter than a tile, empty rows and the indexer's full budget + const count = [_]i32{ 0, 1, 7, 31, 32, 33, 63, 64, 65, 97, 300, 2000, 2048, 650 }; + const sparse = [_]i32{ 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0 }; + const rows = count.len; + const keys = try gpa.alloc(u16, kvh * cap * dims * 2); + defer gpa.free(keys); + for (keys) |*x| { + const v = rng.unit() * 2.0; + x.* = if (kind == 2) rig.bf16Bits(v) else rig.f16Bits(v); + } + const hq = try gpa.alloc(f32, rows * heads * dims); + defer gpa.free(hq); + for (hq) |*x| x.* = rng.unit() * 4.0; + const ids = try gpa.alloc(i32, rows * stride); + defer gpa.free(ids); + for (0..rows) |r| for (0..stride) |j| { + ids[r * stride + j] = @intCast((j * 37 + r * 11 + (j * j) % 13) % cap); + }; + var dk = try t.upload(keys[0 .. kvh * cap * dims]); + defer dk.free(); + var dv = try t.upload(keys[kvh * cap * dims ..]); + defer dv.free(); + var dq = try t.upload(hq); + defer dq.free(); + var di = try t.upload(ids); + defer di.free(); + var dc = try t.upload(&count); + defer dc.free(); + var ds = try t.upload(&sparse); + defer ds.free(); + var outs: [2][3]DeviceBuffer = undefined; + for (&outs) |*o| { + o[0] = try t.alloc(rows * heads * parts * dims * 4); + o[1] = try t.alloc(rows * heads * parts * 2 * 4); + o[2] = try t.alloc(rows * heads * dims * 4); + } + defer for (&outs) |*o| for (o) |*b| b.free(); + const scale: f32 = 1.0 / 16.0; + const st = t.stream.handle; + const Fn = *const @TypeOf(Launcher.fn_sparse_attention); + for ([_]Fn{ &Launcher.fn_sparse_attention_scalar, &Launcher.fn_sparse_attention }, 0..) |call, w| { + try call( + &t.on, + ptr(?[*]const f32, dq), + ptr(?*const anyopaque, dk), + ptr(?*const anyopaque, dv), + kind, + ptr(?[*]const i32, di), + stride, + ptr(?[*]const i32, dc), + ptr(?[*]const i32, ds), + ptr(?[*]f32, outs[w][0]), + ptr(?[*]f32, outs[w][1]), + ptr(?[*]f32, outs[w][2]), + @intCast(rows), + s.heads, + s.kv_heads, + s.dims, + cap, + scale, + s.parts, + st, + ); + } + try t.stream.synchronize(); + for (0..3) |b| { + const want = try rig.download(u32, outs[0][b]); + defer gpa.free(want); + const got = try rig.download(u32, outs[1][b]); + defer gpa.free(got); + for (want, got, 0..) |x, y, i| try rig.expect( + x == y, + "kind {d} heads {d}/{d} dims {d} parts {d}: buffer {d} word {d}: scalar {x} lanes {x}", + .{ kind, s.heads, s.kv_heads, s.dims, s.parts, b, i, x, y }, + ); + } +} diff --git a/zig/src/hip/launches.zig b/zig/src/hip/launches.zig index 6f5c7ca8140..f9c4200ae6e 100644 --- a/zig/src/hip/launches.zig +++ b/zig/src/hip/launches.zig @@ -407,6 +407,7 @@ pub const Launcher = struct { pub const fn_idx_scores = flashnext.idxScores; pub const fn_idx_select = flashnext.idxSelect; pub const fn_sparse_attention = flashnext.sparseAttention; + pub const fn_sparse_attention_scalar = flashnext.sparseAttentionScalar; pub const tf_mamba_conv = mamba.tf_mamba_conv; pub const tf_mamba_dt = mamba.tf_mamba_dt; pub const tf_mamba_scan = mamba.tf_mamba_scan; diff --git a/zig/src/hip/launches/flashnext.zig b/zig/src/hip/launches/flashnext.zig index 811b2f175a8..308db874fb0 100644 --- a/zig/src/hip/launches/flashnext.zig +++ b/zig/src/hip/launches/flashnext.zig @@ -33,6 +33,7 @@ pub const Fns = struct { idx_scores: Function, idx_select: Function, sparse_parts: [2]Function, // groups of up to 6 and up to 12 query heads + sparse_lanes: [2][2]Function, // the same sums from fp16 and bf16 caches, a lane a key and several heads sparse_merge: Function, pub fn load(m: Module) Error!Fns { @@ -50,6 +51,10 @@ pub const Fns = struct { .idx_scores = try m.function("tf_fn_idx_scores"), .idx_select = try m.function("tf_fn_idx_select"), .sparse_parts = .{ try m.function("tf_fn_sparse_parts6"), try m.function("tf_fn_sparse_parts12") }, + .sparse_lanes = .{ + .{ try m.function("tf_fn_sparse_lanes6_f16"), try m.function("tf_fn_sparse_lanes6_bf16") }, + .{ try m.function("tf_fn_sparse_lanes12_f16"), try m.function("tf_fn_sparse_lanes12_bf16") }, + }, .sparse_merge = try m.function("tf_fn_sparse_merge"), }; } @@ -430,6 +435,102 @@ pub fn sparseAttention( scale: f32, parts: c_int, s: S, +) Error!void { + return sparseWith( + .auto, + l, + q, + k, + v, + cache_kind, + ids, + id_stride, + count, + sparse, + parts_o, + parts_ms, + out, + rows, + heads, + kv_heads, + dims, + cap, + scale, + parts, + s, + ); +} + +/// `sparseAttention` on the kernel that stages keys as fp32 one tile at a time, for tests of the faster kernel's bits. +pub fn sparseAttentionScalar( + l: *const Launcher, + q: CF, + k: C, + v: C, + cache_kind: c_int, + ids: CI, + id_stride: i64, + count: CI, + sparse: CI, + parts_o: F, + parts_ms: F, + out: F, + rows: c_int, + heads: c_int, + kv_heads: c_int, + dims: c_int, + cap: i64, + scale: f32, + parts: c_int, + s: S, +) Error!void { + return sparseWith( + .scalar, + l, + q, + k, + v, + cache_kind, + ids, + id_stride, + count, + sparse, + parts_o, + parts_ms, + out, + rows, + heads, + kv_heads, + dims, + cap, + scale, + parts, + s, + ); +} + +fn sparseWith( + kernel: enum { auto, scalar }, + l: *const Launcher, + q: CF, + k: C, + v: C, + cache_kind: c_int, + ids: CI, + id_stride: i64, + count: CI, + sparse: CI, + parts_o: F, + parts_ms: F, + out: F, + rows: c_int, + heads: c_int, + kv_heads: c_int, + dims: c_int, + cap: i64, + scale: f32, + parts: c_int, + s: S, ) Error!void { if (dims > 256 or @rem(heads, kv_heads) != 0 or @divExact(heads, kv_heads) > 12) return util.invalid("sparseAttention"); @@ -453,7 +554,28 @@ pub fn sparseAttention( parts, }) |x| try a.add(x); const wide: usize = if (@divExact(heads, kv_heads) <= 6) 0 else 1; - try l.go(l.fnx.sparse_parts[wide], dim(kv_heads, rows, parts), dim(256, 1, 1), 0, s, &a); + if (kernel == .auto and (cache_kind == 1 or cache_kind == 2) and @rem(dims, 8) == 0) { + var c: Args = .{}; + inline for (.{ + ad(q), + ad(k), + ad(v), + ad(ids), + id_stride, + ad(count), + ad(sparse), + ad(parts_o), + ad(parts_ms), + heads, + kv_heads, + dims, + cap, + scale, + parts, + }) |x| try c.add(x); + const kind: usize = @intCast(cache_kind - 1); + try l.go(l.fnx.sparse_lanes[wide][kind], dim(kv_heads, rows, parts), dim(256, 1, 1), 0, s, &c); + } else try l.go(l.fnx.sparse_parts[wide], dim(kv_heads, rows, parts), dim(256, 1, 1), 0, s, &a); var b: Args = .{}; inline for (.{ ad(parts_o), ad(parts_ms), ad(out), heads, dims, parts }) |x| try b.add(x); try l.go(l.fnx.sparse_merge, dim(heads, rows, 1), dim(256, 1, 1), 0, s, &b); diff --git a/zig/tests/hip/contract_main.zig b/zig/tests/hip/contract_main.zig index 6dea701face..1fa1cce9295 100644 --- a/zig/tests/hip/contract_main.zig +++ b/zig/tests/hip/contract_main.zig @@ -37,6 +37,7 @@ const full_k = @import("contract_vision_attention.zig"); const text_k = @import("contract_dense_text.zig"); const vl_k = @import("contract_vl.zig"); const pos_k = @import("contract_vl_position.zig"); +const sparse_k = @import("contract_sparse_lanes.zig"); const g = core.contract.gates; @@ -330,6 +331,9 @@ fn run(a: std.mem.Allocator, io: std.Io) !usize { for (&pos, std.enums.values(pos_k.Which)) |*p, which_pos| p.* = .init(a, &r, s, vl_kernels, which_pos); defer for (&pos) |*p| p.deinit(); for (&pos) |*p| try kernels.append(a, p.kernel()); + var sparse = sparse_k.SparseLanes.init(a, &r, s, &l); + defer sparse.deinit(); + try kernels.append(a, sparse.kernel()); var t: g.Tally = .{}; const t0 = ms(io); try g.runAll(a, kernels.items, 0x6b63, &t); diff --git a/zig/tests/hip/contract_sparse_lanes.zig b/zig/tests/hip/contract_sparse_lanes.zig new file mode 100644 index 00000000000..1fec7718820 --- /dev/null +++ b/zig/tests/hip/contract_sparse_lanes.zig @@ -0,0 +1,306 @@ +//! Flash Next's sparse attention on the lanes kernel under the contract on HIP: bytes equal to the scalar kernel's. +const std = @import("std"); +const hip = @import("hip"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const kit = @import("contract_kit.zig"); + +const contract = core.contract; +const c = contract.spec; +const g = contract.gates; + +const dims = 256; +const ratio = 4; +const parts = 16; +const stride = 512; // ids a row: at most 120 blocks and a tail of three tokens +const scale: f32 = 1.0 / 16.0; + +/// Fp32 sums over a row's keys and the parts merge. +fn depth(s: c.Shape) usize { + return s.k + 2 * parts; +} + +const names = [2][]const u8{ + "hip tf_fn_sparse_lanes12_f16 and tf_fn_sparse_merge", + "hip tf_fn_sparse_lanes12_bf16 and tf_fn_sparse_merge", +}; +const rule = "a NaN a row did not select never reaches it; a selected value reaches its dim, a selected key the head"; +const why = "the scalar kernel's fp32 sums in its order: a row's keys in 32-key tiles, a dim at a time"; + +pub fn spec(k: kit.Kind) c.Spec { + return .{ + .name = names[@intFromBool(k == .bf16)], + .replaces = "tf_fn_sparse_parts", + .accum = .f32, + .depth = depth, + .ops = 6, // exp, the running rescale, the parts merge and the final divide + .out = .f32, + .nan = .{ .stated = rule }, + .tiles = .{ .{ .size = 4, .min = 1 }, .{}, .{} }, + // a prompt tile, a rank's tail slice, a deep cache, a decode row and the MTP verify windows of 2 to 4 + .served = &.{ + .{ .rows = 64, .n = 24, .k = 1024 }, + .{ .rows = 17, .n = 6, .k = 1024 }, + .{ .rows = 16, .n = 12, .k = 4096 }, + .{ .rows = 1, .n = 24, .k = 4096 }, + .{ .rows = 2, .n = 24, .k = 4096 }, + .{ .rows = 3, .n = 24, .k = 4096 }, + .{ .rows = 4, .n = 24, .k = 4096 }, + }, + .sums = .{ .f16 = 0, .bf16 = 0, .why = why, .exact = false }, + }; +} + +/// A slice of rows over a kv head's cache of the kind, in the format tf_fn_idx_select writes: row 0 dense. +pub const SparseLanes = struct { + rig: rig_.Rig, + l: hip.Launcher, + k: kit.Kind, + arena: std.heap.ArenaAllocator, + shape: c.Shape = undefined, + fill: g.Fill = .random, + heads: usize = 0, + group: usize = 0, + q: []f32 = &.{}, + kc: []f64 = &.{}, + vc: []f64 = &.{}, + ids: []i32 = &.{}, + counts: []i32 = &.{}, + sparse: []i32 = &.{}, + ends: []i32 = &.{}, + dev: [9]u64 = @splat(0), + out: u64 = 0, + base: u64 = 0, // the replaced kernel's output + msg: [200]u8 = undefined, + + pub fn init(a: std.mem.Allocator, rt: *const hip.Runtime, s: hip.Stream, l: *const hip.Launcher) SparseLanes { + return .{ .rig = .{ .a = a, .r = rt, .s = s }, .l = l.*, .k = kit.act(), .arena = .init(a) }; + } + + pub fn deinit(self: *SparseLanes) void { + self.arena.deinit(); + self.rig.deinit(); + } + + pub fn kernel(self: *SparseLanes) g.Kernel { + return .{ .spec = spec(self.k), .ctx = self, .vt = &vt }; + } + + const vt = g.hooks(SparseLanes); + + fn rows(self: *const SparseLanes) usize { + return self.shape.rows; + } + + /// Causal ends march forward, rows 1..7 select five blocks and the rest 120; row 0 is dense unless it is alone. + fn select(self: *SparseLanes, a: std.mem.Allocator) !void { + const n = self.rows(); + const cap = self.shape.k; + self.ids = try a.alloc(i32, n * stride); + @memset(self.ids, 0); + self.counts = try a.alloc(i32, n); + self.sparse = try a.alloc(i32, n); + self.ends = try a.alloc(i32, n); + for (0..n) |r| { + const end = cap - n * 12 + r * 12 + r % 4; // not a multiple of ratio on three rows in four + self.ends[r] = @intCast(end); + const nb = end / ratio; + if (r == 0 and n > 1) { + self.sparse[r] = 0; + self.counts[r] = @intCast(end); + continue; + } + self.sparse[r] = 1; + const want = @min(if (r < 8) @as(usize, 5) else 120, nb - 8); + const start = (r * 3) % (nb - want); + var w: usize = 0; + for (0..want * ratio) |i| { + self.ids[r * stride + w] = @intCast(start * ratio + i); + w += 1; + } + for (nb * ratio..end) |t| { + self.ids[r * stride + w] = @intCast(t); + w += 1; + } + self.counts[r] = @intCast(w); + } + } + + /// Random: values in [-1, 1) exact in the kind. Stress: q = 0 and integer values, so every weight is 1. + pub fn prepare(self: *SparseLanes, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const group: usize = if (shape.n % 12 == 0) 12 else 6; + if (shape.rows < 1 or shape.n % group != 0 or shape.k < 12 * shape.rows + 64 or shape.k > 20000) return false; + self.rig.reset(); + _ = self.arena.reset(.retain_capacity); + const a = self.arena.allocator(); + self.shape = shape; + self.fill = fill; + self.heads = shape.n; + self.group = group; + const kv = shape.n / group; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const stress = fill == .stress; + self.q = try a.alloc(f32, shape.rows * shape.n * dims); + for (self.q) |*x| x.* = if (stress) 0 else @floatCast(rng.float(f64) * 2 - 1); + const cache = kv * shape.k * dims; + self.kc, const kb = try kit.values(a, rng, self.k, cache, -1, 1); + self.vc, const vb = try kit.values(a, rng, self.k, cache, -1, 1); + if (stress) for (self.vc, 0..) |*x, i| { + x.* = @floatFromInt(rng.intRangeAtMost(i32, -8, 8)); + kit.put(self.k, vb, i, x.*); + }; + try self.select(a); + if (fill == .nonfinite) try self.plant(kb, vb); + const ids = try self.rig.input(std.mem.sliceAsBytes(self.ids)); + const cnt = try self.rig.input(std.mem.sliceAsBytes(self.counts)); + const sparse = try self.rig.input(std.mem.sliceAsBytes(self.sparse)); + const ends = try self.rig.input(std.mem.sliceAsBytes(self.ends)); + const po = try self.rig.scratch(shape.rows * shape.n * parts * dims * 4); + const pm = try self.rig.scratch(shape.rows * shape.n * parts * 2 * 4); + const dq = try self.rig.input(std.mem.sliceAsBytes(self.q)); + self.dev = .{ dq, try self.rig.input(kb), try self.rig.input(vb), ids, cnt, sparse, ends, po, pm }; + self.out = try self.rig.output(shape.rows * shape.n * dims * 4); + self.base = try self.rig.scratch(shape.rows * shape.n * dims * 4); + return true; + } + + /// NaN in kv head 0: a key in block 12, a value in block 16 and a value in a sparse row's tail, past row 0's end. + fn plant(self: *SparseLanes, kb: []u8, vb: []u8) !void { + const nan = std.math.nan(f64); + const bad_key = 12 * ratio * dims; + const val = 16 * ratio * dims + 1; + kit.put(self.k, kb, bad_key, nan); + kit.put(self.k, vb, val, nan); + self.kc[bad_key] = nan; + self.vc[val] = nan; + const tail: usize = @intCast(@divTrunc(self.ends[@min(1, self.rows() - 1)], ratio) * ratio); + kit.put(self.k, vb, tail * dims + 5, nan); + self.vc[tail * dims + 5] = nan; + } + + pub fn run(self: *SparseLanes) !void { + const s = self.shape; + const d = self.dev; + try self.l.fn_sparse_attention( + @ptrFromInt(d[0]), + @ptrFromInt(d[1]), + @ptrFromInt(d[2]), + @backingInt(self.k), + @ptrFromInt(d[3]), + stride, + @ptrFromInt(d[4]), + @ptrFromInt(d[5]), + @ptrFromInt(d[7]), + @ptrFromInt(d[8]), + @ptrFromInt(self.out), + @intCast(s.rows), + @intCast(s.n), + @intCast(s.n / self.group), + dims, + @intCast(s.k), + scale, + parts, + self.rig.s.handle, + ); + try self.rig.s.synchronize(); + } + + /// The scalar kernel's output on the same inputs. + pub fn replaced(self: *SparseLanes) ![]const u8 { + const s = self.shape; + const d = self.dev; + try self.l.fn_sparse_attention_scalar( + @ptrFromInt(d[0]), + @ptrFromInt(d[1]), + @ptrFromInt(d[2]), + @backingInt(self.k), + @ptrFromInt(d[3]), + stride, + @ptrFromInt(d[4]), + @ptrFromInt(d[5]), + @ptrFromInt(d[7]), + @ptrFromInt(d[8]), + @ptrFromInt(self.base), + @intCast(s.rows), + @intCast(s.n), + @intCast(s.n / self.group), + dims, + @intCast(s.k), + scale, + parts, + self.rig.s.handle, + ); + try self.rig.s.synchronize(); + return self.rig.bytes(self.base, s.rows * s.n * dims * 4); + } + + pub fn count(self: *SparseLanes) usize { + return self.shape.rows * self.shape.n * dims; + } + + /// The row's selected keys below its end: its listed tokens, or all of a dense row's. + fn key(self: *const SparseLanes, r: usize, j: usize) ?usize { + const t: usize = if (self.sparse[r] != 0) @intCast(self.ids[r * stride + j]) else j; + return if (t < self.ends[r]) t else null; + } + + /// fp64 attention over the selected keys only; a NaN score zeroes the head, as the merge does. + pub fn reference(self: *SparseLanes, want: []f64, mag: []f64) !void { + const a = self.arena.allocator(); + const w = try a.alloc(f64, @intCast(std.mem.max(i32, self.counts))); + defer a.free(w); + for (0..self.rows()) |r| for (0..self.heads) |h| { + const kvh = h / self.group; + const n: usize = @intCast(self.counts[r]); + var top = -std.math.inf(f64); + var nan = false; + for (0..n) |j| { + w[j] = std.math.nan(f64); + const t = self.key(r, j) orelse continue; + var s: f64 = 0; + for (0..dims) |d| { + const kv: f64 = self.kc[(kvh * self.shape.k + t) * dims + d]; + const p = @as(f64, self.q[(r * self.heads + h) * dims + d]) * scale * kv; + s += p; + } + w[j] = s; + nan = nan or std.math.isNan(s); + top = @max(top, s); + } + var total: f64 = 0; + for (0..n) |j| { + if (self.key(r, j) == null) { + w[j] = 0; + continue; + } + w[j] = if (nan) 0 else @exp(w[j] - top); + total += w[j]; + } + for (0..dims) |d| { + var acc: f64 = 0; + var m: f64 = 0; + const i = (r * self.heads + h) * dims + d; + if (nan) { + want[i] = 0; + mag[i] = 0; + continue; + } + for (0..n) |j| { + const t = self.key(r, j) orelse continue; + const v = self.vc[(kvh * self.shape.k + t) * dims + d]; + acc += w[j] * v; + m += w[j] * @abs(v); + } + want[i] = acc / total; + mag[i] = m / total; + } + }; + } + + /// Every sum is exact when every weight is 1 and the values are integers, in any order and either accumulator. + pub fn simulate(self: *SparseLanes, _: c.Accum, _: g.Order, out: []f64) !void { + const mag = try self.arena.allocator().alloc(f64, out.len); + try self.reference(out, mag); + } +};