Skip to content
Merged
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel

## Unreleased

- Qwen3.8-Flash-Next on HIP: `tf_fn_idx_scores` exits inactive decode-graph tiles before synchronization and stages each tile's q rows once in LDS before walking the four key-position slots, cutting kernel time from 276.0 ms to 141.5 ms at 8K and 2,873.9 ms to 2,091.4 ms at 32K on gfx1151 with identical tokens (#3601).

- Tests: the kernel contract checks each qwen27 control's source edit on every chip, for both tensor-unit settings, so a run on a chip without tensor units fails on a stale M5 edit too (#3343, follow-up to #2106). Thanks to @cshintov.

- Docs: the GLM-5.3-Flash CUDA recipe's Verified copy drafts section lists, for one checkpoint at TP=2 with `--parallel 4`, the loads that `TF_GLM_COPIES=1` sped up and the ones it slowed, and says the default stays off (#3335). Thanks to @Bizuayeu.
Expand Down
4 changes: 4 additions & 0 deletions docs/kernel-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,10 @@ is bit-equal to the chain it replaces (`tf_conv_prefill`, `tf_copy_cols`, `tf_rm
Four controls: the recurrence one row short of the prompt and with one key head, and the prework norming q with k's
weights and writing gate and beta to each other's outputs.

HIP also checks Flash Next's indexer block score kernel (`tf_fn_idx_scores`, `contract_idx_scores.zig`, record in
`hip_records_sparse.zig`): staging each tile's rows of `q` in LDS when `heads * dims <= 512`, checked against the
fp64 relu-summed head dots with one control leaving out each row's last head (`shapes`).

On gfx12, HIP also checks the WMMA dense tile (`dense_wmma12_gemm`, both block geometries, fp32 and BF16 out). The
small block meets its depth-k bound. The big block (64-deep K steps over swizzled LDS rows) replaces the 32-deep block
it was before #2245's second lever, byte for byte: gate 3 runs a frozen copy of that block (`tf_ref_wmma12_k32`, in the
Expand Down
20 changes: 17 additions & 3 deletions zig/kernels/hip/flashnext/indexer.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,23 @@ extern "C" __global__ void __launch_bounds__(kFnThreads)
tf_fn_idx_scores(const float* q, const void* pooled, const int* complete, float* scores, int kind, int rows, int heads,
int dims, int blocks, long long stride, int top) {
constexpr int kMost = 8;
// the block's rows of q, staged once for its eight waves when they fit
constexpr int kStage = 512;
__shared__ float qs[8 * kStage];
const int lane = threadIdx.x & 31;
const int b = blockIdx.x * kFnWaves + (threadIdx.x >> 5);
const int b0 = blockIdx.x * kFnWaves, b = b0 + (threadIdx.x >> 5);
const int r0 = blockIdx.y * 8, r1 = min(rows, r0 + 8);
bool wanted = false; // a graph launches over a bound of blocks: those no row scores read nothing
bool tile = false; // a graph launches over a bound of blocks: those no row scores read nothing
if (b0 < blocks)
for (int r = r0; r < r1; ++r) tile = tile || (complete[r] > top && b0 < complete[r]);
if (!tile) return;
const int width = heads * dims;
const bool staged = width <= kStage;
if (staged)
for (int i = threadIdx.x; i < (r1 - r0) * width; i += kFnThreads)
qs[i] = q[static_cast<long long>(r0) * width + i];
__syncthreads();
bool wanted = false;
for (int r = r0; r < r1; ++r) wanted = wanted || (complete[r] > top && b < complete[r]);
if (b >= blocks || !wanted) return;
float key[kMost];
Expand All @@ -64,7 +77,8 @@ tf_fn_idx_scores(const float* q, const void* pooled, const int* complete, float*
if (complete[r] <= top || b >= complete[r]) continue;
float total = 0.f;
for (int h = 0; h < heads; ++h) {
const float* qh = q + (static_cast<long long>(r) * heads + h) * dims;
const float* qh = staged ? qs + ((r - r0) * heads + h) * dims
: q + (static_cast<long long>(r) * heads + h) * dims;
float dot = 0.f;
#pragma unroll
for (int i = 0; i < kMost; ++i) {
Expand Down
30 changes: 28 additions & 2 deletions zig/src/core/contract/hip_records_sparse.zig
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
//! Gate 5's records of Flash Next's lanes sparse attention (tf_fn_sparse_lanes12_*).
const Record = @import("hip_records.zig").Record;
//! Gate 5's records of Flash Next's indexer block scores and sparse attention on HIP.
const std = @import("std");
const hip_records = @import("hip_records.zig");
const Record = hip_records.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 {
Expand All @@ -16,6 +18,30 @@ fn sparseLanes(comptime kind: []const u8, comptime early: u32, comptime late: u3
}

pub const records = [_]Record{
.{
.launch = .{
.name = "flashnext tf_fn_idx_scores",
.symbol = "tf_fn_idx_scores",
.image = "flashnext",
.threads = 256,
},
.usage = .{
.{ .vgprs = 24, .sgprs = 39, .lds = 16384, .private = 0, .bound = 256, .wave = 32 },
.{ .vgprs = 24, .sgprs = 39, .lds = 16384, .private = 0, .bound = 256, .wave = 32 },
.{ .vgprs = 24, .sgprs = 39, .lds = 16384, .private = 0, .bound = 256, .wave = 32 },
.{ .vgprs = 23, .sgprs = 40, .lds = 16384, .private = 0, .bound = 256, .wave = 32 },
},
},
sparseLanes("f16", 74, 72),
sparseLanes("bf16", 84, 83),
};

test "tf_fn_idx_scores carries its LDS-staged Gate 5 record and fits every served RDNA chip" {
var found: ?Record = null;
for (hip_records.records) |r| if (std.mem.eql(u8, r.launch.symbol, "tf_fn_idx_scores")) {
found = r;
};
const rec = found orelse return error.MissingRecord;
try std.testing.expectEqual(@as(u32, 16384), rec.usage[0].lds);
try std.testing.expectEqual(@as(usize, 0), try hip_records.check(std.testing.allocator, &.{rec}, true));
}
29 changes: 28 additions & 1 deletion zig/src/hip/kernel_tests/flashnext_attn.zig
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,12 @@ test "block scores and selection: relu-summed heads, the best blocks with ties t
const ratio = 4;
const top = 32;
const blocks = 3000;
const ends = [_]i32{ 100, 4 * 3000 + 3, 4 * 1500, 4 * 33 + 1, 4 * 2999 + 2 };
// thirteen rows span two 8-row blockIdx.y tiles so staged indexing across tiles is exercised
const ends = [_]i32{
100, 4 * 3000 + 3, 4 * 1500, 4 * 33 + 1, 4 * 2999 + 2,
4 * 200, 4 * 500 + 3, 4 * 12 + 2, 4 * 1024, 4 * 64 + 1,
4 * 1800, 4 * 2500 + 3, 4 * 77 + 1,
};
const rows = ends.len;
var complete: [rows]i32 = undefined;
for (&complete, ends) |*c, e| c.* = @divFloor(e, ratio);
Expand Down Expand Up @@ -230,6 +235,28 @@ test "block scores and selection: relu-summed heads, the best blocks with ties t
.{ r, b },
);
};
// the kernel's own fp32 order, bit for bit: a lane's dims 32 apart, the 32-lane xor tree, then the heads in order
for (0..rows) |r| for (0..blocks) |b| {
if (!(complete[r] > top and b < complete[r])) continue;
var total: f32 = 0;
for (0..heads) |h| {
var lanes: [32]f32 = @splat(0);
for (&lanes, 0..) |*x, l| for (0..dims / 32) |i| {
const d = l + 32 * i;
x.* += hq[(r * heads + h) * dims + d] * @as(f32, @floatCast(t.value(hp[b * dims + d])));
};
var mask: usize = 16;
while (mask > 0) : (mask >>= 1) {
var next: [32]f32 = undefined;
for (&next, 0..) |*x, l| x.* = lanes[l] + lanes[l ^ mask];
lanes = next;
}
total += @max(lanes[0], 0);
}
const want = total / @sqrt(@as(f32, dims));
const got = gs[r * blocks + b];
try rig.expect(got == want, "score row {d} block {d}: {e} != {e}", .{ r, b, got, want });
};
// the selection runs on scores with ties written in: the GPU's, then a few equal to the cut
for (0..rows) |r| for (0..blocks) |b| if (b % 50 == 5) {
gs[r * blocks + b] = 3.0;
Expand Down
171 changes: 171 additions & 0 deletions zig/tests/hip/contract_idx_scores.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
//! Flash Next's indexer block scores under the contract on HIP: relu-summed heads against an fp64 reference.
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 heads = 4;
const dims = 128;
const top = 4;

/// Fp32 sums over a head's dims, then over the heads.
fn depth(_: c.Shape) usize {
return dims + heads;
}

const why = "a lane's dims 32 apart, the 32-lane xor tree, then the heads";
const rule = "a dot that is NaN adds 0 (relu by fmaxf); an infinite q reaches the blocks whose key carries its sign";

pub fn spec(k: kit.Kind) c.Spec {
return .{
.name = if (k == .bf16) "hip tf_fn_idx_scores (bf16 keys)" else "hip tf_fn_idx_scores (fp16 keys)",
.accum = .f32,
.depth = depth,
.ops = 2, // the relu and the divide by sqrt(dims)
.out = .f32,
.nan = .{ .stated = rule },
.tiles = .{ .{ .size = 8, .min = 1 }, .{ .size = 8, .min = 1 }, .{} },
// a 64-row slice over a 32K prompt's blocks, a tail of rows past one tile, and a deep cache
.served = &.{
.{ .rows = 64, .n = 8192, .k = dims },
.{ .rows = 13, .n = 2051, .k = dims },
.{ .rows = 8, .n = 32768, .k = dims },
},
.sums = .{ .f16 = 0, .bf16 = 0, .why = why, .exact = false },
};
}

/// Either the real launch or a control that drops the last head so gate 3 catches the missing sum.
pub const Fault = enum {
none,
one_head_short,

fn name(f: Fault) ?[]const u8 {
return switch (f) {
.none => null,
.one_head_short => "control: tf_fn_idx_scores leaves out each row's last head",
};
}
};

/// Rows of q against a cache of pooled block keys of the kind; every row scores every block.
pub const IdxScores = struct {
rig: rig_.Rig,
l: *const hip.Launcher,
k: kit.Kind,
fault: Fault,
arena: std.heap.ArenaAllocator,
shape: c.Shape = undefined,
q: []f32 = &.{},
keys: []f64 = &.{},
dev: [3]u64 = @splat(0),
out: u64 = 0,

pub fn init(a: std.mem.Allocator, rt: *const hip.Runtime, s: hip.Stream, l: *const hip.Launcher, f: Fault) IdxScores {
return .{ .rig = .{ .a = a, .r = rt, .s = s }, .l = l, .k = kit.act(), .fault = f, .arena = .init(a) };
}

pub fn deinit(self: *IdxScores) void {
self.arena.deinit();
self.rig.deinit();
}

/// The control keeps the spec under its own name and must go red at gate 3 (shapes).
pub fn kernel(self: *IdxScores) g.Kernel {
var s = spec(self.k);
const control = self.fault.name();
if (control) |name| s.name = name;
return .{ .spec = s, .ctx = self, .vt = &vt, .control = if (control != null) .shapes else null };
}

const vt = g.hooks(IdxScores);

/// Random: values in [-1, 1) exact in the kind. Stress: small integers, so every sum is exact.
pub fn prepare(self: *IdxScores, shape: c.Shape, fill: g.Fill, seed: u64) !bool {
if (shape.k != dims or shape.rows < 1 or shape.n <= top or shape.n > 40000) return false;
self.rig.reset();
_ = self.arena.reset(.retain_capacity);
const a = self.arena.allocator();
self.shape = shape;
var prng = std.Random.DefaultPrng.init(seed);
const rng = prng.random();
const stress = fill == .stress;
self.q = try a.alloc(f32, shape.rows * heads * dims);
for (self.q) |*x| {
x.* = if (stress) @floatFromInt(rng.intRangeAtMost(i32, -3, 3)) else @floatCast(rng.float(f64) * 2 - 1);
}
self.keys, const kb = try kit.values(a, rng, self.k, shape.n * dims, -1, 1);
if (stress) for (self.keys, 0..) |*x, i| {
x.* = @floatFromInt(rng.intRangeAtMost(i32, -3, 3));
kit.put(self.k, kb, i, x.*);
};
if (fill == .nonfinite) self.q[heads * dims] = std.math.inf(f32); // row 1, head 0, dim 0
const complete = try a.alloc(i32, shape.rows);
@memset(complete, @intCast(shape.n));
self.dev = .{
try self.rig.input(std.mem.sliceAsBytes(self.q)),
try self.rig.input(kb),
try self.rig.input(std.mem.sliceAsBytes(complete)),
};
self.out = try self.rig.output(shape.rows * shape.n * 4);
return true;
}

pub fn run(self: *IdxScores) !void {
const s = self.shape;
const d = self.dev;
const run_heads: c_int = if (self.fault == .one_head_short) heads - 1 else heads;
try self.l.fn_idx_scores(
@ptrFromInt(d[0]),
@ptrFromInt(d[1]),
@ptrFromInt(d[2]),
@ptrFromInt(self.out),
@backingInt(self.k),
@intCast(s.rows),
run_heads,
dims,
@intCast(s.n),
@intCast(s.n),
top,
self.rig.s.handle,
);
try self.rig.s.synchronize();
}

pub fn count(self: *IdxScores) usize {
return self.shape.rows * self.shape.n;
}

/// fp64 scores: each head's dot over the dims, a NaN dot as 0, the rest relu'd, summed over heads, / sqrt(dims).
pub fn reference(self: *IdxScores, want: []f64, mag: []f64) !void {
const n = self.shape.n;
for (0..self.shape.rows) |r| for (0..n) |b| {
var total: f64 = 0;
var size: f64 = 0;
for (0..heads) |h| {
var dot: f64 = 0;
var m: f64 = 0;
for (0..dims) |d| {
const p = @as(f64, self.q[(r * heads + h) * dims + d]) * self.keys[b * dims + d];
dot += p;
m += @abs(p);
}
if (!std.math.isNan(dot) and dot > 0) total += dot;
size += m;
}
want[r * n + b] = total / @sqrt(@as(f64, dims));
mag[r * n + b] = size / @sqrt(@as(f64, dims));
};
}

/// Every sum is exact on the stress fill's integers, in any order.
pub fn simulate(self: *IdxScores, _: c.Accum, _: g.Order, out: []f64) !void {
const mag = try self.arena.allocator().alloc(f64, out.len);
try self.reference(out, mag);
}
};
5 changes: 5 additions & 0 deletions zig/tests/hip/contract_main.zig
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ const vl_k = @import("contract_vl.zig");
const pos_k = @import("contract_vl_position.zig");
const sparse_k = @import("contract_sparse_lanes.zig");
const skew_k = @import("contract_wmma_skew.zig");
const idx_k = @import("contract_idx_scores.zig");

const g = core.contract.gates;

Expand Down Expand Up @@ -345,6 +346,10 @@ fn run(a: std.mem.Allocator, io: std.Io) !usize {
var sparse = sparse_k.SparseLanes.init(a, &r, s, &l);
defer sparse.deinit();
try kernels.append(a, sparse.kernel());
var idx_scores: [2]idx_k.IdxScores = undefined;
for (&idx_scores, std.enums.values(idx_k.Fault)) |*x, fault| x.* = .init(a, &r, s, &l, fault);
defer for (&idx_scores) |*x| x.deinit();
for (&idx_scores) |*x| try kernels.append(a, x.kernel());
var skews: [skew_k.cases.len]skew_k.Skew = undefined;
for (&skews, 0..) |*x, i| x.* = .init(a, &r, s, &l, i);
defer for (&skews) |*x| x.deinit();
Expand Down
Loading