From 3b6dc91b32969f66915095ce1a7547086b0b1967 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Thu, 5 Nov 2026 12:32:11 +0100 Subject: [PATCH 1/4] xpu: Qwen3-ASR's kernels without DPAS, and lfm3.cl at 2 query heads a KV head, against FP64 (#2105) qwen3_asr.cl holds what no shared Gen12LP kernel covers: a bf16 Linear (64 x 64 tiles as vit_gemm, bf16 rows, bias, GELU and residual epilogue), the 3 x 3 stride-2 conv on channels-last rows, the flatten to torch's order, LayerNorm with bias, erf GELU, the tower's windowed attention and Qwen3's per-head RMSNorm with RoPE rounded at each product and sum (lfm3's rounds once). The language model's RMSNorm, SwiGLU and split-K GQA attention are lfm3.cl's, built again as lfm3_gq2 with GQ 2. tf-xpu-qwen3_asr_ops-test checks each against FP64 with a planted control, the shared kernels as the binding launches them. --- zig/build/xpu.zig | 4 +- zig/kernels/xpu/qwen3_asr.cl | 222 +++++++++++++++ zig/src/xpu/kernels.zig | 4 + zig/tests/xpu/qwen3_asr_ops.zig | 479 ++++++++++++++++++++++++++++++++ 4 files changed, 708 insertions(+), 1 deletion(-) create mode 100644 zig/kernels/xpu/qwen3_asr.cl create mode 100644 zig/tests/xpu/qwen3_asr_ops.zig diff --git a/zig/build/xpu.zig b/zig/build/xpu.zig index 5bd83466f4f..17a7bcf8227 100644 --- a/zig/build/xpu.zig +++ b/zig/build/xpu.zig @@ -250,6 +250,8 @@ const kernels = [_]Kernel{ .{ .name = "nem_attn_dec", .options = cl3 }, .{ .name = "lfm3", .options = cl3 }, .{ .name = "lfm3_mv", .options = cl3 }, + .{ .name = "lfm3_gq2", .src = "lfm3", .options = cl3 ++ " -DGQ=2" }, + .{ .name = "qwen3_asr", .options = cl3 }, }; /// The runtime module; `with_kernels` false builds it host-only (empty images). @@ -325,7 +327,7 @@ fn lfm3Module(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bui /// The standalone op and model tests, each its own program `tf-xpu--test` (step `xpu-tests`). const test_programs = [_][]const u8{ - "panic", "nem_rows", "nem_prefill", "nem_gen", "nem_mtp", "nem_kl", "nem_norm_bench", "nem_mv_bench", "nem_slot", "nem_format", "nem_seam", "nem_attn_dec", "nem_fp64", "memory", "lfm3_conv", "lfm3_rope", "lfm3_attn", "lfm3_norm", "lfm3_fwd", "lfm3_bench", "lfm3_rows", "lfm3_streams", "lfm3_chunks", "lfm3_pgemm", + "panic", "nem_rows", "nem_prefill", "nem_gen", "nem_mtp", "nem_kl", "nem_norm_bench", "nem_mv_bench", "nem_slot", "nem_format", "nem_seam", "nem_attn_dec", "nem_fp64", "memory", "lfm3_conv", "lfm3_rope", "lfm3_attn", "lfm3_norm", "lfm3_fwd", "lfm3_bench", "lfm3_rows", "lfm3_streams", "lfm3_chunks", "lfm3_pgemm", "qwen3_asr_ops", }; /// `-Dxpu` (Linux): Nemotron's SPIR-V images, `tensorfold-xpu` and `tf-xpu-test`; needs ocloc, not nvcc or CUDA. diff --git a/zig/kernels/xpu/qwen3_asr.cl b/zig/kernels/xpu/qwen3_asr.cl new file mode 100644 index 00000000000..e5e546e9bad --- /dev/null +++ b/zig/kernels/xpu/qwen3_asr.cl @@ -0,0 +1,222 @@ +// Qwen3-ASR's ops no shared Gen12LP kernel covers: bf16 rows and weights, fp32 sums, bf16 where torch rounds. +#pragma OPENCL FP_CONTRACT OFF + +inline float bf(ushort v) { return as_float((uint)v << 16); } +inline ushort to_bf(float f) { + uint u = as_uint(f); + if ((u & 0x7fffffffu) > 0x7f800000u) return (ushort)((u >> 16) | 0x40u); + u += 0x7fffu + ((u >> 16) & 1u); + return (ushort)(u >> 16); +} +inline float bfr(float f) { return bf(to_bf(f)); } +inline float gelu(float x) { return 0.5f * x * (1.0f + erf(x * 0.70710678118654752f)); } + +// Sum over a work-group of 256 items (16 sub-groups of 16) in a fixed order. +inline float wg_sum256(float v, __local float *part) { + v = sub_group_reduce_add(v); + if (get_sub_group_local_id() == 0) part[get_sub_group_id()] = v; + barrier(CLK_LOCAL_MEM_FENCE); + float t = 0.0f; + for (uint i = 0; i < 16; i++) t += part[i]; + barrier(CLK_LOCAL_MEM_FENCE); + return t; +} + +// The epilogue of a Linear: bf16(act(bf16(s + bias)) + res), each optional (act 1: GELU). +inline ushort epilogue(float s, __global const ushort *bias, uint has_bias, uint o, uint act, __global const ushort *res, uint has_res, ulong at) { + float t = bfr(has_bias ? s + bf(bias[o]) : s); + if (act == 1) t = bfr(gelu(t)); + if (has_res) t = bfr(t + bf(res[at])); + return to_bf(t); +} + +// A 64 x 64 tile of y in 16 x 16 items of 4 x 4, 16 k a step through local memory (vit_gemm's shape, bf16 rows). +#define TILE_BODY(LOADX) \ + __local float xs[16][64]; \ + __local float ws[16][64]; \ + const uint lx = get_local_id(0), ly = get_local_id(1), t = ly * 16 + lx; \ + const ulong m0 = (ulong)get_group_id(1) * 64, n0 = (ulong)get_group_id(0) * 64; \ + const uint lr = t / 4, lk = (t % 4) * 4; \ + float acc[4][4]; \ + for (uint i = 0; i < 4; i++) \ + for (uint j = 0; j < 4; j++) acc[i][j] = 0.0f; \ + for (uint k0 = 0; k0 < k; k0 += 16) { \ + const ulong xr = m0 + lr, wr = n0 + lr; \ + for (uint j = 0; j < 4; j++) { \ + const uint kk = k0 + lk + j; \ + xs[lk + j][lr] = (xr < m && kk < k) ? LOADX : 0.0f; \ + ws[lk + j][lr] = (wr < n && kk < k) ? bf(w[wr * k + kk]) : 0.0f; \ + } \ + barrier(CLK_LOCAL_MEM_FENCE); \ + float part[4][4]; \ + for (uint i = 0; i < 4; i++) \ + for (uint j = 0; j < 4; j++) part[i][j] = 0.0f; \ + _Pragma("unroll") for (uint q = 0; q < 16; q++) { \ + const float4 a = vload4(ly, &xs[q][0]); \ + const float4 b4 = vload4(lx, &ws[q][0]); \ + const float av[4] = {a.s0, a.s1, a.s2, a.s3}, bv[4] = {b4.s0, b4.s1, b4.s2, b4.s3}; \ + _Pragma("unroll") for (uint i = 0; i < 4; i++) _Pragma("unroll") for (uint j = 0; j < 4; j++) part[i][j] = \ + fma(av[i], bv[j], part[i][j]); \ + } \ + for (uint i = 0; i < 4; i++) \ + for (uint j = 0; j < 4; j++) acc[i][j] += part[i][j]; \ + barrier(CLK_LOCAL_MEM_FENCE); \ + } + +// y[r][o] (rows ldy apart) = epilogue(x[r] . w[o]): x [m, k] and w [n, k] bf16; grid ((n + 63) / 64, (m + 63) / 64). +__attribute__((reqd_work_group_size(16, 16, 1))) +__kernel void asr_gemm(__global const ushort *x, __global const ushort *w, __global const ushort *bias, uint has_bias, __global const ushort *res, + uint has_res, __global ushort *y, uint m, uint n, uint k, uint ldy, uint act) { + TILE_BODY(bf(x[xr * k + kk])) + for (uint i = 0; i < 4; i++) { + const ulong r = m0 + ly * 4 + i; + if (r >= m) continue; + for (uint j = 0; j < 4; j++) { + const uint o = (uint)(n0 + lx * 4 + j); + if (o >= n) continue; + const ulong at = r * ldy + o; + y[at] = epilogue(acc[i][j], bias, has_bias, o, act, res, has_res, at); + } + } +} + +// x value (ci, kh, kw) of output position p for a 3 x 3 stride-2 conv, zero padding 1, channels last [n][fi][ti][c]. +inline float conv_tap(__global const ushort *x, ulong p, uint kk, uint fi, uint ti, uint c, uint fo, uint to) { + const uint ci = kk / 9, kh = (kk % 9) / 3, kw = kk % 3; + const ulong nn = p / ((ulong)fo * to); + const uint rem = (uint)(p % ((ulong)fo * to)), f = rem / to, tt = rem % to; + const int fx = (int)(2 * f + kh) - 1, tx = (int)(2 * tt + kw) - 1; + if (fx < 0 || tx < 0 || fx >= (int)fi || tx >= (int)ti) return 0.0f; + return bf(x[((nn * fi + (uint)fx) * ti + (uint)tx) * c + ci]); +} + +// y [n][fo][to][co] = bf16(taps(x) . w[co][ci * 9 + kh * 3 + kw] + b); m = n * fo * to, k = 9 c; grid as asr_gemm. +__attribute__((reqd_work_group_size(16, 16, 1))) +__kernel void asr_conv(__global const ushort *x, __global const ushort *w, __global const ushort *bias, __global ushort *y, uint m, uint n, uint k, + uint fi, uint ti, uint c) { + const uint fo = (fi - 1) / 2 + 1, to = (ti - 1) / 2 + 1; + TILE_BODY(conv_tap(x, xr, kk, fi, ti, c, fo, to)) + for (uint i = 0; i < 4; i++) { + const ulong r = m0 + ly * 4 + i; + if (r >= m) continue; + for (uint j = 0; j < 4; j++) { + const uint o = (uint)(n0 + lx * 4 + j); + if (o < n) y[r * n + o] = to_bf(acc[i][j] + bf(bias[o])); + } + } +} + +// [n][f][t][c] channels last to rows [n * t][c * f] (torch's permute(0, 3, 1, 2) of [n][c][f][t]); a value an item. +__kernel void asr_flatten(__global const ushort *x, __global ushort *y, uint f, uint t, uint c, uint total) { + const ulong i = get_global_id(0); + if (i >= total) return; + const uint cf = c * f; + const ulong row = i / cf; + const uint col = (uint)(i % cf), ci = col / f, ff = col % f; + const ulong nn = row / t, tt = row % t; + y[i] = x[((nn * f + ff) * t + tt) * c + ci]; +} + +// LayerNorm of row get_group_id(0): bf16((x - mean) * rsqrt(var + eps) * w + b), fp32 inside; 256 items. +__attribute__((intel_reqd_sub_group_size(16))) +__kernel void asr_layernorm(__global const ushort *x, __global const ushort *w, __global const ushort *b, __global ushort *y, uint n, float eps) { + __local float part[16]; + const ulong row = get_group_id(0); + const uint id = get_local_id(0); + __global const ushort *xr = x + row * n; + float s = 0.0f; + for (uint i = id; i < n; i += 256) s += bf(xr[i]); + const float mean = wg_sum256(s, part) / (float)n; + float v = 0.0f; + for (uint i = id; i < n; i += 256) { + const float d = bf(xr[i]) - mean; + v += d * d; + } + const float rs = rsqrt(wg_sum256(v, part) / (float)n + eps); + for (uint i = id; i < n; i += 256) y[row * n + i] = to_bf((bf(xr[i]) - mean) * rs * bf(w[i]) + bf(b[i])); +} + +// y = bf16(gelu(x)) with erf, as torch's GELU; a value an item. +__kernel void asr_gelu(__global const ushort *x, __global ushort *y, uint total) { + const ulong i = get_global_id(0); + if (i < total) y[i] = to_bf(gelu(bf(x[i]))); +} + +// Bidirectional attention over len rows of [q | k | v] (64-dim heads), online softmax as vit_attn; a sub-group a row. +__attribute__((intel_reqd_sub_group_size(16))) +__kernel void asr_attn_full(__global const ushort *qkv, __global ushort *out, uint len, uint heads, float scale) { + const uint row = get_group_id(0), h = get_group_id(1), lane = get_sub_group_local_id(); + const uint d = heads * 64, ld = 3 * d; + float q[64]; + for (uint i = 0; i < 64; i++) q[i] = bf(qkv[(ulong)row * ld + h * 64 + i]); + float m = -INFINITY, l = 0.0f, o[4] = {0.0f, 0.0f, 0.0f, 0.0f}; + for (uint k0 = 0; k0 < len; k0 += 16) { + const uint key = k0 + lane; + float s = -INFINITY; + if (key < len) { + __global const ushort *kr = qkv + (ulong)key * ld + d + h * 64; + float a = 0.0f; + for (uint i = 0; i < 64; i++) a = fma(q[i], bf(kr[i]), a); + s = a * scale; + } + const float mn = fmax(m, sub_group_reduce_max(s)); + const float p = key < len ? exp(s - mn) : 0.0f; + const float c = exp(m - mn); + l = l * c + sub_group_reduce_add(p); + m = mn; + for (uint i = 0; i < 4; i++) o[i] *= c; + const uint kn = min(16u, len - k0); + for (uint j = 0; j < kn; j++) { + const float pj = sub_group_shuffle(p, j); + __global const ushort *vr = qkv + (ulong)(k0 + j) * ld + 2 * d + h * 64 + lane * 4; + for (uint i = 0; i < 4; i++) o[i] = fma(pj, bf(vr[i]), o[i]); + } + } + const float il = 1.0f / l; + for (uint i = 0; i < 4; i++) out[(ulong)row * d + h * 64 + lane * 4 + i] = to_bf(o[i] * il); +} + +// A head of 128: bf16(w * bf16(x * rs)), then RoPE (d, d + 64), each product and sum rounded as Qwen3 (lfm3: once). +inline void norm_rope(__global const ushort *src, __global ushort *dst, __global const ushort *w, __global const float *cs, + __global const float *sn, uint p, float eps) { + const uint lane = get_sub_group_local_id(); + float v[8]; + float s = 0.0f; + for (uint i = 0; i < 8; i++) { + v[i] = bf(src[lane * 8 + i]); + s += v[i] * v[i]; + } + const float rs = rsqrt(sub_group_reduce_add(s) / 128.0f + eps); + for (uint i = 0; i < 8; i++) v[i] = bfr(bf(w[lane * 8 + i]) * bfr(v[i] * rs)); + // the partner of dim d is d + 64 (or d - 64): lane l's dims pair with lane l ^ 8's + for (uint i = 0; i < 8; i++) { + const uint dd = lane * 8 + i; + const float other = sub_group_shuffle_xor(v[i], 8u); + const float rot = dd < 64 ? -other : other; + dst[dd] = to_bf(bfr(v[i] * cs[(ulong)p * 128 + dd]) + bfr(rot * sn[(ulong)p * 128 + dd])); + } +} + +// Row r at pos0 + r of [q | k | v]: q heads to q, k heads to k and kc, v to v and vc; grid (heads + 2 kv_heads, rows). +__attribute__((intel_reqd_sub_group_size(16))) +__kernel void asr_qk_rope(__global const ushort *qkv, __global const ushort *qn, __global const ushort *kn, __global const float *cs, + __global const float *sn, __global ushort *q, __global ushort *k, __global ushort *v, __global ushort *kc, + __global ushort *vc, uint heads, uint kv_heads, uint pos0, float eps) { + const uint hh = get_group_id(0), r = get_group_id(1), p = pos0 + r, lane = get_sub_group_local_id(); + const uint qd = heads * 128, kvd = kv_heads * 128; + __global const ushort *row = qkv + (ulong)r * (qd + 2 * kvd); + if (hh < heads) { + norm_rope(row + hh * 128, q + (ulong)r * qd + hh * 128, qn, cs, sn, p, eps); + } else if (hh < heads + kv_heads) { + const uint kh = hh - heads; + norm_rope(row + qd + kh * 128, k + (ulong)r * kvd + kh * 128, kn, cs, sn, p, eps); + for (uint i = 0; i < 8; i++) kc[(ulong)p * kvd + kh * 128 + lane * 8 + i] = k[(ulong)r * kvd + kh * 128 + lane * 8 + i]; + } else { + const uint vh = hh - heads - kv_heads; + for (uint i = 0; i < 8; i++) { + const ushort x = row[qd + kvd + vh * 128 + lane * 8 + i]; + v[(ulong)r * kvd + vh * 128 + lane * 8 + i] = x; + vc[(ulong)p * kvd + vh * 128 + lane * 8 + i] = x; + } + } +} diff --git a/zig/src/xpu/kernels.zig b/zig/src/xpu/kernels.zig index 93178cba5ed..f85353ee158 100644 --- a/zig/src/xpu/kernels.zig +++ b/zig/src/xpu/kernels.zig @@ -29,3 +29,7 @@ pub const nem_prow_gen12: []const u8 = if (available) &Blob("spv_nem_prow_gen12" pub const nem_attn_dec: []const u8 = if (available) &Blob("spv_nem_attn_dec").bytes else &.{}; pub const lfm3: []const u8 = if (available) &Blob("spv_lfm3").bytes else &.{}; pub const lfm3_mv: []const u8 = if (available) &Blob("spv_lfm3_mv").bytes else &.{}; +/// lfm3.cl at 2 query heads a KV head (Qwen3-0.6B, 16 on 8): its norms, SwiGLU and attention for Qwen3-ASR. +pub const lfm3_gq2: []const u8 = if (available) &Blob("spv_lfm3_gq2").bytes else &.{}; +/// Qwen3-ASR's own ops: bf16 Linear and conv, LayerNorm, GELU, the tower's attention, Qwen3 QK norm and RoPE. +pub const qwen3_asr: []const u8 = if (available) &Blob("spv_qwen3_asr").bytes else &.{}; diff --git a/zig/tests/xpu/qwen3_asr_ops.zig b/zig/tests/xpu/qwen3_asr_ops.zig new file mode 100644 index 00000000000..ec04b416ba0 --- /dev/null +++ b/zig/tests/xpu/qwen3_asr_ops.zig @@ -0,0 +1,479 @@ +//! Qwen3-ASR's XPU ops against FP64 with planted controls: qwen3_asr.cl, and shared kernels as the binding runs them. + +const std = @import("std"); +const o = @import("lfm3_ops.zig"); +const stop = @import("xpu").stop; +const kernels = @import("xpu").kernels; + +const Buf = o.Buf; + +fn upF32(r: *o.rt.Runtime, h: []const f32) !Buf { + const b = try r.alloc(h.len * 4); + try r.upload(b, std.mem.sliceAsBytes(h)); + return b; +} + +/// lfm3_ops.run with usize shapes narrowed to the kernels' 32-bit arguments. +fn run(k: *o.rt.Kernel, groups: anytype, a: anytype) !void { + inline for (a, 0..) |v, i| { + const T = @TypeOf(v); + if (T == Buf) { + try k.setBuffer(i, v); + } else if (T == f32) { + try k.setF32(i, v); + } else try k.setU32(i, @intCast(v)); + } + var g: [3]u32 = undefined; + inline for (groups, 0..) |v, i| g[i] = @intCast(v); + try k.launch(g); +} + +fn rand(n: usize, rnd: std.Random, sd: f64) ![]u16 { + const h = try o.gpa.alloc(u16, n); + o.randBf(h, rnd, sd); + return h; +} + +fn gelu(x: f64) f64 { + return 0.5 * x * (1.0 + erf(x / std.math.sqrt2)); +} + +/// erf to double precision (Abramowitz-Stegun 7.1.26 is too coarse; this is the series / continued fraction pair). +fn erf(x: f64) f64 { + const ax = @abs(x); + if (ax < 2.5) { + var sum: f64 = 0; + var term = ax; + var k: f64 = 0; + while (k < 80) : (k += 1) { + sum += term / (2 * k + 1); + term *= -ax * ax / (k + 1); + } + return (if (x < 0) @as(f64, -1) else @as(f64, 1)) * 2 / @sqrt(std.math.pi) * sum; + } + // continued fraction for erfc + var f: f64 = ax; + var i: f64 = 60; + while (i >= 1) : (i -= 1) f = ax + i / 2 / f; + return (if (x < 0) @as(f64, -1) else @as(f64, 1)) * (1 - @exp(-ax * ax) / @sqrt(std.math.pi) / f); +} + +/// y = act(x . w^T + b) + res over [m, n], all FP64 from bf16 inputs; `tw` reads w transposed (a control). +fn linear64(x: []const f64, w: []const f64, b: ?[]const f64, res: ?[]const f64, m: usize, n: usize, k: usize, act: u32, tw: bool) ![]f64 { + const y = try o.gpa.alloc(f64, m * n); + for (0..m) |r| for (0..n) |c| { + var s: f64 = 0; + for (0..k) |i| s += x[r * k + i] * (if (tw) w[(i * n + c) % (n * k)] else w[c * k + i]); + if (b) |bb| s += bb[c]; + if (act == 1) s = gelu(s); + if (res) |rr| s += rr[r * n + c]; + y[r * n + c] = s; + }; + return y; +} + +fn sub(b: Buf, off: usize) Buf { + return .{ .rt = b.rt, .ptr = @ptrFromInt(@intFromPtr(b.ptr.?) + off), .len = b.len - off }; +} + +pub const panic = std.debug.FullPanic(@import("rig.zig").panicDrain); +pub fn main() !void { + stop.install(); + var r = try o.rt.open(); + defer r.deinit(); + var md = try r.module(kernels.qwen3_asr); + var k_gemm = try md.kernel("asr_gemm", .{ 16, 16, 1 }); + var k_conv = try md.kernel("asr_conv", .{ 16, 16, 1 }); + var k_flat = try md.kernel("asr_flatten", .{ 256, 1, 1 }); + var k_ln = try md.kernel("asr_layernorm", .{ 256, 1, 1 }); + var k_gelu = try md.kernel("asr_gelu", .{ 256, 1, 1 }); + var k_full = try md.kernel("asr_attn_full", .{ 16, 1, 1 }); + var lf = try r.module(kernels.lfm3_gq2); + var gm = try r.module(kernels.glue); + var k_rms = try lf.kernel("lfm3_rmsnorm", .{ 256, 1, 1 }); + var k_add = try gm.kernel("add_bf16", .{ 64, 1, 1 }); + var k_part = try lf.kernel("lfm3_attn_partial", .{ 32, 1, 1 }); + var k_merge = try lf.kernel("lfm3_attn_merge_gate", .{ 16, 1, 1 }); + var k_swi = try lf.kernel("lfm3_swiglu", .{ 64, 1, 1 }); + var k_qk = try md.kernel("asr_qk_rope", .{ 16, 1, 1 }); + var t: o.Tally = .{ .name = "qwen3_asr_ops" }; + var prng = std.Random.DefaultPrng.init(2105); + const rnd = prng.random(); + var buf: [128]u8 = undefined; + std.debug.print("Qwen3-ASR kernels: bf16 rows and weights, fp32 sums, against FP64\n", .{}); + const dummy = try r.alloc(256); + + // Linear: bias, GELU and a residual, ragged m and n, k a multiple of 16 and not + for ([_][3]usize{ .{ 70, 200, 96 }, .{ 1, 130, 1024 }, .{ 37, 64, 40 } }) |shape| { + const m = shape[0]; + const n = shape[1]; + const k = shape[2]; + const xh = try rand(m * k, rnd, 1.0); + const wh = try rand(n * k, rnd, 0.05); + const bh = try rand(n, rnd, 0.1); + const rh = try rand(m * n, rnd, 0.5); + const x = try o.upload(&r, xh); + const w = try o.upload(&r, wh); + const b = try o.upload(&r, bh); + const res = try o.upload(&r, rh); + const y = try r.alloc(m * n * 2); + const xf = try o.widen(o.gpa, xh); + const wf = try o.widen(o.gpa, wh); + const bf = try o.widen(o.gpa, bh); + const rf = try o.widen(o.gpa, rh); + const g = .{ @as(u32, @intCast((n + 63) / 64)), @as(u32, @intCast((m + 63) / 64)), @as(u32, 1) }; + try run(&k_gemm, g, .{ x, w, b, 1, res, 1, y, m, n, k, n, 1 }); + t.check(try std.fmt.bufPrint(&buf, "asr_gemm {d}x{d}x{d}, bias, GELU, residual", .{ m, n, k }), o.relErr(try o.fetch(&r, y, m * n), try linear64(xf, wf, bf, rf, m, n, k, 1, false))); + try run(&k_gemm, g, .{ x, w, dummy, 0, dummy, 0, y, m, n, k, n, 0 }); + const plain = try o.fetch(&r, y, m * n); + t.check(try std.fmt.bufPrint(&buf, "asr_gemm {d}x{d}x{d}, plain", .{ m, n, k }), o.relErr(plain, try linear64(xf, wf, null, null, m, n, k, 0, false))); + t.control(try std.fmt.bufPrint(&buf, "asr_gemm {d}x{d}x{d} against w transposed", .{ m, n, k }), o.relErr(plain, try linear64(xf, wf, null, null, m, n, k, 0, true))); + } + + // the 3 x 3 stride-2 conv, zero padding 1, channels last; control: kh and kw swapped + { + const n: usize = 2; + const fi: usize = 13; + const ti: usize = 11; + const c: usize = 5; + const co: usize = 70; + const fo = (fi - 1) / 2 + 1; + const to = (ti - 1) / 2 + 1; + const xh = try rand(n * fi * ti * c, rnd, 1.0); + const wh = try rand(co * c * 9, rnd, 0.2); + const bh = try rand(co, rnd, 0.1); + const y = try r.alloc(n * fo * to * co * 2); + const m = n * fo * to; + try run(&k_conv, .{ @as(u32, @intCast((co + 63) / 64)), @as(u32, @intCast((m + 63) / 64)), 1 }, .{ try o.upload(&r, xh), try o.upload(&r, wh), try o.upload(&r, bh), y, m, co, c * 9, fi, ti, c }); + const got = try o.fetch(&r, y, m * co); + const xf = try o.widen(o.gpa, xh); + const wf = try o.widen(o.gpa, wh); + const bf = try o.widen(o.gpa, bh); + var want: [2][]f64 = undefined; + for (&want, 0..) |*wv, swap| { + wv.* = try o.gpa.alloc(f64, m * co); + for (0..n) |nn| for (0..fo) |f| for (0..to) |tt| for (0..co) |oc| { + var s: f64 = bf[oc]; + for (0..c) |ci| for (0..3) |kh| for (0..3) |kw| { + const fx = @as(isize, @intCast(2 * f + kh)) - 1; + const tx = @as(isize, @intCast(2 * tt + kw)) - 1; + if (fx < 0 or tx < 0 or fx >= fi or tx >= ti) continue; + const tap = if (swap == 1) ci * 9 + kw * 3 + kh else ci * 9 + kh * 3 + kw; + s += xf[((nn * fi + @as(usize, @intCast(fx))) * ti + @as(usize, @intCast(tx))) * c + ci] * wf[oc * c * 9 + tap]; + }; + wv.*[((nn * fo + f) * to + tt) * co + oc] = s; + }; + } + t.check("asr_conv 2 x 13 x 11 x 5 -> 70", o.relErr(got, want[0])); + t.control("asr_conv with kh and kw swapped", o.relErr(got, want[1])); + } + + // flatten [n][f][t][c] to [n * t][c * f]; control: the f-major order + { + const n: u32 = 2; + const f: u32 = 3; + const tt: u32 = 4; + const c: u32 = 5; + const total = n * f * tt * c; + const xh = try o.gpa.alloc(u16, total); + for (xh, 0..) |*v, i| v.* = @intCast(i); + const y = try r.alloc(total * 2); + try run(&k_flat, .{ (total + 255) / 256, 1, 1 }, .{ try o.upload(&r, xh), y, f, tt, c, total }); + const got = try o.fetch(&r, y, total); + var want = try o.gpa.alloc(u16, total); + var ctl = try o.gpa.alloc(u16, total); + for (0..n) |nn| for (0..tt) |ti| for (0..c) |ci| for (0..f) |fi| { + want[(nn * tt + ti) * c * f + ci * f + fi] = xh[((nn * f + fi) * tt + ti) * c + ci]; + ctl[(nn * tt + ti) * c * f + fi * c + ci] = xh[((nn * f + fi) * tt + ti) * c + ci]; + }; + t.same("asr_flatten = torch's permute(0, 3, 1, 2)", std.mem.eql(u16, got, want)); + const ctl_same = std.mem.eql(u16, got, ctl); + std.debug.print(" control asr_flatten against the f-major order: {s}\n", .{if (ctl_same) "PASSES (control broken)" else "fails as planted"}); + if (ctl_same) t.bad = true; + } + + // LayerNorm with bias; control: no mean subtracted + { + const rows: usize = 5; + const n: usize = 896; + const xh = try rand(rows * n, rnd, 1.0); + for (xh, 0..) |*v, i| v.* = o.toBf(o.bf(v.*) + 0.7 * @as(f64, @floatFromInt(i % 3))); + const wh = try rand(n, rnd, 1.0); + const bh = try rand(n, rnd, 0.2); + const y = try r.alloc(rows * n * 2); + try run(&k_ln, .{ rows, 1, 1 }, .{ try o.upload(&r, xh), try o.upload(&r, wh), try o.upload(&r, bh), y, n, @as(f32, 1e-5) }); + const got = try o.fetch(&r, y, rows * n); + var want: [2][]f64 = undefined; + for (&want, 0..) |*wv, ctl| { + wv.* = try o.gpa.alloc(f64, rows * n); + for (0..rows) |row| { + var mean: f64 = 0; + for (0..n) |i| mean += o.bf(xh[row * n + i]); + mean = if (ctl == 1) 0 else mean / @as(f64, @floatFromInt(n)); + var v: f64 = 0; + for (0..n) |i| v += (o.bf(xh[row * n + i]) - mean) * (o.bf(xh[row * n + i]) - mean); + const rs = 1 / @sqrt(v / @as(f64, @floatFromInt(n)) + 1e-5); + for (0..n) |i| wv.*[row * n + i] = (o.bf(xh[row * n + i]) - mean) * rs * o.bf(wh[i]) + o.bf(bh[i]); + } + } + t.check("asr_layernorm 5 x 896", o.relErr(got, want[0])); + t.control("asr_layernorm without the mean", o.relErr(got, want[1])); + } + + // GELU with erf; control: SiLU + { + const n: u32 = 1000; + const xh = try rand(n, rnd, 2.0); + const y = try r.alloc(n * 2); + try run(&k_gelu, .{ (n + 255) / 256, 1, 1 }, .{ try o.upload(&r, xh), y, n }); + const got = try o.fetch(&r, y, n); + const want = try o.gpa.alloc(f64, n); + const ctl = try o.gpa.alloc(f64, n); + for (xh, want, ctl) |v, *wv, *cv| { + const x = o.bf(v); + wv.* = gelu(x); + cv.* = x / (1 + @exp(-x)); + } + t.check("asr_gelu (erf)", o.relErr(got, want)); + t.control("asr_gelu against SiLU", o.relErr(got, ctl)); + } + + // bidirectional attention over a window of [q | k | v]; control: a causal mask + { + const len: u32 = 45; + const heads: u32 = 3; + const d = heads * 64; + const qh = try rand(len * 3 * d, rnd, 1.0); + const y = try r.alloc(len * d * 2); + try run(&k_full, .{ len, heads, 1 }, .{ try o.upload(&r, qh), y, len, heads, @as(f32, 0.125) }); + const got = try o.fetch(&r, y, len * d); + var want: [2][]f64 = undefined; + for (&want, 0..) |*wv, causal| { + wv.* = try o.gpa.alloc(f64, len * d); + for (0..len) |i| for (0..heads) |h| { + const last = if (causal == 1) i + 1 else len; + var sc = try o.gpa.alloc(f64, last); + defer o.gpa.free(sc); + var mx: f64 = -std.math.inf(f64); + for (0..last) |j| { + var s: f64 = 0; + for (0..64) |e| s += o.bf(qh[i * 3 * d + h * 64 + e]) * o.bf(qh[j * 3 * d + d + h * 64 + e]); + sc[j] = s * 0.125; + mx = @max(mx, sc[j]); + } + var l: f64 = 0; + for (sc) |*s| { + s.* = @exp(s.* - mx); + l += s.*; + } + for (0..64) |e| { + var a: f64 = 0; + for (0..last) |j| a += sc[j] * o.bf(qh[j * 3 * d + 2 * d + h * 64 + e]); + wv.*[i * d + h * 64 + e] = a / l; + } + }; + } + t.check("asr_attn_full 45 rows x 3 heads", o.relErr(got, want[0])); + t.control("asr_attn_full against a causal mask", o.relErr(got, want[1])); + } + + // embedding rows by id, device copies as the binding makes them; control: the next row + { + const vocab: usize = 50; + const hidden: u32 = 300; + const th = try rand(vocab * hidden, rnd, 1.0); + const ids = [_]u32{ 7, 0, 49, 7, 23 }; + const y = try r.alloc(ids.len * hidden * 2); + const tb = try o.upload(&r, th); + for (ids, 0..) |id, i| try r.copy(sub(y, i * hidden * 2), sub(tb, id * hidden * 2), hidden * 2); + const got = try o.fetch(&r, y, ids.len * hidden); + var eq = true; + var ctl = true; + for (ids, 0..) |id, i| { + eq = eq and std.mem.eql(u16, got[i * hidden ..][0..hidden], th[id * hidden ..][0..hidden]); + ctl = ctl and std.mem.eql(u16, got[i * hidden ..][0..hidden], th[((id + 1) % vocab) * hidden ..][0..hidden]); + } + t.same("embedding rows by id (device copies)", eq); + std.debug.print(" control the embedding against the next row: {s}\n", .{if (ctl) "PASSES (control broken)" else "fails as planted"}); + if (ctl) t.bad = true; + } + + // add + RMSNorm as the binding runs it (h = res, glue's add_bf16 h += x, lfm3_rmsnorm h; x alone without res) + for ([_]bool{ true, false }) |with_res| { + const rows: usize = 4; + const n: usize = 1024; + const xh = try rand(rows * n, rnd, 1.0); + const rh = try rand(rows * n, rnd, 1.0); + const wh = try rand(n, rnd, 1.0); + const h = try r.alloc(rows * n * 2); + const y = try r.alloc(rows * n * 2); + const xb = try o.upload(&r, xh); + const wb = try o.upload(&r, wh); + if (with_res) { + try r.upload(h, std.mem.sliceAsBytes(rh)); + try run(&k_add, .{ (rows * n + 63) / 64, 1, 1 }, .{ h, xb, rows * n }); + } + try run(&k_rms, .{ rows, 1, 1 }, .{ if (with_res) h else xb, wb, y, n, @as(f32, 1e-6) }); + const got = try o.fetch(&r, y, rows * n); + var want: [2][]f64 = undefined; + const hs = try o.gpa.alloc(f64, rows * n); + for (hs, 0..) |*v, i| v.* = o.bf(xh[i]) + (if (with_res) o.bf(rh[i]) else 0); + for (&want, 0..) |*wv, ctl| { + wv.* = try o.gpa.alloc(f64, rows * n); + for (0..rows) |row| { + var s: f64 = 0; + for (0..n) |i| s += hs[row * n + i] * hs[row * n + i]; + const rs = 1 / @sqrt(s / @as(f64, @floatFromInt(n)) + 1e-6); + for (0..n) |i| wv.*[row * n + i] = hs[row * n + i] * rs * (if (ctl == 1) 1.0 else o.bf(wh[i])); + } + } + t.check(if (with_res) "add_bf16 + lfm3_rmsnorm, residual" else "lfm3_rmsnorm, no residual", o.relErr(got, want[0])); + if (with_res) t.check("add_bf16's h = x + res", o.relErr(try o.fetch(&r, h, rows * n), hs)); + t.control(if (with_res) "the norm without its weight, residual" else "the norm without its weight, no residual", o.relErr(got, want[1])); + } + + // per-head RMSNorm and RoPE (d, d + 64), k and v into the caches at pos0 + r; control: pairs (2i, 2i + 1) + const heads: u32 = 4; + const kvh: u32 = 2; + const rows: u32 = 3; + const pos0: u32 = 5; + const cap: u32 = 12; + const qd = heads * 128; + const kvd = kvh * 128; + const kc = try r.alloc(cap * kvd * 2); + const vc = try r.alloc(cap * kvd * 2); + const qb = try r.alloc(rows * qd * 2); + { + const qkvh = try rand(rows * (qd + 2 * kvd), rnd, 1.0); + const qnh = try rand(128, rnd, 1.0); + const knh = try rand(128, rnd, 1.0); + const cs = try o.gpa.alloc(f32, cap * 128); + const sn = try o.gpa.alloc(f32, cap * 128); + for (0..cap) |p| for (0..64) |i| { + const inv = 1.0 / std.math.pow(f64, 1e6, @as(f64, @floatFromInt(2 * i)) / 128.0); + const ang = @as(f64, @floatFromInt(p)) * inv; + for ([2]usize{ i, i + 64 }) |col| { + cs[p * 128 + col] = @floatCast(o.bf(o.toBf(@cos(ang)))); + sn[p * 128 + col] = @floatCast(o.bf(o.toBf(@sin(ang)))); + } + }; + const kb = try r.alloc(rows * kvd * 2); + const vb = try r.alloc(rows * kvd * 2); + try run(&k_qk, .{ heads + 2 * kvh, rows, 1 }, .{ try o.upload(&r, qkvh), try o.upload(&r, qnh), try o.upload(&r, knh), try upF32(&r, cs), try upF32(&r, sn), qb, kb, vb, kc, vc, heads, kvh, pos0, @as(f32, 1e-6) }); + const gq = try o.fetch(&r, qb, rows * qd); + const gk = try o.fetch(&r, kb, rows * kvd); + const gkc = try o.fetch(&r, kc, cap * kvd); + const gvc = try o.fetch(&r, vc, cap * kvd); + var want: [2][]f64 = undefined; + for (&want, 0..) |*wv, ctl| { + wv.* = try o.gpa.alloc(f64, rows * qd); + for (0..rows) |row| for (0..heads) |h| { + const src = qkvh[row * (qd + 2 * kvd) + h * 128 ..][0..128]; + var s: f64 = 0; + for (src) |v| s += o.bf(v) * o.bf(v); + const rs = 1 / @sqrt(s / 128 + 1e-6); + var nv: [128]f64 = undefined; + for (&nv, src, qnh) |*v, x, wq| v.* = o.bf(x) * rs * o.bf(wq); + const p = pos0 + row; + for (0..128) |dd| { + const rot = if (ctl == 1) (if (dd % 2 == 0) -nv[dd + 1] else nv[dd - 1]) else (if (dd < 64) -nv[dd + 64] else nv[dd - 64]); + wv.*[row * qd + h * 128 + dd] = nv[dd] * cs[p * 128 + dd] + rot * sn[p * 128 + dd]; + } + }; + } + t.check("asr_qk_rope q heads", o.relErr(gq, want[0])); + t.control("asr_qk_rope with pairs (2i, 2i + 1)", o.relErr(gq, want[1])); + var kc_ok = true; + var vc_ok = true; + for (0..rows) |row| { + kc_ok = kc_ok and std.mem.eql(u16, gkc[(pos0 + row) * kvd ..][0..kvd], gk[row * kvd ..][0..kvd]); + vc_ok = vc_ok and std.mem.eql(u16, gvc[(pos0 + row) * kvd ..][0..kvd], qkvh[row * (qd + 2 * kvd) + qd + kvd ..][0..kvd]); + } + t.same("asr_qk_rope k rows in the cache at pos0 + r", kc_ok); + t.same("asr_qk_rope v rows in the cache at pos0 + r", vc_ok); + } + + // causal GQA attention over the caches (earlier positions random); control: every slot + { + const kch = try o.fetch(&r, kc, cap * kvd); + const vch = try o.fetch(&r, vc, cap * kvd); + for (0..pos0 * kvd) |i| { + kch[i] = o.toBf(rnd.floatNorm(f64)); + vch[i] = o.toBf(rnd.floatNorm(f64)); + } + for ((pos0 + rows) * kvd..cap * kvd) |i| { + kch[i] = o.toBf(rnd.floatNorm(f64)); + vch[i] = o.toBf(rnd.floatNorm(f64)); + } + try r.upload(kc, std.mem.sliceAsBytes(kch)); + try r.upload(vc, std.mem.sliceAsBytes(vch)); + const qh = try o.fetch(&r, qb, rows * qd); + const y = try r.alloc(rows * qd * 2); + const scale: f32 = @floatCast(1.0 / @sqrt(128.0)); + // lfm3's split-K pair at GQ 2, chunks of 4 keys (several a row), the gate +inf: bf16(sigmoid) = 1 + const chunk: u32 = 4; + const maxc = (cap + chunk - 1) / chunk; + const po = try r.alloc(rows * heads * maxc * 128 * 4); + const pm = try r.alloc(rows * heads * maxc * 4); + const pl = try r.alloc(rows * heads * maxc * 4); + const gate_h = try o.gpa.alloc(u16, rows * heads); + @memset(gate_h, 0x7f80); + const gate = try o.upload(&r, gate_h); + try run(&k_part, .{ kvh, (pos0 + rows + chunk - 1) / chunk, rows }, .{ qb, kc, vc, po, pm, pl, pos0, chunk, cap, @as(u32, 0), kvh, maxc, scale }); + try run(&k_merge, .{ heads, rows, 1 }, .{ po, pm, pl, gate, y, pos0, chunk, @as(u32, 0), heads, maxc }); + const got = try o.fetch(&r, y, rows * qd); + var want: [2][]f64 = undefined; + for (&want, 0..) |*wv, ctl| { + wv.* = try o.gpa.alloc(f64, rows * qd); + for (0..rows) |row| for (0..heads) |h| { + const kh = h / (heads / kvh); + const len = if (ctl == 1) cap else pos0 + row + 1; + var sc: [16]f64 = undefined; + var mx: f64 = -std.math.inf(f64); + for (0..len) |j| { + var s: f64 = 0; + for (0..128) |e| s += o.bf(qh[row * qd + h * 128 + e]) * o.bf(kch[j * kvd + kh * 128 + e]); + sc[j] = s * scale; + mx = @max(mx, sc[j]); + } + var l: f64 = 0; + for (sc[0..len]) |*s| { + s.* = @exp(s.* - mx); + l += s.*; + } + for (0..128) |e| { + var a: f64 = 0; + for (0..len) |j| a += sc[j] * o.bf(vch[j * kvd + kh * 128 + e]); + wv.*[row * qd + h * 128 + e] = a / l; + } + }; + } + t.check("lfm3_attn_partial + merge (GQ 2, gate +inf) 3 rows at 5, 4 q heads on 2 KV heads", o.relErr(got, want[0])); + t.control("lfm3 attention against every cache slot", o.relErr(got, want[1])); + } + + // SwiGLU of [gate | up]; control: gate and up swapped + { + const rows2: u32 = 3; + const i_dim: u32 = 300; + const gh = try rand(rows2 * 2 * i_dim, rnd, 1.5); + const y = try r.alloc(rows2 * i_dim * 2); + const gb = try o.upload(&r, gh); + for (0..rows2) |row| try run(&k_swi, .{ (i_dim + 63) / 64, 1, 1 }, .{ sub(gb, row * 4 * i_dim), sub(gb, row * 4 * i_dim + 2 * i_dim), sub(y, row * 2 * i_dim), i_dim }); + const got = try o.fetch(&r, y, rows2 * i_dim); + var want: [2][]f64 = undefined; + for (&want, 0..) |*wv, swap| { + wv.* = try o.gpa.alloc(f64, rows2 * i_dim); + for (0..rows2) |row| for (0..i_dim) |j| { + const a = o.bf(gh[row * 2 * i_dim + j]); + const b = o.bf(gh[row * 2 * i_dim + i_dim + j]); + const g = if (swap == 1) b else a; + const u = if (swap == 1) a else b; + wv.*[row * i_dim + j] = g / (1 + @exp(-g)) * u; + }; + } + t.check("lfm3_swiglu a row at a time over [gate | up] rows", o.relErr(got, want[0])); + t.control("lfm3_swiglu with gate and up swapped", o.relErr(got, want[1])); + } + try t.finish(); +} From bf48bf374cc4f5bec1e8cd966b3496dcce152853 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Thu, 5 Nov 2026 12:32:11 +0100 Subject: [PATCH 2/4] qwen3-asr: the XPU binding and tf-qwen3-asr-xpu (#2105) xpu/ binds the shared tower and Qwen3 schedules to qwen3_asr.cl and the shared kernels on Level Zero, as cuda/ does on CUDA: the store places bf16 tensors as stored, the embedding copies rows by id, and lfm3's attention merge takes a +inf gate (bf16(sigmoid) = 1). tf-qwen3-asr-xpu runs a clip against a qwen3_asr_case.py case, each stage's cosine and the greedy ids. On Iris Xe the three LibriSpeech dev clips (1272-128104-0000, -0001, -0004) are byte-identical to the windowed reference (26, 17 and 91 tokens; worst stage cosine 0.99765). --- zig/build/xpu.zig | 5 + zig/src/families/qwen3_asr/qwen3_asr_xpu.zig | 11 + zig/src/families/qwen3_asr/xpu/lm.zig | 184 +++++++++++++++++ zig/src/families/qwen3_asr/xpu/model.zig | 91 +++++++++ zig/src/families/qwen3_asr/xpu/store.zig | 54 +++++ zig/src/families/qwen3_asr/xpu/tower.zig | 111 ++++++++++ zig/tests/qwen3_asr_xpu.zig | 204 +++++++++++++++++++ 7 files changed, 660 insertions(+) create mode 100644 zig/src/families/qwen3_asr/qwen3_asr_xpu.zig create mode 100644 zig/src/families/qwen3_asr/xpu/lm.zig create mode 100644 zig/src/families/qwen3_asr/xpu/model.zig create mode 100644 zig/src/families/qwen3_asr/xpu/store.zig create mode 100644 zig/src/families/qwen3_asr/xpu/tower.zig create mode 100644 zig/tests/qwen3_asr_xpu.zig diff --git a/zig/build/xpu.zig b/zig/build/xpu.zig index 17a7bcf8227..387d4f3dfc0 100644 --- a/zig/build/xpu.zig +++ b/zig/build/xpu.zig @@ -205,6 +205,11 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil } const tokenizer = b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true }); const template = b.createModule(.{ .root_source_file = b.path("zig/src/core/template/template.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true }); + // tf-qwen3-asr-xpu: Qwen3-ASR's tower and language model on qwen3_asr.cl (no DPAS), a clip against a reference case + const asr = b.createModule(.{ .root_source_file = b.path("zig/src/families/qwen3_asr/qwen3_asr_xpu.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "xpu", .module = nem.xpu }, .{ .name = "core", .module = core } } }); + const asr_main = b.createModule(.{ .root_source_file = b.path("zig/tests/qwen3_asr_xpu.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "xpu", .module = nem.xpu }, .{ .name = "qwen3_asr", .module = asr }, .{ .name = "tokenizer", .module = tokenizer } } }); + const asr_exe = b.addExecutable(.{ .name = "tf-qwen3-asr-xpu", .root_module = asr_main }); + b.step("tf-qwen3-asr-xpu", "Build tf-qwen3-asr-xpu, Qwen3-ASR's tower and language model on the Intel GPU on a clip").dependOn(&b.addInstallArtifact(asr_exe, .{}).step); const checkpoint_cli = b.createModule(.{ .root_source_file = b.path("zig/src/cli/cli.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{ .{ .name = "native_engines", .module = engines }, exlr8_build.cliImport(b, target, .ReleaseSafe, core), .{ .name = "core", .module = core } } }); const server = b.addExecutable(.{ .name = "tensorfold-native", .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/server/main.zig"), diff --git a/zig/src/families/qwen3_asr/qwen3_asr_xpu.zig b/zig/src/families/qwen3_asr/qwen3_asr_xpu.zig new file mode 100644 index 00000000000..91f44828c72 --- /dev/null +++ b/zig/src/families/qwen3_asr/qwen3_asr_xpu.zig @@ -0,0 +1,11 @@ +//! Qwen3-ASR on the Intel GPU: xpu/ binds the shared schedules (tower.zig, lm.zig); tf-qwen3-asr-xpu drives it. +pub const host = @import("qwen3_asr.zig"); +pub const Model = @import("xpu/model.zig").Model; +pub const Options = @import("xpu/model.zig").Options; +pub const Dump = @import("xpu/model.zig").Dump; +pub const Splice = @import("xpu/model.zig").Splice; +pub const view = @import("xpu/store.zig").view; + +test { + _ = @import("xpu/model.zig"); +} diff --git a/zig/src/families/qwen3_asr/xpu/lm.zig b/zig/src/families/qwen3_asr/xpu/lm.zig new file mode 100644 index 00000000000..3153e07d50b --- /dev/null +++ b/zig/src/families/qwen3_asr/xpu/lm.zig @@ -0,0 +1,184 @@ +//! The Qwen3 LM's XPU binding: lfm3_gq2's norm, SwiGLU and attention, glue's add, qwen3_asr.cl's GEMM and QK RoPE. +const std = @import("std"); +const xpu = @import("xpu"); +const cfg = @import("../config.zig"); +const shared = @import("../lm.zig"); +const store = @import("store.zig"); +const tower = @import("tower.zig"); +const rt = xpu.rt; +const run = tower.run; + +/// lfm3_attn_partial's chunk: keys a partial covers. +const chunk = 128; + +pub const Lm = struct { + t: cfg.Text, + r: *rt.Runtime, + asr: rt.Module, + lf: rt.Module, + glue: rt.Module, + k: struct { rms: rt.Kernel, add: rt.Kernel, gemm: rt.Kernel, qk: rt.Kernel, part: rt.Kernel, merge: rt.Kernel, swiglu: rt.Kernel }, + cap: usize, // positions the caches hold + maxc: usize, // chunks a row's keys span at most + pos0: usize = 0, // the pass's first position + b: struct { q: u64, k: u64, v: u64, logits: u64, cos: u64, sin: u64, kc: u64, vc: u64, po: u64, pm: u64, pl: u64, gate: u64 }, + ids: []u32, + rows: usize = 0, + logits: []u16, + last_margin: f32 = 0, // the last pick's lead over the runner-up + sink: ?tower.Dump = null, + + /// Passes of up to `max_rows` rows over up to `span` positions. + pub fn init(gpa: std.mem.Allocator, r: *rt.Runtime, t: cfg.Text, max_rows: usize, span: usize, st: *store.Store) !Lm { + if (t.head_dim != 128 or t.heads != 2 * t.kv_heads) return error.UnsupportedQwen3AsrGeometry; // GQ = 2 + if (span > t.context) return error.ContextTooLong; + if (!xpu.kernels.available) return error.BuiltWithoutKernels; + var asr = try r.module(xpu.kernels.qwen3_asr); + errdefer asr.deinit(); + var lf = try r.module(xpu.kernels.lfm3_gq2); + errdefer lf.deinit(); + var glue = try r.module(xpu.kernels.glue); + errdefer glue.deinit(); + const maxc = (span + chunk - 1) / chunk; + var lm: Lm = .{ + .t = t, + .r = r, + .asr = asr, + .lf = lf, + .glue = glue, + .k = .{ + .rms = try lf.kernel("lfm3_rmsnorm", .{ 256, 1, 1 }), + .add = try glue.kernel("add_bf16", .{ 64, 1, 1 }), + .gemm = try asr.kernel("asr_gemm", .{ 16, 16, 1 }), + .qk = try asr.kernel("asr_qk_rope", .{ 16, 1, 1 }), + .part = try lf.kernel("lfm3_attn_partial", .{ 32, 1, 1 }), + .merge = try lf.kernel("lfm3_attn_merge_gate", .{ 16, 1, 1 }), + .swiglu = try lf.kernel("lfm3_swiglu", .{ 64, 1, 1 }), + }, + .cap = span, + .maxc = maxc, + .b = undefined, + .ids = &.{}, + .logits = &.{}, + }; + const qd = t.heads * t.head_dim; + const kvd = t.kv_heads * t.head_dim; + const kv = t.layers * span * kvd * 2; + lm.b = .{ + .q = try st.alloc(2 * max_rows * qd), + .k = try st.alloc(2 * max_rows * kvd), + .v = try st.alloc(2 * max_rows * kvd), + .logits = try st.alloc(2 * t.vocab), + .cos = try st.alloc(4 * span * t.head_dim), + .sin = try st.alloc(4 * span * t.head_dim), + .kc = try st.alloc(kv), + .vc = try st.alloc(kv), + .po = try st.alloc(4 * max_rows * t.heads * maxc * t.head_dim), + .pm = try st.alloc(4 * max_rows * t.heads * maxc), + .pl = try st.alloc(4 * max_rows * t.heads * maxc), + .gate = try st.alloc(2 * max_rows * t.heads), + }; + const cs = try gpa.alloc(f32, span * t.head_dim); + defer gpa.free(cs); + const sn = try gpa.alloc(f32, span * t.head_dim); + defer gpa.free(sn); + shared.ropeTables(t, cs, sn, span); + try r.upload(store.view(r, lm.b.cos, cs.len * 4), std.mem.sliceAsBytes(cs)); + try r.upload(store.view(r, lm.b.sin, sn.len * 4), std.mem.sliceAsBytes(sn)); + // no gate on Qwen3: lfm3_attn_merge_gate's bf16(sigmoid(+inf)) is 1, so its rows are bf16(O / L) unscaled + const gate = try gpa.alloc(u16, max_rows * t.heads); + defer gpa.free(gate); + @memset(gate, 0x7f80); + try r.upload(store.view(r, lm.b.gate, gate.len * 2), std.mem.sliceAsBytes(gate)); + try r.sync(); + lm.ids = try gpa.alloc(u32, max_rows); + errdefer gpa.free(lm.ids); + lm.logits = try gpa.alloc(u16, t.vocab); + return lm; + } + + pub fn deinit(lm: *Lm, gpa: std.mem.Allocator) void { + gpa.free(lm.logits); + gpa.free(lm.ids); + inline for (.{ &lm.k.rms, &lm.k.add, &lm.k.gemm, &lm.k.qk, &lm.k.part, &lm.k.merge, &lm.k.swiglu }) |k| k.deinit(); + lm.glue.deinit(); + lm.lf.deinit(); + lm.asr.deinit(); + } + + /// The pass's ids (the embedding copies rows by them on the host's side) and its first position. + pub fn positions(lm: *Lm, ids: []const u32, pos: usize) !void { + if (ids.len > lm.ids.len) return error.PassRows; + if (pos + ids.len > lm.cap) return error.ContextFull; + @memcpy(lm.ids[0..ids.len], ids); + lm.rows = ids.len; + lm.pos0 = pos; + } + + pub fn dump(lm: *Lm, stage: []const u8, ptr: u64, rows: usize, cols: usize) !void { + if (lm.sink) |dm| try dm.put(dm.ctx, stage, ptr, rows, cols, null); + } + + /// The table's rows by the pass's ids, device to device. + pub fn embed(lm: *Lm, table: u64, out: u64, rows: usize, hidden: usize) !void { + const row = hidden * 2; + for (lm.ids[0..rows], 0..) |id, i| try lm.copy(out + i * row, table + id * row, row); + } + + pub fn copy(lm: *Lm, dst: u64, src: u64, n: usize) !void { + try lm.r.copy(store.view(lm.r, dst, n), store.view(lm.r, src, n), n); + } + + /// h = bf16(x + res) (x when res is null, h unwritten), y = bf16(w bf16(h rsqrt(mean h^2 + eps))). + pub fn addNorm(lm: *Lm, x: u64, res: ?u64, w: u64, h: u64, y: u64, rows: usize) !void { + const n = lm.t.hidden; + const eps: f32 = @floatCast(lm.t.eps); + const src = if (res) |rs| blk: { + try lm.copy(h, rs, rows * n * 2); + try run(lm.r, &lm.k.add, .{ (rows * n + 63) / 64, 1, 1 }, .{ h, x, rows * n }); + break :blk h; + } else x; + try run(lm.r, &lm.k.rms, .{ rows, 1, 1 }, .{ src, w, y, n, eps }); + } + + pub fn gemm(lm: *Lm, x: u64, w: u64, y: u64, rows: usize, n: usize, k: usize) !void { + const z = lm.b.gate; // unread: no bias, no residual + try run(lm.r, &lm.k.gemm, .{ (n + 63) / 64, (rows + 63) / 64, 1 }, .{ x, w, z, @as(u32, 0), z, @as(u32, 0), y, rows, n, k, n, @as(u32, 0) }); + } + + fn kvAt(lm: *const Lm, base: u64, layer: usize) u64 { + return base + layer * lm.cap * lm.t.kv_heads * lm.t.head_dim * 2; + } + + /// q and k RMS-normed per head and rotated, k and v into layer's caches at the pass's positions. + pub fn qkRope(lm: *Lm, qkv: u64, q_norm: u64, k_norm: u64, layer: usize, rows: usize) !void { + const t = lm.t; + const b = lm.b; + try run(lm.r, &lm.k.qk, .{ t.heads + 2 * t.kv_heads, rows, 1 }, .{ qkv, q_norm, k_norm, b.cos, b.sin, b.q, b.k, b.v, lm.kvAt(b.kc, layer), lm.kvAt(b.vc, layer), t.heads, t.kv_heads, lm.pos0, @as(f32, @floatCast(t.eps)) }); + } + + /// Causal GQA attention of the pass's q rows over layer's caches into out [rows, heads x dim]: lfm3's split-K pair. + pub fn attention(lm: *Lm, layer: usize, out: u64, rows: usize) !void { + const t = lm.t; + const b = lm.b; + const scale: f32 = @floatCast(1.0 / @sqrt(@as(f64, @floatFromInt(t.head_dim)))); + const nch = (lm.pos0 + rows + chunk - 1) / chunk; + try run(lm.r, &lm.k.part, .{ t.kv_heads, nch, rows }, .{ b.q, lm.kvAt(b.kc, layer), lm.kvAt(b.vc, layer), b.po, b.pm, b.pl, lm.pos0, @as(u32, chunk), lm.cap, @as(u32, 0), t.kv_heads, lm.maxc, scale }); + try run(lm.r, &lm.k.merge, .{ t.heads, rows, 1 }, .{ b.po, b.pm, b.pl, b.gate, out, lm.pos0, @as(u32, chunk), @as(u32, 0), t.heads, lm.maxc }); + } + + /// out [rows, i] = bf16(bf16(silu(gate)) up) of gu's [gate | up] rows: lfm3_swiglu a row at a time. + pub fn swiglu(lm: *Lm, gu: u64, out: u64, rows: usize, i: usize) !void { + for (0..rows) |r| try run(lm.r, &lm.k.swiglu, .{ (i + 63) / 64, 1, 1 }, .{ gu + r * 4 * i, gu + r * 4 * i + 2 * i, out + r * 2 * i, i }); + } + + /// The tied head over one normed row, downloaded: its greedy pick. + pub fn greedy(lm: *Lm, row: u64, embed_table: u64) !u32 { + try lm.gemm(row, embed_table, lm.b.logits, 1, lm.t.vocab, lm.t.hidden); + try lm.r.download(std.mem.sliceAsBytes(lm.logits), store.view(lm.r, lm.b.logits, lm.logits.len * 2)); + try lm.r.sync(); + const best = shared.argmax(lm.logits); + lm.last_margin = shared.margin(lm.logits, best); + return best; + } +}; diff --git a/zig/src/families/qwen3_asr/xpu/model.zig b/zig/src/families/qwen3_asr/xpu/model.zig new file mode 100644 index 00000000000..cf1f8191bbd --- /dev/null +++ b/zig/src/families/qwen3_asr/xpu/model.zig @@ -0,0 +1,91 @@ +//! Qwen3-ASR on the Intel GPU: the shared tower and Qwen3 schedules over this directory's bindings, one store. +const std = @import("std"); +const xpu = @import("xpu"); +const core = @import("core"); +const cfg = @import("../config.zig"); +const mel = @import("../mel.zig"); +const tower = @import("../tower.zig"); +const lm = @import("../lm.zig"); +const store = @import("store.zig"); +const xtower = @import("tower.zig"); +const xlm = @import("lm.zig"); + +pub const Dump = xtower.Dump; +pub const Splice = lm.Splice; + +pub const Options = struct { + group: usize = 16, // chunks a convolution pass + audio_rows: usize, // the longest clip's tower rows + pass_rows: usize, // the most ids a language model pass takes + positions: usize, // the most positions the caches hold +}; + +pub const Model = struct { + gpa: std.mem.Allocator, + c: cfg.Config, + st: store.Store, + weight_bytes: u64, + tw: tower.Weights, + lw: lm.Weights, + tb: tower.Buffers, + lb: lm.Buffers, + tr: xtower.Tower, + lr: xlm.Lm, + + /// The checkpoint at `dir` on the device (every tensor used), with scratch for `o`'s clips and passes. + pub fn load(gpa: std.mem.Allocator, io: std.Io, r: *xpu.rt.Runtime, dir: []const u8, c: cfg.Config, o: Options) !*Model { + const m = try gpa.create(Model); + errdefer gpa.destroy(m); + m.gpa = gpa; + m.c = c; + m.st = .{ .gpa = gpa, .r = r }; + errdefer m.st.deinit(); + { + var ck = try core.Checkpoint.openModel(gpa, io, dir); + defer ck.close(); + const src: store.Source = .{ .ck = &ck }; + m.tw = try tower.Weights.load(gpa, c.audio, src, &m.st, o.group); + errdefer m.tw.deinit(gpa); + m.lw = try lm.Weights.load(gpa, c.text, src, &m.st); + errdefer m.lw.deinit(gpa); + if (ck.unused() != 0) return error.UnexpectedTensors; + } + errdefer m.tw.deinit(gpa); + errdefer m.lw.deinit(gpa); + m.weight_bytes = m.st.bytes; + m.tb = try tower.Buffers.alloc(c.audio, o.group, o.audio_rows, &m.st); + m.lb = try lm.Buffers.alloc(c.text, o.pass_rows, &m.st); + m.tr = try xtower.Tower.init(r, &m.st); + errdefer m.tr.deinit(); + m.lr = try xlm.Lm.init(gpa, r, c.text, o.pass_rows, o.positions, &m.st); + return m; + } + + pub fn deinit(m: *Model) void { + m.lr.deinit(m.gpa); + m.tr.deinit(); + m.lw.deinit(m.gpa); + m.tw.deinit(m.gpa); + m.st.deinit(); + m.gpa.destroy(m); + } + + /// The tower over `feats` into `out` [rows, audio.out] bf16, each stage to `sink` when given; the rows returned. + pub fn encode(m: *Model, feats: mel.Features, out: u64, sink: ?Dump) !usize { + m.tr.sink = sink; + defer m.tr.sink = null; + return tower.encode(&m.tr, m.gpa, m.c.audio, &m.tw, m.tb, feats, out); + } + + /// One language model pass over `ids` at [pos, pos + ids.len), `audio` spliced in: the greedy next id. + pub fn forward(m: *Model, ids: []const u32, pos: usize, audio: ?Splice) !u32 { + return m.forwardDump(ids, pos, audio, null); + } + + /// forward with its stages (lm_embed, lm_layer{i}, lm_norm) to `sink`. + pub fn forwardDump(m: *Model, ids: []const u32, pos: usize, audio: ?Splice, sink: ?Dump) !u32 { + m.lr.sink = sink; + defer m.lr.sink = null; + return lm.forward(&m.lr, m.c.text, &m.lw, m.lb, ids, pos, audio); + } +}; diff --git a/zig/src/families/qwen3_asr/xpu/store.zig b/zig/src/families/qwen3_asr/xpu/store.zig new file mode 100644 index 00000000000..80461775629 --- /dev/null +++ b/zig/src/families/qwen3_asr/xpu/store.zig @@ -0,0 +1,54 @@ +//! Device memory for the shared schedules on Level Zero: `put` and `taps` place tensors, `alloc` gives scratch. +const std = @import("std"); +const xpu = @import("xpu"); +const core = @import("core"); +const rt = xpu.rt; + +/// A span another value owns (a device address from the schedules), for one launch argument or copy. +pub fn view(r: *rt.Runtime, ptr: u64, len: usize) rt.Buffer { + return .{ .rt = r, .ptr = @ptrFromInt(ptr), .len = len }; +} + +/// The bf16 bytes of a checkpoint's tensors by name and shape, for tower.Weights.load and lm.Weights.load. +pub const Source = struct { + ck: *core.Checkpoint, + + pub fn expect(s: Source, name: []const u8, shape: []const usize) ![]const u8 { + return (try s.ck.expect(name, .bf16, shape)).bytes; + } +}; + +/// Every allocation the model holds, freed together. +pub const Store = struct { + gpa: std.mem.Allocator, + r: *rt.Runtime, + list: std.ArrayList(rt.Buffer) = .empty, + bytes: u64 = 0, + + pub fn deinit(st: *Store) void { + for (st.list.items) |*b| b.free(); + st.list.deinit(st.gpa); + } + + pub fn alloc(st: *Store, n: usize) !u64 { + var b = try st.r.alloc(@max(n, 256)); + errdefer b.free(); + try st.list.append(st.gpa, b); + st.bytes += b.len; + return @intFromPtr(b.ptr.?); + } + + /// The bytes copied before returning: the caller may free them (tower.joined does). + pub fn put(st: *Store, bytes: []const u8) !u64 { + const p = try st.alloc(bytes.len); + try st.r.upload(view(st.r, p, bytes.len), bytes); + try st.r.sync(); + return p; + } + + /// A conv's [co, k] taps as stored: asr_conv reads rows k values apart. + pub fn taps(st: *Store, bytes: []const u8, co: usize, k: usize) !u64 { + if (bytes.len != co * k * 2) return error.TapsShape; + return st.put(bytes); + } +}; diff --git a/zig/src/families/qwen3_asr/xpu/tower.zig b/zig/src/families/qwen3_asr/xpu/tower.zig new file mode 100644 index 00000000000..e060eda97e0 --- /dev/null +++ b/zig/src/families/qwen3_asr/xpu/tower.zig @@ -0,0 +1,111 @@ +//! The audio tower's binding on the Intel GPU without DPAS: qwen3_asr.cl's conv, Linear, LayerNorm, GELU and attention. +const std = @import("std"); +const xpu = @import("xpu"); +const shared = @import("../tower.zig"); +const store = @import("store.zig"); +const rt = xpu.rt; + +/// Where a stage's device rows go when a check asks for them: bf16 `rows` x `cols` at `ptr`, channels last for convs. +pub const Dump = struct { + ctx: *anyopaque, + put: *const fn (ctx: *anyopaque, stage: []const u8, ptr: u64, rows: usize, cols: usize, conv: ?[3]usize) anyerror!void, +}; + +/// A launch: device addresses (u64) as buffers, f32 as floats, every other integer as a 32-bit argument. +pub fn run(r: *rt.Runtime, k: *rt.Kernel, groups: [3]usize, args: anytype) !void { + inline for (args, 0..) |v, i| { + const T = @TypeOf(v); + if (T == u64) { + try k.setBuffer(i, store.view(r, v, 0)); + } else if (T == f32) { + try k.setF32(i, v); + } else try k.setU32(i, @intCast(v)); + } + try k.launch(.{ @intCast(groups[0]), @intCast(groups[1]), @intCast(groups[2]) }); +} + +pub const Tower = struct { + r: *rt.Runtime, + md: rt.Module, + gemm: rt.Kernel, + conv_k: rt.Kernel, + flat: rt.Kernel, + ln: rt.Kernel, + gelu_k: rt.Kernel, + attn: rt.Kernel, + zero: u64, // a missing bias or residual + sink: ?Dump = null, + + pub fn init(r: *rt.Runtime, st: *store.Store) !Tower { + if (!xpu.kernels.available) return error.BuiltWithoutKernels; + var md = try r.module(xpu.kernels.qwen3_asr); + errdefer md.deinit(); + return .{ + .r = r, + .md = md, + .gemm = try md.kernel("asr_gemm", .{ 16, 16, 1 }), + .conv_k = try md.kernel("asr_conv", .{ 16, 16, 1 }), + .flat = try md.kernel("asr_flatten", .{ 256, 1, 1 }), + .ln = try md.kernel("asr_layernorm", .{ 256, 1, 1 }), + .gelu_k = try md.kernel("asr_gelu", .{ 256, 1, 1 }), + .attn = try md.kernel("asr_attn_full", .{ 16, 1, 1 }), + .zero = try st.alloc(256), + }; + } + + pub fn deinit(t: *Tower) void { + inline for (.{ &t.gemm, &t.conv_k, &t.flat, &t.ln, &t.gelu_k, &t.attn }) |k| k.deinit(); + t.md.deinit(); + } + + pub fn upload(t: *Tower, dst: u64, bytes: []const u8) !void { + try t.r.upload(store.view(t.r, dst, bytes.len), bytes); + } + + /// y [n, fo, to, co] = bf16(taps(x [n, fi, ti, c]) . w^T + b), a 3x3 stride-2 conv with zero padding 1. + pub fn conv(t: *Tower, w: u64, b: u64, x: u64, y: u64, n: usize, fi: usize, ti: usize, c: usize, co: usize) !void { + const m = n * ((fi - 1) / 2 + 1) * ((ti - 1) / 2 + 1); + try run(t.r, &t.conv_k, .{ (co + 63) / 64, (m + 63) / 64, 1 }, .{ x, w, b, y, m, co, 9 * c, fi, ti, c }); + } + + /// Whether stages go to a sink (the schedule then runs conv_out once more without the positions, for its tap). + pub fn dumping(t: *const Tower) bool { + return t.sink != null; + } + + pub fn dump(t: *Tower, stage: []const u8, ptr: u64, rows: usize, cols: usize, conv_shape: ?[3]usize) !void { + if (t.sink) |dm| try dm.put(dm.ctx, stage, ptr, rows, cols, conv_shape); + } + + pub fn flatten(t: *Tower, x: u64, y: u64, n: usize, f: usize, tt: usize, c: usize) !void { + const total = n * tt * c * f; + try run(t.r, &t.flat, .{ (total + 255) / 256, 1, 1 }, .{ x, y, f, tt, c, total }); + } + + /// y = bf16(act(bf16(x . w^T + b)) + res); a missing bias is none, `res` may be y itself. + pub fn linear(t: *Tower, x: u64, w: u64, b: ?u64, y: u64, rows: usize, n: usize, k: usize, act: shared.Act, res: ?u64) !void { + const a: u32 = switch (act) { + .none => 0, + .gelu => 1, + }; + try run(t.r, &t.gemm, .{ (n + 63) / 64, (rows + 63) / 64, 1 }, .{ x, w, b orelse t.zero, @as(u32, @intFromBool(b != null)), res orelse t.zero, @as(u32, @intFromBool(res != null)), y, rows, n, k, n, a }); + } + + pub fn layernorm(t: *Tower, x: u64, w: u64, b: u64, y: u64, rows: usize, d: usize) !void { + try run(t.r, &t.ln, .{ rows, 1, 1 }, .{ x, w, b, y, d, @as(f32, 1e-5) }); + } + + /// Bidirectional attention over one window of `len` rows of [q | k | v] (heads x 64 each). + pub fn attention(t: *Tower, qkv: u64, out: u64, len: usize, heads: usize, dim: usize) !void { + if (dim != 64) return error.UnsupportedHeadDim; + try run(t.r, &t.attn, .{ len, heads, 1 }, .{ qkv, out, len, heads, @as(f32, 0.125) }); + } + + pub fn gelu(t: *Tower, x: u64, y: u64, count: usize) !void { + try run(t.r, &t.gelu_k, .{ (count + 255) / 256, 1, 1 }, .{ x, y, count }); + } + + pub fn sync(t: *Tower) !void { + try t.r.sync(); + } +}; diff --git a/zig/tests/qwen3_asr_xpu.zig b/zig/tests/qwen3_asr_xpu.zig new file mode 100644 index 00000000000..12e7fff17c7 --- /dev/null +++ b/zig/tests/qwen3_asr_xpu.zig @@ -0,0 +1,204 @@ +//! tf-qwen3-asr-xpu: a clip through Qwen3-ASR on the Intel GPU, greedy, one stream; each stage against a case. +const std = @import("std"); +const xpu = @import("xpu"); +const qa = @import("qwen3_asr"); +const tok = @import("tokenizer"); +const host = qa.host; + +const usage = "usage: tf-qwen3-asr-xpu MODEL_DIR CLIP.wav [--case DIR [--ids-only]] [--tokens N]\n"; +const eos = [_]u32{ 151645, 151643 }; + +fn seconds() f64 { + var ts: std.c.timespec = undefined; + _ = std.c.clock_gettime(std.c.CLOCK.MONOTONIC, &ts); + return @as(f64, @floatFromInt(ts.sec)) + @as(f64, @floatFromInt(ts.nsec)) * 1e-9; +} + +fn widen(bits: u16) f64 { + return @as(f32, @bitCast(@as(u32, bits) << 16)); +} + +/// Each dumped stage downloaded and compared with the case's; the worst cosine kept. +const Compare = struct { + gpa: std.mem.Allocator, + case: *host.case.Case, + r: *xpu.rt.Runtime, + worst: f64 = 1, + conv: std.StringHashMapUnmanaged(std.ArrayList(f64)) = .empty, + + fn put(ctx: *anyopaque, stage: []const u8, ptr: u64, rows: usize, cols: usize, conv: ?[3]usize) anyerror!void { + const c: *Compare = @ptrCast(@alignCast(ctx)); + const raw = try c.gpa.alloc(u16, rows * cols); + defer c.gpa.free(raw); + try c.r.sync(); + try c.r.download(std.mem.sliceAsBytes(raw), qa.view(c.r, ptr, raw.len * 2)); + try c.r.sync(); + const vals = try c.gpa.alloc(f64, raw.len); + defer c.gpa.free(vals); + const conv_out = std.mem.eql(u8, stage, "conv_out"); // [n][rows][d], a chunk group at a time + if (conv != null or conv_out) { + if (conv) |sh| { // channels last [n][f][t][c] to the export's [n][c][f][t] + const per = sh[1] * sh[2] * cols; + for (0..sh[0]) |n| for (0..sh[1]) |f| for (0..sh[2]) |t| for (0..cols) |k| { + vals[n * per + (k * sh[1] + f) * sh[2] + t] = widen(raw[((n * sh[1] + f) * sh[2] + t) * cols + k]); + }; + } else for (vals, raw) |*v, r| { + v.* = widen(r); + } + const got = try c.conv.getOrPut(c.gpa, stage); + if (!got.found_existing) got.value_ptr.* = .empty; + try got.value_ptr.appendSlice(c.gpa, vals); + return; + } + for (vals, raw) |*v, r| v.* = widen(r); + try c.report(stage, vals); + } + + fn report(c: *Compare, stage: []const u8, vals: []const f64) !void { + // not every layer is in a case, and a shared case may leave out a stage's file (conv1, conv2) + const want = c.case.floats(c.gpa, stage) catch |e| return if (e == error.NoSuchStage or e == error.FileNotFound) {} else e; + defer c.gpa.free(want); + if (want.len != vals.len) return error.StageSize; + const m = host.case.Match.of(vals, want); + c.worst = @min(c.worst, m.cosine); + std.debug.print("STAGE {s:<12} cos {d:.9} worst {e:.3} at {d} rms(diff)/rms(ref) {e:.3}\n", .{ stage, m.cosine, m.worst, m.at, m.rms_diff / @max(m.rms_want, 1e-300) }); + } + + /// The conv stages and conv_out, gathered over every chunk group, compared once whole. + fn finishConvs(c: *Compare) !void { + for ([_][]const u8{ "conv1", "conv2", "conv3", "conv_out" }) |n| if (c.conv.getPtr(n)) |l| { + try c.report(n, l.items); + l.deinit(c.gpa); + }; + c.conv.deinit(c.gpa); + } +}; + +pub fn main(init: std.process.Init) !u8 { + const gpa = init.gpa; + const io = init.io; + const args = try init.minimal.args.toSlice(init.arena.allocator()); + if (args.len < 3) { + std.debug.print(usage, .{}); + return 2; + } + var case_dir: ?[]const u8 = null; + var max_new: usize = 448; + var ids_only = false; // a case of ids and margins only: no stage compared + var i: usize = 3; + while (i < args.len) : (i += 2) { + if (std.mem.eql(u8, args[i], "--ids-only")) { + ids_only = true; + i -= 1; + } else if (i + 1 >= args.len) { + std.debug.print(usage, .{}); + return 2; + } else if (std.mem.eql(u8, args[i], "--case")) case_dir = args[i + 1] else if (std.mem.eql(u8, args[i], "--tokens")) { + max_new = try std.fmt.parseInt(usize, args[i + 1], 10); + } else { + std.debug.print(usage, .{}); + return 2; + } + } + const cfg = try host.config.read(gpa, io, args[1]); + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, args[2], gpa, .limited(1 << 31)); + defer gpa.free(bytes); + const samples = try host.wav.decode(gpa, bytes); + defer gpa.free(samples); + const t_mel = seconds(); + var feats = try host.mel.features(gpa, samples, cfg.audio.mels); + defer feats.deinit(gpa); + const mel_s = seconds() - t_mel; + const plan = try host.chunks.Plan.init(cfg.audio, feats.frames); + var tk = try tok.loadTokenizer(io, gpa, args[1]); + defer tk.deinit(); + const text = try host.prompt.text(gpa, plan.rows, "", null); + defer gpa.free(text); + const ids = try tk.encode(gpa, text); + defer gpa.free(ids); + const at = std.mem.indexOfScalar(u32, ids, cfg.audio_token) orelse return error.NoAudioRows; + + var driver = try xpu.Driver.open(); + var ctx = try xpu.Context.init(&driver, null); + const stream = try xpu.Stream.init(&ctx); + var r = try xpu.rt.Runtime.init(&ctx, stream); + defer r.deinit(); + const t_load = seconds(); + const opts: qa.Options = .{ .audio_rows = plan.rows, .pass_rows = ids.len, .positions = ids.len + max_new + 1 }; + const m = try qa.Model.load(gpa, io, &r, args[1], cfg, opts); + defer m.deinit(); + var rows_buf = try r.alloc(plan.rows * cfg.audio.out * 2); + defer rows_buf.free(); + const rows_ptr: u64 = @intFromPtr(rows_buf.ptr.?); + const gib = struct { + fn f(x: u64) f64 { + return @as(f64, @floatFromInt(x)) / (1 << 30); + } + }.f; + std.debug.print("XPU: weights {d:.2} GiB, scratch {d:.2} GiB, load {d:.2} s\n", .{ gib(m.weight_bytes), gib(m.st.bytes - m.weight_bytes), seconds() - t_load }); + std.debug.print("CLIP {d:.2} s: {d} frames, {d} chunks, {d} rows, {d} windows; prompt {d} ids\n", .{ @as(f64, @floatFromInt(samples.len)) / 16000.0, feats.frames, plan.chunks, plan.rows, plan.windows(), ids.len }); + + var case: ?host.case.Case = if (case_dir) |dir| try host.case.Case.open(gpa, io, dir) else null; + defer if (case) |*c| c.deinit(); + var cmp: ?Compare = if (case) |*c| .{ .gpa = gpa, .case = c, .r = &r } else null; + if (cmp) |*c| { + const want = try c.case.ids(gpa, "prompt_ids"); + defer gpa.free(want); + std.debug.print("PROMPT ids {s} the case's\n", .{if (std.mem.eql(u32, want, ids)) "equal to" else "DIFFERENT from"}); + } + // a warm pass first: the timed pass after it sees no first-launch costs + _ = try m.encode(feats, rows_ptr, null); + try r.sync(); + const t_tower = seconds(); + const rows = try m.encode(feats, rows_ptr, null); + try r.sync(); + const tower_s = seconds() - t_tower; + if (cmp) |*c| if (!ids_only) { + _ = try m.encode(feats, rows_ptr, .{ .ctx = c, .put = Compare.put }); + try c.finishConvs(); + }; + const t_prompt = seconds(); + const splice: qa.Splice = .{ .ptr = rows_ptr, .at = at, .n = rows }; + var next = try m.forward(ids, 0, splice); + const prompt_s = seconds() - t_prompt; + var out: std.ArrayList(u32) = .empty; + defer out.deinit(gpa); + var margins: std.ArrayList(f32) = .empty; + defer margins.deinit(gpa); + try margins.append(gpa, m.lr.last_margin); + if (cmp) |*c| if (!ids_only) { // the prompt pass's stages, then the pass again: its caches written as before + _ = try m.forwardDump(ids, 0, splice, .{ .ctx = c, .put = Compare.put }); + }; + const t_dec = seconds(); + while (out.items.len < max_new) { + try out.append(gpa, next); + if (std.mem.indexOfScalar(u32, &eos, next) != null) break; + next = try m.forward(&.{next}, ids.len + out.items.len - 1, null); + try margins.append(gpa, m.lr.last_margin); + } + const dec_s = seconds() - t_dec; + const body = if (out.items.len > 0 and std.mem.indexOfScalar(u32, &eos, out.items[out.items.len - 1]) != null) out.items[0 .. out.items.len - 1] else out.items; + const reply = try tk.decode(gpa, body, true); + defer gpa.free(reply); + std.debug.print("TIMES mel {d:.1} ms, tower {d:.1} ms ({d} rows), prompt pass {d:.1} ms ({d} rows), decode {d} tokens {d:.1} tok/s\n", .{ mel_s * 1e3, tower_s * 1e3, rows, prompt_s * 1e3, ids.len, out.items.len, @as(f64, @floatFromInt(out.items.len)) / @max(dec_s, 1e-9) }); + std.debug.print("TEXT {s}\n", .{reply}); + if (cmp) |*c| { + const want = try c.case.ids(gpa, "greedy_ids"); + defer gpa.free(want); + const n = @min(want.len, out.items.len); + const first = std.mem.indexOfDiff(u32, want[0..n], out.items[0..n]) orelse n; + const same = first == n and want.len == out.items.len; + std.debug.print("GREEDY {d} tokens vs the case's {d}: {s}", .{ out.items.len, want.len, if (same) "byte-identical\n" else "differ" }); + if (!same) { + const ref = c.case.floats(gpa, "greedy_margin") catch try gpa.alloc(f32, 0); // older cases have none + defer gpa.free(ref); + std.debug.print(" from token {d}: ours {d} (margin {d:.4}), the case's {d} (margin {d:.4})\n", .{ + first, if (first < out.items.len) out.items[first] else 0, + if (first < margins.items.len) margins.items[first] else 0, if (first < want.len) want[first] else 0, + if (first < ref.len) ref[first] else 0, + }); + } + std.debug.print("SUMMARY qwen3-asr xpu: worst stage cosine {d:.9}, transcript {s}\n", .{ c.worst, if (same) "equal" else "different" }); + } + return 0; +} From bb07f9b91724e54af8f6d673e2583919238fbb4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:10:55 +0100 Subject: [PATCH 3/4] qwen3-asr xpu: tf-qwen3-asr-xpu-forced, #2239's tie rule on the Intel GPU; the forced tools share forced.zig (#2105) tf-qwen3-asr-xpu-forced runs a clip teacher-forced on a case's greedy ids and judges every step by the tie rule, as tf-qwen3-asr-forced does on CUDA: a differing top token passes only as a swap with both margins at most 0.25. With logits_fp32 and logits_bf16 in the case it prints both distances to fp32. --plant splice and --plant norms (q_norm and k_norm swapped in every layer, Model.swapQkNorms) are the faults it must catch. forced.zig now holds the distance and the step tally both tools print, byte for byte the change #2254 makes for its Metal tool. --- zig/build/xpu.zig | 4 + zig/src/families/qwen3_asr/forced.zig | 72 ++++++++++++++++ zig/src/families/qwen3_asr/xpu/model.zig | 5 ++ zig/tests/qwen3_asr_forced.zig | 67 ++------------- zig/tests/qwen3_asr_xpu_forced.zig | 104 +++++++++++++++++++++++ 5 files changed, 191 insertions(+), 61 deletions(-) create mode 100644 zig/tests/qwen3_asr_xpu_forced.zig diff --git a/zig/build/xpu.zig b/zig/build/xpu.zig index 387d4f3dfc0..fdd2c65a461 100644 --- a/zig/build/xpu.zig +++ b/zig/build/xpu.zig @@ -210,6 +210,10 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil const asr_main = b.createModule(.{ .root_source_file = b.path("zig/tests/qwen3_asr_xpu.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "xpu", .module = nem.xpu }, .{ .name = "qwen3_asr", .module = asr }, .{ .name = "tokenizer", .module = tokenizer } } }); const asr_exe = b.addExecutable(.{ .name = "tf-qwen3-asr-xpu", .root_module = asr_main }); b.step("tf-qwen3-asr-xpu", "Build tf-qwen3-asr-xpu, Qwen3-ASR's tower and language model on the Intel GPU on a clip").dependOn(&b.addInstallArtifact(asr_exe, .{}).step); + // teacher-forced on a case's greedy ids under #2239's tie rule, as tf-qwen3-asr-forced on CUDA + const asr_forced = b.createModule(.{ .root_source_file = b.path("zig/tests/qwen3_asr_xpu_forced.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "xpu", .module = nem.xpu }, .{ .name = "qwen3_asr", .module = asr } } }); + const asr_forced_exe = b.addExecutable(.{ .name = "tf-qwen3-asr-xpu-forced", .root_module = asr_forced }); + b.step("tf-qwen3-asr-xpu-forced", "Build tf-qwen3-asr-xpu-forced, a clip teacher-forced on a case under the tie rule").dependOn(&b.addInstallArtifact(asr_forced_exe, .{}).step); const checkpoint_cli = b.createModule(.{ .root_source_file = b.path("zig/src/cli/cli.zig"), .target = target, .optimize = .ReleaseSafe, .link_libc = true, .imports = &.{ .{ .name = "native_engines", .module = engines }, exlr8_build.cliImport(b, target, .ReleaseSafe, core), .{ .name = "core", .module = core } } }); const server = b.addExecutable(.{ .name = "tensorfold-native", .root_module = b.createModule(.{ .root_source_file = b.path("zig/src/server/main.zig"), diff --git a/zig/src/families/qwen3_asr/forced.zig b/zig/src/families/qwen3_asr/forced.zig index dc2843620c0..3e8c85603e5 100644 --- a/zig/src/families/qwen3_asr/forced.zig +++ b/zig/src/families/qwen3_asr/forced.zig @@ -1,5 +1,6 @@ //! The teacher-forced tie rule (#2648's): on the reference's history, a differing top token passes only as a swap. const std = @import("std"); +const case_ = @import("case.zig"); /// The widest top-1/top-2 margin a swapped step may have, on either side, in logits. pub const bar: f32 = 0.25; @@ -46,6 +47,77 @@ pub fn top(logits: []const u16) Top { return .{ .first = a, .second = second, .margin = if (nan) std.math.nan(f32) else m }; } +/// The largest |a - b| over every column of every step, where it is, and the mean |a - b|. +pub const Dist = struct { + worst: f64 = 0, + step: usize = 0, + col: usize = 0, + sum: f64 = 0, + n: usize = 0, + + pub fn add(d: *Dist, step: usize, a: []const f64, b: []const f32) void { + for (a, b, 0..) |x, y, c| { + const e = @abs(x - y); + d.sum += e; + d.n += 1; + if (!(e <= d.worst)) { + d.worst = e; + d.step = step; + d.col = c; + } + } + } + + pub fn print(d: Dist, label: []const u8) void { + std.debug.print("DIST {s}: worst column {d:.6} (step {d}, id {d}), mean {e:.4} over {d} logits\n", .{ label, d.worst, d.step, d.col, d.sum / @as(f64, @floatFromInt(@max(d.n, 1))), d.n }); + } +}; + +/// A clip's steps against the reference's, each swap or fail printed as it is met; then the FORCED line. +pub const Tally = struct { + same: usize = 0, + swaps: usize = 0, + fails: usize = 0, + + /// Step k: our bf16 logits row against the case's top pair, margin and greedy id. + pub fn step(t: *Tally, clip: []const u8, k: usize, logits: []const u16, first: u32, second: u32, margin: f32, greedy: u32) !void { + const ours = top(logits); + const ref = try reference(first, second, margin, greedy); + switch (judge(ours, ref, bar)) { + .same => t.same += 1, + inline else => |v| { + if (v == .swap) t.swaps += 1 else t.fails += 1; + std.debug.print("{s} {s} step {d}: ours {d} (margin {d:.4}, runner-up {d}), reference {d} (margin {d:.4}, runner-up {d})\n", .{ if (v == .swap) "SWAP" else "FAIL", clip, k, ours.first, ours.margin, ours.second, ref.first, ref.margin, ref.second }); + }, + } + } + + pub fn print(t: Tally, clip: []const u8, steps: usize, note: []const u8) void { + std.debug.print("FORCED {s}: {d} steps, {d} same top token, {d} swaps within {d}, {d} fail{s}\n", .{ clip, steps, t.same, t.swaps, bar, t.fails, note }); + } +}; + +/// With logits_fp32 and logits_bf16 in the case: ours (`steps`, bf16 rows) and the package's bf16 to its fp32. +pub fn distances(gpa: std.mem.Allocator, case: *case_.Case, steps: []const u16, n: usize, vocab: usize) !void { + const fp32 = case.floats(gpa, "logits_fp32") catch |e| return if (e == error.NoSuchStage) {} else e; + defer gpa.free(fp32); + const bf16 = try case.floats(gpa, "logits_bf16"); + defer gpa.free(bf16); + if (fp32.len != n * vocab or bf16.len != fp32.len or steps.len < n * vocab) return error.StageSize; + var ours: Dist = .{}; + var pkg: Dist = .{}; + const row = try gpa.alloc(f64, vocab); + defer gpa.free(row); + for (0..n) |k| { + for (row, steps[k * vocab ..][0..vocab]) |*r, b| r.* = widen(b); + ours.add(k, row, fp32[k * vocab ..][0..vocab]); + for (row, bf16[k * vocab ..][0..vocab]) |*r, b| r.* = b; + pkg.add(k, row, fp32[k * vocab ..][0..vocab]); + } + ours.print("ours to the package's fp32"); + pkg.print("the package's bf16 to its fp32"); +} + fn bf(x: f32) u16 { return @intCast(@as(u32, @bitCast(x)) >> 16); } diff --git a/zig/src/families/qwen3_asr/xpu/model.zig b/zig/src/families/qwen3_asr/xpu/model.zig index cf1f8191bbd..14a2d67ddf2 100644 --- a/zig/src/families/qwen3_asr/xpu/model.zig +++ b/zig/src/families/qwen3_asr/xpu/model.zig @@ -82,6 +82,11 @@ pub const Model = struct { return m.forwardDump(ids, pos, audio, null); } + /// A planted fault for tf-qwen3-asr-xpu-forced: every layer's q_norm and k_norm swapped (again: back). + pub fn swapQkNorms(m: *Model) void { + for (m.lw.layers) |*l| std.mem.swap(u64, &l.q_norm, &l.k_norm); + } + /// forward with its stages (lm_embed, lm_layer{i}, lm_norm) to `sink`. pub fn forwardDump(m: *Model, ids: []const u32, pos: usize, audio: ?Splice, sink: ?Dump) !u32 { m.lr.sink = sink; diff --git a/zig/tests/qwen3_asr_forced.zig b/zig/tests/qwen3_asr_forced.zig index 80389571891..652b8b4f64f 100644 --- a/zig/tests/qwen3_asr_forced.zig +++ b/zig/tests/qwen3_asr_forced.zig @@ -19,32 +19,6 @@ fn widen(bits: u16) f64 { return @as(f32, @bitCast(@as(u32, bits) << 16)); } -/// The largest |a - b| over every column of every step, where it is, and the mean |a - b|. -const Dist = struct { - worst: f64 = 0, - step: usize = 0, - col: usize = 0, - sum: f64 = 0, - n: usize = 0, - - fn add(d: *Dist, step: usize, a: []const f64, b: []const f32) void { - for (a, b, 0..) |x, y, c| { - const e = @abs(x - y); - d.sum += e; - d.n += 1; - if (!(e <= d.worst)) { - d.worst = e; - d.step = step; - d.col = c; - } - } - } - - fn print(d: Dist, label: []const u8) void { - std.debug.print("DIST {s}: worst column {d:.6} (step {d}, id {d}), mean {e:.4} over {d} logits\n", .{ label, d.worst, d.step, d.col, d.sum / @as(f64, @floatFromInt(@max(d.n, 1))), d.n }); - } -}; - const Rows = struct { equal: usize, rows: usize, worst: f64 }; /// Rows of logits bit-equal between two runs, and the largest |difference|. @@ -139,44 +113,15 @@ pub fn main(init: std.process.Init) !u8 { m.keep = null; const clip = std.fs.path.basename(case_dir.?); - var same: usize = 0; - var swaps: usize = 0; - var fails: usize = 0; - for (0..want.len) |k| { - const ours = forced.top(steps.items[k * vocab ..][0..vocab]); - const ref = try forced.reference(top2[2 * k], top2[2 * k + 1], ref_margin[k], want[k]); - switch (forced.judge(ours, ref, forced.bar)) { - .same => same += 1, - inline else => |v| { - if (v == .swap) swaps += 1 else fails += 1; - std.debug.print("{s} {s} step {d}: ours {d} (margin {d:.4}, runner-up {d}), reference {d} (margin {d:.4}, runner-up {d})\n", .{ if (v == .swap) "SWAP" else "FAIL", clip, k, ours.first, ours.margin, ours.second, ref.first, ref.margin, ref.second }); - }, - } - } - var ok = fails == 0; - std.debug.print("FORCED {s}: {d} steps, {d} same top token, {d} swaps within {d}, {d} fail{s}\n", .{ clip, want.len, same, swaps, forced.bar, fails, if (plant) |p| switch (p) { + var tally: forced.Tally = .{}; + for (0..want.len) |k| try tally.step(clip, k, steps.items[k * vocab ..][0..vocab], top2[2 * k], top2[2 * k + 1], ref_margin[k], want[k]); + var ok = tally.fails == 0; + tally.print(clip, want.len, if (plant) |p| switch (p) { .splice => " (planted: the audio rows one position late)", .norms => " (planted: q_norm and k_norm swapped in every layer)", - } else "" }); + } else ""); - if (case.floats(gpa, "logits_fp32")) |fp32| { - defer gpa.free(fp32); - const bf = try case.floats(gpa, "logits_bf16"); - defer gpa.free(bf); - if (fp32.len != want.len * vocab or bf.len != fp32.len) return error.StageSize; - var ours: Dist = .{}; - var pkg: Dist = .{}; - const row = try gpa.alloc(f64, vocab); - defer gpa.free(row); - for (0..want.len) |k| { - for (row, steps.items[k * vocab ..][0..vocab]) |*r, b| r.* = widen(b); - ours.add(k, row, fp32[k * vocab ..][0..vocab]); - for (row, bf[k * vocab ..][0..vocab]) |*r, b| r.* = b; - pkg.add(k, row, fp32[k * vocab ..][0..vocab]); - } - ours.print("ours to the package's fp32"); - pkg.print("the package's bf16 to its fp32"); - } else |e| if (e != error.NoSuchStage) return e; + try forced.distances(gpa, &case, steps.items, want.len, vocab); if (check_rows > 0) { // one prompt pass over the prompt and the first K reply ids, the head over its last K + 1 rows diff --git a/zig/tests/qwen3_asr_xpu_forced.zig b/zig/tests/qwen3_asr_xpu_forced.zig new file mode 100644 index 00000000000..f488ab72eba --- /dev/null +++ b/zig/tests/qwen3_asr_xpu_forced.zig @@ -0,0 +1,104 @@ +//! tf-qwen3-asr-xpu-forced: a clip on the Intel GPU teacher-forced on a case's greedy ids, each step by the tie rule. +const std = @import("std"); +const xpu = @import("xpu"); +const qa = @import("qwen3_asr"); +const host = qa.host; +const forced = host.forced; + +const usage = "usage: tf-qwen3-asr-xpu-forced MODEL_DIR CLIP.wav --case DIR [--plant splice|norms]\n" ++ + " every step on the case's greedy history: a differing top token passes only as a swap with both margins <= 0.25\n" ++ + " (each listed); anything else fails, exit 1. With logits_fp32 and logits_bf16 in the case, the distances to fp32.\n" ++ + " --plant: the audio rows one position late (splice) or q_norm and k_norm swapped in every layer (norms).\n"; + +/// A planted fault the tool must catch: the audio rows one position late, or q_norm and k_norm swapped. +const Plant = enum { splice, norms }; + +pub fn main(init: std.process.Init) !u8 { + const gpa = init.gpa; + const io = init.io; + const args = try init.minimal.args.toSlice(init.arena.allocator()); + if (args.len < 5) { + std.debug.print(usage, .{}); + return 2; + } + var case_dir: ?[]const u8 = null; + var plant: ?Plant = null; + var i: usize = 3; + while (i + 1 < args.len) : (i += 2) { + if (std.mem.eql(u8, args[i], "--case")) case_dir = args[i + 1] else if (std.mem.eql(u8, args[i], "--plant")) { + plant = std.meta.stringToEnum(Plant, args[i + 1]) orelse { + std.debug.print(usage, .{}); + return 2; + }; + } else { + std.debug.print(usage, .{}); + return 2; + } + } + if (i < args.len or case_dir == null) { + std.debug.print(usage, .{}); + return 2; + } + const cfg = try host.config.read(gpa, io, args[1]); + var case = try host.case.Case.open(gpa, io, case_dir.?); + defer case.deinit(); + if (case.attention != .windows) return error.GlobalCase; + const ids = try case.ids(gpa, "prompt_ids"); + defer gpa.free(ids); + const want = try case.ids(gpa, "greedy_ids"); + defer gpa.free(want); + const top2 = try case.ids(gpa, "greedy_top2"); + defer gpa.free(top2); + const ref_margin = try case.floats(gpa, "greedy_margin"); + defer gpa.free(ref_margin); + if (want.len == 0 or top2.len != 2 * want.len or ref_margin.len != want.len) return error.BadCase; + + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, args[2], gpa, .limited(1 << 31)); + defer gpa.free(bytes); + const samples = try host.wav.decode(gpa, bytes); + defer gpa.free(samples); + var feats = try host.mel.features(gpa, samples, cfg.audio.mels); + defer feats.deinit(gpa); + const plan = try host.chunks.Plan.init(cfg.audio, feats.frames); + const at = std.mem.indexOfScalar(u32, ids, cfg.audio_token) orelse return error.NoAudioRows; + if (std.mem.count(u32, ids, &.{cfg.audio_token}) != plan.rows) return error.AudioRowsDiffer; + + var driver = try xpu.Driver.open(); + var ctx = try xpu.Context.init(&driver, null); + const stream = try xpu.Stream.init(&ctx); + var r = try xpu.rt.Runtime.init(&ctx, stream); + defer r.deinit(); + const opts: qa.Options = .{ .audio_rows = plan.rows, .pass_rows = ids.len, .positions = ids.len + want.len + 1 }; + const m = try qa.Model.load(gpa, io, &r, args[1], cfg, opts); + defer m.deinit(); + var rows_buf = try r.alloc(plan.rows * cfg.audio.out * 2); + defer rows_buf.free(); + const rows_ptr: u64 = @intFromPtr(rows_buf.ptr.?); + const n_rows = try m.encode(feats, rows_ptr, null); + const splice: qa.Splice = .{ .ptr = rows_ptr, .at = at + @intFromBool(plant == .splice), .n = n_rows }; + if (plant == .norms) m.swapQkNorms(); + const vocab = cfg.text.vocab; + + // the prompt pass, then one decode step a reference id: each pass's head row (the greedy pick's logits) kept + var steps: std.ArrayList(u16) = .empty; + defer steps.deinit(gpa); + _ = try m.forward(ids, 0, splice); + try steps.appendSlice(gpa, m.lr.logits); + for (want[0 .. want.len - 1], 0..) |id, k| { + _ = try m.forward(&.{id}, ids.len + k, null); + try steps.appendSlice(gpa, m.lr.logits); + } + if (steps.items.len != want.len * vocab) return error.StepRows; + + const clip = std.fs.path.basename(case_dir.?); + var tally: forced.Tally = .{}; + for (0..want.len) |k| try tally.step(clip, k, steps.items[k * vocab ..][0..vocab], top2[2 * k], top2[2 * k + 1], ref_margin[k], want[k]); + tally.print(clip, want.len, if (plant) |p| switch (p) { + .splice => " (planted: the audio rows one position late)", + .norms => " (planted: q_norm and k_norm swapped in every layer)", + } else ""); + try forced.distances(gpa, &case, steps.items, want.len, vocab); + const ok = tally.fails == 0; + std.debug.print("SUMMARY qwen3-asr xpu forced {s}: {s}\n", .{ clip, if (ok) "PASS" else "FAIL" }); + return if (ok) 0 else 1; +} From e7e03b4856e602c0f497bdf2caab12ed6f97383f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Sun, 22 Nov 2026 15:11:01 +0100 Subject: [PATCH 4/4] xpu: Qwen3-ASR's Gen12LP kernels in the kernel contract, FP64 gates, a planted control each, gate 5 live (#2105) tf-xpu-qwen3_asr_contract-test (in xpu-tests) runs gates 1 to 4 on the card for every kernel the binding launches from qwen3_asr.cl (the Linear plain, with bias and residual and with bias and GELU; the conv, flatten, LayerNorm, GELU, the tower's attention, Qwen3's q/k norm and RoPE with its cache writes) and from lfm3.cl at GQ 2 (RMSNorm, the split-K attention pair, SwiGLU), each against float64. Each has a planted control: the same source with one edit (cl_edit fails the build when the edited line is gone), red at the shapes gate, and one at the sums gate (the Linear's steps added in bf16). Gate 5 reads the card's properties against a Gen12LP row (xpu_limits.gen12lp) and every loaded kernel against its record (qwen3_asr_xpu_records.zig); the declared control at 1,024 work-items is red. The guarded buffers move to contract_guarded.zig, generic over the device, so both XPU contract runners share them. --- zig/build/cl_edit.zig | 23 + zig/build/xpu.zig | 23 +- zig/build/xpu_qwen3_asr_contract.zig | 48 ++ zig/src/core/contract.zig | 2 + .../core/contract/qwen3_asr_xpu_records.zig | 83 +++ zig/src/core/contract/xpu_limits.zig | 16 + zig/tests/xpu/contract_guarded.zig | 134 +++++ zig/tests/xpu/contract_rig.zig | 130 +---- zig/tests/xpu/qwen3_asr_contract.zig | 170 ++++++ zig/tests/xpu/qwen3_asr_contract_kit.zig | 203 +++++++ zig/tests/xpu/qwen3_asr_contract_lm.zig | 440 ++++++++++++++ zig/tests/xpu/qwen3_asr_contract_rows.zig | 194 ++++++ zig/tests/xpu/qwen3_asr_contract_tower.zig | 551 ++++++++++++++++++ 13 files changed, 1888 insertions(+), 129 deletions(-) create mode 100644 zig/build/cl_edit.zig create mode 100644 zig/build/xpu_qwen3_asr_contract.zig create mode 100644 zig/src/core/contract/qwen3_asr_xpu_records.zig create mode 100644 zig/tests/xpu/contract_guarded.zig create mode 100644 zig/tests/xpu/qwen3_asr_contract.zig create mode 100644 zig/tests/xpu/qwen3_asr_contract_kit.zig create mode 100644 zig/tests/xpu/qwen3_asr_contract_lm.zig create mode 100644 zig/tests/xpu/qwen3_asr_contract_rows.zig create mode 100644 zig/tests/xpu/qwen3_asr_contract_tower.zig diff --git a/zig/build/cl_edit.zig b/zig/build/cl_edit.zig new file mode 100644 index 00000000000..85b38e067ab --- /dev/null +++ b/zig/build/cl_edit.zig @@ -0,0 +1,23 @@ +//! cl_edit SRC OUT FROM TO [FROM TO ...]: a control's source, each FROM (exactly once) replaced by its TO. +const std = @import("std"); + +pub fn main(init: std.process.Init) !u8 { + const a = init.arena.allocator(); + const args = try init.minimal.args.toSlice(a); + if (args.len < 5 or (args.len - 3) % 2 != 0) { + std.debug.print("usage: cl_edit SRC OUT FROM TO [FROM TO ...]\n", .{}); + return 2; + } + var text: []const u8 = try std.Io.Dir.cwd().readFileAlloc(init.io, args[1], a, .limited(1 << 24)); + var i: usize = 3; + while (i < args.len) : (i += 2) { + const n = std.mem.count(u8, text, args[i]); + if (n != 1) { + std.debug.print("cl_edit: {s} holds \"{s}\" {d} times, not once: update the control\n", .{ args[1], args[i], n }); + return 1; + } + text = try std.mem.replaceOwned(u8, a, text, args[i], args[i + 1]); + } + try std.Io.Dir.cwd().writeFile(init.io, .{ .sub_path = args[2], .data = text }); + return 0; +} diff --git a/zig/build/xpu.zig b/zig/build/xpu.zig index fdd2c65a461..a278391a492 100644 --- a/zig/build/xpu.zig +++ b/zig/build/xpu.zig @@ -229,14 +229,14 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil // Nemotron's device binaries: the same modules over the runners' `core`, the SPIR-V images shared var runners = family(b, target, optimize, runtime(b, target, optimize, &nem.images, ze_mod, runner_core, dpas), runner_core, lanes); runners.images = nem.images; - nemotronSteps(b, target, optimize, runners); + nemotronSteps(b, target, optimize, runners, .{ .ocloc = ocloc, .device = device, .dpas = dpas }); const with_contract = b.option(bool, "xpu-contract", "Build the XPU kernel contract's limits audit (needs ocloc for the objects)") orelse false; const images = b.option([]const u8, "xpu-images", "A directory of zebins made with xpu-kernel-contract-objects: glue, tp, decode, contract_attn_upstream, contract_merge_upstream, contract_controls, contract_gate_controls (.bin)"); if (with_contract) xpu_contract.steps(b, target, optimize, ocloc, device, images); } /// One SPIR-V image: the .cl in zig/kernels/xpu (`src`, else `name`) and its ocloc options (dot/matrix kernels: CL3.0). -const Kernel = struct { name: []const u8, src: ?[]const u8 = null, options: []const u8 = "", include: bool = false }; +pub const Kernel = struct { name: []const u8, src: ?[]const u8 = null, options: []const u8 = "", include: bool = false }; const cl3 = "-cl-std=CL3.0"; @@ -305,18 +305,29 @@ fn cliModule(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil /// ocloc -spv_only on one kernel source: `name`.spv in its own output directory. fn spirv(b: *std.Build, ocloc: []const u8, device: []const u8, dpas: bool, k: Kernel) std.Build.LazyPath { + return spirvOf(b, ocloc, device, dpas, k, b.path(b.fmt("zig/kernels/xpu/{s}.cl", .{k.src orelse k.name}))); +} + +/// As `spirv`, from a source at `file` (a control's edited copy) with `k`'s name and options. +pub fn spirvOf(b: *std.Build, ocloc: []const u8, device: []const u8, dpas: bool, k: Kernel, file: std.Build.LazyPath) std.Build.LazyPath { const run = b.addSystemCommand(&.{ ocloc, "compile", "-device", device, "-spv_only", "-output", k.name, "-output_no_suffix", "-q" }); // ocloc builds from a copy of the source, so the header directory is named (the Run step's cwd is the build root) const options = if (dpas) k.options else b.fmt("{s} -DTF_XPU_NO_DPAS", .{k.options}); // Gen12LP: the kernels' plain fallbacks if (options.len > 0) run.addArgs(&.{ "-options", if (k.include) b.fmt("{s} -I zig/kernels/xpu", .{options}) else options }); _ = k.include; run.addArg("-file"); - run.addFileArg(b.path(b.fmt("zig/kernels/xpu/{s}.cl", .{k.src orelse k.name}))); + run.addFileArg(file); run.addArg("-out_dir"); const out = run.addOutputDirectoryArg(b.fmt("{s}_spirv", .{k.name})); return out.path(b, b.fmt("{s}.spv", .{k.name})); } +/// The SPIR-V image list entry `name`: its source and ocloc options. +pub fn kernelNamed(name: []const u8) Kernel { + for (kernels) |k| if (std.mem.eql(u8, k.name, name)) return k; + @panic("kernelNamed: no such XPU image"); +} + /// Whether ocloc's `device` has DPAS (XMX): not Gen12LP (Tiger Lake, Rocket Lake, Alder Lake, DG1). fn hasDpas(device: []const u8) bool { for ([_][]const u8{ "tgllp", "rkl", "adl", "dg1", "gen12lp" }) |p| if (std.mem.startsWith(u8, device, p)) return false; @@ -340,7 +351,7 @@ const test_programs = [_][]const u8{ }; /// `-Dxpu` (Linux): Nemotron's SPIR-V images, `tensorfold-xpu` and `tf-xpu-test`; needs ocloc, not nvcc or CUDA. -fn nemotronSteps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, mods: Modules) void { +fn nemotronSteps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, mods: Modules, cl: Ocloc) void { const enabled = b.option(bool, "xpu", "Build Nemotron on the Intel GPU into the install step (needs ocloc)") orelse false; if (!enabled or target.result.os.tag != .linux) return; const spirv_step = b.step("xpu-spirv", "Compile the Intel GPU kernels to SPIR-V and install them"); @@ -362,8 +373,12 @@ fn nemotronSteps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std. mod.addImport("lfm3_xpu", lfm3); tests_step.dependOn(&b.addInstallArtifact(b.addExecutable(.{ .name = b.fmt("tf-xpu-{s}-test", .{name}), .root_module = mod }), .{}).step); } + @import("xpu_qwen3_asr_contract.zig").program(b, target, optimize, xpu, mods.core, tests_step, cl); } +/// How the SPIR-V images are built: the compiler, its device and whether DPAS fallbacks are off. +pub const Ocloc = struct { ocloc: []const u8, device: []const u8, dpas: bool }; + /// Host unit tests of the Intel GPU runtime, the Nemotron family on it and its CLI (no GPU, no ocloc), on any host. pub fn hostTests(b: *std.Build, step: *std.Build.Step) void { const host = b.graph.host; diff --git a/zig/build/xpu_qwen3_asr_contract.zig b/zig/build/xpu_qwen3_asr_contract.zig new file mode 100644 index 00000000000..0867cd517e0 --- /dev/null +++ b/zig/build/xpu_qwen3_asr_contract.zig @@ -0,0 +1,48 @@ +//! tf-xpu-qwen3_asr_contract-test and its controls: each the binding's source with one edit (cl_edit.zig). +const std = @import("std"); +const xpu = @import("xpu.zig"); + +/// A control's image: `image`'s source and options with each edit applied once. +const Control = struct { name: []const u8, image: []const u8, edits: []const [2][]const u8 }; + +/// The names here are the test's `Mutation` tags: a missing image is a compile error there. +pub const controls = [_]Control{ + .{ .name = "gemm_no_residual", .image = "qwen3_asr", .edits = &.{.{ "if (has_res) t = bfr(t + bf(res[at]));", "if (has_res) t = bfr(t);" }} }, + .{ .name = "gemm_bf16_sums", .image = "qwen3_asr", .edits = &.{.{ "acc[i][j] += part[i][j];", "acc[i][j] = bfr(acc[i][j] + part[i][j]);" }} }, + .{ .name = "conv_taps_transposed", .image = "qwen3_asr", .edits = &.{.{ "kh = (kk % 9) / 3, kw = kk % 3;", "kw = (kk % 9) / 3, kh = kk % 3;" }} }, + .{ .name = "flatten_f_major", .image = "qwen3_asr", .edits = &.{.{ "ci = col / f, ff = col % f;", "ff = col / c, ci = col % c;" }} }, + .{ .name = "layernorm_no_bias", .image = "qwen3_asr", .edits = &.{.{ "* rs * bf(w[i]) + bf(b[i]));", "* rs * bf(w[i]));" }} }, + .{ .name = "gelu_is_silu", .image = "qwen3_asr", .edits = &.{.{ "if (i < total) y[i] = to_bf(gelu(bf(x[i])));", "if (i < total) y[i] = to_bf(bf(x[i]) / (1.0f + exp(-bf(x[i]))));" }} }, + .{ .name = "attn_causal", .image = "qwen3_asr", .edits = &.{.{ "s = a * scale;", "s = key <= row ? a * scale : -INFINITY;" }} }, + .{ .name = "rope_turns_back", .image = "qwen3_asr", .edits = &.{.{ "const float rot = dd < 64 ? -other : other;", "const float rot = dd < 64 ? other : -other;" }} }, + .{ .name = "rms_no_weight", .image = "lfm3_gq2", .edits = &.{.{ "to_bf(bf(w[lid + 256 * k]) * bfr(v[k] * rs));", "to_bf(bfr(v[k] * rs));" }} }, + .{ .name = "attn_reads_ahead", .image = "lfm3_gq2", .edits = &.{.{ "const uint hi = min(p + 1, lo + chunk);", "const uint hi = lo + chunk;" }} }, + .{ .name = "swiglu_swapped", .image = "lfm3_gq2", .edits = &.{ + .{ "const float x = bf(a[i]);", "const float x = bf(b[i]);" }, + .{ "out[i] = to_bf(bfr(x / (1.0f + exp(-x))) * bf(b[i]));", "out[i] = to_bf(bfr(x / (1.0f + exp(-x))) * bf(a[i]));" }, + } }, +}; + +/// The test program, in `xpu-tests`: the binding's images through `xpu`, the controls' images in their own module. +pub fn program(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, x: *std.Build.Module, core: *std.Build.Module, step: *std.Build.Step, cl: xpu.Ocloc) void { + const editor = b.addExecutable(.{ .name = "cl_edit", .root_module = b.createModule(.{ .root_source_file = b.path("zig/build/cl_edit.zig"), .target = b.graph.host, .optimize = .ReleaseSafe }) }); + const files = b.addWriteFiles(); + var decls: std.ArrayList(u8) = .empty; + for (controls) |ctl| { + const k = xpu.kernelNamed(ctl.image); + const edit = b.addRunArtifact(editor); + edit.addFileArg(b.path(b.fmt("zig/kernels/xpu/{s}.cl", .{k.src orelse k.name}))); + const src = edit.addOutputFileArg(b.fmt("{s}.cl", .{ctl.name})); + for (ctl.edits) |e| edit.addArgs(&e); + var named = k; + named.name = ctl.name; + _ = files.addCopyFile(xpu.spirvOf(b, cl.ocloc, cl.device, cl.dpas, named, src), b.fmt("{s}.spv", .{ctl.name})); + decls.print(b.allocator, "pub const {s} align(16) = @embedFile(\"{s}.spv\").*;\n", .{ ctl.name, ctl.name }) catch @panic("OOM"); + } + const images = b.createModule(.{ .root_source_file = files.add("qwen3_asr_contract_images.zig", decls.items), .target = target, .optimize = optimize }); + const mod = b.createModule(.{ .root_source_file = b.path("zig/tests/xpu/qwen3_asr_contract.zig"), .target = target, .optimize = optimize, .link_libc = true }); + mod.addImport("xpu", x); + mod.addImport("core", core); + mod.addImport("qwen3_asr_contract_images", images); + step.dependOn(&b.addInstallArtifact(b.addExecutable(.{ .name = "tf-xpu-qwen3_asr_contract-test", .root_module = mod }), .{}).step); +} diff --git a/zig/src/core/contract.zig b/zig/src/core/contract.zig index 8f6d85d8ba1..16e925e889d 100644 --- a/zig/src/core/contract.zig +++ b/zig/src/core/contract.zig @@ -20,6 +20,7 @@ pub const hip_records = @import("contract/hip_records.zig"); pub const vulkan_records = @import("contract/vulkan_records.zig"); pub const xpu_limits = @import("contract/xpu_limits.zig"); pub const xpu_records = @import("contract/xpu_records.zig"); +pub const qwen3_asr_xpu_records = @import("contract/qwen3_asr_xpu_records.zig"); pub const xpu_ref = @import("contract/xpu_ref.zig"); pub const zebin = @import("contract/zebin.zig"); pub const zeinfo = @import("contract/zeinfo.zig"); @@ -28,6 +29,7 @@ test { } test { _ = xpu_records; + _ = qwen3_asr_xpu_records; } test { _ = xpu_ref; diff --git a/zig/src/core/contract/qwen3_asr_xpu_records.zig b/zig/src/core/contract/qwen3_asr_xpu_records.zig new file mode 100644 index 00000000000..a6fa46c97a4 --- /dev/null +++ b/zig/src/core/contract/qwen3_asr_xpu_records.zig @@ -0,0 +1,83 @@ +//! Qwen3-ASR's Gen12LP launches (qwen3_asr.cl, lfm3.cl at GQ 2) and what the driver builds of their SPIR-V. +const std = @import("std"); +const limits = @import("xpu_limits.zig"); + +const X = limits.XpuLaunch; +const U = limits.XpuUsage; + +/// A launch as the binding sets it, what the driver reports for it, and its kernel's argument count. +pub const Record = struct { launch: X, usage: U, args: u32 }; + +const spv = limits.Format.spirv; + +fn rec(name: []const u8, symbol: []const u8, image: []const u8, threads: [3]u32, slm: u32, args: u32) Record { + return built(name, symbol, image, threads, slm, args, 16, 0); +} + +/// A kernel the driver builds at its own SIMD width (no required sub-group), with the spill it reports. +fn built(name: []const u8, symbol: []const u8, image: []const u8, threads: [3]u32, slm: u32, args: u32, sub_group: u32, spill: u32) Record { + return .{ + .launch = .{ .name = name, .symbol = symbol, .image = image, .format = spv, .threads = threads, .slm = slm, .sub_group = sub_group, .grf = 128 }, + .usage = .{ .threads = threads, .slm = slm, .sub_group = sub_group, .grf = 128, .spill = spill }, + .args = args, + }; +} + +/// Every launch tf-qwen3-asr-xpu makes of these images (glue's add_bf16 is Nemotron's, outside this family). +pub const records = [_]Record{ + // the 64 x 64 tile builds at SIMD 8; the Linear's spills 1,024 bytes, the conv's none (Iris Xe's driver) + built("qwen3-asr asr_gemm", "asr_gemm", "qwen3_asr", .{ 16, 16, 1 }, 8192, 12, 8, 1024), + built("qwen3-asr asr_conv", "asr_conv", "qwen3_asr", .{ 16, 16, 1 }, 8192, 10, 8, 0), + rec("qwen3-asr asr_flatten", "asr_flatten", "qwen3_asr", .{ 256, 1, 1 }, 0, 6), + rec("qwen3-asr asr_layernorm", "asr_layernorm", "qwen3_asr", .{ 256, 1, 1 }, 64, 6), + rec("qwen3-asr asr_gelu", "asr_gelu", "qwen3_asr", .{ 256, 1, 1 }, 0, 3), + rec("qwen3-asr asr_attn_full", "asr_attn_full", "qwen3_asr", .{ 16, 1, 1 }, 0, 5), + rec("qwen3-asr asr_qk_rope", "asr_qk_rope", "qwen3_asr", .{ 16, 1, 1 }, 0, 14), + rec("qwen3-asr lfm3_gq2 lfm3_rmsnorm", "lfm3_rmsnorm", "lfm3_gq2", .{ 256, 1, 1 }, 64, 5), + rec("qwen3-asr lfm3_gq2 lfm3_attn_partial", "lfm3_attn_partial", "lfm3_gq2", .{ 32, 1, 1 }, 0, 13), + rec("qwen3-asr lfm3_gq2 lfm3_attn_merge_gate", "lfm3_attn_merge_gate", "lfm3_gq2", .{ 16, 1, 1 }, 0, 10), + rec("qwen3-asr lfm3_gq2 lfm3_swiglu", "lfm3_swiglu", "lfm3_gq2", .{ 64, 1, 1 }, 0, 4), +}; + +/// Gate 5's planted control: the norm at 1,024 work-items, twice what a Gen12LP work-group holds. +pub const control: Record = blk: { + var r = rec("control: qwen3-asr asr_layernorm at 1024 work-items", "asr_layernorm", "qwen3_asr", .{ 1024, 1, 1 }, 64, 6); + r.usage.threads = .{ 256, 1, 1 }; + break :blk r; +}; + +/// Every problem the records have against the Gen12LP row from their declarations alone; returns how many. +pub fn check(a: std.mem.Allocator, out: *std.ArrayList(u8)) !usize { + var n: usize = 0; + for (records) |r| n += try limits.fits(r.launch, limits.gen12lp, out, a); + return n; +} + +test "every Qwen3-ASR XPU launch fits Gen12LP, and the planted control does not" { + const a = std.testing.allocator; + var out: std.ArrayList(u8) = .empty; + defer out.deinit(a); + try std.testing.expectEqual(@as(usize, 0), try check(a, &out)); + try std.testing.expect(try limits.fits(control.launch, limits.gen12lp, &out, a) > 0); + // the control is only red for its work-group: at the norm's own 256 it fits + var legal = control.launch; + legal.threads = .{ 256, 1, 1 }; + try std.testing.expectEqual(@as(usize, 0), try limits.fits(legal, limits.gen12lp, &out, a)); +} + +test "Gen12LP has no 256-GRF mode, and a work-group of 512 fits at sub-group 16" { + const a = std.testing.allocator; + var out: std.ArrayList(u8) = .empty; + defer out.deinit(a); + const t = limits.gen12lp; + var l = records[2].launch; + l.grf = 256; + try std.testing.expectEqual(@as(usize, 1), try limits.fits(l, t, &out, a)); + l = records[2].launch; + l.threads = .{ 512, 1, 1 }; + try std.testing.expectEqual(@as(usize, 0), try limits.fits(l, t, &out, a)); + // at SIMD 8 a subslice holds 8 EUs x 7 threads x 8 lanes = 448 work-items: 512 does not fit + l.sub_group = 8; + try std.testing.expectEqual(@as(usize, 1), try limits.fits(l, t, &out, a)); + try std.testing.expectEqual(@as(u64, 96), @as(u64, t.eus_xe_core) * t.xe_cores); +} diff --git a/zig/src/core/contract/xpu_limits.zig b/zig/src/core/contract/xpu_limits.zig index a32e63171b3..423022b4a80 100644 --- a/zig/src/core/contract/xpu_limits.zig +++ b/zig/src/core/contract/xpu_limits.zig @@ -28,6 +28,22 @@ pub const xe = [_]Xe{ .{ .name = "bmg-g31", .ocloc_device = "bmg", .pci = 0xe223 }, }; +/// Gen12LP (Iris Xe, 12 subslices of 8 EUs, 128 GRF only), outside `xe`: only Qwen3-ASR's SPIR-V images serve it. +pub const gen12lp: Xe = .{ + .name = "tgllp", + .ocloc_device = "tgllp", + .pci = 0x9a49, + .max_threads = 512, + .max_dims = .{ 512, 512, 512 }, + .slm_workgroup = 65536, + .slm_xe_core = 65536, + .sub_groups = &.{ 8, 16, 32 }, + .eus_xe_core = 8, + .threads_eu = 7, + .xe_cores = 12, + .grf_modes = &.{128}, +}; + /// The image kind the launcher loads: a native zebin (format 1), or SPIR-V IL the driver builds (format 0). pub const Format = enum { native, spirv }; diff --git a/zig/tests/xpu/contract_guarded.zig b/zig/tests/xpu/contract_guarded.zig new file mode 100644 index 00000000000..b126c7ca3b1 --- /dev/null +++ b/zig/tests/xpu/contract_guarded.zig @@ -0,0 +1,134 @@ +//! The XPU contract's guarded buffers: inputs, outputs and scratch on one stream, poisoned outputs, intact guards. +const std = @import("std"); +const xpu = @import("xpu"); + +pub const guard = 256; +const pattern = 0xa5; + +const Kind = enum { input, output, scratch }; +const Slot = struct { buf: xpu.DeviceBuffer, len: usize, kind: Kind }; + +/// One call's buffers on `Dev`'s stream (its `ctx` and `s`): each payload its own allocation, guarded both sides. +pub fn Rig(comptime Dev: type) type { + return struct { + const Self = @This(); + + a: std.mem.Allocator, + dev: *Dev, + slots: std.ArrayList(Slot) = .empty, + seen: std.ArrayList(u8) = .empty, + outs: std.ArrayList(u8) = .empty, + host: std.ArrayList(u8) = .empty, + + pub fn deinit(r: *Self) void { + r.reset(); + r.slots.deinit(r.a); + r.seen.deinit(r.a); + r.outs.deinit(r.a); + r.host.deinit(r.a); + } + + pub fn reset(r: *Self) void { + r.dev.s.synchronize() catch {}; + for (r.slots.items) |*s| s.buf.free(); + r.slots.clearRetainingCapacity(); + } + + fn slot(r: *Self, data: ?[]const u8, len: usize, fill: u8, kind: Kind) !?*anyopaque { + const all = try r.a.alloc(u8, len + 2 * guard); + defer r.a.free(all); + @memset(all, pattern); + if (data) |d| @memcpy(all[guard..][0..len], d) else @memset(all[guard..][0..len], fill); + var buf = try xpu.DeviceBuffer.alloc(&r.dev.ctx, all.len); + errdefer buf.free(); + try buf.upload(r.dev.s, 0, all); + try r.slots.append(r.a, .{ .buf = buf, .len = len, .kind = kind }); + return try buf.at(guard); + } + + pub fn input(r: *Self, data: []const u8) !?*anyopaque { + return r.slot(data, data.len, 0, .input); + } + + /// An output of `len` bytes, all 0xff: an element no launch writes reads as NaN. + pub fn output(r: *Self, len: usize) !?*anyopaque { + return r.slot(null, len, 0xff, .output); + } + + /// Working memory between a call's launches: neither an input nor an output. + pub fn scratch(r: *Self, len: usize) !?*anyopaque { + return r.slot(null, len, 0, .scratch); + } + + fn find(r: *Self, p: ?*anyopaque) !struct { xpu.DeviceBuffer, usize } { + const at = @intFromPtr(p); + for (r.slots.items) |s| { + const base = @intFromPtr(s.buf.ptr); + if (at >= base and at < base + s.buf.len) return .{ s.buf, at - base }; + } + return error.Invalid; + } + + /// `len` bytes at a device address of this rig's, downloaded after the stream drains. + pub fn bytes(r: *Self, p: ?*anyopaque, len: usize) ![]u8 { + try r.dev.s.synchronize(); + try r.host.resize(r.a, len); + const b, const off = try r.find(p); + try b.download(r.dev.s, off, r.host.items); + return r.host.items; + } + + /// Writes `data` at a device address of this rig's (a run restoring a state it updates in place). + pub fn put(r: *Self, p: ?*anyopaque, data: []const u8) !void { + try r.dev.s.synchronize(); + const b, const off = try r.find(p); + try b.upload(r.dev.s, off, data); + } + + /// Sets the arguments in order and queues the kernel; the call is waited for. + pub fn launch(r: *Self, k: xpu.Kernel, groups: [3]u32, args: anytype) !void { + try xpu.launch.dispatch(k, r.dev.s, groups, args); + try r.dev.s.synchronize(); + } + + fn gather(r: *Self, kind: Kind, out: *std.ArrayList(u8), whole: bool) ![]const u8 { + try r.dev.s.synchronize(); + out.clearRetainingCapacity(); + for (r.slots.items) |s| if (s.kind == kind or whole) { + const at = out.items.len; + const n = if (whole) s.len + 2 * guard else s.len; + try out.resize(r.a, at + n); + try s.buf.download(r.dev.s, if (whole) 0 else guard, out.items[at..][0..n]); + }; + return out.items; + } + + pub fn outputBytes(r: *Self) ![]const u8 { + return r.gather(.output, &r.outs, false); + } + + pub fn inputBytes(r: *Self) ![]const u8 { + return r.gather(.input, &r.seen, false); + } + + /// Every guard of every buffer still holds its pattern. + pub fn intact(r: *Self) !bool { + const all = try r.gather(.input, &r.seen, true); + var at: usize = 0; + for (r.slots.items) |s| { + for (all[at..][0..guard]) |v| if (v != pattern) return false; + for (all[at + guard + s.len ..][0..guard]) |v| if (v != pattern) return false; + at += s.len + 2 * guard; + } + return true; + } + + /// Each payload is its own allocation, so an overlap means one buffer bound as both input and output. + pub fn overlap(r: *Self) bool { + for (r.slots.items, 0..) |s, i| for (r.slots.items[i + 1 ..]) |t| { + if (s.buf.ptr == t.buf.ptr and s.kind != t.kind) return true; + }; + return false; + } + }; +} diff --git a/zig/tests/xpu/contract_rig.zig b/zig/tests/xpu/contract_rig.zig index c1174cd0a42..5df35f4a6fa 100644 --- a/zig/tests/xpu/contract_rig.zig +++ b/zig/tests/xpu/contract_rig.zig @@ -5,8 +5,9 @@ const ze = @import("ze"); const core = @import("core"); const images = @import("xpu_contract_images"); -pub const guard = 256; -const pattern = 0xa5; +const guarded = @import("contract_guarded.zig"); + +pub const guard = guarded.guard; /// The image a kernel lives in: the Qwen3.8-27B glue, TP collectives, gate 5's controls, or gates 1 to 4's. pub const Image = enum { glue, tp, decode, attn_upstream, merge_upstream, controls, gate }; @@ -112,126 +113,5 @@ pub fn recordOf(symbol: []const u8) ?core.xpu_records.Record { return null; } -const Kind = enum { input, output, scratch }; -const Slot = struct { buf: xpu.DeviceBuffer, len: usize, kind: Kind }; - -/// One call's device buffers on one stream: each payload its own allocation, guarded on both sides. -pub const Rig = struct { - a: std.mem.Allocator, - dev: *Dev, - slots: std.ArrayList(Slot) = .empty, - seen: std.ArrayList(u8) = .empty, - outs: std.ArrayList(u8) = .empty, - host: std.ArrayList(u8) = .empty, - - pub fn deinit(r: *Rig) void { - r.reset(); - r.slots.deinit(r.a); - r.seen.deinit(r.a); - r.outs.deinit(r.a); - r.host.deinit(r.a); - } - - pub fn reset(r: *Rig) void { - r.dev.s.synchronize() catch {}; - for (r.slots.items) |*s| s.buf.free(); - r.slots.clearRetainingCapacity(); - } - - fn slot(r: *Rig, data: ?[]const u8, len: usize, fill: u8, kind: Kind) !?*anyopaque { - const all = try r.a.alloc(u8, len + 2 * guard); - defer r.a.free(all); - @memset(all, pattern); - if (data) |d| @memcpy(all[guard..][0..len], d) else @memset(all[guard..][0..len], fill); - var buf = try xpu.DeviceBuffer.alloc(&r.dev.ctx, all.len); - errdefer buf.free(); - try buf.upload(r.dev.s, 0, all); - try r.slots.append(r.a, .{ .buf = buf, .len = len, .kind = kind }); - return try buf.at(guard); - } - - pub fn input(r: *Rig, data: []const u8) !?*anyopaque { - return r.slot(data, data.len, 0, .input); - } - - /// An output of `len` bytes, all 0xff: an element no launch writes reads as NaN. - pub fn output(r: *Rig, len: usize) !?*anyopaque { - return r.slot(null, len, 0xff, .output); - } - - /// Working memory between a call's launches: neither an input nor an output. - pub fn scratch(r: *Rig, len: usize) !?*anyopaque { - return r.slot(null, len, 0, .scratch); - } - - fn find(r: *Rig, p: ?*anyopaque) !struct { xpu.DeviceBuffer, usize } { - const at = @intFromPtr(p); - for (r.slots.items) |s| { - const base = @intFromPtr(s.buf.ptr); - if (at >= base and at < base + s.buf.len) return .{ s.buf, at - base }; - } - return error.Invalid; - } - - /// `len` bytes at a device address of this rig's, downloaded after the stream drains. - pub fn bytes(r: *Rig, p: ?*anyopaque, len: usize) ![]u8 { - try r.dev.s.synchronize(); - try r.host.resize(r.a, len); - const b, const off = try r.find(p); - try b.download(r.dev.s, off, r.host.items); - return r.host.items; - } - - /// Writes `data` at a device address of this rig's (a run restoring a state it updates in place). - pub fn put(r: *Rig, p: ?*anyopaque, data: []const u8) !void { - try r.dev.s.synchronize(); - const b, const off = try r.find(p); - try b.upload(r.dev.s, off, data); - } - - /// Sets the arguments in order and queues the kernel; the call is waited for. - pub fn launch(r: *Rig, k: xpu.Kernel, groups: [3]u32, args: anytype) !void { - try xpu.launch.dispatch(k, r.dev.s, groups, args); - try r.dev.s.synchronize(); - } - - fn gather(r: *Rig, kind: Kind, out: *std.ArrayList(u8), whole: bool) ![]const u8 { - try r.dev.s.synchronize(); - out.clearRetainingCapacity(); - for (r.slots.items) |s| if (s.kind == kind or whole) { - const at = out.items.len; - const n = if (whole) s.len + 2 * guard else s.len; - try out.resize(r.a, at + n); - try s.buf.download(r.dev.s, if (whole) 0 else guard, out.items[at..][0..n]); - }; - return out.items; - } - - pub fn outputBytes(r: *Rig) ![]const u8 { - return r.gather(.output, &r.outs, false); - } - - pub fn inputBytes(r: *Rig) ![]const u8 { - return r.gather(.input, &r.seen, false); - } - - /// Every guard of every buffer still holds its pattern. - pub fn intact(r: *Rig) !bool { - const all = try r.gather(.input, &r.seen, true); - var at: usize = 0; - for (r.slots.items) |s| { - for (all[at..][0..guard]) |v| if (v != pattern) return false; - for (all[at + guard + s.len ..][0..guard]) |v| if (v != pattern) return false; - at += s.len + 2 * guard; - } - return true; - } - - /// Each payload is its own allocation, so an overlap means one buffer bound as both input and output. - pub fn overlap(r: *Rig) bool { - for (r.slots.items, 0..) |s, i| for (r.slots.items[i + 1 ..]) |t| { - if (s.buf.ptr == t.buf.ptr and s.kind != t.kind) return true; - }; - return false; - } -}; +/// One call's device buffers on the contract's card. +pub const Rig = guarded.Rig(Dev); diff --git a/zig/tests/xpu/qwen3_asr_contract.zig b/zig/tests/xpu/qwen3_asr_contract.zig new file mode 100644 index 00000000000..598a4213a8d --- /dev/null +++ b/zig/tests/xpu/qwen3_asr_contract.zig @@ -0,0 +1,170 @@ +//! tf-xpu-qwen3_asr_contract-test [--device N] [--only TEXT]: gates 1 to 4, each control red, gate 5 live. +const std = @import("std"); +const core = @import("core"); +const kit = @import("qwen3_asr_contract_kit.zig"); +const tower = @import("qwen3_asr_contract_tower.zig"); +const row_k = @import("qwen3_asr_contract_rows.zig"); +const lm = @import("qwen3_asr_contract_lm.zig"); + +const g = core.contract.gates; +const limits = core.contract.xpu_limits; +const records = core.contract.qwen3_asr_xpu_records; +const Mutation = kit.Mutation; + +fn ms(io: std.Io) i96 { + return @divTrunc(std.Io.Clock.awake.now(io).toNanoseconds(), std.time.ns_per_ms); +} + +/// Every test on the heap (the gates hold pointers to them): each kernel, then its control. +const Suite = struct { + a: std.mem.Allocator, + frees: std.ArrayList(Free) = .empty, + + const Free = struct { ctx: *anyopaque, f: *const fn (std.mem.Allocator, *anyopaque) void }; + + fn add(s: *Suite, comptime T: type, out: *std.ArrayList(g.Kernel), only: ?[]const u8, value: T) !void { + const x = try s.a.create(T); + x.* = value; + try s.keep(T, x, out, only); + } + + fn keep(s: *Suite, comptime T: type, x: *T, out: *std.ArrayList(g.Kernel), only: ?[]const u8) !void { + try s.frees.append(s.a, .{ .ctx = x, .f = struct { + fn f(a: std.mem.Allocator, p: *anyopaque) void { + const t: *T = @ptrCast(@alignCast(p)); + t.deinit(); + a.destroy(t); + } + }.f }); + const k = x.kernel(); + if (only == null or std.mem.indexOf(u8, k.spec.name, only.?) != null) try out.append(s.a, k); + } + + fn deinit(s: *Suite) void { + for (s.frees.items) |e| e.f(s.a, e.ctx); + s.frees.deinit(s.a); + } +}; + +fn collect(s: *Suite, dev: *kit.Dev, out: *std.ArrayList(g.Kernel), only: ?[]const u8) !void { + const a = s.a; + for ([_]struct { tower.Epi, Mutation }{ .{ .plain, .gemm_bf16_sums }, .{ .bias_res, .gemm_no_residual }, .{ .bias_gelu, .none } }) |p| { + try s.add(tower.Gemm, out, only, try tower.Gemm.init(a, dev, .none, p[0])); + if (p[1] != .none) try s.add(tower.Gemm, out, only, try tower.Gemm.init(a, dev, p[1], p[0])); + } + for ([_]Mutation{ .none, .conv_taps_transposed }) |m| try s.add(tower.Conv, out, only, try tower.Conv.init(a, dev, m)); + for ([_]Mutation{ .none, .flatten_f_major }) |m| try s.add(tower.Flatten, out, only, try tower.Flatten.init(a, dev, m)); + for ([_]Mutation{ .none, .attn_causal }) |m| try s.add(tower.AttnFull, out, only, try tower.AttnFull.init(a, dev, m)); + for ([_]struct { row_k.Which, Mutation }{ .{ .layernorm, .layernorm_no_bias }, .{ .gelu, .gelu_is_silu }, .{ .rms, .rms_no_weight } }) |p| { + for ([_]Mutation{ .none, p[1] }) |m| try s.add(row_k.Row, out, only, try row_k.Row.init(a, dev, m, p[0])); + } + for ([_]Mutation{ .none, .swiglu_swapped }) |m| try s.add(row_k.Swiglu, out, only, try row_k.Swiglu.init(a, dev, m)); + for ([_]Mutation{ .none, .rope_turns_back }) |m| try s.add(lm.QkRope, out, only, try lm.QkRope.init(a, dev, m, .rows)); + const cache = try a.create(lm.QkCache); + cache.init(a, dev, .none) catch |e| { + a.destroy(cache); + return e; + }; + try s.keep(lm.QkCache, cache, out, only); + for ([_]Mutation{ .none, .attn_reads_ahead }) |m| try s.add(lm.Attn, out, only, try lm.Attn.init(a, dev, m)); +} + +/// Gate 5 on this card: its properties against the Gen12LP row, each loaded kernel against its record, the control red. +fn live(a: std.mem.Allocator, dev: *kit.Dev) !usize { + var n: usize = 0; + const t = limits.gen12lp; + const p = dev.ctx.gpu.props; + var out: std.ArrayList(u8) = .empty; + defer out.deinit(a); + const device = limits.Device{ .deviceId = p.deviceId, .numEUsPerSubslice = p.numEUsPerSubslice, .numThreadsPerEU = p.numThreadsPerEU, .physicalEUSimdWidth = p.physicalEUSimdWidth, .numSlices = p.numSlices, .numSubslicesPerSlice = p.numSubslicesPerSlice }; + const row = try limits.liveRow(device, t, &out, a); + n += row; + std.debug.print("{s} limits live {s}: PCI id 0x{x}, {d} EUs a subslice, {d} threads an EU, SIMD {d}, {d} slices x {d} subslices{s}", .{ + if (row == 0) "PASS" else "FAIL", t.name, device.deviceId, device.numEUsPerSubslice, device.numThreadsPerEU, device.physicalEUSimdWidth, device.numSlices, device.numSubslicesPerSlice, if (out.items.len > 0) ": " else "\n", + }); + if (out.items.len > 0) std.debug.print("{s}", .{out.items}); + for (records.records) |rec| { + out.clearRetainingCapacity(); + const img: kit.Image = if (std.mem.eql(u8, rec.launch.image, "qwen3_asr")) .qwen3_asr else .lfm3_gq2; + const sym = try a.allocSentinel(u8, rec.launch.symbol.len, 0); + defer a.free(sym); + @memcpy(sym, rec.launch.symbol); + var k = try (try dev.module(img, .none)).kernelAt(sym); + defer k.deinit(); + var props: KernelProps = .{}; + try dev.ctx.d.check(dev.ctx.d.api.zeKernelGetProperties(k.handle, &props), "zeKernelGetProperties"); + const u = rec.usage; + const loaded = limits.Loaded{ + .threads = if (props.requiredGroupSize[0] == 0) u.threads else props.requiredGroupSize, + .sub_group = if (props.requiredSubgroupSize == 0) u.sub_group else props.requiredSubgroupSize, + .max_sub_group = if (props.maxSubgroupSize == 0) u.sub_group else props.maxSubgroupSize, + .slm = props.localMemSize, + .spill = props.spillMemSize, + .args = props.numKernelArgs, + }; + const problems = try limits.liveKernel(rec.launch, u, loaded, rec.args, t, &out, a); + const fits = try limits.fits(rec.launch, t, &out, a); + n += problems + fits; + const items = @as(u64, loaded.threads[0]) * loaded.threads[1] * loaded.threads[2]; + std.debug.print("{s} limits live {s}: {d} work-items (required {d}), sub-group {d} (required {d}, the kernel's most {d}), {d} SLM bytes, " ++ + "{d} spill bytes, {d} private bytes, {d} arguments{s}", .{ + if (problems + fits != 0) "FAIL" else "PASS", rec.launch.name, items, props.requiredGroupSize[0] * @max(props.requiredGroupSize[1], 1) * @max(props.requiredGroupSize[2], 1), + loaded.sub_group, props.requiredSubgroupSize, props.maxSubgroupSize, loaded.slm, + loaded.spill, props.privateMemSize, loaded.args, if (out.items.len > 0) ": " else "\n", + }); + if (out.items.len > 0) std.debug.print("{s}", .{out.items}); + } + out.clearRetainingCapacity(); + const red = try limits.fits(records.control.launch, t, &out, a); + if (red == 0) n += 1; + std.debug.print("{s} limits live {s}: declared only{s}", .{ if (red != 0) "RED " else "MISSED", records.control.launch.name, if (out.items.len > 0) ": " else "\n" }); + if (out.items.len > 0) std.debug.print("{s}", .{out.items}); + return n; +} + +const KernelProps = @import("xpu").ze.KernelProperties; + +pub fn main(init: std.process.Init) !u8 { + const a = init.gpa; + const args = try init.minimal.args.toSlice(init.arena.allocator()); + const usage = "usage: tf-xpu-qwen3_asr_contract-test [--device N] [--only TEXT]\n"; + var ordinal: ?u32 = null; + var only: ?[]const u8 = null; + var i: usize = 1; + while (i < args.len) : (i += 2) { + if (i + 1 >= args.len) { + std.debug.print(usage, .{}); + return 2; + } + if (std.mem.eql(u8, args[i], "--device")) { + ordinal = std.fmt.parseInt(u32, args[i + 1], 10) catch { + std.debug.print(usage, .{}); + return 2; + }; + } else if (std.mem.eql(u8, args[i], "--only")) only = args[i + 1] else { + std.debug.print(usage, .{}); + return 2; + } + } + var dev: kit.Dev = undefined; + dev.init(ordinal) catch |e| { + std.debug.print("FAIL qwen3_asr_contract: no card opened ({t})\n", .{e}); + return 1; + }; + defer dev.deinit(); + var suite: Suite = .{ .a = a }; + defer suite.deinit(); + var kernels: std.ArrayList(g.Kernel) = .empty; + defer kernels.deinit(a); + try collect(&suite, &dev, &kernels, only); + var t: g.Tally = .{}; + const t0 = ms(init.io); + try g.runAll(a, kernels.items, 0x2105, &t); + const t1 = ms(init.io); + const lim = if (only == null) try live(a, &dev) else 0; + const t2 = ms(init.io); + const tally = .{ t.kernels, t.passed, t.failed, t.known, t.controls, t.caught, t.missed, lim, t1 - t0, t2 - t1 }; + std.debug.print("SUMMARY {s} 0x{x} {d} kernels: {d} pass gates 1-4, {d} fail, {d} known findings; {d} controls: " ++ + "{d} red as planted, {d} missed; {d} limit problems; gates {d} ms, limits {d} ms\n", .{ limits.gen12lp.name, dev.ctx.gpu.props.deviceId } ++ tally); + return @intCast(@min(t.problems() + lim, 255)); +} diff --git a/zig/tests/xpu/qwen3_asr_contract_kit.zig b/zig/tests/xpu/qwen3_asr_contract_kit.zig new file mode 100644 index 00000000000..a1db2802fcd --- /dev/null +++ b/zig/tests/xpu/qwen3_asr_contract_kit.zig @@ -0,0 +1,203 @@ +//! What Qwen3-ASR's XPU contract tests share: the card, its images and each control's, buffers, bf16 values. +const std = @import("std"); +const xpu = @import("xpu"); +const core = @import("core"); +const images = @import("qwen3_asr_contract_images"); +const guarded = @import("contract_guarded.zig"); + +const contract = core.contract; +const c = contract.spec; +const g = contract.gates; +const records = contract.qwen3_asr_xpu_records; + +/// The binding's image a kernel lives in. +pub const Image = enum { qwen3_asr, lfm3_gq2 }; + +/// The image a test builds: the binding's, or a control's (an edit of the same source, xpu_qwen3_asr_contract.zig). +pub const Mutation = enum { + none, + gemm_no_residual, + gemm_bf16_sums, + conv_taps_transposed, + flatten_f_major, + layernorm_no_bias, + gelu_is_silu, + attn_causal, + rope_turns_back, + rms_no_weight, + attn_reads_ahead, + swiglu_swapped, + + pub fn name(m: Mutation) []const u8 { + return switch (m) { + .none => "", + .gemm_no_residual => "control: xpu qwen3-asr asr_gemm, the residual is not added", + .gemm_bf16_sums => "control: xpu qwen3-asr asr_gemm, each 16-k step added in bf16", + .conv_taps_transposed => "control: xpu qwen3-asr asr_conv, kh and kw swapped", + .flatten_f_major => "control: xpu qwen3-asr asr_flatten, rows written f-major", + .layernorm_no_bias => "control: xpu qwen3-asr asr_layernorm, the bias is dropped", + .gelu_is_silu => "control: xpu qwen3-asr asr_gelu, SiLU in place of GELU", + .attn_causal => "control: xpu qwen3-asr asr_attn_full, a causal mask", + .rope_turns_back => "control: xpu qwen3-asr asr_qk_rope, the rotation turns the other way", + .rms_no_weight => "control: xpu qwen3-asr lfm3_gq2 lfm3_rmsnorm, the weight is dropped", + .attn_reads_ahead => "control: xpu qwen3-asr lfm3_gq2 lfm3_attn_partial, keys past the row's position", + .swiglu_swapped => "control: xpu qwen3-asr lfm3_gq2 lfm3_swiglu, gate and up swapped", + }; + } + + /// The gate a control must fail. + pub fn gate(m: Mutation) c.Gate { + return if (m == .gemm_bf16_sums) .sums else .shapes; + } +}; + +fn blob(m: Mutation) []const u8 { + return switch (m) { + .none => unreachable, + inline else => |t| &@field(images, @tagName(t)), + }; +} + +/// One card, its context and stream, the binding's two images and each control's, built from SPIR-V by the driver. +pub const Dev = struct { + drv: xpu.Driver, + ctx: xpu.Context, + s: xpu.Stream, + asr: xpu.Module, + lf: xpu.Module, + controls: [std.enums.values(Mutation).len]?xpu.Module = @splat(null), + + /// Opens the card `ordinal` names (else the first), loads the binding's images; `self` stays where it is. + pub fn init(self: *Dev, ordinal: ?u32) !void { + if (!xpu.kernels.available) return error.BuiltWithoutKernels; + self.drv = try xpu.Driver.open(); + self.ctx = try xpu.Context.init(&self.drv, ordinal); + self.s = try xpu.Stream.init(&self.ctx); + self.asr = try xpu.Module.load(&self.ctx, xpu.kernels.qwen3_asr); + self.lf = try xpu.Module.load(&self.ctx, xpu.kernels.lfm3_gq2); + self.controls = @splat(null); + } + + pub fn deinit(self: *Dev) void { + for (&self.controls) |*m| if (m.*) |*x| x.unload(); + self.lf.unload(); + self.asr.unload(); + self.s.deinit(); + self.ctx.deinit(); + self.drv.close(); + } + + /// The image `m` builds for `img`: the binding's for none, else the control's (loaded once). + pub fn module(self: *Dev, img: Image, m: Mutation) !*xpu.Module { + if (m == .none) return if (img == .qwen3_asr) &self.asr else &self.lf; + const slot = &self.controls[@backingInt(m)]; + if (slot.* == null) slot.* = try xpu.Module.load(&self.ctx, blob(m)); + return &slot.*.?; + } + + /// `symbol` at the work-group its record holds, from the binding's image or the control's. + pub fn kernel(self: *Dev, img: Image, m: Mutation, symbol: [:0]const u8) !xpu.Kernel { + const rec = recordOf(symbol) orelse return error.NoRecord; + return (try self.module(img, m)).kernel(symbol, rec.launch.threads); + } +}; + +pub const Rig = guarded.Rig(Dev); + +pub fn recordOf(symbol: []const u8) ?records.Record { + for (records.records) |r| if (std.mem.eql(u8, r.launch.symbol, symbol)) return r; + return null; +} + +/// A test's kernel under its control's name and gate. +pub fn mark(k: g.Kernel, m: Mutation) g.Kernel { + var out = k; + if (m != .none) { + out.spec.name = m.name(); + out.control = m.gate(); + } + return out; +} + +pub fn noSums(_: c.Shape) usize { + return 0; +} + +pub fn u(x: usize) u32 { + return @intCast(x); +} + +/// A value rounded to bf16 (to nearest even), as the kernels' to_bf. +pub fn bf(v: f64) f64 { + return c.fromBf16(c.toBf16(@floatCast(v))); +} + +pub fn val(bits: u16) f64 { + return c.fromBf16(bits); +} + +pub const planted = [_]f32{ std.math.nan(f32), std.math.inf(f32), -std.math.inf(f32) }; + +/// Random bf16 values in (-s, s). +pub fn fill(rng: std.Random, out: []u16, s: f32) void { + for (out) |*v| v.* = c.toBf16((rng.float(f32) * 2 - 1) * s); +} + +/// NaN, +Inf and -Inf at three spread places of `x` (and both infinities once more when it is long enough). +pub fn plant(x: []u16) void { + for (planted, 0..) |v, i| x[(x.len / 3 * i + 1) % x.len] = c.toBf16(v); + if (x.len > 8) x[x.len - 2] = c.toBf16(planted[1]); +} + +/// fp32's unit roundoff. +pub const u32r = 0x1p-24; +/// bf16's: half an ulp at 1. +pub const ubf = 0x1p-8; +/// The least step a bf16 output takes near zero. +pub const floor_bf = 0x1p-133; + +/// One query row's attention over `keys` rows into `out` (max subtracted); `allow`: its error bound, as derived. +pub fn attention(a: std.mem.Allocator, q: []const f64, keys: usize, kv: anytype, scale: f64, chunks: usize, out: []f64, allow: ?[]f64) !void { + const d = q.len; + const s = try a.alloc(f64, keys); + defer a.free(s); + const ds = try a.alloc(f64, keys); + defer a.free(ds); + var mx: f64 = -std.math.inf(f64); + for (0..keys) |j| { + var dot: f64 = 0; + var abs: f64 = 0; + for (0..d) |e| { + const t = q[e] * kv.k(j, e); + dot += t; + abs += @abs(t); + } + s[j] = dot * scale; + ds[j] = c.gamma(@floatFromInt(d + 2), u32r) * abs * scale; + if (std.math.isNan(s[j]) or s[j] > mx) mx = s[j]; + } + var l: f64 = 0; + for (s) |*x| { + x.* = @exp(x.* - mx); + l += x.*; + } + var worst: f64 = 0; + for (ds) |e| worst = @max(worst, e); + // each weight's relative error: its score's and the max's dot errors, exp, the rescales (a key a step) and merges + const rel_w = 2 * worst + @as(f64, @floatFromInt(2 * keys + 4 * chunks + 8)) * u32r; + for (0..d) |e| { + var acc: f64 = 0; + for (0..keys) |j| acc += s[j] * kv.v(j, e); + out[e] = acc / l; + if (allow) |al| { + var spread: f64 = 0; + var mag: f64 = 0; + for (0..keys) |j| { + spread += s[j] * @abs(kv.v(j, e) - out[e]); + mag += s[j] * @abs(kv.v(j, e)); + } + const work = rel_w * spread / l + c.gamma(@floatFromInt(keys + chunks + 4), u32r) * mag / l + 4 * u32r * @abs(out[e]); + al[e] = work + ubf * (@abs(out[e]) + work) + floor_bf; + } + } +} diff --git a/zig/tests/xpu/qwen3_asr_contract_lm.zig b/zig/tests/xpu/qwen3_asr_contract_lm.zig new file mode 100644 index 00000000000..5bb2b81ee92 --- /dev/null +++ b/zig/tests/xpu/qwen3_asr_contract_lm.zig @@ -0,0 +1,440 @@ +//! The LM's kernels under the contract on XPU: asr_qk_rope (with its cache writes) and lfm3_gq2's attention pair. +const std = @import("std"); +const xpu = @import("xpu"); +const core = @import("core"); +const kit = @import("qwen3_asr_contract_kit.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const rows = core.contract.rows; +const Mutation = kit.Mutation; +const val = kit.val; +const u = kit.u; + +const HD = 128; +const pos0 = 5; // the pass's first position: rows land at 5, 6, ... + +/// Each lane's chain over its 8 values, then the 16-lane sub-group tree. +fn ropeDepth(_: c.Shape) usize { + return 8 + 4 + 1; +} + +/// asr_qk_rope's outputs (q, k and v rows; numbers against float64), or its cache rows (bits against the k and v rows). +pub const Part = enum { rows, cache }; + +const rope_why = "a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps, and " ++ + "an fp16 sum past its range zeroes rs, so an output misses by at most itself over its bound (about 85x)"; + +/// rows: a pass's rows; n: q heads; k: KV heads (128-dim each). +pub const QkRope = struct { + a: std.mem.Allocator, + rig: kit.Rig, + k: xpu.Kernel, + m: Mutation, + part: Part, + shape: c.Shape = undefined, + fill: g.Fill = .random, + qkv: []u16 = &.{}, + qn: [HD]u16 = undefined, + kn: [HD]u16 = undefined, + cs: []f32 = &.{}, + sn: []f32 = &.{}, + bufs: [10]?*anyopaque = undefined, + + pub fn spec(part: Part) c.Spec { + // a small odd pass; a decode row of the 0.6B and 1.7B LM (16 q heads on 8); a prompt pass + const served: []const c.Shape = &.{ .{ .rows = 3, .n = 4, .k = 2 }, .{ .rows = 1, .n = 16, .k = 8 }, .{ .rows = 150, .n = 16, .k = 8 } }; + return switch (part) { + .rows => .{ .name = "xpu qwen3-asr asr_qk_rope (q, k and v rows)", .accum = .f32, .depth = ropeDepth, .ops = 8, .mids = 3, .out = .bf16, .served = served, .sums = .{ .f16 = 50, .bf16 = 0, .why = rope_why } }, + .cache => .{ .name = "xpu qwen3-asr asr_qk_rope (k and v into the caches at pos0 + r)", .accum = .none, .depth = kit.noSums, .out = .bf16, .served = served }, + }; + } + + pub fn init(a: std.mem.Allocator, dev: *kit.Dev, m: Mutation, part: Part) !QkRope { + return .{ .a = a, .rig = .{ .a = a, .dev = dev }, .k = try dev.kernel(.qwen3_asr, m, "asr_qk_rope"), .m = m, .part = part }; + } + + pub fn deinit(t: *QkRope) void { + t.free(); + t.k.deinit(); + t.rig.deinit(); + } + + fn free(t: *QkRope) void { + t.a.free(t.qkv); + t.a.free(t.cs); + t.a.free(t.sn); + t.qkv = &.{}; + t.cs = &.{}; + t.sn = &.{}; + } + + pub fn kernel(t: *QkRope) g.Kernel { + return kit.mark(.{ .spec = spec(t.part), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(QkRope); + + fn width(t: *const QkRope) usize { + return (t.shape.n + 2 * t.shape.k) * HD; + } + + fn cap(t: *const QkRope) usize { + return pos0 + t.shape.rows + 2; + } + + pub fn prepare(t: *QkRope, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.k == 0) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + t.fill = fill; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + t.qkv = try t.a.alloc(u16, shape.rows * t.width()); + if (fill == .stress) { + // integers -63..64: a head's sum of squares is exact in fp32 (<= 2^19) and passes fp16's range + for (t.qkv) |*v| v.* = c.toBf16(@as(f32, @floatFromInt(rng.uintLessThan(u32, 128))) - 63); + } else kit.fill(rng, t.qkv, 2); + kit.fill(rng, &t.qn, 1.5); + kit.fill(rng, &t.kn, 1.5); + if (fill == .nonfinite) { + // NaN, +Inf, -Inf in three heads of row 0, and in a v column + const wd = t.width(); + for (kit.planted, 0..) |v, i| t.qkv[(i * HD + 7 * i + 3) % wd] = c.toBf16(v); + t.qkv[wd - 5] = c.toBf16(kit.planted[1]); + } + const n = t.cap() * HD; + t.cs = try t.a.alloc(f32, n); + t.sn = try t.a.alloc(f32, n); + for (0..t.cap()) |p| for (0..HD / 2) |i| { + const inv = 1.0 / std.math.pow(f64, 1e6, @as(f64, @floatFromInt(2 * i)) / HD); + const ang = @as(f64, @floatFromInt(p)) * inv; + for ([2]usize{ i, i + HD / 2 }) |col| { + t.cs[p * HD + col] = @floatCast(kit.bf(@cos(ang))); + t.sn[p * HD + col] = @floatCast(kit.bf(@sin(ang))); + } + }; + const r = shape.rows; + const qd = shape.n * HD; + const kvd = shape.k * HD; + t.bufs[0] = try t.rig.input(std.mem.sliceAsBytes(t.qkv)); + t.bufs[1] = try t.rig.input(std.mem.sliceAsBytes(&t.qn)); + t.bufs[2] = try t.rig.input(std.mem.sliceAsBytes(&t.kn)); + t.bufs[3] = try t.rig.input(std.mem.sliceAsBytes(t.cs)); + t.bufs[4] = try t.rig.input(std.mem.sliceAsBytes(t.sn)); + const sizes = [_]usize{ r * qd, r * kvd, r * kvd, t.cap() * kvd, t.cap() * kvd }; + for (sizes, 5..) |sz, i| { + const out = (t.part == .rows) == (i < 8); + t.bufs[i] = if (out) try t.rig.output(sz * 2) else try t.rig.scratch(sz * 2); + } + return true; + } + + pub fn run(t: *QkRope) !void { + const s = t.shape; + const b = t.bufs; + try t.rig.launch(t.k, .{ u(s.n + 2 * s.k), u(s.rows), 1 }, .{ b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8], b[9], u(s.n), u(s.k), @as(u32, pos0), @as(f32, 1e-6) }); + } + + pub fn count(t: *QkRope) usize { + const s = t.shape; + return if (t.part == .rows) s.rows * (s.n + 2 * s.k) * HD else 2 * t.cap() * s.k * HD; + } + + /// Output i's head: its normed values (x rs w, float64) and the sum's magnitude, for want and the bound. + fn head(t: *QkRope, r: usize, h: usize, out: *[HD]f64) f64 { + const src = t.qkv[r * t.width() + h * HD ..][0..HD]; + const w = if (h < t.shape.n) &t.qn else &t.kn; + var ss: f64 = 0; + for (src) |v| ss += val(v) * val(v); + const rs = 1 / @sqrt(ss / HD + 1e-6); + for (out, src, w) |*o, x, wv| o.* = val(x) * rs * val(wv); + return ss; + } + + /// q, k (normed, rotated), v (copied) in the outputs' order, and each value's bound when `allow` is given. + fn each(t: *QkRope, want: []f64, allow: ?[]f64) void { + const s = t.shape; + const qd = s.n * HD; + const kvd = s.k * HD; + const chain = if (t.fill == .stress) 0 else c.gamma(@floatFromInt(ropeDepth(s)), kit.u32r); + for (0..s.rows) |r| { + const p = pos0 + r; + for (0..s.n + s.k) |h| { + var nv: [HD]f64 = undefined; + _ = t.head(r, h, &nv); + const at = if (h < s.n) r * qd + h * HD else s.rows * qd + r * kvd + (h - s.n) * HD; + for (0..HD) |d| { + const rot = if (d < HD / 2) -nv[d + HD / 2] else nv[d - HD / 2]; + const cs: f64 = t.cs[p * HD + d]; + const sn: f64 = t.sn[p * HD + d]; + want[at + d] = nv[d] * cs + rot * sn; + if (allow) |al| { + // the norm's two bf16 roundings and sum error, then each product's and the sum's roundings + const rel = chain / 2 + 2 * kit.ubf + 6 * kit.u32r; + const work = rel * (@abs(nv[d] * cs) + @abs(rot * sn)) + (kit.ubf + kit.u32r) * (@abs(nv[d] * cs) + @abs(rot * sn)) * (1 + rel) + kit.u32r * @abs(want[at + d]); + al[at + d] = work + kit.ubf * (@abs(want[at + d]) + work) + kit.floor_bf; + } + } + } + const vat = s.rows * (qd + kvd) + r * kvd; + for (0..kvd) |i| { + want[vat + i] = val(t.qkv[r * t.width() + qd + kvd + i]); + if (allow) |al| al[vat + i] = kit.floor_bf; + } + } + } + + pub fn reference(t: *QkRope, want: []f64, mag: []f64) !void { + t.each(want, null); + @memset(mag, 0); + } + + pub fn bounds(t: *QkRope, _: []const f64, _: []const f64, allow: []f64) !void { + const want = try t.a.alloc(f64, allow.len); + defer t.a.free(want); + t.each(want, allow); + } + + /// The sums of squares in `acc` and `order`, the rest exact. + pub fn simulate(t: *QkRope, acc: c.Accum, order: g.Order, out: []f64) !void { + t.each(out, null); + const s = t.shape; + var sq: [HD]f64 = undefined; + for (0..s.rows) |r| for (0..s.n + s.k) |h| { + var nv: [HD]f64 = undefined; + const ss = t.head(r, h, &nv); + const src = t.qkv[r * t.width() + h * HD ..][0..HD]; + for (&sq, src) |*q, x| q.* = val(x) * val(x); + // the exact rs to the simulated one: every normed value of the head scales by their ratio + const ratio = @sqrt((ss / HD + 1e-6) / (rows.sumIn(acc, order, &sq) / HD + 1e-6)); + const at = if (h < s.n) r * s.n * HD + h * HD else s.rows * s.n * HD + r * s.k * HD + (h - s.n) * HD; + for (out[at..][0..HD]) |*o| o.* *= ratio; + }; + } +}; + +/// asr_qk_rope's cache writes: rows pos0 + r of kc and vc bit-equal to the k and v rows, every other slot untouched. +pub const QkCache = struct { + base: QkRope, + rig: *kit.Rig, + msg: [160]u8 = undefined, + + /// In place: `rig` points into `base`. + pub fn init(t: *QkCache, a: std.mem.Allocator, dev: *kit.Dev, m: Mutation) !void { + t.* = .{ .base = try QkRope.init(a, dev, m, .cache), .rig = undefined }; + t.rig = &t.base.rig; + } + + pub fn deinit(t: *QkCache) void { + t.base.deinit(); + } + + pub fn kernel(t: *QkCache) g.Kernel { + return kit.mark(.{ .spec = QkRope.spec(.cache), .ctx = t, .vt = &vt }, t.base.m); + } + const vt = g.hooks(QkCache); + + pub fn prepare(t: *QkCache, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + return t.base.prepare(shape, fill, seed); + } + + pub fn run(t: *QkCache) !void { + return t.base.run(); + } + + pub fn count(t: *QkCache) usize { + return t.base.count(); + } + + pub fn reference(_: *QkCache, want: []f64, mag: []f64) !void { + @memset(want, 0); + @memset(mag, 0); + } + + pub fn check(t: *QkCache, _: g.Gate) !?[]const u8 { + const b = &t.base; + const s = b.shape; + const kvd = s.k * HD; + const k_rows = try b.a.dupe(u8, try b.rig.bytes(b.bufs[6], s.rows * kvd * 2)); + defer b.a.free(k_rows); + const got = try b.rig.outputBytes(); + for (0..2) |which| for (0..b.cap()) |p| for (0..kvd) |i| { + const v = std.mem.readInt(u16, got[2 * ((which * b.cap() + p) * kvd + i) ..][0..2], .little); + const live = p >= pos0 and p < pos0 + s.rows; + const r = p -% pos0; + const want: u16 = if (!live) 0xffff else if (which == 0) std.mem.readInt(u16, k_rows[2 * (r * kvd + i) ..][0..2], .little) else b.qkv[r * b.width() + (s.n + s.k) * HD + i]; + if (v != want) return try std.fmt.bufPrint(&t.msg, "{s} slot {d} value {d} has bits {x:0>4} where {x:0>4} belongs", .{ if (which == 0) "kc" else "vc", p, i, v, want }); + }; + return null; + } +}; + +/// lfm3's split-K pass and merge at GQ 2, gate +inf, 128-key chunks; rows, n q heads, k positions before the pass. +pub const Attn = struct { + a: std.mem.Allocator, + rig: kit.Rig, + part: xpu.Kernel, + merge: xpu.Kernel, + m: Mutation, + shape: c.Shape = undefined, + q: []u16 = &.{}, + kc: []u16 = &.{}, + vc: []u16 = &.{}, + bufs: [8]?*anyopaque = undefined, + + const chunk = 128; + const why = "softmax weights in [0, 1] and a bf16 output: no accumulator's error survives its rounding 100x"; + + fn depth(s: c.Shape) usize { + return 14 + s.k + s.rows; + } + + pub fn spec() c.Spec { + // a small pass; decode rows after 300 and 1,000 positions (3 and 8 chunks); a prompt pass from 0 + const served: []const c.Shape = &.{ .{ .rows = 3, .n = 4, .k = 5 }, .{ .rows = 1, .n = 16, .k = 300 }, .{ .rows = 1, .n = 16, .k = 1000 }, .{ .rows = 150, .n = 16, .k = 0 } }; + return .{ .name = "xpu qwen3-asr lfm3_gq2 lfm3_attn_partial + lfm3_attn_merge_gate (causal GQA 2)", .accum = .f32, .depth = depth, .ops = 8, .out = .bf16, .served = served, .sums = .{ .f16 = 0, .bf16 = 0, .exact = false, .why = why } }; + } + + pub fn init(a: std.mem.Allocator, dev: *kit.Dev, m: Mutation) !Attn { + var p = try dev.kernel(.lfm3_gq2, m, "lfm3_attn_partial"); + errdefer p.deinit(); + return .{ .a = a, .rig = .{ .a = a, .dev = dev }, .part = p, .merge = try dev.kernel(.lfm3_gq2, m, "lfm3_attn_merge_gate"), .m = m }; + } + + pub fn deinit(t: *Attn) void { + t.free(); + t.part.deinit(); + t.merge.deinit(); + t.rig.deinit(); + } + + fn free(t: *Attn) void { + inline for (.{ "q", "kc", "vc" }) |f| { + t.a.free(@field(t, f)); + @field(t, f) = &.{}; + } + } + + pub fn kernel(t: *Attn) g.Kernel { + return kit.mark(.{ .spec = spec(), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Attn); + + fn cap(t: *const Attn) usize { + return t.shape.k + t.shape.rows + 3; + } + + fn maxc(t: *const Attn) usize { + return (t.cap() + chunk - 1) / chunk; + } + + pub fn prepare(t: *Attn, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.n % 2 != 0) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const qd = shape.n * HD; + const kvd = shape.n / 2 * HD; + t.q = try t.a.alloc(u16, shape.rows * qd); + t.kc = try t.a.alloc(u16, t.cap() * kvd); + t.vc = try t.a.alloc(u16, t.cap() * kvd); + kit.fill(rng, t.q, 1); + kit.fill(rng, t.kc, 1); + kit.fill(rng, t.vc, 2); + if (fill == .nonfinite) { + kit.plant(t.q); + t.vc[kvd + 9] = c.toBf16(std.math.nan(f32)); + t.kc[2 * kvd + 4] = c.toBf16(-std.math.inf(f32)); + } + const gate = try t.a.alloc(u16, shape.rows * shape.n); + defer t.a.free(gate); + @memset(gate, 0x7f80); + const parts = shape.rows * shape.n * t.maxc(); + t.bufs[0] = try t.rig.input(std.mem.sliceAsBytes(t.q)); + t.bufs[1] = try t.rig.input(std.mem.sliceAsBytes(t.kc)); + t.bufs[2] = try t.rig.input(std.mem.sliceAsBytes(t.vc)); + t.bufs[3] = try t.rig.input(std.mem.sliceAsBytes(gate)); + t.bufs[4] = try t.rig.scratch(parts * HD * 4); + t.bufs[5] = try t.rig.scratch(parts * 4); + t.bufs[6] = try t.rig.scratch(parts * 4); + t.bufs[7] = try t.rig.output(shape.rows * qd * 2); + return true; + } + + pub fn run(t: *Attn) !void { + const s = t.shape; + const b = t.bufs; + const scale: f32 = @floatCast(1.0 / @sqrt(@as(f64, HD))); + const nch = (s.k + s.rows + chunk - 1) / chunk; + try t.rig.launch(t.part, .{ u(s.n / 2), u(nch), u(s.rows) }, .{ b[0], b[1], b[2], b[4], b[5], b[6], u(s.k), @as(u32, chunk), u(t.cap()), @as(u32, 0), u(s.n / 2), u(t.maxc()), scale }); + try t.rig.launch(t.merge, .{ u(s.n), u(s.rows), 1 }, .{ b[4], b[5], b[6], b[3], b[7], u(s.k), @as(u32, chunk), @as(u32, 0), u(s.n), u(t.maxc()) }); + } + + pub fn count(t: *Attn) usize { + return t.shape.rows * t.shape.n * HD; + } + + const Kv = struct { + t: *const Attn, + kvh: usize, + pub fn k(kv: Kv, j: usize, e: usize) f64 { + return val(kv.t.kc[(j * kv.t.shape.n / 2 + kv.kvh) * HD + e]); + } + pub fn v(kv: Kv, j: usize, e: usize) f64 { + return val(kv.t.vc[(j * kv.t.shape.n / 2 + kv.kvh) * HD + e]); + } + }; + + fn each(t: *Attn, want: []f64, allow: ?[]f64) !void { + const s = t.shape; + var q: [HD]f64 = undefined; + const scale = 1.0 / @sqrt(@as(f64, HD)); + for (0..s.rows) |r| for (0..s.n) |h| { + for (&q, 0..) |*x, e| x.* = val(t.q[(r * s.n + h) * HD + e]); + const keys = s.k + r + 1; + const at = (r * s.n + h) * HD; + try kit.attention(t.a, &q, keys, Kv{ .t = t, .kvh = h / 2 }, scale, (keys + chunk - 1) / chunk, want[at..][0..HD], if (allow) |al| al[at..][0..HD] else null); + }; + } + + pub fn reference(t: *Attn, want: []f64, mag: []f64) !void { + try t.each(want, null); + for (mag, want) |*m, w| m.* = @abs(w); + } + + pub fn bounds(t: *Attn, _: []const f64, _: []const f64, allow: []f64) !void { + const want = try t.a.alloc(f64, allow.len); + defer t.a.free(want); + try t.each(want, allow); + } + + /// The scores and the two weighted sums in `acc` and `order`, exp and the division exact. + pub fn simulate(t: *Attn, acc: c.Accum, order: g.Order, out: []f64) !void { + const s = t.shape; + const scale = 1.0 / @sqrt(@as(f64, HD)); + const most = s.k + s.rows; + const buf = try t.a.alloc(f64, @max(most, HD)); + defer t.a.free(buf); + const p = try t.a.alloc(f64, most); + defer t.a.free(p); + for (0..s.rows) |r| for (0..s.n) |h| { + const kv: Kv = .{ .t = t, .kvh = h / 2 }; + const keys = s.k + r + 1; + var mx: f64 = -std.math.inf(f64); + for (0..keys) |j| { + for (buf[0..HD], 0..) |*x, e| x.* = val(t.q[(r * s.n + h) * HD + e]) * kv.k(j, e); + p[j] = rows.sumIn(acc, order, buf[0..HD]) * scale; + mx = @max(mx, p[j]); + } + for (p[0..keys]) |*x| x.* = @exp(x.* - mx); + const l = rows.sumIn(acc, order, p[0..keys]); + for (0..HD) |e| { + for (buf[0..keys], 0..) |*x, j| x.* = p[j] * kv.v(j, e); + out[(r * s.n + h) * HD + e] = rows.sumIn(acc, order, buf[0..keys]) / l; + } + }; + } +}; diff --git a/zig/tests/xpu/qwen3_asr_contract_rows.zig b/zig/tests/xpu/qwen3_asr_contract_rows.zig new file mode 100644 index 00000000000..19db0a91e74 --- /dev/null +++ b/zig/tests/xpu/qwen3_asr_contract_rows.zig @@ -0,0 +1,194 @@ +//! The row kernels under the contract on XPU: asr_layernorm, asr_gelu, lfm3_gq2's RMSNorm and SwiGLU. +const std = @import("std"); +const xpu = @import("xpu"); +const core = @import("core"); +const kit = @import("qwen3_asr_contract_kit.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const rows = core.contract.rows; +const Mutation = kit.Mutation; +const val = kit.val; +const u = kit.u; + +pub const Which = enum { layernorm, rms, gelu }; + +/// A 256-item row: each item's chain over every 256th value, a 16-lane sub-group tree, then the 16 parts in order. +fn rowDepth(s: c.Shape) usize { + return (s.k + 255) / 256 + 4 + 16; +} + +const ln_why = "a bf16 output follows the variance as var^-1/2: a bf16 sum's error is a few output ulps"; +const rms_why = "a bf16 output follows the sum of squares as ss^-1/2: a bf16 sum's error is a few output ulps"; + +pub fn rowSpec(which: Which) c.Spec { + return switch (which) { + // the 0.6B tower (896), the 1.7B's (1024), a short last window + .layernorm => .{ .name = "xpu qwen3-asr asr_layernorm (bias, eps 1e-5)", .accum = .f32, .depth = rowDepth, .ops = 8, .out = .bf16, .served = &.{ .{ .rows = 5, .n = 896, .k = 896 }, .{ .rows = 104, .n = 1024, .k = 1024 }, .{ .rows = 13, .n = 896, .k = 896 } }, .sums = .{ .bf16 = 0, .why = ln_why } }, + // the 0.6B LM (1024), the 1.7B's (2048), a prompt's rows + .rms => .{ .name = "xpu qwen3-asr lfm3_gq2 lfm3_rmsnorm (eps 1e-6)", .accum = .f32, .depth = rowDepth, .ops = 8, .mids = 1, .out = .bf16, .served = &.{ .{ .rows = 4, .n = 1024, .k = 1024 }, .{ .rows = 1, .n = 2048, .k = 2048 }, .{ .rows = 150, .n = 1024, .k = 1024 } }, .sums = .{ .bf16 = 0, .why = rms_why } }, + // the convs' channels, fc1's rows, proj1's + .gelu => .{ .name = "xpu qwen3-asr asr_gelu (erf)", .accum = .none, .depth = kit.noSums, .ops = 8, .out = .bf16, .served = &.{ .{ .rows = 4, .n = 1000, .k = 1000 }, .{ .rows = 104, .n = 3584, .k = 3584 }, .{ .rows = 13, .n = 896, .k = 896 } } }, + }; +} + +pub const Row = struct { + a: std.mem.Allocator, + rig: kit.Rig, + k: xpu.Kernel, + m: Mutation, + which: Which, + r: ?rows.Rows = null, + x: ?*anyopaque = null, + w: ?*anyopaque = null, + b: ?*anyopaque = null, + out: ?*anyopaque = null, + + pub fn init(a: std.mem.Allocator, dev: *kit.Dev, m: Mutation, which: Which) !Row { + const k = switch (which) { + .layernorm => try dev.kernel(.qwen3_asr, m, "asr_layernorm"), + .gelu => try dev.kernel(.qwen3_asr, m, "asr_gelu"), + .rms => try dev.kernel(.lfm3_gq2, m, "lfm3_rmsnorm"), + }; + return .{ .a = a, .rig = .{ .a = a, .dev = dev }, .k = k, .m = m, .which = which }; + } + + pub fn deinit(t: *Row) void { + if (t.r) |r| r.deinit(); + t.k.deinit(); + t.rig.deinit(); + } + + pub fn kernel(t: *Row) g.Kernel { + return kit.mark(.{ .spec = rowSpec(t.which), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Row); + + fn op(w: Which) rows.Op { + return switch (w) { + .layernorm => .layer_norm, + .rms => .rms, + .gelu => .gelu, + }; + } + + pub fn prepare(t: *Row, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.k == 0 or shape.n != shape.k) return false; + // lfm3_rmsnorm holds 16 values an item: whole 256-item passes up to 4,096 + if (t.which == .rms and (shape.k % 256 != 0 or shape.k > 4096)) return false; + if (t.r) |r| r.deinit(); + t.r = null; + t.rig.reset(); + const r = try rows.Rows.init(t.a, op(t.which), shape); + t.r = r; + r.fill(fill, seed); + t.x = try t.rig.input(std.mem.sliceAsBytes(r.x)); + if (t.which != .gelu) t.w = try t.rig.input(std.mem.sliceAsBytes(r.w)); + if (t.which == .layernorm) t.b = try t.rig.input(std.mem.sliceAsBytes(r.b)); + t.out = try t.rig.output(r.outputs() * 2); + return true; + } + + pub fn run(t: *Row) !void { + const r = t.r.?; + const k = r.shape.k; + switch (t.which) { + .layernorm => try t.rig.launch(t.k, .{ u(r.shape.rows), 1, 1 }, .{ t.x, t.w, t.b, t.out, u(k), r.eps }), + .rms => try t.rig.launch(t.k, .{ u(r.shape.rows), 1, 1 }, .{ t.x, t.w, t.out, u(k), r.eps }), + .gelu => try t.rig.launch(t.k, .{ u((r.outputs() + 255) / 256), 1, 1 }, .{ t.x, t.out, u(r.outputs()) }), + } + } + + pub fn count(t: *Row) usize { + return t.r.?.outputs(); + } + + pub fn reference(t: *Row, want: []f64, mag: []f64) !void { + return t.r.?.reference(want, mag); + } + + /// GELU only: what an fp32 erf of 16 ulps (OpenCL's allowance) adds, x / 2 times 2^-20 near erf = +-1. + pub fn bounds(t: *Row, _: []const f64, _: []const f64, allow: []f64) !void { + if (t.which != .gelu) return; + for (allow, t.r.?.x) |*l, x| l.* += 0.5 * @abs(val(x)) * 0x1p-20; + } + + pub fn simulate(t: *Row, acc: c.Accum, order: g.Order, out: []f64) !void { + return t.r.?.simulate(acc, order, out); + } +}; + +/// lfm3_swiglu over [gate | up] rows: bf16(bf16(silu(gate)) up), a value an item. rows x n values, k = n. +pub const Swiglu = struct { + a: std.mem.Allocator, + rig: kit.Rig, + k: xpu.Kernel, + m: Mutation, + shape: c.Shape = undefined, + gate: []u16 = &.{}, + up: []u16 = &.{}, + ins: [2]?*anyopaque = undefined, + out: ?*anyopaque = null, + + pub fn spec() c.Spec { + // the 0.6B's intermediate (3072), the 1.7B's (6144), an odd count + return .{ .name = "xpu qwen3-asr lfm3_gq2 lfm3_swiglu", .accum = .none, .depth = kit.noSums, .ops = 10, .mids = 1, .out = .bf16, .served = &.{ .{ .rows = 3, .n = 300, .k = 300 }, .{ .rows = 1, .n = 3072, .k = 3072 }, .{ .rows = 1, .n = 6144, .k = 6144 }, .{ .rows = 37, .n = 3072, .k = 3072 } } }; + } + + pub fn init(a: std.mem.Allocator, dev: *kit.Dev, m: Mutation) !Swiglu { + return .{ .a = a, .rig = .{ .a = a, .dev = dev }, .k = try dev.kernel(.lfm3_gq2, m, "lfm3_swiglu"), .m = m }; + } + + pub fn deinit(t: *Swiglu) void { + t.a.free(t.gate); + t.a.free(t.up); + t.k.deinit(); + t.rig.deinit(); + } + + pub fn kernel(t: *Swiglu) g.Kernel { + return kit.mark(.{ .spec = spec(), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Swiglu); + + pub fn prepare(t: *Swiglu, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0) return false; + t.rig.reset(); + t.a.free(t.gate); + t.a.free(t.up); + t.shape = shape; + const n = shape.rows * shape.n; + t.gate = try t.a.alloc(u16, n); + t.up = try t.a.alloc(u16, n); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + kit.fill(rng, t.gate, 6); + kit.fill(rng, t.up, 3); + if (fill == .nonfinite) { + kit.plant(t.gate); + t.up[n / 2] = c.toBf16(std.math.nan(f32)); + } + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.gate)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.up)); + t.out = try t.rig.output(n * 2); + return true; + } + + pub fn run(t: *Swiglu) !void { + const n = t.shape.rows * t.shape.n; + try t.rig.launch(t.k, .{ u((n + 63) / 64), 1, 1 }, .{ t.ins[0], t.ins[1], t.out, u(n) }); + } + + pub fn count(t: *Swiglu) usize { + return t.shape.rows * t.shape.n; + } + + /// silu(gate) up in float64, as the kernel's formula (NaN where -inf meets inf). + pub fn reference(t: *Swiglu, want: []f64, mag: []f64) !void { + for (want, mag, t.gate, t.up) |*w, *m, a, b| { + const x = val(a); + w.* = x / (1 + @exp(-x)) * val(b); + m.* = 0; + } + } +}; diff --git a/zig/tests/xpu/qwen3_asr_contract_tower.zig b/zig/tests/xpu/qwen3_asr_contract_tower.zig new file mode 100644 index 00000000000..0a702a849a4 --- /dev/null +++ b/zig/tests/xpu/qwen3_asr_contract_tower.zig @@ -0,0 +1,551 @@ +//! qwen3_asr.cl's tower kernels under the contract on XPU: the Linear, conv, flatten and windowed attention. +const std = @import("std"); +const xpu = @import("xpu"); +const core = @import("core"); +const kit = @import("qwen3_asr_contract_kit.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; +const rows = core.contract.rows; +const Mutation = kit.Mutation; +const bf = kit.bf; +const val = kit.val; +const u = kit.u; + +/// The Linear's epilogue as the binding asks it: none (LM, conv_out), bias and residual (o, fc2), bias and GELU (fc1). +pub const Epi = enum { plain, bias_res, bias_gelu }; + +/// TILE_BODY: a 16-deep fma chain a k step, then the step's sum into the accumulator: at most k / 16 + 16 adds. +fn gemmDepth(s: c.Shape) usize { + return (s.k + 15) / 16 + 17; +} + +/// |gelu'| at most: its slope peaks near x = 1.4. +const gelu_slope = 1.13; + +pub const Gemm = struct { + a: std.mem.Allocator, + rig: kit.Rig, + k: xpu.Kernel, + m: Mutation, + epi: Epi, + shape: c.Shape = undefined, + fill: g.Fill = .random, + x: []u16 = &.{}, + w: []u16 = &.{}, + b: []u16 = &.{}, + res: []u16 = &.{}, + pre: []f64 = &.{}, // each output's float64 sum plus bias, before the activation and residual + ins: [4]?*anyopaque = undefined, + out: ?*anyopaque = null, + + /// rows: x rows; n: outputs a row; k: the input width. + pub fn spec(epi: Epi) c.Spec { + const names = [_][]const u8{ "xpu qwen3-asr asr_gemm", "xpu qwen3-asr asr_gemm, bias and residual", "xpu qwen3-asr asr_gemm, bias and GELU" }; + const served: []const c.Shape = switch (epi) { + // an odd call for the edges; the 0.6B LM's qkv, down, prompt gate | up and head; conv_out (480 x 16) + .plain => &.{ .{ .rows = 37, .n = 130, .k = 40 }, .{ .rows = 1, .n = 4096, .k = 1024 }, .{ .rows = 1, .n = 1024, .k = 3072 }, .{ .rows = 37, .n = 6144, .k = 1024 }, .{ .rows = 1, .n = 151936, .k = 1024 }, .{ .rows = 13, .n = 896, .k = 7680 } }, + // a window's o and fc2 on the 0.6B and the 1.7B tower + .bias_res => &.{ .{ .rows = 37, .n = 130, .k = 40 }, .{ .rows = 104, .n = 896, .k = 896 }, .{ .rows = 104, .n = 896, .k = 3584 }, .{ .rows = 104, .n = 1024, .k = 4096 } }, + // fc1 + .bias_gelu => &.{ .{ .rows = 37, .n = 130, .k = 40 }, .{ .rows = 104, .n = 3584, .k = 896 }, .{ .rows = 104, .n = 4096, .k = 1024 } }, + }; + return .{ + .name = names[@backingInt(epi)], + .accum = .f32, + .depth = gemmDepth, + .ops = 2, + .mids = 1, + .out = .bf16, + .tiles = .{ .{ .size = 64, .min = 1 }, .{ .size = 64, .min = 1 }, .{ .size = 16, .min = 1 } }, + .served = served, + }; + } + + pub fn init(a: std.mem.Allocator, dev: *kit.Dev, m: Mutation, epi: Epi) !Gemm { + return .{ .a = a, .rig = .{ .a = a, .dev = dev }, .k = try dev.kernel(.qwen3_asr, m, "asr_gemm"), .m = m, .epi = epi }; + } + + pub fn deinit(t: *Gemm) void { + t.free(); + t.k.deinit(); + t.rig.deinit(); + } + + fn free(t: *Gemm) void { + inline for (.{ "x", "w", "b", "res" }) |f| { + t.a.free(@field(t, f)); + @field(t, f) = &.{}; + } + t.a.free(t.pre); + t.pre = &.{}; + } + + pub fn kernel(t: *Gemm) g.Kernel { + return kit.mark(.{ .spec = spec(t.epi), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Gemm); + + pub fn prepare(t: *Gemm, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.k == 0) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + t.fill = fill; + const r = shape.rows; + const n = shape.n; + const kk = shape.k; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + t.x = try t.a.alloc(u16, r * kk); + t.w = try t.a.alloc(u16, n * kk); + t.b = try t.a.alloc(u16, n); + t.res = try t.a.alloc(u16, r * n); + t.pre = try t.a.alloc(f64, r * n); + @memset(t.b, 0); + @memset(t.res, 0); + if (fill == .stress) { + // mirrored integer halves, 8 nudged down: a small exact dot (+sum w), partials past fp16's range + const h = kk / 2; + @memset(t.x, 0); + @memset(t.w, 0); + for (0..r) |row| for (0..h) |i| { + const v: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 255)); + t.x[row * kk + i] = c.toBf16(v); + t.x[row * kk + h + i] = c.toBf16(v - @as(f32, if (i < 8) 1 else 0)); + }; + for (0..n) |col| for (0..h) |i| { + const q: f32 = @floatFromInt(1 + rng.uintLessThan(u32, 15)); + t.w[col * kk + i] = c.toBf16(q); + t.w[col * kk + h + i] = c.toBf16(-q); + }; + } else { + kit.fill(rng, t.x, 2); + kit.fill(rng, t.w, 0.1); + if (t.epi != .plain) kit.fill(rng, t.b, 0.5); + if (t.epi == .bias_res) kit.fill(rng, t.res, 2); + } + if (fill == .nonfinite) { + // NaN in row 0, +Inf in row 1, -Inf in row 2, both infinities in row 3 + const at = [_][2]usize{ .{ 0, kk / 3 }, .{ 1, kk / 2 }, .{ 2, kk - 1 }, .{ 3, 0 }, .{ 3, kk - 1 } }; + const vals = [_]f32{ kit.planted[0], kit.planted[1], kit.planted[2], kit.planted[1], kit.planted[2] }; + for (at, vals) |p, v| if (p[0] < r) { + t.x[p[0] * kk + p[1]] = c.toBf16(v); + }; + } + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.x)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.w)); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(t.b)); + t.ins[3] = try t.rig.input(std.mem.sliceAsBytes(t.res)); + t.out = try t.rig.output(r * n * 2); + return true; + } + + pub fn run(t: *Gemm) !void { + const s = t.shape; + const has_b: u32 = @intFromBool(t.epi != .plain); + const has_r: u32 = @intFromBool(t.epi == .bias_res); + const act: u32 = @intFromBool(t.epi == .bias_gelu); + try t.rig.launch(t.k, .{ u((s.n + 63) / 64), u((s.rows + 63) / 64), 1 }, .{ t.ins[0], t.ins[1], t.ins[2], has_b, t.ins[3], has_r, t.out, u(s.rows), u(s.n), u(s.k), u(s.n), act }); + } + + pub fn count(t: *Gemm) usize { + return t.shape.rows * t.shape.n; + } + + /// Output i from its sum: the bias, GELU and residual in float64, as the epilogue orders them. + fn finish(t: *Gemm, i: usize, sum: f64) f64 { + const pre = sum + val(t.b[i % t.shape.n]); + var v = if (t.epi == .bias_gelu) rows.gelu(pre) else pre; + if (t.epi == .bias_res) v += val(t.res[i]); + return v; + } + + fn terms(t: *Gemm, r: usize, col: usize, buf: []f64) void { + const kk = t.shape.k; + for (buf, 0..) |*v, i| v.* = val(t.x[r * kk + i]) * val(t.w[col * kk + i]); + } + + pub fn reference(t: *Gemm, want: []f64, mag: []f64) !void { + const buf = try t.a.alloc(f64, t.shape.k); + defer t.a.free(buf); + for (0..t.shape.rows) |r| for (0..t.shape.n) |col| { + t.terms(r, col, buf); + var s: f64 = 0; + var m: f64 = 0; + for (buf) |v| { + s += v; + m += @abs(v); + } + const i = r * t.shape.n + col; + t.pre[i] = s + val(t.b[col]); + want[i] = t.finish(i, s); + mag[i] = m; + }; + } + + /// The sums' chain (none under stress), then the epilogue's roundings: bias, GELU (erf 16 ulps), residual, store. + pub fn bounds(t: *Gemm, want: []const f64, mag: []const f64, allow: []f64) !void { + const chain = if (t.fill == .stress) 0 else c.gamma(@floatFromInt(gemmDepth(t.shape)), kit.u32r); + for (allow, want, mag, t.pre) |*l, w, m, pre| { + const sum_err = chain * m + kit.u32r * @abs(pre); + var work = switch (t.epi) { + .plain => chain * m, + .bias_res => sum_err + kit.ubf * (@abs(pre) + sum_err) + kit.u32r * @abs(w), + .bias_gelu => gelu_slope * (sum_err + kit.ubf * (@abs(pre) + sum_err)) + 0.5 * @abs(pre) * 0x1p-20 + 8 * kit.u32r * (@abs(w) + @abs(pre)), + }; + if (!std.math.isFinite(work)) work = 0; + l.* = work + kit.ubf * (@abs(w) + work) + kit.floor_bf; + } + } + + pub fn simulate(t: *Gemm, acc: c.Accum, order: g.Order, out: []f64) !void { + const buf = try t.a.alloc(f64, t.shape.k); + defer t.a.free(buf); + for (0..t.shape.rows) |r| for (0..t.shape.n) |col| { + t.terms(r, col, buf); + const i = r * t.shape.n + col; + out[i] = t.finish(i, rows.sumIn(acc, order, buf)); + }; + } +}; + +/// A conv call's geometry from its shape: rows chunks, n output channels, k = c << 16 | fi << 8 | ti. +const ConvGeo = struct { n: usize, co: usize, ci: usize, fi: usize, ti: usize, fo: usize, to: usize }; + +fn convGeo(s: c.Shape) ConvGeo { + const ci = s.k >> 16; + const fi = (s.k >> 8) & 0xff; + const ti = s.k & 0xff; + return .{ .n = s.rows, .co = s.n, .ci = ci, .fi = fi, .ti = ti, .fo = (fi -| 1) / 2 + 1, .to = (ti -| 1) / 2 + 1 }; +} + +fn convDepth(s: c.Shape) usize { + return gemmDepth(.{ .rows = 1, .n = 1, .k = 9 * (s.k >> 16) }); +} + +/// The 3 x 3 stride-2 conv with zero padding 1 on channels-last rows: bf16(taps . w + b), asr_gemm's tile body. +pub const Conv = struct { + a: std.mem.Allocator, + rig: kit.Rig, + k: xpu.Kernel, + m: Mutation, + shape: c.Shape = undefined, + x: []u16 = &.{}, + w: []u16 = &.{}, + b: []u16 = &.{}, + ins: [3]?*anyopaque = undefined, + out: ?*anyopaque = null, + + const why = "asr_conv sums in asr_gemm's tile body, which gate 4 proves fp32 on asr_gemm; zero padding leaves " ++ + "no mirrored stress for the taps"; + + pub fn spec() c.Spec { + // an odd small grid; the tower's conv1 on two 100-frame chunks, conv2 and conv3 on a 3-frame-wide chunk's grid + const served: []const c.Shape = &.{ .{ .rows = 2, .n = 70, .k = 5 << 16 | 13 << 8 | 11 }, .{ .rows = 2, .n = 480, .k = 1 << 16 | 128 << 8 | 100 }, .{ .rows = 1, .n = 480, .k = 480 << 16 | 64 << 8 | 3 }, .{ .rows = 1, .n = 480, .k = 480 << 16 | 32 << 8 | 3 } }; + return .{ .name = "xpu qwen3-asr asr_conv (3x3 stride 2, zero padding)", .accum = .f32, .depth = convDepth, .ops = 1, .out = .bf16, .served = served, .sums = .{ .f16 = 0, .bf16 = 0, .exact = false, .why = why } }; + } + + pub fn init(a: std.mem.Allocator, dev: *kit.Dev, m: Mutation) !Conv { + return .{ .a = a, .rig = .{ .a = a, .dev = dev }, .k = try dev.kernel(.qwen3_asr, m, "asr_conv"), .m = m }; + } + + pub fn deinit(t: *Conv) void { + t.free(); + t.k.deinit(); + t.rig.deinit(); + } + + fn free(t: *Conv) void { + inline for (.{ "x", "w", "b" }) |f| { + t.a.free(@field(t, f)); + @field(t, f) = &.{}; + } + } + + pub fn kernel(t: *Conv) g.Kernel { + return kit.mark(.{ .spec = spec(), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Conv); + + pub fn prepare(t: *Conv, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const q = convGeo(shape); + if (q.n == 0 or q.co == 0 or q.ci == 0 or q.fi == 0 or q.ti == 0) return false; + t.rig.reset(); + t.free(); + t.shape = shape; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + t.x = try t.a.alloc(u16, q.n * q.fi * q.ti * q.ci); + t.w = try t.a.alloc(u16, q.co * 9 * q.ci); + t.b = try t.a.alloc(u16, q.co); + kit.fill(rng, t.x, 2); + kit.fill(rng, t.w, 0.2); + kit.fill(rng, t.b, 0.5); + if (fill == .nonfinite) kit.plant(t.x); + t.ins[0] = try t.rig.input(std.mem.sliceAsBytes(t.x)); + t.ins[1] = try t.rig.input(std.mem.sliceAsBytes(t.w)); + t.ins[2] = try t.rig.input(std.mem.sliceAsBytes(t.b)); + t.out = try t.rig.output(t.count() * 2); + return true; + } + + pub fn run(t: *Conv) !void { + const q = convGeo(t.shape); + const m = q.n * q.fo * q.to; + try t.rig.launch(t.k, .{ u((q.co + 63) / 64), u((m + 63) / 64), 1 }, .{ t.ins[0], t.ins[1], t.ins[2], t.out, u(m), u(q.co), u(9 * q.ci), u(q.fi), u(q.ti), u(q.ci) }); + } + + pub fn count(t: *Conv) usize { + const q = convGeo(t.shape); + return q.n * q.fo * q.to * q.co; + } + + /// Output (p, oc)'s terms: tap kk = ci 9 + kh 3 + kw, zero where the padding is. + fn terms(t: *Conv, p: usize, oc: usize, buf: []f64) void { + const q = convGeo(t.shape); + const nn = p / (q.fo * q.to); + const f = p / q.to % q.fo; + const tt = p % q.to; + for (buf, 0..) |*v, kk| { + const ci = kk / 9; + const fx = @as(isize, @intCast(2 * f + kk % 9 / 3)) - 1; + const tx = @as(isize, @intCast(2 * tt + kk % 3)) - 1; + v.* = 0; + if (fx < 0 or tx < 0 or fx >= q.fi or tx >= q.ti) continue; + const xi = ((nn * q.fi + @as(usize, @intCast(fx))) * q.ti + @as(usize, @intCast(tx))) * q.ci + ci; + v.* = val(t.x[xi]) * val(t.w[oc * 9 * q.ci + kk]); + } + } + + pub fn reference(t: *Conv, want: []f64, mag: []f64) !void { + const q = convGeo(t.shape); + const buf = try t.a.alloc(f64, 9 * q.ci); + defer t.a.free(buf); + for (0..q.n * q.fo * q.to) |p| for (0..q.co) |oc| { + t.terms(p, oc, buf); + var s: f64 = val(t.b[oc]); + var m: f64 = 0; + for (buf) |v| { + s += v; + m += @abs(v); + } + want[p * q.co + oc] = s; + mag[p * q.co + oc] = m; + }; + } + + pub fn simulate(t: *Conv, acc: c.Accum, order: g.Order, out: []f64) !void { + const q = convGeo(t.shape); + const buf = try t.a.alloc(f64, 9 * q.ci); + defer t.a.free(buf); + for (0..q.n * q.fo * q.to) |p| for (0..q.co) |oc| { + t.terms(p, oc, buf); + out[p * q.co + oc] = rows.sumIn(acc, order, buf) + val(t.b[oc]); + }; + } +}; + +/// [n][f][t][c] to rows [n t][c f], bit for bit; rows: chunks, n: channels, k = f << 8 | t. +pub const Flatten = struct { + a: std.mem.Allocator, + rig: kit.Rig, + k: xpu.Kernel, + m: Mutation, + shape: c.Shape = undefined, + x: []u16 = &.{}, + want: []u16 = &.{}, + in: ?*anyopaque = null, + out: ?*anyopaque = null, + msg: [160]u8 = undefined, + + pub fn spec() c.Spec { + const served: []const c.Shape = &.{ .{ .rows = 3, .n = 8, .k = 5 << 8 | 3 }, .{ .rows = 2, .n = 480, .k = 16 << 8 | 13 }, .{ .rows = 1, .n = 1, .k = 1 << 8 | 1 } }; + return .{ .name = "xpu qwen3-asr asr_flatten (conv rows to torch's [c, f] order)", .accum = .none, .depth = kit.noSums, .out = .bf16, .served = served }; + } + + pub fn init(a: std.mem.Allocator, dev: *kit.Dev, m: Mutation) !Flatten { + return .{ .a = a, .rig = .{ .a = a, .dev = dev }, .k = try dev.kernel(.qwen3_asr, m, "asr_flatten"), .m = m }; + } + + pub fn deinit(t: *Flatten) void { + t.a.free(t.x); + t.a.free(t.want); + t.k.deinit(); + t.rig.deinit(); + } + + pub fn kernel(t: *Flatten) g.Kernel { + return kit.mark(.{ .spec = spec(), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(Flatten); + + pub fn prepare(t: *Flatten, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const f = shape.k >> 8; + const tt = shape.k & 0xff; + if (shape.rows == 0 or shape.n == 0 or f == 0 or tt == 0) return false; + t.rig.reset(); + t.a.free(t.x); + t.a.free(t.want); + t.shape = shape; + const n = shape.rows; + const ch = shape.n; + t.x = try t.a.alloc(u16, n * f * tt * ch); + var prng = std.Random.DefaultPrng.init(seed); + kit.fill(prng.random(), t.x, 4); + if (fill == .nonfinite) kit.plant(t.x); + t.want = try t.a.alloc(u16, t.x.len); + for (0..n) |nn| for (0..tt) |ti| for (0..ch) |ci| for (0..f) |fi| { + t.want[(nn * tt + ti) * ch * f + ci * f + fi] = t.x[((nn * f + fi) * tt + ti) * ch + ci]; + }; + t.in = try t.rig.input(std.mem.sliceAsBytes(t.x)); + t.out = try t.rig.output(t.x.len * 2); + return true; + } + + pub fn run(t: *Flatten) !void { + const total = t.x.len; + try t.rig.launch(t.k, .{ u((total + 255) / 256), 1, 1 }, .{ t.in, t.out, u(t.shape.k >> 8), u(t.shape.k & 0xff), u(t.shape.n), u(total) }); + } + + pub fn count(t: *Flatten) usize { + return t.want.len; + } + + pub fn reference(t: *Flatten, want: []f64, mag: []f64) !void { + for (want, t.want) |*w, b| w.* = val(b); + @memset(mag, 0); + } + + /// Every output's bits equal to the host's copy (NaN payloads too). + pub fn check(t: *Flatten, _: g.Gate) !?[]const u8 { + const got = try t.rig.outputBytes(); + for (t.want, 0..) |w, i| { + const v = std.mem.readInt(u16, got[2 * i ..][0..2], .little); + if (v != w) return try std.fmt.bufPrint(&t.msg, "output {d} has bits {x:0>4} where the copy has {x:0>4}", .{ i, v, w }); + } + return null; + } +}; + +/// The tower's attention over one window of [q | k | v] rows (64-dim heads); rows: the window, n = heads x 64. +pub const AttnFull = struct { + a: std.mem.Allocator, + rig: kit.Rig, + k: xpu.Kernel, + m: Mutation, + shape: c.Shape = undefined, + qkv: []u16 = &.{}, + in: ?*anyopaque = null, + out: ?*anyopaque = null, + + const why = "softmax weights in [0, 1] and a bf16 output: no accumulator's error survives its rounding 100x"; + + fn depth(s: c.Shape) usize { + return 66 + s.rows; + } + + pub fn spec() c.Spec { + // a small odd window; a full window of the 0.6B's 14 heads and of the 1.7B's 16; a short last window + const served: []const c.Shape = &.{ .{ .rows = 45, .n = 192, .k = 64 }, .{ .rows = 104, .n = 896, .k = 64 }, .{ .rows = 104, .n = 1024, .k = 64 }, .{ .rows = 7, .n = 896, .k = 64 } }; + return .{ .name = "xpu qwen3-asr asr_attn_full (a window, 64-dim heads)", .accum = .f32, .depth = depth, .ops = 8, .out = .bf16, .tiles = .{ .{ .size = 16, .min = 1 }, .{}, .{} }, .served = served, .sums = .{ .f16 = 0, .bf16 = 0, .exact = false, .why = why } }; + } + + pub fn init(a: std.mem.Allocator, dev: *kit.Dev, m: Mutation) !AttnFull { + return .{ .a = a, .rig = .{ .a = a, .dev = dev }, .k = try dev.kernel(.qwen3_asr, m, "asr_attn_full"), .m = m }; + } + + pub fn deinit(t: *AttnFull) void { + t.a.free(t.qkv); + t.k.deinit(); + t.rig.deinit(); + } + + pub fn kernel(t: *AttnFull) g.Kernel { + return kit.mark(.{ .spec = spec(), .ctx = t, .vt = &vt }, t.m); + } + const vt = g.hooks(AttnFull); + + pub fn prepare(t: *AttnFull, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + if (shape.rows == 0 or shape.n == 0 or shape.n % 64 != 0 or shape.k != 64) return false; + t.rig.reset(); + t.a.free(t.qkv); + t.shape = shape; + t.qkv = try t.a.alloc(u16, shape.rows * 3 * shape.n); + var prng = std.Random.DefaultPrng.init(seed); + kit.fill(prng.random(), t.qkv, 1.5); + if (fill == .nonfinite) kit.plant(t.qkv); + t.in = try t.rig.input(std.mem.sliceAsBytes(t.qkv)); + t.out = try t.rig.output(shape.rows * shape.n * 2); + return true; + } + + pub fn run(t: *AttnFull) !void { + const s = t.shape; + try t.rig.launch(t.k, .{ u(s.rows), u(s.n / 64), 1 }, .{ t.in, t.out, u(s.rows), u(s.n / 64), @as(f32, 0.125) }); + } + + pub fn count(t: *AttnFull) usize { + return t.shape.rows * t.shape.n; + } + + const Kv = struct { + t: *const AttnFull, + h: usize, + pub fn k(kv: Kv, j: usize, e: usize) f64 { + const d = kv.t.shape.n; + return val(kv.t.qkv[j * 3 * d + d + kv.h * 64 + e]); + } + pub fn v(kv: Kv, j: usize, e: usize) f64 { + const d = kv.t.shape.n; + return val(kv.t.qkv[j * 3 * d + 2 * d + kv.h * 64 + e]); + } + }; + + fn each(t: *AttnFull, want: []f64, allow: ?[]f64) !void { + const d = t.shape.n; + const len = t.shape.rows; + var q: [64]f64 = undefined; + for (0..len) |r| for (0..d / 64) |h| { + for (&q, 0..) |*x, e| x.* = val(t.qkv[r * 3 * d + h * 64 + e]); + const at = r * d + h * 64; + try kit.attention(t.a, &q, len, Kv{ .t = t, .h = h }, 0.125, (len + 15) / 16, want[at..][0..64], if (allow) |al| al[at..][0..64] else null); + }; + } + + pub fn reference(t: *AttnFull, want: []f64, mag: []f64) !void { + try t.each(want, null); + for (mag, want) |*m, w| m.* = @abs(w); + } + + pub fn bounds(t: *AttnFull, _: []const f64, _: []const f64, allow: []f64) !void { + const want = try t.a.alloc(f64, allow.len); + defer t.a.free(want); + try t.each(want, allow); + } + + /// The scores and the two weighted sums in `acc` and `order`, exp and the division exact. + pub fn simulate(t: *AttnFull, acc: c.Accum, order: g.Order, out: []f64) !void { + const d = t.shape.n; + const len = t.shape.rows; + const buf = try t.a.alloc(f64, @max(len, 64)); + defer t.a.free(buf); + const p = try t.a.alloc(f64, len); + defer t.a.free(p); + for (0..len) |r| for (0..d / 64) |h| { + const kv: Kv = .{ .t = t, .h = h }; + var mx: f64 = -std.math.inf(f64); + for (0..len) |j| { + for (buf[0..64], 0..) |*x, e| x.* = val(t.qkv[r * 3 * d + h * 64 + e]) * kv.k(j, e); + p[j] = rows.sumIn(acc, order, buf[0..64]) * 0.125; + mx = @max(mx, p[j]); + } + for (p) |*x| x.* = @exp(x.* - mx); + const l = rows.sumIn(acc, order, p); + for (0..64) |e| { + for (buf[0..len], 0..) |*x, j| x.* = p[j] * kv.v(j, e); + out[r * d + h * 64 + e] = rows.sumIn(acc, order, buf[0..len]) / l; + } + }; + } +};