From b0cdc70e79fdfccf7d8b7c6f12f501ddbb45a33a 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 08:46:28 +0100 Subject: [PATCH 01/28] qwen3-asr: host config, tensor map, mel rows and a float64 tower (#2105) Qwen3-ASR's 0.6B and 1.7B admitted from config.json: the audio tower's geometry (chunks of 100 frames, windows of n_window_infer frames) and the Qwen3 language model's, its interleaved M-RoPE refused unless its sections span the head (audio positions are equal on all three axes, so it is plain RoPE). Every stored tensor checked by name, shape and dtype, none left over; the stored lm_head must be bit-equal to the tied embedding. WhisperFeatureExtractor's log-mel rows in float64, and the tower in float64 stage by stage, either exact or at torch's bf16 rounding points. The checkpoint ships no tokenizer.json; the shared tokenizer reads its slow export (#2225). tf-qwen3-asr-check compares weights, prompt ids, the reply's decode, mel rows and every tower stage with a case from tools/zig/qwen3_asr_case.py (the qwen-asr 0.0.6 package's transformers backend, hooked stage by stage). --- build.zig | 1 + tools/zig/qwen3_asr_case.py | 105 ++++++++ zig/build/qwen3_asr_host.zig | 22 ++ zig/qwen3_asr_check.zig | 147 +++++++++++ zig/src/families/qwen3_asr/case.zig | 122 ++++++++++ zig/src/families/qwen3_asr/chunks.zig | 78 ++++++ zig/src/families/qwen3_asr/config.zig | 181 ++++++++++++++ zig/src/families/qwen3_asr/config_test.zig | 46 ++++ zig/src/families/qwen3_asr/mel.zig | 140 +++++++++++ zig/src/families/qwen3_asr/names.zig | 129 ++++++++++ zig/src/families/qwen3_asr/prompt.zig | 50 ++++ zig/src/families/qwen3_asr/qwen3_asr.zig | 23 ++ zig/src/families/qwen3_asr/ref_ops.zig | 186 ++++++++++++++ zig/src/families/qwen3_asr/tower_ref.zig | 268 +++++++++++++++++++++ zig/src/families/qwen3_asr/wav.zig | 69 ++++++ 15 files changed, 1567 insertions(+) create mode 100644 tools/zig/qwen3_asr_case.py create mode 100644 zig/build/qwen3_asr_host.zig create mode 100644 zig/qwen3_asr_check.zig create mode 100644 zig/src/families/qwen3_asr/case.zig create mode 100644 zig/src/families/qwen3_asr/chunks.zig create mode 100644 zig/src/families/qwen3_asr/config.zig create mode 100644 zig/src/families/qwen3_asr/config_test.zig create mode 100644 zig/src/families/qwen3_asr/mel.zig create mode 100644 zig/src/families/qwen3_asr/names.zig create mode 100644 zig/src/families/qwen3_asr/prompt.zig create mode 100644 zig/src/families/qwen3_asr/qwen3_asr.zig create mode 100644 zig/src/families/qwen3_asr/ref_ops.zig create mode 100644 zig/src/families/qwen3_asr/tower_ref.zig create mode 100644 zig/src/families/qwen3_asr/wav.zig diff --git a/build.zig b/build.zig index b73b401db17..05aea4bcbd9 100644 --- a/build.zig +++ b/build.zig @@ -126,6 +126,7 @@ pub fn build(b: *std.Build) void { @import("zig/build/flashnext_budget.zig").steps(b, test_step); @import("zig/build/flashnext_batch_host.zig").tests(b, test_step); @import("zig/build/lfm3_host.zig").steps(b, test_step); + @import("zig/build/qwen3_asr_host.zig").steps(b, test_step); if (b.graph.host.result.os.tag == .macos) { const budget_mods = metalEngineModules(b, b.graph.host, .Debug, draft_ids); const budget_empty = b.addWriteFiles().add("budget-compile-only.metallib", ""); diff --git a/tools/zig/qwen3_asr_case.py b/tools/zig/qwen3_asr_case.py new file mode 100644 index 00000000000..bbaa998b369 --- /dev/null +++ b/tools/zig/qwen3_asr_case.py @@ -0,0 +1,105 @@ +"""Qwen3-ASR's per-stage tensors from qwen-asr 0.0.6's transformers backend: tf-qwen3-asr's reference case.""" +# usage: python3 -I tools/zig/qwen3_asr_case.py MODEL_DIR CLIP.wav OUT_DIR [--tokens N]; float32/int32 files a stage + +import argparse +import json +import os +import sys + +import numpy as np +import soundfile as sf +import torch + + +def save(out, manifest, name, t, kind="f32"): + a = t.detach().to(torch.float32 if kind == "f32" else torch.int32).cpu().numpy() + a.astype("= 0) @intCast(v.integer) else return error.BadCase; + try c.stages.put(a, e.key_ptr.*, .{ .shape = dims, .int = std.mem.eql(u8, kind.string, "i32") }); + } + if (doc.object.get("frames")) |f| c.frames = if (f == .integer and f.integer >= 0) @intCast(f.integer) else return error.BadCase; + if (doc.object.get("text")) |t| c.text = if (t == .string) t.string else return error.BadCase; + return c; + } + + pub fn deinit(c: *Case) void { + c.arena.deinit(); + } + + pub fn count(s: Stage) usize { + var n: usize = 1; + for (s.shape) |d| n *= d; + return n; + } + + fn bytes(c: *Case, gpa: std.mem.Allocator, name: []const u8, want_int: bool) !struct { Stage, []u8 } { + const s = c.stages.get(name) orelse return error.NoSuchStage; + if (s.int != want_int) return error.StageType; + var buf: [256]u8 = undefined; + const path = try std.fs.path.join(gpa, &.{ c.dir, try std.fmt.bufPrint(&buf, "{s}.bin", .{name}) }); + defer gpa.free(path); + const raw = try std.Io.Dir.cwd().readFileAlloc(c.io, path, gpa, .limited(1 << 32)); + if (raw.len != 4 * count(s)) { + gpa.free(raw); + return error.StageSize; + } + return .{ s, raw }; + } + + /// Stage `name`'s float32 values (the caller frees them). + pub fn floats(c: *Case, gpa: std.mem.Allocator, name: []const u8) ![]f32 { + _, const raw = try c.bytes(gpa, name, false); + defer gpa.free(raw); + const out = try gpa.alloc(f32, raw.len / 4); + for (out, 0..) |*o, i| o.* = @bitCast(std.mem.readInt(u32, raw[4 * i ..][0..4], .little)); + return out; + } + + /// Stage `name`'s int32 values as token ids. + pub fn ids(c: *Case, gpa: std.mem.Allocator, name: []const u8) ![]u32 { + _, const raw = try c.bytes(gpa, name, true); + defer gpa.free(raw); + const out = try gpa.alloc(u32, raw.len / 4); + for (out, 0..) |*o, i| o.* = std.mem.readInt(u32, raw[4 * i ..][0..4], .little); + return out; + } +}; + +/// How close `got` is to `want`: cosine, the worst absolute difference and its place, the norm of `want`. +pub const Match = struct { + cosine: f64, + worst: f64, + at: usize, + rms_want: f64, + rms_diff: f64, + + pub fn of(got: []const f64, want: []const f32) Match { + var dot: f64 = 0; + var gg: f64 = 0; + var ww: f64 = 0; + var dd: f64 = 0; + var m: Match = .{ .cosine = 0, .worst = 0, .at = 0, .rms_want = 0, .rms_diff = 0 }; + for (got, want, 0..) |g, w64, i| { + const w: f64 = w64; + dot += g * w; + gg += g * g; + ww += w * w; + const d = @abs(g - w); + dd += d * d; + if (d > m.worst or std.math.isNan(d)) { + m.worst = d; + m.at = i; + } + } + const n: f64 = @floatFromInt(@max(1, got.len)); + m.cosine = if (gg == 0 or ww == 0) @as(f64, if (gg == ww) 1 else 0) else dot / @sqrt(gg * ww); + m.rms_want = @sqrt(ww / n); + m.rms_diff = @sqrt(dd / n); + return m; + } +}; + +test "match: identical rows give cosine 1, a sign flip -1" { + const want = [_]f32{ 1, -2, 3 }; + const m = Match.of(&.{ 1, -2, 3 }, &want); + try std.testing.expectEqual(@as(f64, 0), m.worst); + try std.testing.expectApproxEqAbs(@as(f64, 1), m.cosine, 1e-15); + try std.testing.expectApproxEqAbs(@as(f64, -1), Match.of(&.{ -1, 2, -3 }, &want).cosine, 1e-15); +} diff --git a/zig/src/families/qwen3_asr/chunks.zig b/zig/src/families/qwen3_asr/chunks.zig new file mode 100644 index 00000000000..583055b0e9c --- /dev/null +++ b/zig/src/families/qwen3_asr/chunks.zig @@ -0,0 +1,78 @@ +//! The tower's chunk and window plan: 100-frame chunks through the convolutions, then attention over whole windows. +const std = @import("std"); +const Audio = @import("config.zig").Audio; + +/// Mel frames of `samples` 16 kHz samples: the STFT's centered frames less the last. +pub fn frames(samples: usize) usize { + return samples / @import("config.zig").hop; +} + +fn floorHalf(x: i64) i64 { + return @divFloor(x - 1, 2) + 1; +} + +/// Rows the convolutions leave of `len` frames: three stride-2 steps of the remainder, 13 a whole chunk. +pub fn rows(len: usize) usize { + const rem: i64 = @intCast(len % 100); + const tail = floorHalf(floorHalf(floorHalf(rem))); + return @as(usize, @intCast(tail)) + (len / 100) * 13; +} + +/// A clip's plan: its chunks' frames and rows, and the attention windows over the rows. +pub const Plan = struct { + frames: usize, + chunks: usize, + last_frames: usize, // the last chunk's frames (a full chunk when frames divide) + rows: usize, + chunk_rows: usize, // rows of the longest chunk: a row's position inside its chunk runs to this + window_rows: usize, // rows an attention window spans + + pub fn init(a: Audio, n: usize) error{EmptyClip}!Plan { + if (n == 0) return error.EmptyClip; + const cf = a.chunkFrames(); + const chunks = (n + cf - 1) / cf; + const last = if (n % cf == 0) cf else n % cf; + const longest = if (chunks > 1) rows(cf) else rows(last); + return .{ .frames = n, .chunks = chunks, .last_frames = last, .rows = rows(n), .chunk_rows = longest, .window_rows = longest * (a.window_infer / cf) }; + } + + /// Rows chunk `i` leaves. + pub fn rowsOf(p: Plan, i: usize) usize { + return rows(if (i + 1 == p.chunks) p.last_frames else 100); + } + + pub fn windows(p: Plan) usize { + return (p.rows + p.window_rows - 1) / p.window_rows; + } + + /// Window `w`'s first row and its rows. + pub fn window(p: Plan, w: usize) struct { start: usize, len: usize } { + const start = w * p.window_rows; + return .{ .start = start, .len = @min(p.window_rows, p.rows - start) }; + } +}; + +test "rows: the package's _get_feat_extract_output_lengths" { + // values printed by qwen-asr 0.0.6's formula for these frame counts + const cases = [_][2]usize{ .{ 1, 1 }, .{ 7, 1 }, .{ 8, 1 }, .{ 9, 2 }, .{ 99, 13 }, .{ 100, 13 }, .{ 101, 14 }, .{ 481, 63 }, .{ 585, 76 }, .{ 2940, 382 }, .{ 3000, 390 } }; + for (cases) |c| try std.testing.expectEqual(c[1], rows(c[0])); +} + +test "plan: chunks, the short last chunk, windows of eight chunks" { + const a: Audio = .{ .d = 896, .layers = 18, .heads = 14, .ffn = 3584, .mels = 128, .conv = 480, .out = 1024, .window = 50, .window_infer = 800, .positions = 1500, .conv_chunks = 500 }; + const p = try Plan.init(a, 2940); + try std.testing.expectEqual(@as(usize, 30), p.chunks); + try std.testing.expectEqual(@as(usize, 40), p.last_frames); + try std.testing.expectEqual(@as(usize, 382), p.rows); + try std.testing.expectEqual(@as(usize, 104), p.window_rows); + try std.testing.expectEqual(@as(usize, 4), p.windows()); + try std.testing.expectEqual(@as(usize, 70), p.window(3).len); + var sum: usize = 0; + for (0..p.chunks) |i| sum += p.rowsOf(i); + try std.testing.expectEqual(p.rows, sum); + const short = try Plan.init(a, 60); + try std.testing.expectEqual(@as(usize, 8), short.chunk_rows); + try std.testing.expectEqual(@as(usize, 64), short.window_rows); + try std.testing.expectEqual(@as(usize, 1), short.windows()); + try std.testing.expectError(error.EmptyClip, Plan.init(a, 0)); +} diff --git a/zig/src/families/qwen3_asr/config.zig b/zig/src/families/qwen3_asr/config.zig new file mode 100644 index 00000000000..d13d8174c89 --- /dev/null +++ b/zig/src/families/qwen3_asr/config.zig @@ -0,0 +1,181 @@ +//! Qwen3-ASR admission (0.6B and 1.7B): the audio tower's and the Qwen3 language model's geometry from config.json. +const std = @import("std"); + +/// The tower's audio as the package reads it: 16 kHz mono, 25 ms frames every 10 ms, 128 mel bins. +pub const sample_rate = 16000; +pub const n_fft = 400; +pub const hop = 160; +/// The three stride-2 convolutions' kernel: 3 x 3, padding 1. +pub const conv_taps = 3; + +pub const Audio = struct { + d: usize, // d_model + layers: usize, + heads: usize, + ffn: usize, + mels: usize, + conv: usize, // downsample_hidden_size + out: usize, // output_dim: the language model's width + window: usize, // n_window: half a chunk, in frames + window_infer: usize, // n_window_infer: frames an attention window spans + positions: usize, // max_source_positions + conv_chunks: usize, // conv_chunksize + + pub fn headDim(a: Audio) usize { + return a.d / a.heads; + } + + /// Mel bins after the three convolutions: ((m + 1) / 2 + 1) / 2 + 1) / 2. + pub fn convBins(a: Audio) usize { + return (((a.mels + 1) / 2 + 1) / 2 + 1) / 2; + } + + /// Frames a chunk holds: 2 n_window. + pub fn chunkFrames(a: Audio) usize { + return 2 * a.window; + } +}; + +pub const Text = struct { + hidden: usize, + layers: usize, + heads: usize, + kv_heads: usize, + head_dim: usize, + intermediate: usize, + vocab: usize, + eps: f32, + theta: f64, + context: usize, +}; + +pub const Config = struct { + audio: Audio, + text: Text, + audio_token: u32, + audio_start: u32, + audio_end: u32, +}; + +const Object = std.json.ObjectMap; + +fn object(v: ?std.json.Value) !Object { + const x = v orelse return error.BadQwen3AsrConfig; + return if (x == .object) x.object else error.BadQwen3AsrConfig; +} + +fn field(o: Object, key: []const u8) !std.json.Value { + return o.get(key) orelse error.BadQwen3AsrConfig; +} + +fn integer(o: Object, key: []const u8) !usize { + const v = try field(o, key); + if (v != .integer or v.integer < 1) return error.BadQwen3AsrConfig; + return std.math.cast(usize, v.integer) orelse error.BadQwen3AsrConfig; +} + +fn id(o: Object, key: []const u8) !u32 { + return std.math.cast(u32, try integer(o, key)) orelse error.BadQwen3AsrConfig; +} + +fn float(o: Object, key: []const u8) !f64 { + return switch (try field(o, key)) { + .integer => |i| @floatFromInt(i), + .float => |f| f, + else => error.BadQwen3AsrConfig, + }; +} + +fn expect(o: Object, key: []const u8, want: []const u8) !void { + const v = try field(o, key); + if (v != .string or !std.mem.eql(u8, v.string, want)) return error.UnsupportedQwen3AsrConfig; +} + +fn flag(o: Object, key: []const u8, want: bool) !void { + const v = o.get(key) orelse return; + if (v != .bool or v.bool != want) return error.UnsupportedQwen3AsrConfig; +} + +fn audio(o: Object) !Audio { + try expect(o, "model_type", "qwen3_asr_audio_encoder"); + try expect(o, "activation_function", "gelu"); + try flag(o, "scale_embedding", false); + const a: Audio = .{ + .d = try integer(o, "d_model"), + .layers = try integer(o, "encoder_layers"), + .heads = try integer(o, "encoder_attention_heads"), + .ffn = try integer(o, "encoder_ffn_dim"), + .mels = try integer(o, "num_mel_bins"), + .conv = try integer(o, "downsample_hidden_size"), + .out = try integer(o, "output_dim"), + .window = try integer(o, "n_window"), + .window_infer = try integer(o, "n_window_infer"), + .positions = try integer(o, "max_source_positions"), + .conv_chunks = try integer(o, "conv_chunksize"), + }; + if (a.d % a.heads != 0 or a.d % 8 != 0 or a.ffn % 8 != 0 or a.conv % 8 != 0) return error.UnsupportedQwen3AsrGeometry; + // the package's per-chunk lengths assume a chunk of 100 frames (13 rows) and windows of whole chunks + if (a.chunkFrames() != 100 or a.window_infer % a.chunkFrames() != 0) return error.UnsupportedQwen3AsrGeometry; + if (a.mels != 128) return error.UnsupportedQwen3AsrGeometry; + return a; +} + +fn text(o: Object) !Text { + try expect(o, "model_type", "qwen3"); + try expect(o, "hidden_act", "silu"); + try flag(o, "attention_bias", false); + try flag(o, "tie_word_embeddings", true); + const t: Text = .{ + .hidden = try integer(o, "hidden_size"), + .layers = try integer(o, "num_hidden_layers"), + .heads = try integer(o, "num_attention_heads"), + .kv_heads = try integer(o, "num_key_value_heads"), + .head_dim = try integer(o, "head_dim"), + .intermediate = try integer(o, "intermediate_size"), + .vocab = try integer(o, "vocab_size"), + .eps = @floatCast(try float(o, "rms_norm_eps")), + .theta = try float(o, "rope_theta"), + .context = try integer(o, "max_position_embeddings"), + }; + if (t.heads % t.kv_heads != 0 or t.head_dim % 2 != 0) return error.UnsupportedQwen3AsrGeometry; + try rope(try object(o.get("rope_scaling")), t.head_dim); + return t; +} + +/// The interleaved M-RoPE the config names: positions are equal on all three axes for audio, so it is plain RoPE. +fn rope(o: Object, head_dim: usize) !void { + try expect(o, "rope_type", "default"); + const v = try field(o, "mrope_section"); + if (v != .array) return error.BadQwen3AsrConfig; + var sum: usize = 0; + for (v.array.items) |x| { + if (x != .integer or x.integer < 0) return error.BadQwen3AsrConfig; + sum += @intCast(x.integer); + } + if (sum != head_dim / 2) return error.UnsupportedQwen3AsrRotary; +} + +/// The config of a Qwen3-ASR checkpoint folder's config.json text. +pub fn parse(gpa: std.mem.Allocator, json: []const u8) !Config { + const doc = try std.json.parseFromSlice(std.json.Value, gpa, json, .{}); + defer doc.deinit(); + const root = try object(doc.value); + try expect(root, "model_type", "qwen3_asr"); + const thinker = try object(root.get("thinker_config")); + return .{ + .audio = try audio(try object(thinker.get("audio_config"))), + .text = try text(try object(thinker.get("text_config"))), + .audio_token = try id(thinker, "audio_token_id"), + .audio_start = try id(thinker, "audio_start_token_id"), + .audio_end = try id(thinker, "audio_end_token_id"), + }; +} + +/// `dir`/config.json, parsed and admitted. +pub fn read(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !Config { + const path = try std.fs.path.join(gpa, &.{ dir, "config.json" }); + defer gpa.free(path); + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, gpa, .limited(1 << 22)); + defer gpa.free(bytes); + return parse(gpa, bytes); +} diff --git a/zig/src/families/qwen3_asr/config_test.zig b/zig/src/families/qwen3_asr/config_test.zig new file mode 100644 index 00000000000..2b9ea526b45 --- /dev/null +++ b/zig/src/families/qwen3_asr/config_test.zig @@ -0,0 +1,46 @@ +//! Config admission: the 0.6B's fields as released, and the refusals for what the tower and LM do not run. +const std = @import("std"); +const c = @import("config.zig"); + +const base = + \\{"model_type": "qwen3_asr", "thinker_config": {"audio_token_id": 151676, "audio_start_token_id": 151669, + \\ "audio_end_token_id": 151670, "audio_config": {"model_type": "qwen3_asr_audio_encoder", + \\ "activation_function": "gelu", "scale_embedding": false, "d_model": 896, "encoder_layers": 18, + \\ "encoder_attention_heads": 14, "encoder_ffn_dim": 3584, "num_mel_bins": 128, "downsample_hidden_size": 480, + \\ "output_dim": 1024, "n_window": 50, "n_window_infer": 800, "max_source_positions": 1500, "conv_chunksize": 500}, + \\ "text_config": {"model_type": "qwen3", "hidden_act": "silu", "attention_bias": false, "tie_word_embeddings": true, + \\ "hidden_size": 1024, "num_hidden_layers": 28, "num_attention_heads": 16, "num_key_value_heads": 8, "head_dim": 128, + \\ "intermediate_size": 3072, "vocab_size": 151936, "rms_norm_eps": 1e-06, "rope_theta": 1000000, + \\ "max_position_embeddings": 65536, "rope_scaling": {"rope_type": "default", "mrope_section": [24, 20, 20]}}}} +; + +fn swapped(a: std.mem.Allocator, from: []const u8, to: []const u8) ![]u8 { + return std.mem.replaceOwned(u8, a, base, from, to); +} + +test "the 0.6B: tower and LM geometry, chunk frames, mel bins after the convolutions" { + const cfg = try c.parse(std.testing.allocator, base); + try std.testing.expectEqual(@as(usize, 64), cfg.audio.headDim()); + try std.testing.expectEqual(@as(usize, 16), cfg.audio.convBins()); + try std.testing.expectEqual(@as(usize, 100), cfg.audio.chunkFrames()); + try std.testing.expectEqual(@as(usize, 8), cfg.text.kv_heads); + try std.testing.expectEqual(@as(f64, 1e6), cfg.text.theta); + try std.testing.expectEqual(@as(u32, 151676), cfg.audio_token); +} + +test "refusals: another activation, M-RoPE sections not spanning the head, biased attention, other mel bins" { + const a = std.testing.allocator; + const cases = [_][3][]const u8{ + .{ "\"activation_function\": \"gelu\"", "\"activation_function\": \"relu\"", "UnsupportedQwen3AsrConfig" }, + .{ "[24, 20, 20]", "[24, 20, 16]", "UnsupportedQwen3AsrRotary" }, + .{ "\"attention_bias\": false", "\"attention_bias\": true", "UnsupportedQwen3AsrConfig" }, + .{ "\"num_mel_bins\": 128", "\"num_mel_bins\": 80", "UnsupportedQwen3AsrGeometry" }, + .{ "\"n_window\": 50", "\"n_window\": 40", "UnsupportedQwen3AsrGeometry" }, + .{ "\"model_type\": \"qwen3_asr\"", "\"model_type\": \"qwen3\"", "UnsupportedQwen3AsrConfig" }, + }; + for (cases) |x| { + const text = try swapped(a, x[0], x[1]); + defer a.free(text); + if (c.parse(a, text)) |_| return error.TestExpectedError else |err| try std.testing.expectEqualStrings(x[2], @errorName(err)); + } +} diff --git a/zig/src/families/qwen3_asr/mel.zig b/zig/src/families/qwen3_asr/mel.zig new file mode 100644 index 00000000000..64b0bf00f00 --- /dev/null +++ b/zig/src/families/qwen3_asr/mel.zig @@ -0,0 +1,140 @@ +//! WhisperFeatureExtractor's log-mel rows in float64: a centered, reflect-padded STFT, slaney mel filters, log10. +const std = @import("std"); +const cfg = @import("config.zig"); + +const bins = cfg.n_fft / 2 + 1; + +fn hzToMel(f: f64) f64 { + const logstep = 27.0 / @log(6.4); + return if (f >= 1000.0) 15.0 + @log(f / 1000.0) * logstep else 3.0 * f / 200.0; +} + +fn melToHz(m: f64) f64 { + const logstep = @log(6.4) / 27.0; + return if (m >= 15.0) 1000.0 * @exp(logstep * (m - 15.0)) else 200.0 * m / 3.0; +} + +/// transformers' mel_filter_bank(201, mels, 0, 8000, 16000, "slaney", "slaney"): [bins][mels], float64. +pub fn filters(gpa: std.mem.Allocator, mels: usize) ![]f64 { + const out = try gpa.alloc(f64, bins * mels); + errdefer gpa.free(out); + const edges = try gpa.alloc(f64, mels + 2); + defer gpa.free(edges); + const lo = hzToMel(0); + const hi = hzToMel(8000); + for (edges, 0..) |*e, i| e.* = melToHz(lo + (hi - lo) * @as(f64, @floatFromInt(i)) / @as(f64, @floatFromInt(mels + 1))); + for (0..bins) |b| { + const f = @as(f64, @floatFromInt(cfg.sample_rate / 2)) * @as(f64, @floatFromInt(b)) / @as(f64, @floatFromInt(bins - 1)); + for (0..mels) |m| { + const down = -(edges[m] - f) / (edges[m + 1] - edges[m]); + const up = (edges[m + 2] - f) / (edges[m + 2] - edges[m + 1]); + const enorm = 2.0 / (edges[m + 2] - edges[m]); + out[b * mels + m] = @max(0.0, @min(down, up)) * enorm; + } + } + return out; +} + +/// The features of `x` (16 kHz samples): [mels][frames] float32, frames = len / 160. +pub const Features = struct { + data: []f32, + mels: usize, + frames: usize, + + pub fn deinit(f: *Features, gpa: std.mem.Allocator) void { + gpa.free(f.data); + f.* = undefined; + } + + pub fn at(f: Features, mel: usize, frame: usize) f32 { + return f.data[mel * f.frames + frame]; + } +}; + +/// Sample `i` of x reflect-padded by n_fft / 2 on each side (torch.stft's center=True, pad_mode="reflect"). +fn padded(x: []const f32, i: isize) f64 { + const n: isize = @intCast(x.len); + var j = i - cfg.n_fft / 2; + if (j < 0) j = -j; + if (j >= n) j = 2 * (n - 1) - j; + return x[@intCast(j)]; +} + +/// Log-mel features of `x`, as the package's processor gives them for one clip (no padding to 30 s). +pub fn features(gpa: std.mem.Allocator, x: []const f32, mels: usize) !Features { + if (x.len <= cfg.n_fft / 2) return error.AudioTooShort; + const n_frames = x.len / cfg.hop; + const fb = try filters(gpa, mels); + defer gpa.free(fb); + const window = try gpa.alloc(f64, cfg.n_fft); + defer gpa.free(window); + // torch.hann_window(400): periodic + for (window, 0..) |*w, i| w.* = 0.5 - 0.5 * @cos(2.0 * std.math.pi * @as(f64, @floatFromInt(i)) / cfg.n_fft); + const twiddle = try gpa.alloc([2]f64, cfg.n_fft); + defer gpa.free(twiddle); + for (twiddle, 0..) |*t, k| { + const a = -2.0 * std.math.pi * @as(f64, @floatFromInt(k)) / cfg.n_fft; + t.* = .{ @cos(a), @sin(a) }; + } + const logs = try gpa.alloc(f64, mels * n_frames); + defer gpa.free(logs); + var frame: [cfg.n_fft]f64 = undefined; + var power: [bins]f64 = undefined; + var top: f64 = -std.math.inf(f64); + for (0..n_frames) |t| { + for (&frame, 0..) |*v, i| v.* = padded(x, @intCast(t * cfg.hop + i)) * window[i]; + for (&power, 0..) |*p, b| { + var re: f64 = 0; + var im: f64 = 0; + for (frame, 0..) |v, i| { + const w = twiddle[(b * i) % cfg.n_fft]; + re += v * w[0]; + im += v * w[1]; + } + p.* = re * re + im * im; + } + for (0..mels) |m| { + var s: f64 = 0; + for (power, 0..) |p, b| s += fb[b * mels + m] * p; + const l = std.math.log10(@max(s, 1e-10)); + logs[m * n_frames + t] = l; + top = @max(top, l); + } + } + const out = try gpa.alloc(f32, mels * n_frames); + for (out, logs) |*o, l| o.* = @floatCast((@max(l, top - 8.0) + 4.0) / 4.0); + return .{ .data = out, .mels = mels, .frames = n_frames }; +} + +test "filters: slaney triangles, each mel's area-normalized peak" { + const fb = try filters(std.testing.allocator, 128); + defer std.testing.allocator.free(fb); + // bin 0 (0 Hz) is only in mel 0's lower edge, at its start: zero + try std.testing.expectEqual(@as(f64, 0), fb[0]); + var nonzero: usize = 0; + for (0..128) |m| { + var any = false; + for (0..bins) |b| any = any or fb[b * 128 + m] > 0; + nonzero += @intFromBool(any); + } + // 128 slaney mels over 201 bins: the lowest are narrower than a bin, so a few see no bin centre + try std.testing.expect(nonzero > 100); +} + +test "features: a 440 Hz tone peaks in the mel band that holds 440 Hz, frames = samples / 160" { + const a = std.testing.allocator; + const x = try a.alloc(f32, 16000); + defer a.free(x); + for (x, 0..) |*v, i| v.* = @floatCast(0.5 * @sin(2.0 * std.math.pi * 440.0 * @as(f64, @floatFromInt(i)) / 16000.0)); + var f = try features(a, x, 128); + defer f.deinit(a); + try std.testing.expectEqual(@as(usize, 100), f.frames); + var best: usize = 0; + for (0..128) |m| if (f.at(m, 50) > f.at(best, 50)) { + best = m; + }; + const lo = melToHz(hzToMel(0) + (hzToMel(8000) - hzToMel(0)) * @as(f64, @floatFromInt(best)) / 129.0); + const hi = melToHz(hzToMel(0) + (hzToMel(8000) - hzToMel(0)) * @as(f64, @floatFromInt(best + 2)) / 129.0); + try std.testing.expect(lo < 440.0 and 440.0 < hi); + try std.testing.expectError(error.AudioTooShort, features(a, x[0..200], 128)); +} diff --git a/zig/src/families/qwen3_asr/names.zig b/zig/src/families/qwen3_asr/names.zig new file mode 100644 index 00000000000..873636f7cf2 --- /dev/null +++ b/zig/src/families/qwen3_asr/names.zig @@ -0,0 +1,129 @@ +//! Every tensor a Qwen3-ASR checkpoint stores, by name and shape from its config: all bf16, none left unread. +const std = @import("std"); +const cfg = @import("config.zig"); + +pub const tower = "thinker.audio_tower."; +pub const lm = "thinker.model."; +pub const head = "thinker.lm_head.weight"; + +pub const Want = struct { + name: []const u8, + rank: u8, + shape: [4]usize, +}; + +fn put(list: *std.ArrayList(Want), arena: std.mem.Allocator, name: []const u8, shape: []const usize) !void { + var w: Want = .{ .name = name, .rank = @intCast(shape.len), .shape = .{ 0, 0, 0, 0 } }; + @memcpy(w.shape[0..shape.len], shape); + try list.append(arena, w); +} + +/// The audio tower's tensors. +fn towerNames(list: *std.ArrayList(Want), arena: std.mem.Allocator, a: cfg.Audio) !void { + const k = cfg.conv_taps; + try put(list, arena, tower ++ "conv2d1.weight", &.{ a.conv, 1, k, k }); + for ([_][]const u8{ "conv2d2.weight", "conv2d3.weight" }) |n| try put(list, arena, try std.mem.concat(arena, u8, &.{ tower, n }), &.{ a.conv, a.conv, k, k }); + for ([_][]const u8{ "conv2d1.bias", "conv2d2.bias", "conv2d3.bias" }) |n| try put(list, arena, try std.mem.concat(arena, u8, &.{ tower, n }), &.{a.conv}); + try put(list, arena, tower ++ "conv_out.weight", &.{ a.d, a.conv * a.convBins() }); + for (0..a.layers) |i| { + const p = try std.fmt.allocPrint(arena, tower ++ "layers.{d}.", .{i}); + const sq = &[_]usize{ a.d, a.d }; + for ([_][]const u8{ "q_proj", "k_proj", "v_proj", "out_proj" }) |n| { + try put(list, arena, try std.mem.concat(arena, u8, &.{ p, "self_attn.", n, ".weight" }), sq); + try put(list, arena, try std.mem.concat(arena, u8, &.{ p, "self_attn.", n, ".bias" }), &.{a.d}); + } + for ([_][]const u8{ "self_attn_layer_norm", "final_layer_norm" }) |n| for ([_][]const u8{ ".weight", ".bias" }) |s| + try put(list, arena, try std.mem.concat(arena, u8, &.{ p, n, s }), &.{a.d}); + try put(list, arena, try std.mem.concat(arena, u8, &.{ p, "fc1.weight" }), &.{ a.ffn, a.d }); + try put(list, arena, try std.mem.concat(arena, u8, &.{ p, "fc1.bias" }), &.{a.ffn}); + try put(list, arena, try std.mem.concat(arena, u8, &.{ p, "fc2.weight" }), &.{ a.d, a.ffn }); + try put(list, arena, try std.mem.concat(arena, u8, &.{ p, "fc2.bias" }), &.{a.d}); + } + try put(list, arena, tower ++ "ln_post.weight", &.{a.d}); + try put(list, arena, tower ++ "ln_post.bias", &.{a.d}); + try put(list, arena, tower ++ "proj1.weight", &.{ a.d, a.d }); + try put(list, arena, tower ++ "proj1.bias", &.{a.d}); + try put(list, arena, tower ++ "proj2.weight", &.{ a.out, a.d }); + try put(list, arena, tower ++ "proj2.bias", &.{a.out}); +} + +/// The language model's tensors, and the stored head (bit-equal to the tied embedding, checked at load). +fn lmNames(list: *std.ArrayList(Want), arena: std.mem.Allocator, t: cfg.Text) !void { + const qd = t.heads * t.head_dim; + const kvd = t.kv_heads * t.head_dim; + try put(list, arena, lm ++ "embed_tokens.weight", &.{ t.vocab, t.hidden }); + try put(list, arena, head, &.{ t.vocab, t.hidden }); + try put(list, arena, lm ++ "norm.weight", &.{t.hidden}); + for (0..t.layers) |i| { + const p = try std.fmt.allocPrint(arena, lm ++ "layers.{d}.", .{i}); + const parts = .{ + .{ "input_layernorm.weight", &[_]usize{t.hidden} }, .{ "post_attention_layernorm.weight", &[_]usize{t.hidden} }, + .{ "self_attn.q_proj.weight", &[_]usize{ qd, t.hidden } }, .{ "self_attn.k_proj.weight", &[_]usize{ kvd, t.hidden } }, + .{ "self_attn.v_proj.weight", &[_]usize{ kvd, t.hidden } }, .{ "self_attn.o_proj.weight", &[_]usize{ t.hidden, qd } }, + .{ "self_attn.q_norm.weight", &[_]usize{t.head_dim} }, .{ "self_attn.k_norm.weight", &[_]usize{t.head_dim} }, + .{ "mlp.gate_proj.weight", &[_]usize{ t.intermediate, t.hidden } }, .{ "mlp.up_proj.weight", &[_]usize{ t.intermediate, t.hidden } }, + .{ "mlp.down_proj.weight", &[_]usize{ t.hidden, t.intermediate } }, + }; + inline for (parts) |x| try put(list, arena, try std.mem.concat(arena, u8, &.{ p, x[0] }), x[1]); + } +} + +/// Every tensor `c` admits, names in `arena`. +pub fn all(arena: std.mem.Allocator, c: cfg.Config) ![]Want { + var list: std.ArrayList(Want) = .empty; + try towerNames(&list, arena, c.audio); + try lmNames(&list, arena, c.text); + return list.items; +} + +/// A stored tensor as its header names it. +pub const Have = struct { name: []const u8, bf16: bool, shape: []const usize }; + +/// Every wanted tensor present once at its shape in bf16, and nothing else stored; the first problem by name. +pub fn validate(arena: std.mem.Allocator, c: cfg.Config, have: []const Have, problem: *[]const u8) !void { + var by: std.StringHashMapUnmanaged(Have) = .empty; + for (have) |h| if (try by.fetchPut(arena, h.name, h) != null) { + problem.* = h.name; + return error.DuplicateTensor; + }; + const want = try all(arena, c); + for (want) |w| { + problem.* = w.name; + const h = by.get(w.name) orelse return error.MissingTensor; + if (!h.bf16) return error.UnexpectedDtype; + if (!std.mem.eql(usize, h.shape, w.shape[0..w.rank])) return error.UnexpectedShape; + } + if (have.len != want.len) { + var seen: std.StringHashMapUnmanaged(void) = .empty; + for (want) |w| try seen.put(arena, w.name, {}); + for (have) |h| if (!seen.contains(h.name)) { + problem.* = h.name; + break; + }; + return error.UnexpectedTensor; + } +} + +test "names: the 0.6B's 612 tensors" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const c: cfg.Config = .{ + .audio = .{ .d = 896, .layers = 18, .heads = 14, .ffn = 3584, .mels = 128, .conv = 480, .out = 1024, .window = 50, .window_infer = 800, .positions = 1500, .conv_chunks = 500 }, + .text = .{ .hidden = 1024, .layers = 28, .heads = 16, .kv_heads = 8, .head_dim = 128, .intermediate = 3072, .vocab = 151936, .eps = 1e-6, .theta = 1e6, .context = 65536 }, + .audio_token = 151676, + .audio_start = 151669, + .audio_end = 151670, + }; + const w = try all(arena.allocator(), c); + try std.testing.expectEqual(@as(usize, 612), w.len); + try std.testing.expectEqual(@as(usize, 7680), w[6].shape[1]); + var have = try arena.allocator().alloc(Have, w.len + 1); + for (w, 0..) |*x, i| have[i] = .{ .name = x.name, .bf16 = true, .shape = x.shape[0..x.rank] }; + var problem: []const u8 = ""; + try validate(arena.allocator(), c, have[0..w.len], &problem); + have[w.len] = .{ .name = "thinker.extra", .bf16 = true, .shape = &.{1} }; + try std.testing.expectError(error.UnexpectedTensor, validate(arena.allocator(), c, have, &problem)); + try std.testing.expectEqualStrings("thinker.extra", problem); + have[3].bf16 = false; + try std.testing.expectError(error.UnexpectedDtype, validate(arena.allocator(), c, have[0..w.len], &problem)); +} diff --git a/zig/src/families/qwen3_asr/prompt.zig b/zig/src/families/qwen3_asr/prompt.zig new file mode 100644 index 00000000000..c7ab065dc7b --- /dev/null +++ b/zig/src/families/qwen3_asr/prompt.zig @@ -0,0 +1,50 @@ +//! The package's ASR prompt (chat_template.json with one audio part) and the reply's "language X" split. +const std = @import("std"); + +pub const audio_pad = "<|audio_pad|>"; +pub const asr_text = ""; + +/// The prompt text for a clip of `rows` audio rows: an empty system turn, the audio, the assistant's turn opened. +pub fn text(gpa: std.mem.Allocator, rows: usize, context: []const u8, language: ?[]const u8) ![]u8 { + var out: std.ArrayList(u8) = .empty; + errdefer out.deinit(gpa); + try out.appendSlice(gpa, "<|im_start|>system\n"); + try out.appendSlice(gpa, context); + try out.appendSlice(gpa, "<|im_end|>\n<|im_start|>user\n<|audio_start|>"); + for (0..rows) |_| try out.appendSlice(gpa, audio_pad); + try out.appendSlice(gpa, "<|audio_end|><|im_end|>\n<|im_start|>assistant\n"); + if (language) |l| { + try out.appendSlice(gpa, "language "); + try out.appendSlice(gpa, l); + try out.appendSlice(gpa, asr_text); + } + return out.toOwnedSlice(gpa); +} + +/// A reply split as parse_asr_output splits it: "language Xbody" gives X and body, else no language. +pub fn split(reply: []const u8) struct { language: []const u8, body: []const u8 } { + const s = std.mem.trim(u8, reply, " \t\r\n"); + const at = std.mem.indexOf(u8, s, asr_text) orelse return .{ .language = "", .body = s }; + const meta = std.mem.trim(u8, s[0..at], " \t\r\n"); + const lang = if (std.mem.startsWith(u8, meta, "language ")) std.mem.trim(u8, meta["language ".len..], " ") else meta; + if (std.mem.eql(u8, lang, "None")) return .{ .language = "", .body = "" }; + return .{ .language = lang, .body = std.mem.trim(u8, s[at + asr_text.len ..], " \t\r\n") }; +} + +test "text: the template's turns around the audio rows, and a forced language" { + const a = std.testing.allocator; + const t = try text(a, 2, "", null); + defer a.free(t); + try std.testing.expectEqualStrings("<|im_start|>system\n<|im_end|>\n<|im_start|>user\n<|audio_start|><|audio_pad|><|audio_pad|><|audio_end|><|im_end|>\n<|im_start|>assistant\n", t); + const f = try text(a, 0, "", "English"); + defer a.free(f); + try std.testing.expect(std.mem.endsWith(u8, f, "assistant\nlanguage English")); +} + +test "split: language and body, and the silent clip" { + const s = split("language EnglishMr. Quilter is the apostle."); + try std.testing.expectEqualStrings("English", s.language); + try std.testing.expectEqualStrings("Mr. Quilter is the apostle.", s.body); + try std.testing.expectEqualStrings("", split("language None").body); + try std.testing.expectEqualStrings("plain", split(" plain ").body); +} diff --git a/zig/src/families/qwen3_asr/qwen3_asr.zig b/zig/src/families/qwen3_asr/qwen3_asr.zig new file mode 100644 index 00000000000..62dcc2ac025 --- /dev/null +++ b/zig/src/families/qwen3_asr/qwen3_asr.zig @@ -0,0 +1,23 @@ +//! Qwen3-ASR (0.6B, 1.7B): the audio tower and Qwen3 language model's host parts; CUDA runs them in cuda.zig. +pub const config = @import("config.zig"); +pub const chunks = @import("chunks.zig"); +pub const mel = @import("mel.zig"); +pub const wav = @import("wav.zig"); +pub const names = @import("names.zig"); +pub const ref_ops = @import("ref_ops.zig"); +pub const tower_ref = @import("tower_ref.zig"); +pub const case = @import("case.zig"); +pub const prompt = @import("prompt.zig"); + +test { + _ = config; + _ = chunks; + _ = mel; + _ = wav; + _ = names; + _ = ref_ops; + _ = tower_ref; + _ = case; + _ = prompt; + _ = @import("config_test.zig"); +} diff --git a/zig/src/families/qwen3_asr/ref_ops.zig b/zig/src/families/qwen3_asr/ref_ops.zig new file mode 100644 index 00000000000..89c18bbd587 --- /dev/null +++ b/zig/src/families/qwen3_asr/ref_ops.zig @@ -0,0 +1,186 @@ +//! The tower reference's float64 operators: torch's Linear, LayerNorm, exact GELU, attention, each row-parallel. +const std = @import("std"); + +/// A stored bf16 value widened. +pub fn widen(bits: u16) f64 { + return @as(f32, @bitCast(@as(u32, bits) << 16)); +} + +/// x rounded to fp32, then to bf16 (nearest, ties to even), as a torch bf16 op stores its result. +pub fn bf16(x: f64) f64 { + const f: f32 = @floatCast(x); + const u: u32 = @bitCast(f); + if (std.math.isNan(f)) return f; + const r = u + 0x7fff + ((u >> 16) & 1); + return @as(f32, @bitCast(r & 0xffff0000)); +} + +/// Rounding points: `exact` keeps every value in float64; `torch` rounds where a torch bf16 forward stores a tensor. +pub const Points = enum { exact, torch }; + +pub fn round(p: Points, x: f64) f64 { + return if (p == .torch) bf16(x) else x; +} + +pub fn roundAll(p: Points, xs: []f64) void { + if (p == .torch) for (xs) |*x| { + x.* = bf16(x.*); + }; +} + +/// A bf16 tensor's values, widened. +pub fn values(gpa: std.mem.Allocator, bytes: []const u8) ![]f64 { + const out = try gpa.alloc(f64, bytes.len / 2); + for (out, 0..) |*o, i| o.* = widen(std.mem.readInt(u16, bytes[2 * i ..][0..2], .little)); + return out; +} + +fn threads() usize { + return @min(std.Thread.getCpuCount() catch 1, 16); +} + +/// `job(ctx, lo, hi)` over [0, n) in contiguous slices, one a thread. +pub fn parallel(n: usize, ctx: anytype, comptime job: fn (@TypeOf(ctx), usize, usize) void) void { + const t = @min(threads(), @max(1, n / 4)); + if (t <= 1) return job(ctx, 0, n); + var pool: [16]?std.Thread = @splat(null); + const step = (n + t - 1) / t; + for (0..t) |i| { + const lo = i * step; + const hi = @min(n, lo + step); + if (lo >= hi) break; + pool[i] = std.Thread.spawn(.{}, job, .{ ctx, lo, hi }) catch { + job(ctx, lo, hi); + continue; + }; + } + for (pool) |th| if (th) |h| h.join(); +} + +const LinearJob = struct { y: []f64, x: []const f64, w: []const f64, b: ?[]const f64, n: usize, k: usize }; + +fn linearRows(j: *const LinearJob, lo: usize, hi: usize) void { + for (lo..hi) |r| { + const xr = j.x[r * j.k ..][0..j.k]; + for (0..j.n) |o| { + const wr = j.w[o * j.k ..][0..j.k]; + var s: f64 = if (j.b) |b| b[o] else 0; + for (xr, wr) |a, c| s += a * c; + j.y[r * j.n + o] = s; + } + } +} + +/// y [rows, n] = x [rows, k] . w [n, k]^T + b. +pub fn linear(y: []f64, x: []const f64, w: []const f64, b: ?[]const f64, rows: usize, n: usize, k: usize) void { + const j: LinearJob = .{ .y = y, .x = x, .w = w, .b = b, .n = n, .k = k }; + parallel(rows, &j, linearRows); +} + +/// torch's LayerNorm over rows of `width`, eps 1e-5, in place. +pub fn layerNorm(x: []f64, w: []const f64, b: []const f64, width: usize) void { + var r: usize = 0; + while (r < x.len) : (r += width) { + const row = x[r..][0..width]; + var mean: f64 = 0; + for (row) |v| mean += v; + mean /= @floatFromInt(width); + var vr: f64 = 0; + for (row) |v| vr += (v - mean) * (v - mean); + vr /= @floatFromInt(width); + const inv = 1.0 / @sqrt(vr + 1e-5); + for (row, w, b) |*v, g, c| v.* = (v.* - mean) * inv * g + c; + } +} + +/// torch's exact GELU: x Phi(x). +pub fn gelu(x: f64) f64 { + return 0.5 * x * (1.0 + erf(x / std.math.sqrt2)); +} + +/// erf by its Taylor series near 0 and its continued fraction from 2 (float64 to a few ulps). +pub fn erf(x: f64) f64 { + const ax = @abs(x); + if (ax < 2.0) { + var term = ax; + var sum = ax; + var n: f64 = 0; + while (n < 200) : (n += 1) { + term *= -ax * ax / (n + 1); + const add = term / (2 * n + 3); + sum += add; + if (@abs(add) < 1e-17 * @abs(sum)) break; + } + const r = 2.0 / @sqrt(std.math.pi) * sum; + return if (x < 0) -r else r; + } + // erfc(x) = exp(-x^2) / (x sqrt(pi)) / (1 + 1/(2x^2) / (1 + 2/(2x^2) / ...)), Lentz's evaluation + var f: f64 = ax; + var n: f64 = 200; + while (n >= 1) : (n -= 1) f = ax + (n / 2.0) / f; + const erfc = @exp(-ax * ax) / @sqrt(std.math.pi) / f; + return if (x < 0) erfc - 1.0 else 1.0 - erfc; +} + +const AttnJob = struct { out: []f64, qkv: []const f64, start: usize, len: usize, heads: usize, dim: usize, scale: f64 }; + +fn attnRows(j: *const AttnJob, lo: usize, hi: usize) void { + const d = j.heads * j.dim; + var p: [2048]f64 = undefined; + for (lo..hi) |i| { + const r = j.start + i; + for (0..j.heads) |h| { + const q = j.qkv[r * 3 * d + h * j.dim ..][0..j.dim]; + var top: f64 = -std.math.inf(f64); + for (0..j.len) |t| { + const k = j.qkv[(j.start + t) * 3 * d + d + h * j.dim ..][0..j.dim]; + var s: f64 = 0; + for (q, k) |a, b| s += a * b; + p[t] = s * j.scale; + top = @max(top, p[t]); + } + var den: f64 = 0; + for (p[0..j.len]) |*v| { + v.* = @exp(v.* - top); + den += v.*; + } + const o = j.out[r * d + h * j.dim ..][0..j.dim]; + @memset(o, 0); + for (0..j.len) |t| { + const v = j.qkv[(j.start + t) * 3 * d + 2 * d + h * j.dim ..][0..j.dim]; + const wt = p[t] / den; + for (o, v) |*a, b| a.* += wt * b; + } + } + } +} + +/// Bidirectional attention of rows [start, start + len) over themselves; qkv rows are [q | k | v], heads by head. +pub fn attention(out: []f64, qkv: []const f64, start: usize, len: usize, heads: usize, dim: usize) !void { + if (len > 2048) return error.AttentionWindow; + const j: AttnJob = .{ .out = out, .qkv = qkv, .start = start, .len = len, .heads = heads, .dim = dim, .scale = 1.0 / @sqrt(@as(f64, @floatFromInt(dim))) }; + parallel(len, &j, attnRows); +} + +test "bf16: ties to even, values kept" { + try std.testing.expectEqual(@as(f64, 1.0), bf16(1.0 + 1.0 / 256.0)); + try std.testing.expectEqual(@as(f64, 1.0 + 1.0 / 64.0), bf16(1.0 + 3.0 / 256.0)); + try std.testing.expectEqual(@as(f64, -2.5), bf16(-2.5)); +} + +test "erf: against known values, odd" { + const cases = [_][2]f64{ .{ 0.5, 0.5204998778130465 }, .{ 1.0, 0.8427007929497149 }, .{ 2.5, 0.9995930479825550 }, .{ 3.5, 0.9999992569016276 } }; + for (cases) |c| { + try std.testing.expectApproxEqAbs(c[1], erf(c[0]), 1e-13); + try std.testing.expectApproxEqAbs(-c[1], erf(-c[0]), 1e-13); + } +} + +test "linear and layerNorm: a hand-sized case" { + var y: [2]f64 = undefined; + linear(&y, &.{ 1, 2 }, &.{ 3, 4, 5, 6 }, &.{ 0.5, -1 }, 1, 2, 2); + try std.testing.expectEqualSlices(f64, &.{ 11.5, 16 }, &y); + var x = [_]f64{ 1, 3 }; + layerNorm(&x, &.{ 1, 1 }, &.{ 0, 0 }, 2); + try std.testing.expectApproxEqAbs(@as(f64, -1), x[0], 1e-5); +} diff --git a/zig/src/families/qwen3_asr/tower_ref.zig b/zig/src/families/qwen3_asr/tower_ref.zig new file mode 100644 index 00000000000..b1d50509c40 --- /dev/null +++ b/zig/src/families/qwen3_asr/tower_ref.zig @@ -0,0 +1,268 @@ +//! The audio tower in float64, stage by stage as the package's Qwen3ASRAudioEncoder runs it: the check's reference. +const std = @import("std"); +const cfg = @import("config.zig"); +const chunks = @import("chunks.zig"); +const mel = @import("mel.zig"); +const ops = @import("ref_ops.zig"); +const names = @import("names.zig"); + +/// The tower's bf16 tensors by name (a mapped checkpoint), widened on use. +pub const Source = struct { + ctx: *anyopaque, + get: *const fn (ctx: *anyopaque, name: []const u8) ?[]const u8, + + fn take(s: Source, gpa: std.mem.Allocator, name: []const u8) ![]f64 { + const bytes = s.get(s.ctx, name) orelse return error.MissingTensor; + return ops.values(gpa, bytes); + } +}; + +/// Where each stage goes: `values` are the stage's elements from `offset` on, in the package's layout. +pub const Sink = struct { + ctx: *anyopaque, + put: *const fn (ctx: *anyopaque, stage: []const u8, offset: usize, values: []const f64) anyerror!void, +}; + +/// A conv over one chunk: x [fi][ti][ci] channels last, to y [fo][to][co] with its bias, rounded (GELU follows). +fn conv(gpa: std.mem.Allocator, p: ops.Points, w: []const f64, b: []const f64, x: []const f64, fi: usize, ti: usize, ci: usize, co: usize) ![]f64 { + const fo = (fi - 1) / 2 + 1; + const to = (ti - 1) / 2 + 1; + const k = ci * 9; + const cols = try gpa.alloc(f64, fo * to * k); + defer gpa.free(cols); + for (0..fo) |f| for (0..to) |t| { + const row = cols[(f * to + t) * k ..][0..k]; + for (0..ci) |c| for (0..3) |kh| for (0..3) |kw| { + const sf = @as(isize, @intCast(2 * f + kh)) - 1; + const st = @as(isize, @intCast(2 * t + kw)) - 1; + const inside = sf >= 0 and st >= 0 and sf < fi and st < ti; + row[c * 9 + kh * 3 + kw] = if (inside) x[(@as(usize, @intCast(sf)) * ti + @as(usize, @intCast(st))) * ci + c] else 0; + }; + }; + const y = try gpa.alloc(f64, fo * to * co); + ops.linear(y, cols, w, b, fo * to, co, k); + ops.roundAll(p, y); + return y; +} + +fn geluAll(p: ops.Points, y: []f64) void { + for (y) |*v| v.* = ops.round(p, ops.gelu(v.*)); +} + +/// A channels-last chunk [f][t][c] in the export's [c][f][t] order. +fn channelsFirst(gpa: std.mem.Allocator, x: []const f64, f: usize, t: usize, c: usize) ![]f64 { + const out = try gpa.alloc(f64, x.len); + for (0..f) |i| for (0..t) |j| for (0..c) |k| { + out[(k * f + i) * t + j] = x[(i * t + j) * c + k]; + }; + return out; +} + +/// A conv's output to the sink (the package's hook sees it before the GELU), then the GELU in place. +fn tap(gpa: std.mem.Allocator, sink: Sink, name: []const u8, n: usize, y: []f64, s: [2]usize, co: usize, p: ops.Points) !void { + const cfirst = try channelsFirst(gpa, y, s[0], s[1], co); + defer gpa.free(cfirst); + try sink.put(sink.ctx, name, n * cfirst.len, cfirst); + geluAll(p, y); +} + +/// The sinusoid table's first `rows` rows [rows][d]: sin on the first half, cos on the second, as the package has it. +pub fn positions(gpa: std.mem.Allocator, p: ops.Points, rows: usize, d: usize) ![]f64 { + const out = try gpa.alloc(f64, rows * d); + const half = d / 2; + const inc = @log(10000.0) / @as(f64, @floatFromInt(half - 1)); + for (0..rows) |r| for (0..half) |i| { + const scaled: f64 = if (p == .torch) blk: { + const inv: f32 = @exp(@as(f32, @floatCast(-inc * @as(f64, @floatFromInt(i))))); + break :blk @as(f32, @floatFromInt(r)) * inv; + } else @as(f64, @floatFromInt(r)) * @exp(-inc * @as(f64, @floatFromInt(i))); + const s: f64 = if (p == .torch) @sin(@as(f32, @floatCast(scaled))) else @sin(scaled); + const c: f64 = if (p == .torch) @cos(@as(f32, @floatCast(scaled))) else @cos(scaled); + out[r * d + i] = ops.round(p, s); + out[r * d + half + i] = ops.round(p, c); + }; + return out; +} + +/// The convolutions and conv_out over every chunk: the tower's input rows [plan.rows][d], positions added. +fn front(gpa: std.mem.Allocator, a: cfg.Audio, p: ops.Points, src: Source, feats: mel.Features, plan: chunks.Plan, sink: Sink) ![]f64 { + const t = names.tower; + const w1 = try src.take(gpa, t ++ "conv2d1.weight"); + defer gpa.free(w1); + const b1 = try src.take(gpa, t ++ "conv2d1.bias"); + defer gpa.free(b1); + const w2 = try src.take(gpa, t ++ "conv2d2.weight"); + defer gpa.free(w2); + const b2 = try src.take(gpa, t ++ "conv2d2.bias"); + defer gpa.free(b2); + const w3 = try src.take(gpa, t ++ "conv2d3.weight"); + defer gpa.free(w3); + const b3 = try src.take(gpa, t ++ "conv2d3.bias"); + defer gpa.free(b3); + const wo = try src.take(gpa, t ++ "conv_out.weight"); + defer gpa.free(wo); + const cf = a.chunkFrames(); + const bins = a.convBins(); + const crow = chunks.rows(cf); + const pos = try positions(gpa, p, crow, a.d); + defer gpa.free(pos); + const out = try gpa.alloc(f64, plan.rows * a.d); + errdefer gpa.free(out); + const input = try gpa.alloc(f64, a.mels * cf); + defer gpa.free(input); + const flat = try gpa.alloc(f64, crow * a.conv * bins); + defer gpa.free(flat); + const emb = try gpa.alloc(f64, crow * a.d); + defer gpa.free(emb); + var row: usize = 0; + for (0..plan.chunks) |n| { + for (0..a.mels) |m| for (0..cf) |j| { + const fr = n * cf + j; + input[m * cf + j] = if (fr < feats.frames) ops.round(p, feats.at(m, fr)) else 0; + }; + const s1 = [3]usize{ a.mels, cf, 1 }; + const y1 = try conv(gpa, p, w1, b1, input, s1[0], s1[1], s1[2], a.conv); + defer gpa.free(y1); + const s2 = [2]usize{ (s1[0] - 1) / 2 + 1, (s1[1] - 1) / 2 + 1 }; + try tap(gpa, sink, "conv1", n, y1, s2, a.conv, p); + const y2 = try conv(gpa, p, w2, b2, y1, s2[0], s2[1], a.conv, a.conv); + defer gpa.free(y2); + const s3 = [2]usize{ (s2[0] - 1) / 2 + 1, (s2[1] - 1) / 2 + 1 }; + try tap(gpa, sink, "conv2", n, y2, s3, a.conv, p); + const y3 = try conv(gpa, p, w3, b3, y2, s3[0], s3[1], a.conv, a.conv); + defer gpa.free(y3); + const s4 = [2]usize{ (s3[0] - 1) / 2 + 1, (s3[1] - 1) / 2 + 1 }; + try tap(gpa, sink, "conv3", n, y3, s4, a.conv, p); + if (s4[0] != bins or s4[1] != crow) return error.TowerShape; + for (0..crow) |tt| for (0..a.conv) |c| for (0..bins) |f| { + flat[tt * a.conv * bins + c * bins + f] = y3[(f * crow + tt) * a.conv + c]; + }; + ops.linear(emb, flat, wo, null, crow, a.d, a.conv * bins); + ops.roundAll(p, emb); + try sink.put(sink.ctx, "conv_out", n * emb.len, emb); + for (emb, 0..) |*v, i| v.* = ops.round(p, v.* + pos[i]); + const keep = plan.rowsOf(n); + @memcpy(out[row * a.d ..][0 .. keep * a.d], emb[0 .. keep * a.d]); + row += keep; + } + return out; +} + +/// One encoder layer over the rows x [rows][d], in place, attention within the plan's windows. +fn layer(gpa: std.mem.Allocator, a: cfg.Audio, p: ops.Points, src: Source, i: usize, x: []f64, plan: chunks.Plan) !void { + var buf: [128]u8 = undefined; + const W = struct { + fn get(s: Source, g: std.mem.Allocator, b: []u8, li: usize, n: []const u8) ![]f64 { + return s.take(g, try std.fmt.bufPrint(b, names.tower ++ "layers.{d}.{s}", .{ li, n })); + } + }; + const rows = plan.rows; + const d = a.d; + const h = try gpa.alloc(f64, rows * d); + defer gpa.free(h); + const qkv = try gpa.alloc(f64, rows * 3 * d); + defer gpa.free(qkv); + const att = try gpa.alloc(f64, rows * d); + defer gpa.free(att); + const wide = try gpa.alloc(f64, rows * a.ffn); + defer gpa.free(wide); + { + const ln_w = try W.get(src, gpa, &buf, i, "self_attn_layer_norm.weight"); + defer gpa.free(ln_w); + const ln_b = try W.get(src, gpa, &buf, i, "self_attn_layer_norm.bias"); + defer gpa.free(ln_b); + @memcpy(h, x); + ops.layerNorm(h, ln_w, ln_b, d); + ops.roundAll(p, h); + } + const proj = try gpa.alloc(f64, rows * d); + defer gpa.free(proj); + for ([_][]const u8{ "q_proj", "k_proj", "v_proj" }, 0..) |n, part| { + var nb: [48]u8 = undefined; + const w = try W.get(src, gpa, &buf, i, try std.fmt.bufPrint(&nb, "self_attn.{s}.weight", .{n})); + defer gpa.free(w); + const b = try W.get(src, gpa, &buf, i, try std.fmt.bufPrint(&nb, "self_attn.{s}.bias", .{n})); + defer gpa.free(b); + ops.linear(proj, h, w, b, rows, d, d); + for (0..rows) |r| for (0..d) |c| { + qkv[r * 3 * d + part * d + c] = ops.round(p, proj[r * d + c]); + }; + } + for (0..plan.windows()) |wi| { + const win = plan.window(wi); + try ops.attention(att, qkv, win.start, win.len, a.heads, a.headDim()); + } + ops.roundAll(p, att); + try addLinear(gpa, p, src, &buf, i, "self_attn.out_proj", x, att, rows, d, d); + { + const ln_w = try W.get(src, gpa, &buf, i, "final_layer_norm.weight"); + defer gpa.free(ln_w); + const ln_b = try W.get(src, gpa, &buf, i, "final_layer_norm.bias"); + defer gpa.free(ln_b); + @memcpy(h, x); + ops.layerNorm(h, ln_w, ln_b, d); + ops.roundAll(p, h); + } + { + const w = try W.get(src, gpa, &buf, i, "fc1.weight"); + defer gpa.free(w); + const b = try W.get(src, gpa, &buf, i, "fc1.bias"); + defer gpa.free(b); + ops.linear(wide, h, w, b, rows, a.ffn, d); + for (wide) |*v| v.* = ops.round(p, ops.gelu(ops.round(p, v.*))); + } + try addLinear(gpa, p, src, &buf, i, "fc2", x, wide, rows, d, a.ffn); +} + +/// x = round(x + round(in . w^T + b)) for layer i's Linear `name`. +fn addLinear(gpa: std.mem.Allocator, p: ops.Points, src: Source, buf: []u8, i: usize, name: []const u8, x: []f64, in: []const f64, rows: usize, n: usize, k: usize) !void { + const w = try src.take(gpa, try std.fmt.bufPrint(buf, names.tower ++ "layers.{d}.{s}.weight", .{ i, name })); + defer gpa.free(w); + const b = try src.take(gpa, try std.fmt.bufPrint(buf, names.tower ++ "layers.{d}.{s}.bias", .{ i, name })); + defer gpa.free(b); + const y = try gpa.alloc(f64, rows * n); + defer gpa.free(y); + ops.linear(y, in, w, b, rows, n, k); + for (x, y) |*v, o| v.* = ops.round(p, v.* + ops.round(p, o)); +} + +/// The tower over `feats`: every stage to `sink`, the audio rows [plan.rows][out] returned. +pub fn run(gpa: std.mem.Allocator, a: cfg.Audio, p: ops.Points, src: Source, feats: mel.Features, sink: Sink) ![]f64 { + const plan = try chunks.Plan.init(a, feats.frames); + const x = try front(gpa, a, p, src, feats, plan, sink); + defer gpa.free(x); + try sink.put(sink.ctx, "embed", 0, x); + var name: [16]u8 = undefined; + for (0..a.layers) |i| { + try layer(gpa, a, p, src, i, x, plan); + try sink.put(sink.ctx, try std.fmt.bufPrint(&name, "layer{d}", .{i}), 0, x); + } + const t = names.tower; + const lw = try src.take(gpa, t ++ "ln_post.weight"); + defer gpa.free(lw); + const lb = try src.take(gpa, t ++ "ln_post.bias"); + defer gpa.free(lb); + ops.layerNorm(x, lw, lb, a.d); + ops.roundAll(p, x); + try sink.put(sink.ctx, "ln_post", 0, x); + const h = try gpa.alloc(f64, plan.rows * a.d); + defer gpa.free(h); + const w1 = try src.take(gpa, t ++ "proj1.weight"); + defer gpa.free(w1); + const b1 = try src.take(gpa, t ++ "proj1.bias"); + defer gpa.free(b1); + ops.linear(h, x, w1, b1, plan.rows, a.d, a.d); + ops.roundAll(p, h); + try sink.put(sink.ctx, "proj1", 0, h); + for (h) |*v| v.* = ops.round(p, ops.gelu(v.*)); + const out = try gpa.alloc(f64, plan.rows * a.out); + errdefer gpa.free(out); + const w2 = try src.take(gpa, t ++ "proj2.weight"); + defer gpa.free(w2); + const b2 = try src.take(gpa, t ++ "proj2.bias"); + defer gpa.free(b2); + ops.linear(out, h, w2, b2, plan.rows, a.out, a.d); + ops.roundAll(p, out); + try sink.put(sink.ctx, "audio_rows", 0, out); + return out; +} diff --git a/zig/src/families/qwen3_asr/wav.zig b/zig/src/families/qwen3_asr/wav.zig new file mode 100644 index 00000000000..f645cb516fd --- /dev/null +++ b/zig/src/families/qwen3_asr/wav.zig @@ -0,0 +1,69 @@ +//! A RIFF WAV clip's samples as the package reads them (soundfile, float32): 16 kHz mono, PCM16 or float32 data. +const std = @import("std"); + +fn le16(b: []const u8) u16 { + return std.mem.readInt(u16, b[0..2], .little); +} + +fn le32(b: []const u8) u32 { + return std.mem.readInt(u32, b[0..4], .little); +} + +/// The samples of `bytes`, each PCM16 value v as v / 32768; refuses other rates, channel counts and encodings. +pub fn decode(gpa: std.mem.Allocator, bytes: []const u8) ![]f32 { + if (bytes.len < 12 or !std.mem.eql(u8, bytes[0..4], "RIFF") or !std.mem.eql(u8, bytes[8..12], "WAVE")) return error.NotWav; + var at: usize = 12; + var format: ?struct { tag: u16, channels: u16, rate: u32, bits: u16 } = null; + while (at + 8 <= bytes.len) { + const id = bytes[at..][0..4]; + const len = le32(bytes[at + 4 ..]); + const body_at = at + 8; + if (len > bytes.len - body_at) return error.BadWav; + const body = bytes[body_at..][0..len]; + if (std.mem.eql(u8, id, "fmt ")) { + if (len < 16) return error.BadWav; + format = .{ .tag = le16(body), .channels = le16(body[2..]), .rate = le32(body[4..]), .bits = le16(body[14..]) }; + } else if (std.mem.eql(u8, id, "data")) { + const f = format orelse return error.BadWav; + if (f.channels != 1) return error.WavNotMono; + if (f.rate != 16000) return error.WavNot16kHz; + const tag = f.tag; // WAVE_FORMAT_EXTENSIBLE is refused with the other encodings + if (tag == 1 and f.bits == 16) { + const out = try gpa.alloc(f32, len / 2); + for (out, 0..) |*o, i| o.* = @as(f32, @floatFromInt(@as(i16, @bitCast(le16(body[2 * i ..]))))) / 32768.0; + return out; + } + if (tag == 3 and f.bits == 32) { + const out = try gpa.alloc(f32, len / 4); + for (out, 0..) |*o, i| o.* = @bitCast(le32(body[4 * i ..])); + return out; + } + return error.WavEncoding; + } + at = body_at + len + (len & 1); + } + return error.BadWav; +} + +test "decode: PCM16 mono 16 kHz, other rates refused" { + var buf: [48]u8 = undefined; + @memcpy(buf[0..4], "RIFF"); + std.mem.writeInt(u32, buf[4..8], 40, .little); + @memcpy(buf[8..16], "WAVEfmt "); + std.mem.writeInt(u32, buf[16..20], 16, .little); + std.mem.writeInt(u16, buf[20..22], 1, .little); + std.mem.writeInt(u16, buf[22..24], 1, .little); + std.mem.writeInt(u32, buf[24..28], 16000, .little); + std.mem.writeInt(u32, buf[28..32], 32000, .little); + std.mem.writeInt(u16, buf[32..34], 2, .little); + std.mem.writeInt(u16, buf[34..36], 16, .little); + @memcpy(buf[36..40], "data"); + std.mem.writeInt(u32, buf[40..44], 4, .little); + std.mem.writeInt(i16, buf[44..46], -16384, .little); + std.mem.writeInt(i16, buf[46..48], 32767, .little); + const x = try decode(std.testing.allocator, &buf); + defer std.testing.allocator.free(x); + try std.testing.expectEqualSlices(f32, &.{ -0.5, 32767.0 / 32768.0 }, x); + std.mem.writeInt(u32, buf[24..28], 44100, .little); + try std.testing.expectError(error.WavNot16kHz, decode(std.testing.allocator, &buf)); +} From 00e0ae75f09d49df2228156bf24b918390c32bd8 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 08:26:22 +0100 Subject: [PATCH 02/28] qwen3-asr: the tower and Qwen3 schedules, generic over a backend binding (#2105) tower.zig and lm.zig load weights by name through the binding's put and run the schedule through r.conv, r.linear, r.attention and the rest; they import no backend. schedule_test.zig runs both on a host binding: the tower matches the float64 reference at torch's points (global attention fails it), and the LM's ops stay inside their buffers. --- zig/src/families/qwen3_asr/lm.zig | 162 ++++++++++ zig/src/families/qwen3_asr/qwen3_asr.zig | 7 +- zig/src/families/qwen3_asr/schedule_test.zig | 324 +++++++++++++++++++ zig/src/families/qwen3_asr/tower.zig | 214 ++++++++++++ 4 files changed, 706 insertions(+), 1 deletion(-) create mode 100644 zig/src/families/qwen3_asr/lm.zig create mode 100644 zig/src/families/qwen3_asr/schedule_test.zig create mode 100644 zig/src/families/qwen3_asr/tower.zig diff --git a/zig/src/families/qwen3_asr/lm.zig b/zig/src/families/qwen3_asr/lm.zig new file mode 100644 index 00000000000..74017b24c95 --- /dev/null +++ b/zig/src/families/qwen3_asr/lm.zig @@ -0,0 +1,162 @@ +//! The Qwen3 language model's weights by name and its greedy pass for every backend; `r` binds the kernels. +const std = @import("std"); +const cfg = @import("config.zig"); +const names = @import("names.zig"); +const tower = @import("tower.zig"); + +/// A layer's tensors: q, k and v as one [(h + 2 hk) d, hidden] matrix, gate and up as one [2 i, hidden]. +pub const Layer = struct { in_norm: u64, post_norm: u64, qkv: u64, o: u64, q_norm: u64, k_norm: u64, gate_up: u64, down: u64 }; + +pub const Weights = struct { + embed: u64, // also the head: the stored lm_head is checked bit-equal to it + norm: u64, + layers: []Layer, + + pub fn deinit(w: *Weights, gpa: std.mem.Allocator) void { + gpa.free(w.layers); + } + + pub fn load(gpa: std.mem.Allocator, t: cfg.Text, src: anytype, up: anytype) !Weights { + const embed = try src.expect(names.lm ++ "embed_tokens.weight", &.{ t.vocab, t.hidden }); + if (!std.mem.eql(u8, embed, try src.expect(names.head, &.{ t.vocab, t.hidden }))) return error.UntiedHead; + var w: Weights = .{ .embed = try up.put(embed), .norm = try up.put(try src.expect(names.lm ++ "norm.weight", &.{t.hidden})), .layers = &.{} }; + w.layers = try gpa.alloc(Layer, t.layers); + errdefer gpa.free(w.layers); + const qd = t.heads * t.head_dim; + const kvd = t.kv_heads * t.head_dim; + var nb: [3][160]u8 = undefined; + for (w.layers, 0..) |*l, i| { + const p = struct { + fn f(b: *[160]u8, li: usize, n: []const u8) ![]const u8 { + return std.fmt.bufPrint(b, names.lm ++ "layers.{d}.{s}", .{ li, n }); + } + }.f; + const qkv = [3][]const u8{ try src.expect(try p(&nb[0], i, "self_attn.q_proj.weight"), &.{ qd, t.hidden }), try src.expect(try p(&nb[1], i, "self_attn.k_proj.weight"), &.{ kvd, t.hidden }), try src.expect(try p(&nb[2], i, "self_attn.v_proj.weight"), &.{ kvd, t.hidden }) }; + l.qkv = try tower.joined(gpa, up, &qkv); + const gu = [2][]const u8{ try src.expect(try p(&nb[0], i, "mlp.gate_proj.weight"), &.{ t.intermediate, t.hidden }), try src.expect(try p(&nb[1], i, "mlp.up_proj.weight"), &.{ t.intermediate, t.hidden }) }; + l.gate_up = try tower.joined(gpa, up, &gu); + const one = .{ + .{ &l.in_norm, "input_layernorm.weight", &[_]usize{t.hidden} }, .{ &l.post_norm, "post_attention_layernorm.weight", &[_]usize{t.hidden} }, + .{ &l.o, "self_attn.o_proj.weight", &[_]usize{ t.hidden, qd } }, .{ &l.q_norm, "self_attn.q_norm.weight", &[_]usize{t.head_dim} }, + .{ &l.k_norm, "self_attn.k_norm.weight", &[_]usize{t.head_dim} }, .{ &l.down, "mlp.down_proj.weight", &[_]usize{ t.hidden, t.intermediate } }, + }; + inline for (one) |x| x[0].* = try up.put(try src.expect(try p(&nb[2], i, x[1]), x[2])); + } + return w; + } +}; + +/// Audio rows spliced into a pass: `n` rows of the model's width at `ptr`, standing at positions [at, at + n). +pub const Splice = struct { ptr: u64, at: usize, n: usize }; + +/// A pass's bf16 rows, each from the backend's `al.alloc(bytes)`; the KV caches are the binding's. +pub const Buffers = struct { + e: u64, + h: [2]u64, + y: u64, + qkv: u64, + att: u64, + o: u64, + gu: u64, + act: u64, + dn: u64, + max_rows: usize, + + pub fn alloc(t: cfg.Text, max_rows: usize, al: anytype) !Buffers { + const r = max_rows; + const qd = t.heads * t.head_dim; + const kvd = t.kv_heads * t.head_dim; + return .{ + .e = try al.alloc(2 * r * t.hidden), + .h = .{ try al.alloc(2 * r * t.hidden), try al.alloc(2 * r * t.hidden) }, + .y = try al.alloc(2 * r * t.hidden), + .qkv = try al.alloc(2 * r * (qd + 2 * kvd)), + .att = try al.alloc(2 * r * qd), + .o = try al.alloc(2 * r * t.hidden), + .gu = try al.alloc(2 * r * 2 * t.intermediate), + .act = try al.alloc(2 * r * t.intermediate), + .dn = try al.alloc(2 * r * t.hidden), + .max_rows = max_rows, + }; + } +}; + +/// One pass over `ids` at positions [pos, pos + ids.len), the audio rows spliced in: the last row's greedy pick. +pub fn forward(r: anytype, t: cfg.Text, w: *const Weights, b: Buffers, ids: []const u32, pos: usize, audio: ?Splice) !u32 { + const rows = ids.len; + if (rows == 0 or rows > b.max_rows) return error.PassRows; + try r.positions(ids, pos); + try r.embed(w.embed, b.e, rows, t.hidden); + if (audio) |sp| { + if (sp.at < pos or sp.at + sp.n > pos + rows) return error.SpliceOutsidePass; + try r.copy(b.e + (sp.at - pos) * t.hidden * 2, sp.ptr, sp.n * t.hidden * 2); + } + const qd = t.heads * t.head_dim; + const kvd = t.kv_heads * t.head_dim; + var x = b.e; + var res: ?u64 = null; + var cur: usize = 0; + for (w.layers, 0..) |l, i| { + try r.addNorm(x, res, l.in_norm, b.h[cur], b.y, rows); + try r.gemm(b.y, l.qkv, b.qkv, rows, qd + 2 * kvd, t.hidden); + try r.qkRope(b.qkv, l.q_norm, l.k_norm, i, rows); + try r.attention(i, b.att, rows); + try r.gemm(b.att, l.o, b.o, rows, t.hidden, qd); + try r.addNorm(b.o, b.h[cur], l.post_norm, b.h[1 - cur], b.y, rows); + cur = 1 - cur; + try r.gemm(b.y, l.gate_up, b.gu, rows, 2 * t.intermediate, t.hidden); + try r.swiglu(b.gu, b.act, rows, t.intermediate); + try r.gemm(b.act, l.down, b.dn, rows, t.hidden, t.intermediate); + x = b.dn; + res = b.h[cur]; + cur = 1 - cur; + } + try r.addNorm(x, res, w.norm, b.h[cur], b.y, rows); + return r.greedy(b.y + (rows - 1) * t.hidden * 2, w.embed); +} + +/// The first largest bf16 logit (torch.argmax's tie rule); a NaN logit wins, as torch's max does. +pub fn argmax(logits: []const u16) u32 { + var best: usize = 0; + var top: f32 = -std.math.inf(f32); + for (logits, 0..) |bits, i| { + const v: f32 = @bitCast(@as(u32, bits) << 16); + if (std.math.isNan(v)) return @intCast(i); + if (v > top) { + top = v; + best = i; + } + } + return @intCast(best); +} + +/// RoPE's cos and sin at positions [0, n) as transformers stores them: fp32 angles, the values cast to bf16. +pub fn ropeTables(t: cfg.Text, cs: []f32, sn: []f32, n: usize) void { + const dim = t.head_dim; + for (0..dim / 2) |i| { + const e: f32 = @as(f32, @floatFromInt(2 * i)) / @as(f32, @floatFromInt(dim)); + const inv: f32 = 1.0 / @as(f32, @floatCast(std.math.pow(f64, t.theta, e))); + for (0..n) |p| { + const ang: f32 = @as(f32, @floatFromInt(p)) * inv; + for ([2]usize{ i, i + dim / 2 }) |col| { + cs[p * dim + col] = @bitCast(@as(u32, tower.bf16Bits(@cos(ang))) << 16); + sn[p * dim + col] = @bitCast(@as(u32, tower.bf16Bits(@sin(ang))) << 16); + } + } + } +} + +test "argmax: the first of equal logits, a NaN first" { + try std.testing.expectEqual(@as(u32, 1), argmax(&.{ 0x3f80, 0x4000, 0x4000 })); + try std.testing.expectEqual(@as(u32, 2), argmax(&.{ 0x3f80, 0x4000, 0x7fc0 })); +} + +test "ropeTables: position 0 is cos 1, sin 0; the halves repeat" { + const t: cfg.Text = .{ .hidden = 8, .layers = 1, .heads = 1, .kv_heads = 1, .head_dim = 4, .intermediate = 8, .vocab = 4, .eps = 1e-6, .theta = 1e6, .context = 8 }; + var cs: [8]f32 = undefined; + var sn: [8]f32 = undefined; + ropeTables(t, &cs, &sn, 2); + try std.testing.expectEqualSlices(f32, &.{ 1, 1, 1, 1 }, cs[0..4]); + try std.testing.expectEqual(@as(f32, 0), sn[0]); + try std.testing.expectEqual(cs[4], cs[6]); +} diff --git a/zig/src/families/qwen3_asr/qwen3_asr.zig b/zig/src/families/qwen3_asr/qwen3_asr.zig index 62dcc2ac025..cb220dc9acb 100644 --- a/zig/src/families/qwen3_asr/qwen3_asr.zig +++ b/zig/src/families/qwen3_asr/qwen3_asr.zig @@ -1,4 +1,4 @@ -//! Qwen3-ASR (0.6B, 1.7B): the audio tower and Qwen3 language model's host parts; CUDA runs them in cuda.zig. +//! Qwen3-ASR (0.6B, 1.7B): the audio tower and Qwen3 language model's host parts; the schedules every backend binds. pub const config = @import("config.zig"); pub const chunks = @import("chunks.zig"); pub const mel = @import("mel.zig"); @@ -8,6 +8,8 @@ pub const ref_ops = @import("ref_ops.zig"); pub const tower_ref = @import("tower_ref.zig"); pub const case = @import("case.zig"); pub const prompt = @import("prompt.zig"); +pub const tower = @import("tower.zig"); +pub const lm = @import("lm.zig"); test { _ = config; @@ -19,5 +21,8 @@ test { _ = tower_ref; _ = case; _ = prompt; + _ = tower; + _ = lm; _ = @import("config_test.zig"); + _ = @import("schedule_test.zig"); } diff --git a/zig/src/families/qwen3_asr/schedule_test.zig b/zig/src/families/qwen3_asr/schedule_test.zig new file mode 100644 index 00000000000..66f3e75a4d8 --- /dev/null +++ b/zig/src/families/qwen3_asr/schedule_test.zig @@ -0,0 +1,324 @@ +//! The shared schedules on a host binding: the tower against the float64 reference, the LM's extents, any OS. +const std = @import("std"); +const cfg = @import("config.zig"); +const chunks = @import("chunks.zig"); +const mel = @import("mel.zig"); +const ops = @import("ref_ops.zig"); +const tower = @import("tower.zig"); +const lm = @import("lm.zig"); +const tower_ref = @import("tower_ref.zig"); + +/// Device memory on the host: an address is (allocation + 1) << 40 plus a byte offset, each value a bf16 slot. +const Mem = struct { + gpa: std.mem.Allocator, + list: std.ArrayList([]f64) = .empty, + + fn deinit(m: *Mem) void { + for (m.list.items) |x| m.gpa.free(x); + m.list.deinit(m.gpa); + } + + pub fn alloc(m: *Mem, bytes: usize) !u64 { + const v = try m.gpa.alloc(f64, (bytes + 1) / 2); + @memset(v, std.math.nan(f64)); + try m.list.append(m.gpa, v); + return @as(u64, m.list.items.len) << 40; + } + + pub fn put(m: *Mem, bytes: []const u8) !u64 { + const p = try m.alloc(bytes.len); + const v = try m.at(p, bytes.len / 2); + for (v, 0..) |*x, i| x.* = ops.widen(std.mem.readInt(u16, bytes[2 * i ..][0..2], .little)); + return p; + } + + pub fn taps(m: *Mem, bytes: []const u8, _: usize, _: usize) !u64 { + return m.put(bytes); + } + + /// `n` values at `ptr`, refused unless they lie inside one allocation. + fn at(m: *Mem, ptr: u64, n: usize) ![]f64 { + const id = ptr >> 40; + const off = ptr & ((1 << 40) - 1); + if (id == 0 or id > m.list.items.len or off % 2 != 0) return error.BadAddress; + const v = m.list.items[id - 1]; + if (off / 2 + n > v.len) return error.OutOfBounds; + return v[off / 2 ..][0..n]; + } +}; + +/// The tower's operators at torch's rounding points, the stages kept for the comparison. +const TowerHost = struct { + m: *Mem, + gpa: std.mem.Allocator, + stages: std.StringHashMapUnmanaged([]f64) = .empty, + + fn deinit(t: *TowerHost) void { + var it = t.stages.iterator(); + while (it.next()) |e| { + t.gpa.free(e.key_ptr.*); + t.gpa.free(e.value_ptr.*); + } + t.stages.deinit(t.gpa); + } + + pub fn upload(t: *TowerHost, dst: u64, bytes: []const u8) !void { + const v = try t.m.at(dst, bytes.len / 2); + for (v, 0..) |*x, i| x.* = ops.widen(std.mem.readInt(u16, bytes[2 * i ..][0..2], .little)); + } + + pub fn conv(t: *TowerHost, w: u64, b: u64, x: u64, y: u64, n: usize, fi: usize, ti: usize, c: usize, co: usize) !void { + const fo = (fi - 1) / 2 + 1; + const to = (ti - 1) / 2 + 1; + const xs = try t.m.at(x, n * fi * ti * c); + const ws = try t.m.at(w, co * c * 9); + const bs = try t.m.at(b, co); + const ys = try t.m.at(y, n * fo * to * co); + for (0..n) |s| for (0..fo) |f| for (0..to) |tt| for (0..co) |o| { + var acc: f64 = bs[o]; + for (0..c) |ci| for (0..3) |kh| for (0..3) |kw| { + const sf = @as(isize, @intCast(2 * f + kh)) - 1; + const st = @as(isize, @intCast(2 * tt + kw)) - 1; + if (sf < 0 or st < 0 or sf >= fi or st >= ti) continue; + acc += xs[((s * fi + @as(usize, @intCast(sf))) * ti + @as(usize, @intCast(st))) * c + ci] * ws[(o * c + ci) * 9 + kh * 3 + kw]; + }; + ys[((s * fo + f) * to + tt) * co + o] = ops.bf16(acc); + }; + } + + pub fn dump(t: *TowerHost, stage: []const u8, ptr: u64, rows: usize, cols: usize, conv_shape: ?[3]usize) !void { + const v = try t.m.at(ptr, rows * cols); + if (conv_shape != null) return; // the reference taps convs per chunk, channels first: extents only here + const got = try t.stages.getOrPut(t.gpa, stage); + if (got.found_existing) t.gpa.free(got.value_ptr.*) else got.key_ptr.* = try t.gpa.dupe(u8, stage); + got.value_ptr.* = try t.gpa.dupe(f64, v); + } + + pub fn flatten(t: *TowerHost, x: u64, y: u64, n: usize, f: usize, tt: usize, c: usize) !void { + const xs = try t.m.at(x, n * f * tt * c); + const ys = try t.m.at(y, n * tt * c * f); + for (0..n) |s| for (0..tt) |r| for (0..c) |ci| for (0..f) |fi| { + ys[(s * tt + r) * c * f + ci * f + fi] = xs[((s * f + fi) * tt + r) * c + ci]; + }; + } + + pub fn linear(t: *TowerHost, x: u64, w: u64, b: ?u64, y: u64, rows: usize, n: usize, k: usize, act: tower.Act, res: ?u64) !void { + const tmp = try t.gpa.alloc(f64, rows * n); + defer t.gpa.free(tmp); + ops.linear(tmp, try t.m.at(x, rows * k), try t.m.at(w, n * k), if (b) |p| try t.m.at(p, n) else null, rows, n, k); + const r = if (res) |p| try t.m.at(p, rows * n) else null; + const ys = try t.m.at(y, rows * n); + for (tmp, 0..) |v0, i| { + var v = ops.bf16(v0); + if (act == .gelu) v = ops.bf16(ops.gelu(v)); + if (r) |rr| v = ops.bf16(v + rr[i]); + ys[i] = v; + } + } + + pub fn layernorm(t: *TowerHost, x: u64, w: u64, b: u64, y: u64, rows: usize, d: usize) !void { + const ys = try t.m.at(y, rows * d); + @memcpy(ys, try t.m.at(x, rows * d)); + ops.layerNorm(ys, try t.m.at(w, d), try t.m.at(b, d), d); + ops.roundAll(.torch, ys); + } + + pub fn attention(t: *TowerHost, qkv: u64, out: u64, len: usize, heads: usize, dim: usize) !void { + const o = try t.m.at(out, len * heads * dim); + try ops.attention(o, try t.m.at(qkv, len * 3 * heads * dim), 0, len, heads, dim); + ops.roundAll(.torch, o); + } + + pub fn gelu(t: *TowerHost, x: u64, y: u64, count: usize) !void { + const xs = try t.m.at(x, count); + for (try t.m.at(y, count), xs) |*o, v| o.* = ops.bf16(ops.gelu(v)); + } + + pub fn sync(_: *TowerHost) !void {} +}; + +/// Random bf16 tensors made on first ask, the same bytes for the schedule and the reference. +const Fake = struct { + gpa: std.mem.Allocator, + rng: std.Random.DefaultPrng = .init(0x2105), + map: std.StringHashMapUnmanaged([]u8) = .empty, + + fn deinit(f: *Fake) void { + var it = f.map.iterator(); + while (it.next()) |e| { + f.gpa.free(e.key_ptr.*); + f.gpa.free(e.value_ptr.*); + } + f.map.deinit(f.gpa); + } + + pub fn expect(f: *Fake, name: []const u8, shape: []const usize) ![]const u8 { + if (f.map.get(name)) |b| return b; + var n: usize = 1; + for (shape) |s| n *= s; + const b = try f.gpa.alloc(u8, 2 * n); + const fan: f32 = @floatFromInt(if (shape.len > 1) n / shape[0] else 4); + const norm = std.mem.endsWith(u8, name, "layer_norm.weight") or std.mem.endsWith(u8, name, "ln_post.weight"); + for (0..n) |i| { + const v: f32 = if (norm) 1 + 0.1 * f.rng.random().floatNorm(f32) else f.rng.random().floatNorm(f32) / @sqrt(fan); + std.mem.writeInt(u16, b[2 * i ..][0..2], tower.bf16Bits(v), .little); + } + try f.map.put(f.gpa, try f.gpa.dupe(u8, name), b); + return b; + } + + fn get(ctx: *anyopaque, name: []const u8) ?[]const u8 { + const f: *Fake = @ptrCast(@alignCast(ctx)); + return f.map.get(name); + } +}; + +const Ref = struct { + gpa: std.mem.Allocator, + stages: std.StringHashMapUnmanaged([]f64) = .empty, + + fn put(ctx: *anyopaque, stage: []const u8, offset: usize, values: []const f64) anyerror!void { + const r: *Ref = @ptrCast(@alignCast(ctx)); + if (offset != 0 or std.mem.startsWith(u8, stage, "conv")) return; + try r.stages.put(r.gpa, try r.gpa.dupe(u8, stage), try r.gpa.dupe(f64, values)); + } + + fn deinit(r: *Ref) void { + var it = r.stages.iterator(); + while (it.next()) |e| { + r.gpa.free(e.key_ptr.*); + r.gpa.free(e.value_ptr.*); + } + r.stages.deinit(r.gpa); + } +}; + +fn cosine(a: []const f64, b: []const f64) f64 { + var ab: f64 = 0; + var aa: f64 = 0; + var bb: f64 = 0; + for (a, b) |x, y| { + ab += x * y; + aa += x * x; + bb += y * y; + } + return ab / @sqrt(aa * bb); +} + +const small: cfg.Audio = .{ .d = 8, .layers = 2, .heads = 2, .ffn = 16, .mels = 16, .conv = 4, .out = 6, .window = 50, .window_infer = 200, .positions = 1500, .conv_chunks = 500 }; + +test "tower schedule: a host binding matches the float64 reference at torch's points, two windows, a short chunk" { + const gpa = std.testing.allocator; + var mem: Mem = .{ .gpa = gpa }; + defer mem.deinit(); + var fake: Fake = .{ .gpa = gpa }; + defer fake.deinit(); + var w = try tower.Weights.load(gpa, small, &fake, &mem, 3); // groups of 3 over 4 chunks: one short group + defer w.deinit(gpa); + const frames = 350; + const data = try gpa.alloc(f32, small.mels * frames); + defer gpa.free(data); + var rng: std.Random.DefaultPrng = .init(7); + for (data) |*v| v.* = rng.random().floatNorm(f32); + const feats: mel.Features = .{ .data = data, .mels = small.mels, .frames = frames }; + const plan = try chunks.Plan.init(small, frames); + try std.testing.expectEqual(@as(usize, 2), plan.windows()); + const b = try tower.Buffers.alloc(small, 3, plan.rows, &mem); + const out = try mem.alloc(2 * plan.rows * small.out); + var host: TowerHost = .{ .m = &mem, .gpa = gpa }; + defer host.deinit(); + try std.testing.expectEqual(plan.rows, try tower.encode(&host, gpa, small, &w, b, feats, out)); + var ref: Ref = .{ .gpa = gpa }; + defer ref.deinit(); + const want = try tower_ref.run(gpa, small, .torch, .{ .ctx = &fake, .get = Fake.get }, feats, .{ .ctx = &ref, .put = Ref.put }); + defer gpa.free(want); + var it = ref.stages.iterator(); + var seen: usize = 0; + while (it.next()) |e| { + const got = host.stages.get(e.key_ptr.*) orelse continue; + seen += 1; + try std.testing.expectEqual(e.value_ptr.len, got.len); + const c = cosine(got, e.value_ptr.*); + if (c < 0.9999) std.debug.print("stage {s}: cosine {d}\n", .{ e.key_ptr.*, c }); + try std.testing.expect(c >= 0.9999); + } + try std.testing.expect(seen >= small.layers + 4); // embed, each layer, ln_post, proj1, audio_rows +} + +/// The LM's operators as extents only: every row an op touches lies inside the buffer it names. +const LmBounds = struct { + m: *Mem, + t: cfg.Text, + calls: usize = 0, + pos: usize = 0, + rows: usize = 0, + + fn touch(b: *LmBounds, ptr: u64, values: usize) !void { + _ = try b.m.at(ptr, values); + b.calls += 1; + } + + pub fn positions(b: *LmBounds, ids: []const u32, pos: usize) !void { + b.pos = pos; + b.rows = ids.len; + } + pub fn embed(b: *LmBounds, table: u64, out: u64, rows: usize, hidden: usize) !void { + try b.touch(table, b.t.vocab * hidden); + try b.touch(out, rows * hidden); + } + pub fn copy(b: *LmBounds, dst: u64, src: u64, n: usize) !void { + try b.touch(dst, n / 2); + try b.touch(src, n / 2); + } + pub fn addNorm(b: *LmBounds, x: u64, res: ?u64, w: u64, h: u64, y: u64, rows: usize) !void { + for ([_]u64{ x, res orelse x, h, y }) |p| try b.touch(p, rows * b.t.hidden); + try b.touch(w, b.t.hidden); + } + pub fn gemm(b: *LmBounds, x: u64, w: u64, y: u64, rows: usize, n: usize, k: usize) !void { + try b.touch(x, rows * k); + try b.touch(w, n * k); + try b.touch(y, rows * n); + } + pub fn qkRope(b: *LmBounds, qkv: u64, qn: u64, kn: u64, layer: usize, rows: usize) !void { + try std.testing.expect(layer < b.t.layers and rows == b.rows); + try b.touch(qkv, rows * (b.t.heads + 2 * b.t.kv_heads) * b.t.head_dim); + try b.touch(qn, b.t.head_dim); + try b.touch(kn, b.t.head_dim); + } + pub fn attention(b: *LmBounds, layer: usize, out: u64, rows: usize) !void { + try std.testing.expect(layer < b.t.layers and rows == b.rows); + try b.touch(out, rows * b.t.heads * b.t.head_dim); + } + pub fn swiglu(b: *LmBounds, gu: u64, out: u64, rows: usize, i: usize) !void { + try b.touch(gu, rows * 2 * i); + try b.touch(out, rows * i); + } + pub fn greedy(b: *LmBounds, row: u64, embed_table: u64) !u32 { + try b.touch(row, b.t.hidden); + try b.touch(embed_table, b.t.vocab * b.t.hidden); + return 7; + } +}; + +test "lm schedule: every op inside its buffers, the splice inside the pass, the head tied" { + const gpa = std.testing.allocator; + const t: cfg.Text = .{ .hidden = 16, .layers = 3, .heads = 4, .kv_heads = 2, .head_dim = 8, .intermediate = 24, .vocab = 32, .eps = 1e-6, .theta = 1e6, .context = 64 }; + var mem: Mem = .{ .gpa = gpa }; + defer mem.deinit(); + var fake: Fake = .{ .gpa = gpa }; + defer fake.deinit(); + _ = try fake.expect("thinker.lm_head.weight", &.{ t.vocab, t.hidden }); + try std.testing.expectError(error.UntiedHead, lm.Weights.load(gpa, t, &fake, &mem)); + const head = fake.map.getPtr("thinker.lm_head.weight").?; + @memcpy(head.*, try fake.expect("thinker.model.embed_tokens.weight", &.{ t.vocab, t.hidden })); + var w = try lm.Weights.load(gpa, t, &fake, &mem); + defer w.deinit(gpa); + const b = try lm.Buffers.alloc(t, 10, &mem); + const rows = try mem.alloc(2 * 4 * t.hidden); + var bounds: LmBounds = .{ .m = &mem, .t = t }; + const ids = [_]u32{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; + try std.testing.expectEqual(@as(u32, 7), try lm.forward(&bounds, t, &w, b, &ids, 0, .{ .ptr = rows, .at = 3, .n = 4 })); + try std.testing.expectEqual(@as(u32, 7), try lm.forward(&bounds, t, &w, b, ids[0..1], 10, null)); + try std.testing.expectError(error.SpliceOutsidePass, lm.forward(&bounds, t, &w, b, &ids, 0, .{ .ptr = rows, .at = 8, .n = 4 })); + try std.testing.expectError(error.PassRows, lm.forward(&bounds, t, &w, b, &(ids ++ ids), 0, null)); +} diff --git a/zig/src/families/qwen3_asr/tower.zig b/zig/src/families/qwen3_asr/tower.zig new file mode 100644 index 00000000000..a2b09b1df96 --- /dev/null +++ b/zig/src/families/qwen3_asr/tower.zig @@ -0,0 +1,214 @@ +//! The audio tower's weights by name and its schedule for every backend; `r` binds the kernels, `up` the uploads. +const std = @import("std"); +const cfg = @import("config.zig"); +const chunks = @import("chunks.zig"); +const mel = @import("mel.zig"); +const names = @import("names.zig"); +const tower_ref = @import("tower_ref.zig"); + +pub const Layer = struct { ln1: u64, ln1_b: u64, qkv: u64, qkv_b: u64, out: u64, out_b: u64, ln2: u64, ln2_b: u64, fc1: u64, fc1_b: u64, fc2: u64, fc2_b: u64 }; + +/// A GELU after a Linear, or none. +pub const Act = enum { none, gelu }; + +/// The tower's tensors as device addresses, each put by the backend's `up` (q, k and v as one [3 d, d] matrix). +pub const Weights = struct { + conv: [3]u64, + conv_b: [3]u64, + conv_out: u64, + positions: u64, // the per-chunk sinusoid rows (bf16 as the package casts them), tiled over `group` chunks + layers: []Layer, + ln_post: u64, + ln_post_b: u64, + proj1: u64, + proj1_b: u64, + proj2: u64, + proj2_b: u64, + group: usize, + + pub fn deinit(w: *Weights, gpa: std.mem.Allocator) void { + gpa.free(w.layers); + } + + /// `src.expect(name, shape)` gives a bf16 tensor's bytes; `up.put(bytes)` and `up.taps(bytes, co, k)` place them. + pub fn load(gpa: std.mem.Allocator, a: cfg.Audio, src: anytype, up: anytype, group: usize) !Weights { + const t = names.tower; + const k = cfg.conv_taps; + var w: Weights = undefined; + w.group = group; + w.conv[0] = try up.taps(try src.expect(t ++ "conv2d1.weight", &.{ a.conv, 1, k, k }), a.conv, 9); + w.conv[1] = try up.taps(try src.expect(t ++ "conv2d2.weight", &.{ a.conv, a.conv, k, k }), a.conv, 9 * a.conv); + w.conv[2] = try up.taps(try src.expect(t ++ "conv2d3.weight", &.{ a.conv, a.conv, k, k }), a.conv, 9 * a.conv); + inline for (.{ "conv2d1.bias", "conv2d2.bias", "conv2d3.bias" }, 0..) |n, i| w.conv_b[i] = try up.put(try src.expect(t ++ n, &.{a.conv})); + w.conv_out = try up.put(try src.expect(t ++ "conv_out.weight", &.{ a.d, a.conv * a.convBins() })); + w.positions = try positions(gpa, a, up, group); + w.layers = try gpa.alloc(Layer, a.layers); + errdefer gpa.free(w.layers); + var nb: [4][160]u8 = undefined; + for (w.layers, 0..) |*l, i| { + const p = struct { + fn f(b: *[160]u8, li: usize, n: []const u8) ![]const u8 { + return std.fmt.bufPrint(b, names.tower ++ "layers.{d}.{s}", .{ li, n }); + } + }.f; + const sq = &[_]usize{ a.d, a.d }; + const v = &[_]usize{a.d}; + const qkv = [3][]const u8{ try src.expect(try p(&nb[0], i, "self_attn.q_proj.weight"), sq), try src.expect(try p(&nb[1], i, "self_attn.k_proj.weight"), sq), try src.expect(try p(&nb[2], i, "self_attn.v_proj.weight"), sq) }; + l.qkv = try joined(gpa, up, &qkv); + const qkv_b = [3][]const u8{ try src.expect(try p(&nb[0], i, "self_attn.q_proj.bias"), v), try src.expect(try p(&nb[1], i, "self_attn.k_proj.bias"), v), try src.expect(try p(&nb[2], i, "self_attn.v_proj.bias"), v) }; + l.qkv_b = try joined(gpa, up, &qkv_b); + const one = .{ + .{ &l.out, "self_attn.out_proj.weight", sq }, .{ &l.out_b, "self_attn.out_proj.bias", v }, + .{ &l.ln1, "self_attn_layer_norm.weight", v }, .{ &l.ln1_b, "self_attn_layer_norm.bias", v }, + .{ &l.ln2, "final_layer_norm.weight", v }, .{ &l.ln2_b, "final_layer_norm.bias", v }, + .{ &l.fc1, "fc1.weight", &[_]usize{ a.ffn, a.d } }, .{ &l.fc1_b, "fc1.bias", &[_]usize{a.ffn} }, + .{ &l.fc2, "fc2.weight", &[_]usize{ a.d, a.ffn } }, .{ &l.fc2_b, "fc2.bias", v }, + }; + inline for (one) |x| x[0].* = try up.put(try src.expect(try p(&nb[3], i, x[1]), x[2])); + } + w.ln_post = try up.put(try src.expect(t ++ "ln_post.weight", &.{a.d})); + w.ln_post_b = try up.put(try src.expect(t ++ "ln_post.bias", &.{a.d})); + w.proj1 = try up.put(try src.expect(t ++ "proj1.weight", &.{ a.d, a.d })); + w.proj1_b = try up.put(try src.expect(t ++ "proj1.bias", &.{a.d})); + w.proj2 = try up.put(try src.expect(t ++ "proj2.weight", &.{ a.out, a.d })); + w.proj2_b = try up.put(try src.expect(t ++ "proj2.bias", &.{a.out})); + return w; + } +}; + +/// Tensors put as one: their rows back to back. +pub fn joined(gpa: std.mem.Allocator, up: anytype, parts: []const []const u8) !u64 { + const all = try std.mem.concat(gpa, u8, parts); + defer gpa.free(all); + return up.put(all); +} + +/// The 13-row sinusoid table at torch's points, bf16, tiled over `group` chunks. +fn positions(gpa: std.mem.Allocator, a: cfg.Audio, up: anytype, group: usize) !u64 { + const crow = chunks.rows(a.chunkFrames()); + const table = try tower_ref.positions(gpa, .torch, crow, a.d); + defer gpa.free(table); + const tiled = try gpa.alloc(u16, group * table.len); + defer gpa.free(tiled); + for (0..group) |g| for (table, 0..) |v, i| { + tiled[g * table.len + i] = @intCast(@as(u32, @bitCast(@as(f32, @floatCast(v)))) >> 16); + }; + return up.put(std.mem.sliceAsBytes(tiled)); +} + +/// f32 to bf16 bits, nearest even (torch's cast of the features to the model's dtype). +pub fn bf16Bits(x: f32) u16 { + const u: u32 = @bitCast(x); + if (std.math.isNan(x)) return @intCast((u >> 16) | 0x40); + return @intCast((u + 0x7fff + ((u >> 16) & 1)) >> 16); +} + +/// The schedule's bf16 buffers, each from the backend's `al.alloc(bytes)`. +pub const Buffers = struct { + in: u64, + c1: u64, + c2: u64, + x: u64, + h: u64, + qkv: u64, + a: u64, + wide: u64, + max_rows: usize, + + /// For clips of up to `max_rows` rows, `group` chunks a convolution pass. + pub fn alloc(a: cfg.Audio, group: usize, max_rows: usize, al: anytype) !Buffers { + const cf = a.chunkFrames(); + const p1 = group * ((a.mels - 1) / 2 + 1) * ((cf - 1) / 2 + 1); + const rows = max_rows + chunks.rows(cf); + return .{ + .in = try al.alloc(2 * group * a.mels * cf), + .c1 = try al.alloc(2 * p1 * a.conv), + .c2 = try al.alloc(2 * (p1 / 4 + 1) * a.conv), + .x = try al.alloc(2 * rows * a.d), + .h = try al.alloc(2 * rows * @max(a.d, a.out)), + .qkv = try al.alloc(2 * rows * 3 * a.d), + .a = try al.alloc(2 * rows * a.d), + .wide = try al.alloc(2 * @max(rows * a.ffn, group * chunks.rows(cf) * a.conv * a.convBins())), // also conv_out's input + .max_rows = max_rows, + }; + } +}; + +/// The bf16 input of chunks [first, first + n) of `feats`: [n][mels][frames a chunk], zero past the clip. +fn input(a: cfg.Audio, feats: mel.Features, first: usize, n: usize, host: []u16) []u16 { + const cf = a.chunkFrames(); + const out = host[0 .. n * a.mels * cf]; + @memset(out, 0); + for (0..n) |i| for (0..a.mels) |m| for (0..cf) |j| { + const fr = (first + i) * cf + j; + if (fr < feats.frames) out[(i * a.mels + m) * cf + j] = bf16Bits(feats.at(m, fr)); + }; + return out; +} + +/// The convolutions over a group of chunks into rows of b.x from first * 13 on, positions added. +fn front(r: anytype, a: cfg.Audio, w: *const Weights, b: Buffers, feats: mel.Features, first: usize, n: usize, host: []u16) !void { + const cf = a.chunkFrames(); + try r.upload(b.in, std.mem.sliceAsBytes(input(a, feats, first, n, host))); + const f1 = (a.mels - 1) / 2 + 1; + const t1 = (cf - 1) / 2 + 1; + const f2 = (f1 - 1) / 2 + 1; + const t2 = (t1 - 1) / 2 + 1; + const f3 = (f2 - 1) / 2 + 1; + const t3 = (t2 - 1) / 2 + 1; + // each conv: bf16(taps . w^T + b), dumped as the package's hook sees it, then the GELU in place + try r.conv(w.conv[0], w.conv_b[0], b.in, b.c1, n, a.mels, cf, 1, a.conv); + try r.dump("conv1", b.c1, n * f1 * t1, a.conv, .{ n, f1, t1 }); + try r.gelu(b.c1, b.c1, n * f1 * t1 * a.conv); + try r.conv(w.conv[1], w.conv_b[1], b.c1, b.c2, n, f1, t1, a.conv, a.conv); + try r.dump("conv2", b.c2, n * f2 * t2, a.conv, .{ n, f2, t2 }); + try r.gelu(b.c2, b.c2, n * f2 * t2 * a.conv); + try r.conv(w.conv[2], w.conv_b[2], b.c2, b.c1, n, f2, t2, a.conv, a.conv); + try r.dump("conv3", b.c1, n * f3 * t3, a.conv, .{ n, f3, t3 }); + try r.gelu(b.c1, b.c1, n * f3 * t3 * a.conv); + try r.flatten(b.c1, b.wide, n, f3, t3, a.conv); + try r.linear(b.wide, w.conv_out, null, b.x + first * t3 * a.d * 2, n * t3, a.d, a.conv * f3, .none, w.positions); +} + +/// The tower over `feats` into `out` [rows, a.out] bf16; the plan's rows returned. +pub fn encode(r: anytype, gpa: std.mem.Allocator, a: cfg.Audio, w: *const Weights, b: Buffers, feats: mel.Features, out: u64) !usize { + const plan = try chunks.Plan.init(a, feats.frames); + if (plan.rows > b.max_rows) return error.AudioTooLong; + const host = try gpa.alloc(u16, w.group * a.mels * a.chunkFrames()); + defer gpa.free(host); + var first: usize = 0; + while (first < plan.chunks) : (first += w.group) { + try front(r, a, w, b, feats, first, @min(w.group, plan.chunks - first), host); + try r.sync(); // the host input is refilled for the next group + } + const rows = plan.rows; + const d = a.d; + try r.dump("embed", b.x, rows, d, null); + var name: [16]u8 = undefined; + for (w.layers, 0..) |l, i| { + try r.layernorm(b.x, l.ln1, l.ln1_b, b.h, rows, d); + try r.linear(b.h, l.qkv, l.qkv_b, b.qkv, rows, 3 * d, d, .none, null); + for (0..plan.windows()) |wi| { + const win = plan.window(wi); + try r.attention(b.qkv + win.start * 3 * d * 2, b.a + win.start * d * 2, win.len, a.heads, a.headDim()); + } + try r.linear(b.a, l.out, l.out_b, b.x, rows, d, d, .none, b.x); + try r.layernorm(b.x, l.ln2, l.ln2_b, b.h, rows, d); + try r.linear(b.h, l.fc1, l.fc1_b, b.wide, rows, a.ffn, d, .gelu, null); + try r.linear(b.wide, l.fc2, l.fc2_b, b.x, rows, d, a.ffn, .none, b.x); + try r.dump(try std.fmt.bufPrint(&name, "layer{d}", .{i}), b.x, rows, d, null); + } + try r.layernorm(b.x, w.ln_post, w.ln_post_b, b.h, rows, d); + try r.dump("ln_post", b.h, rows, d, null); + try r.linear(b.h, w.proj1, w.proj1_b, b.a, rows, d, d, .none, null); + try r.dump("proj1", b.a, rows, d, null); + try r.gelu(b.a, b.h, rows * d); + try r.linear(b.h, w.proj2, w.proj2_b, out, rows, a.out, d, .none, null); + try r.dump("audio_rows", out, rows, a.out, null); + return rows; +} + +test "bf16Bits: nearest even" { + try std.testing.expectEqual(@as(u16, 0x3f80), bf16Bits(1.0 + 1.0 / 256.0)); + try std.testing.expectEqual(@as(u16, 0x3f82), bf16Bits(1.0 + 3.0 / 256.0)); +} From 42344da9300670ca1c26a9a74affff178f74a900 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 09:09:51 +0100 Subject: [PATCH 03/28] qwen3-asr case tool: each greedy step's top two and margin, and an ids-only case (#2105) A transcript that differs from the package's is listed with the reference's margin where it first differs; the gate set's cases keep only the prompt, the greedy ids and the margins. --- tools/zig/qwen3_asr_case.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/tools/zig/qwen3_asr_case.py b/tools/zig/qwen3_asr_case.py index bbaa998b369..35267a80e7e 100644 --- a/tools/zig/qwen3_asr_case.py +++ b/tools/zig/qwen3_asr_case.py @@ -12,6 +12,8 @@ def save(out, manifest, name, t, kind="f32"): + if manifest.get("ids_only") and name not in ("prompt_ids", "greedy_ids", "greedy_top2", "greedy_margin"): + return a = t.detach().to(torch.float32 if kind == "f32" else torch.int32).cpu().numpy() a.astype(" Date: Thu, 5 Nov 2026 11:44:42 +0100 Subject: [PATCH 04/28] qwen3-asr case tool: layer 0's steps as stages (#2105) The input norm, the attention before o_proj, o_proj, the post-attention norm and the MLP of the first decoder layer, so a wrong LM stage is found inside its first layer. --- tools/zig/qwen3_asr_case.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tools/zig/qwen3_asr_case.py b/tools/zig/qwen3_asr_case.py index 35267a80e7e..582c5c3078b 100644 --- a/tools/zig/qwen3_asr_case.py +++ b/tools/zig/qwen3_asr_case.py @@ -78,6 +78,10 @@ def hook(_m, args): manifest["attention"] = "global" if a.global_attention else "windows" hooks.append(lm.layers[0].register_forward_pre_hook(tap_in("lm_embed"))) hooks.append(lm.norm.register_forward_hook(tap("lm_norm"))) + l0 = lm.layers[0] # layer 0's steps: a wrong LM stage is found inside its first layer + hooks += [l0.input_layernorm.register_forward_hook(tap("lm0_norm")), l0.self_attn.o_proj.register_forward_pre_hook(tap_in("lm0_attn")), + l0.self_attn.o_proj.register_forward_hook(tap("lm0_o")), l0.post_attention_layernorm.register_forward_hook(tap("lm0_post")), + l0.mlp.register_forward_hook(tap("lm0_mlp"))] for i in (0, len(lm.layers) // 2, len(lm.layers) - 1): hooks.append(lm.layers[i].register_forward_hook(tap(f"lm_layer{i}"))) inputs = inputs.to(model.dtype) @@ -91,7 +95,7 @@ def hook(_m, args): save(a.out, manifest, name, taps[name][0]) ids = inputs["input_ids"][0] save(a.out, manifest, "prompt_ids", ids, "i32") - for name in [k for k in taps if k.startswith("lm_")]: + for name in [k for k in taps if k.startswith("lm")]: save(a.out, manifest, name, taps[name][0][0]) new = gen.sequences[0, ids.shape[0]:] save(a.out, manifest, "greedy_ids", new, "i32") From e04071f4a058ed6bc066e63373fb2c7bef42e6ca 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 11:44:42 +0100 Subject: [PATCH 05/28] qwen3-asr: the CUDA binding, tower and Qwen3 LM, greedy on one stream (#2105) families/qwen3_asr/cuda/ binds the shared schedules: a device store for the weights by name and the scratch, the tower over vit.cu's LayerNorm, pointwise and cuBLASLt Linear kernels, and the LM over the shared rows (addRmsTail, qk_rows, Nemotron's chunked GQA attention, SwiGLU). New kernels: tf_vit_conv_cols (3x3 stride-2 conv taps, channels last), tf_vit_conv_flatten (torch's [c, f] rows) and vision_kernel<64, 8>; qwen3-asr-contract registers all three, each copy with a planted control, and their usage is recorded for nvcc 13.0 and 13.2. The LM schedule dumps its stages (lm_embed, layer 0's steps, lm_layer{i}, lm_norm), and its first post-attention norm takes the embeddings as the stream (the input norm writes no h without a residual). tf-qwen3-asr runs a clip against a case: on 40 public clips (LibriSpeech test-clean, FLEURS cmn test) 38 greedy transcripts are byte-identical to the package's windowed reference; the two others split at near-ties (margins 0.000 and 0.25 on the reference's side). --- zig/build/cuda.zig | 1 + zig/build/qwen3_asr_cuda.zig | 10 + zig/kernels/cuda/contract_controls_set.cu | 1 + .../cuda/contract_qwen3_asr_controls.cuh | 33 +++ zig/kernels/cuda/prefill_attention.cu | 3 + zig/kernels/cuda/vit.cu | 31 ++- .../core/contract/qwen3_asr_cuda_records.zig | 24 ++ zig/src/core/contract/registry_joins.zig | 4 +- .../core/contract/registry_pending_test.zig | 3 + zig/src/cuda/vit.zig | 28 ++- zig/src/families/qwen3_asr/cuda/lm.zig | 204 ++++++++++++++++ zig/src/families/qwen3_asr/cuda/model.zig | 91 ++++++++ zig/src/families/qwen3_asr/cuda/store.zig | 61 +++++ zig/src/families/qwen3_asr/cuda/tower.zig | 110 +++++++++ zig/src/families/qwen3_asr/lm.zig | 30 ++- zig/src/families/qwen3_asr/qwen3_asr_cuda.zig | 10 + zig/src/families/qwen3_asr/schedule_test.zig | 3 + zig/tests/cuda/contract_family_sets.zig | 5 + zig/tests/cuda/contract_qwen3_asr.zig | 218 ++++++++++++++++++ zig/tests/cuda/contract_qwen3_asr_attn.zig | 161 +++++++++++++ zig/tests/cuda/main.zig | 1 + zig/tests/qwen3_asr_cuda.zig | 199 ++++++++++++++++ 22 files changed, 1226 insertions(+), 5 deletions(-) create mode 100644 zig/build/qwen3_asr_cuda.zig create mode 100644 zig/kernels/cuda/contract_qwen3_asr_controls.cuh create mode 100644 zig/src/core/contract/qwen3_asr_cuda_records.zig create mode 100644 zig/src/families/qwen3_asr/cuda/lm.zig create mode 100644 zig/src/families/qwen3_asr/cuda/model.zig create mode 100644 zig/src/families/qwen3_asr/cuda/store.zig create mode 100644 zig/src/families/qwen3_asr/cuda/tower.zig create mode 100644 zig/src/families/qwen3_asr/qwen3_asr_cuda.zig create mode 100644 zig/tests/cuda/contract_qwen3_asr.zig create mode 100644 zig/tests/cuda/contract_qwen3_asr_attn.zig create mode 100644 zig/tests/qwen3_asr_cuda.zig diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index 6e107f8f134..d2db1468e0b 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -162,6 +162,7 @@ pub fn targets(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.bu b.getInstallStep().dependOn(&q35_install.step); b.step("qwen35-cuda", "Build the Qwen CUDA forward and raw state receipt tool").dependOn(&q35_install.step); @import("moss_image_tools.zig").install(b, target, optimize, strip, cuda, mods.core); + @import("qwen3_asr_cuda.zig").tool(b, target, optimize, cuda, mods.core, mods.tokenizer, strip); const d3_tool = b.createModule(.{ .root_source_file = b.path("zig/src/families/drama3/generate.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "core", .module = mods.core }, .{ .name = "drama3", .module = @import("drama3_host.zig").module(b, target, optimize, cuda, mods.core) } } }); const d3_exe = b.addExecutable(.{ .name = "drama3-generate", .root_module = d3_tool }); b.step("drama3-generate", "Drama generation and replay controls on CUDA").dependOn(&b.addInstallArtifact(d3_exe, .{}).step); diff --git a/zig/build/qwen3_asr_cuda.zig b/zig/build/qwen3_asr_cuda.zig new file mode 100644 index 00000000000..1150989d223 --- /dev/null +++ b/zig/build/qwen3_asr_cuda.zig @@ -0,0 +1,10 @@ +//! tf-qwen3-asr: Qwen3-ASR's tower and language model on CUDA, a clip at a time against a reference case. +const std = @import("std"); + +pub fn tool(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, core: *std.Build.Module, tokenizer: *std.Build.Module, strip: ?bool) void { + const family = b.createModule(.{ .root_source_file = b.path("zig/src/families/qwen3_asr/qwen3_asr_cuda.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core } } }); + const main = b.createModule(.{ .root_source_file = b.path("zig/tests/qwen3_asr_cuda.zig"), .target = target, .optimize = optimize, .link_libc = true, .strip = strip, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "qwen3_asr", .module = family }, .{ .name = "tokenizer", .module = tokenizer } } }); + const exe = b.addExecutable(.{ .name = "tf-qwen3-asr", .root_module = main }); + b.installArtifact(exe); + b.step("tf-qwen3-asr", "Build tf-qwen3-asr, Qwen3-ASR's CUDA tower and language model on a clip").dependOn(&b.addInstallArtifact(exe, .{}).step); +} diff --git a/zig/kernels/cuda/contract_controls_set.cu b/zig/kernels/cuda/contract_controls_set.cu index df0f2139831..9469c0ea90a 100644 --- a/zig/kernels/cuda/contract_controls_set.cu +++ b/zig/kernels/cuda/contract_controls_set.cu @@ -10,3 +10,4 @@ #include "contract_hcn_controls.cuh" // Idol decoders: controls for rounding, sums and exceptional values. #include "contract_controls_idol_decoder.cuh" +#include "contract_qwen3_asr_controls.cuh" diff --git a/zig/kernels/cuda/contract_qwen3_asr_controls.cuh b/zig/kernels/cuda/contract_qwen3_asr_controls.cuh new file mode 100644 index 00000000000..5d156766e7a --- /dev/null +++ b/zig/kernels/cuda/contract_qwen3_asr_controls.cuh @@ -0,0 +1,33 @@ +// Gate 3: vit.cu's conv taps and flatten for Qwen3-ASR's tower, each with one planted fault the shapes gate must catch. +#pragma once + +// tf_vit_conv_cols reading the clamped edge sample where the conv's padding is zero. +extern "C" __global__ void __launch_bounds__(256) tf_ctl_vit_conv_cols_edge(const __nv_bfloat16* __restrict__ X, + __nv_bfloat16* __restrict__ Y, int fi, int ti, + int c, int ld) { + const int fo = (fi - 1) / 2 + 1, to = (ti - 1) / 2 + 1; + const int64_t r = blockIdx.x; + const int64_t n = r / (static_cast(fo) * to); + const int f = static_cast(r / to % fo), t = static_cast(r % to); + const int j = blockIdx.y * 256 + threadIdx.x; + if (j >= ld) return; + __nv_bfloat16 v = __float2bfloat16_rn(0.0f); + if (j < 9 * c) { + const int ci = j / 9, kh = j % 9 / 3, kw = j % 3; + const int sf = min(max(2 * f - 1 + kh, 0), fi - 1), st = min(max(2 * t - 1 + kw, 0), ti - 1); + v = X[((n * fi + sf) * ti + st) * c + ci]; + } + Y[r * ld + j] = v; +} + +// tf_vit_conv_flatten writing a row f-major (f c + ci) where torch flattens [c][f] (ci f + fb). +extern "C" __global__ void __launch_bounds__(256) tf_ctl_vit_conv_flatten_fc(const __nv_bfloat16* __restrict__ X, + __nv_bfloat16* __restrict__ Y, int f, int t, + int c) { + const int64_t row = blockIdx.x, n = row / t; + const int tt = static_cast(row % t); + for (int e = threadIdx.x; e < c * f; e += 256) { + const int fb = e / c, ci = e % c; + Y[row * c * f + e] = X[((n * f + fb) * t + tt) * c + ci]; + } +} diff --git a/zig/kernels/cuda/prefill_attention.cu b/zig/kernels/cuda/prefill_attention.cu index 1c6e0f073df..d0be0a7b089 100644 --- a/zig/kernels/cuda/prefill_attention.cu +++ b/zig/kernels/cuda/prefill_attention.cu @@ -335,6 +335,9 @@ template __global__ void tf_prefill_attention::full_kernel<72, 8, 8>(const __nv_ // Head dim 80, eight warps, two blocks an SM (RADIO's tower, 16 heads of 80): full_kernel<80>'s bits, 1.35x faster. template __global__ void tf_prefill_attention::vision_kernel<80, 8>(const __nv_bfloat16* __restrict__, __nv_bfloat16* __restrict__, int, int, float); +// Head dim 64, eight warps (Qwen3-ASR's audio tower, 14 or 16 heads of 64 over a window of its rows). +template __global__ void tf_prefill_attention::vision_kernel<64, 8>(const __nv_bfloat16* __restrict__, __nv_bfloat16* __restrict__, int, int, + float); // Head dim 128, eight warps (MOSS-Image's denoiser, 24 heads of 128 over its image and prompt rows). template __global__ void tf_prefill_attention::vision_kernel<128, 8>(const __nv_bfloat16* __restrict__, __nv_bfloat16* __restrict__, int, int, float); diff --git a/zig/kernels/cuda/vit.cu b/zig/kernels/cuda/vit.cu index 47faadecc80..def2b3303d6 100644 --- a/zig/kernels/cuda/vit.cu +++ b/zig/kernels/cuda/vit.cu @@ -1,4 +1,4 @@ -// Vision towers' glue (cuda/vit.zig; LFM2-VL's SigLIP2, RADIO): LayerNorm, Linear epilogues, activations, unshuffle. +// Vision and audio towers' glue (cuda/vit.zig): LayerNorm, Linear epilogues, activations, unshuffle, conv taps. #include #include @@ -91,6 +91,35 @@ extern "C" __global__ void __launch_bounds__(NT) tf_vit_unshuffle(const __nv_bfl } } +// Block (row (n, fo, to), columns): 3x3 stride-2 pad-1 taps of X [n][fi][ti][c], column ci 9 + kh 3 + kw; 0 past 9 c. +extern "C" __global__ void __launch_bounds__(NT) tf_vit_conv_cols(const __nv_bfloat16* __restrict__ X, __nv_bfloat16* __restrict__ Y, int fi, + int ti, int c, int ld) { + const int fo = (fi - 1) / 2 + 1, to = (ti - 1) / 2 + 1; + const int64_t r = blockIdx.x; + const int64_t n = r / (static_cast(fo) * to); + const int f = static_cast(r / to % fo), t = static_cast(r % to); + const int j = blockIdx.y * NT + threadIdx.x; + if (j >= ld) return; + __nv_bfloat16 v = __float2bfloat16_rn(0.0f); + if (j < 9 * c) { + const int ci = j / 9, kh = j % 9 / 3, kw = j % 3; + const int sf = 2 * f - 1 + kh, st = 2 * t - 1 + kw; + if (sf >= 0 && st >= 0 && sf < fi && st < ti) v = X[((n * fi + sf) * ti + st) * c + ci]; + } + Y[r * ld + j] = v; +} + +// Block a row (n, t): Y [n][t][c * f + fb] = X [n][fb][t][c], a conv's channels-last rows as torch flattens [c][f]. +extern "C" __global__ void __launch_bounds__(NT) tf_vit_conv_flatten(const __nv_bfloat16* __restrict__ X, __nv_bfloat16* __restrict__ Y, int f, + int t, int c) { + const int64_t row = blockIdx.x, n = row / t; + const int tt = static_cast(row % t); + for (int e = threadIdx.x; e < c * f; e += NT) { + const int ci = e / f, fb = e % f; + Y[row * c * f + e] = X[((n * f + fb) * t + tt) * c + ci]; + } +} + // Element i: bf16(x), round to nearest even (a picture's float patches for the tower's first Linear). extern "C" __global__ void __launch_bounds__(NT) tf_vit_cast(const float* __restrict__ X, __nv_bfloat16* __restrict__ Y, int64_t count) { const int64_t at = static_cast(blockIdx.x) * NT + threadIdx.x; diff --git a/zig/src/core/contract/qwen3_asr_cuda_records.zig b/zig/src/core/contract/qwen3_asr_cuda_records.zig new file mode 100644 index 00000000000..4e2ab3c3212 --- /dev/null +++ b/zig/src/core/contract/qwen3_asr_cuda_records.zig @@ -0,0 +1,24 @@ +//! Qwen3-ASR's CUDA launches: the tower's conv taps and flatten (vit.cu), and full attention at head dim 64. +const std = @import("std"); +const registry = @import("registry.zig"); + +/// nvcc 13.0's usage, the compiler of the release fatbins. +pub const cuda = [_]registry.CudaRecord{ + .{ .launch = .{ .name = "vit tf_vit_conv_cols (Qwen3-ASR)", .symbol = "tf_vit_conv_cols", .image = "vit", .threads = 256 }, .usage = .{ .{ .regs = 22, .static = 0, .bound = 256 }, .{ .regs = 22, .static = 0, .bound = 256 }, .{ .regs = 22, .static = 0, .bound = 256 }, .{ .regs = 22, .static = 0, .bound = 256 }, .{ .regs = 22, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "vit tf_vit_conv_flatten (Qwen3-ASR)", .symbol = "tf_vit_conv_flatten", .image = "vit", .threads = 256 }, .usage = .{ .{ .regs = 31, .static = 0, .bound = 256 }, .{ .regs = 36, .static = 0, .bound = 256 }, .{ .regs = 36, .static = 0, .bound = 256 }, .{ .regs = 34, .static = 0, .bound = 256 }, .{ .regs = 34, .static = 0, .bound = 256 } } }, + .{ .launch = .{ .name = "vit vision_kernel<64, 8> (Qwen3-ASR)", .symbol = "_ZN20tf_prefill_attention13vision_kernelILi64ELi8EEEvPK13__nv_bfloat16PS1_iif", .image = "prefill_attention", .threads = 256, .dynamic = 36864 }, .usage = .{ .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 120, .static = 0, .bound = 256 }, .{ .regs = 120, .static = 0, .bound = 256 } } }, +}; + +/// nvcc 13.2's: the attention at 64 takes 8 more registers on sm_120 and sm_121; the copies compile the same. +pub const cuda_132 = [_]registry.Override{ + .{ .name = "vit vision_kernel<64, 8> (Qwen3-ASR)", .usage = .{ .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 132, .static = 0, .bound = 256 }, .{ .regs = 128, .static = 0, .bound = 256 }, .{ .regs = 128, .static = 0, .bound = 256 } } }, +}; + +test "Qwen3-ASR CUDA: every launch is in the live registry and fits every SM" { + for (cuda) |r| { + var found: usize = 0; + for (registry.all_cuda) |active| found += @intFromBool(std.mem.eql(u8, active.launch.name, r.launch.name)); + try std.testing.expectEqual(@as(usize, 1), found); + try std.testing.expectEqual(@as(usize, 0), try registry.checkCuda(std.testing.allocator, &.{r}, true)); + } +} diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index 4a3ebbaa106..6b4e5f243ef 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -22,6 +22,7 @@ pub const cuda_after = @import("registry_media.zig").cuda ++ @import("moss_image_cuda_records.zig").cuda ++ @import("nemo_audio_cuda_records.zig").cuda ++ @import("idol_cuda_sets.zig").cuda ++ + @import("qwen3_asr_cuda_records.zig").cuda ++ @import("exl3_dense_records.zig").cuda ++ @import("exl3_finish_records.zig").cuda ++ @import("lfm2_moe_cuda_records.zig").cuda ++ @@ -38,7 +39,8 @@ pub const nvcc_132_after = @import("registry_learning.zig").cuda_132 ++ @import("experts_bf16_records.zig").cuda_132 ++ @import("pocket_records.zig").cuda_132 ++ @import("minimax_cuda_records.zig").cuda_132 ++ - @import("inkling2_cuda_records.zig").cuda_132; + @import("inkling2_cuda_records.zig").cuda_132 ++ + @import("qwen3_asr_cuda_records.zig").cuda_132; pub const nvcc_133_after = @import("flashnext_tile_records.zig").cuda_133 ++ @import("glm_cuda_records.zig").cuda_133 ++ @import("nvcc_133_records.zig").cuda_133 ++ diff --git a/zig/src/core/contract/registry_pending_test.zig b/zig/src/core/contract/registry_pending_test.zig index 26d0a9a4cad..6a49cc39d07 100644 --- a/zig/src/core/contract/registry_pending_test.zig +++ b/zig/src/core/contract/registry_pending_test.zig @@ -1,6 +1,9 @@ //! Missing 13.0 resources still refuse qualification after measured rows are restored. const std = @import("std"); const registry = @import("registry.zig"); +test { + _ = @import("qwen3_asr_cuda_records.zig"); +} const limits = @import("limits.zig"); const none = registry.none; const cuda_pending = registry.cuda_pending; diff --git a/zig/src/cuda/vit.zig b/zig/src/cuda/vit.zig index 4f765f5f6e4..0e9068dab46 100644 --- a/zig/src/cuda/vit.zig +++ b/zig/src/cuda/vit.zig @@ -1,4 +1,4 @@ -//! Vision towers' shared glue (vit.cu), torch Linears through cuBLASLt, and full attention over a picture's rows. +//! Vision and audio towers' shared glue (vit.cu), torch Linears through cuBLASLt, and full attention over their rows. const std = @import("std"); const kernels = @import("kernels.zig"); const module = @import("module.zig"); @@ -34,6 +34,8 @@ pub const Kernels = struct { unshuffle_fn: module.Function, cast_fn: module.Function, position_fn: module.Function, + conv_cols_fn: module.Function, + conv_flatten_fn: module.Function, pub fn load(d: *const Driver) !Kernels { if (!kernels.available) return error.BuiltWithoutKernels; @@ -52,6 +54,8 @@ pub const Kernels = struct { .unshuffle_fn = try mod.function("tf_vit_unshuffle"), .cast_fn = try mod.function("tf_vit_cast"), .position_fn = try mod.function("tf_vit_position_add"), + .conv_cols_fn = try mod.function("tf_vit_conv_cols"), + .conv_flatten_fn = try mod.function("tf_vit_conv_flatten"), }; } @@ -155,6 +159,25 @@ pub const Kernels = struct { try go(k.cast_fn, s, blocks(count, threads), 1, &a); } + /// y [n fo to, ld]: the 3x3 stride-2 pad-1 conv taps of x [n, fi, ti, c] (channels last), zero past 9 c columns. + pub fn convCols(k: *const Kernels, s: Stream, x: u64, y: u64, n: usize, fi: usize, ti: usize, c: usize, ld: usize) !void { + if (ld < 9 * c or fi == 0 or ti == 0) return error.RowShape; + var a: Args = .{}; + a.add(x); + a.add(y); + for ([_]usize{ fi, ti, c, ld }) |v| a.add(int(v)); + try go(k.conv_cols_fn, s, n * ((fi - 1) / 2 + 1) * ((ti - 1) / 2 + 1), blocks(ld, threads), &a); + } + + /// y [n t, c f] = x [n, f, t, c] with each row's (f, c) block transposed: torch's flatten of a [c, f] conv row. + pub fn convFlatten(k: *const Kernels, s: Stream, x: u64, y: u64, n: usize, f: usize, t: usize, c: usize) !void { + var a: Args = .{}; + a.add(x); + a.add(y); + for ([_]usize{ f, t, c }) |v| a.add(int(v)); + try go(k.conv_flatten_fn, s, n * t, 1, &a); + } + /// o [h * w, c] = bf16(x + bf16(the table [side * side, c] resized to the longer side's square, y < h, x < w)). pub fn positionAdd(k: *const Kernels, s: Stream, x: u64, table: u64, o: u64, h: usize, w: usize, side: usize, c: usize) !void { var a: Args = .{}; @@ -272,8 +295,9 @@ const Full = struct { } }; -/// Full attention by head dim: SigLIP2's 72, RADIO's 80 (full_kernel's bits in one barrier a tile), MOSS-Image's 128. +/// Full attention by head dim: Qwen3-ASR's 64, SigLIP2's 72, RADIO's 80 (full_kernel's bits), MOSS-Image's 128. const fulls = [_]Full{ + .{ .dim = 64, .warps = 8 }, .{ .dim = 72, .warps = 8, .slots = 8 }, .{ .dim = 80, .warps = 8 }, .{ .dim = 128, .warps = 8 }, diff --git a/zig/src/families/qwen3_asr/cuda/lm.zig b/zig/src/families/qwen3_asr/cuda/lm.zig new file mode 100644 index 00000000000..020ed87f28e --- /dev/null +++ b/zig/src/families/qwen3_asr/cuda/lm.zig @@ -0,0 +1,204 @@ +//! The Qwen3 language model's binding on CUDA's shared rows: RMS norms, QK norm with RoPE, Nemotron's GQA attention. +const std = @import("std"); +const cuda = @import("cuda"); +const cfg = @import("../config.zig"); +const shared = @import("../lm.zig"); +const store = @import("store.zig"); + +/// nemotron_attention.cu's chunk: keys a partial covers, and the most chunk blocks a row launches. +const chunk_keys = 512; +const chunk_blocks = 64; + +const Attn = struct { + mod: cuda.Module, + chunk: cuda.Function, + chunk_pf: cuda.Function, + merge: cuda.Function, + + fn load(d: *const cuda.Driver) !Attn { + if (!cuda.kernels.available) return error.BuiltWithoutKernels; + var mod = try cuda.Module.load(d, cuda.kernels.nemotron_attention); + errdefer mod.unload(); + const f = .{ try mod.function("tf_nemo_attn_chunk"), try mod.function("tf_nemo_attn_chunk_pf"), try mod.function("tf_nemo_attn_merge") }; + return .{ .mod = mod, .chunk = f[0], .chunk_pf = f[1], .merge = f[2] }; + } +}; + +pub const Lm = struct { + t: cfg.Text, + d: *const cuda.Driver, + s: cuda.Stream, + g: cuda.vit.Gemms, + nm: cuda.norms.Norms, + qk: cuda.qk_rows.QkRows, + act: cuda.act_rows.ActRows, + emb: cuda.embed_rows.EmbedRows, + attn: Attn, + cap: usize, // positions the caches hold + b: Buffers, + host_ids: []i32, + host_pos: []i32, + logits: []u16, + last_margin: f32 = 0, // the last pick's lead over the runner-up + sink: ?@import("tower.zig").Dump = null, + + const Buffers = struct { ids: u64, pos: u64, meta: u64, q: u64, k: u64, v: u64, po: u64, pm: u64, pl: u64, xs: u64, logits: u64, cos: u64, sin: u64, kc: u64, vc: u64 }; + + /// Passes of up to `max_rows` rows over up to `span` positions. + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, s: cuda.Stream, t: cfg.Text, max_rows: usize, span: usize, st: *store.Store) !Lm { + if (t.head_dim != 128 or t.heads % t.kv_heads != 0 or t.heads / t.kv_heads > 16) return error.UnsupportedQwen3AsrGeometry; + const cap = std.mem.alignForward(usize, span, chunk_keys); + if (cap > t.context) return error.ContextTooLong; + var lm: Lm = undefined; + lm.t = t; + lm.d = d; + lm.s = s; + lm.cap = cap; + lm.g = try cuda.vit.Gemms.init(gpa, d); + errdefer lm.g.deinit(); + lm.nm = try cuda.norms.Norms.load(d); + errdefer lm.nm.unload(); + lm.qk = try cuda.qk_rows.QkRows.load(d); + errdefer lm.qk.unload(); + lm.act = try cuda.act_rows.ActRows.load(d); + errdefer lm.act.unload(); + lm.emb = try cuda.embed_rows.EmbedRows.load(d); + errdefer lm.emb.unload(); + lm.attn = try Attn.load(d); + errdefer lm.attn.mod.unload(); + const r = max_rows; + const qd = t.heads * t.head_dim; + const kvd = t.kv_heads * t.head_dim; + const nch = cap / chunk_keys; + const kv = t.layers * cap * kvd * 2; + lm.b = .{ + .ids = try st.alloc(4 * r), + .pos = try st.alloc(4 * r), + .meta = try st.alloc(4), + .q = try st.alloc(2 * r * qd), + .k = try st.alloc(2 * r * kvd), + .v = try st.alloc(2 * r * kvd), + .po = try st.alloc(4 * r * nch * qd), + .pm = try st.alloc(4 * r * nch * t.heads), + .pl = try st.alloc(4 * r * nch * t.heads), + .xs = try st.alloc(4 * r * qd / 64), + .logits = try st.alloc(2 * t.vocab), + .cos = try st.alloc(4 * cap * t.head_dim), + .sin = try st.alloc(4 * cap * t.head_dim), + .kc = try st.alloc(kv), + .vc = try st.alloc(kv), + }; + const cs = try gpa.alloc(f32, cap * t.head_dim); + defer gpa.free(cs); + const sn = try gpa.alloc(f32, cap * t.head_dim); + defer gpa.free(sn); + shared.ropeTables(t, cs, sn, cap); + try store.view(d, lm.b.cos, cs.len * 4).upload(0, std.mem.sliceAsBytes(cs)); + try store.view(d, lm.b.sin, sn.len * 4).upload(0, std.mem.sliceAsBytes(sn)); + lm.host_ids = try gpa.alloc(i32, r); + errdefer gpa.free(lm.host_ids); + lm.host_pos = try gpa.alloc(i32, r); + errdefer gpa.free(lm.host_pos); + 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.host_pos); + gpa.free(lm.host_ids); + lm.attn.mod.unload(); + lm.emb.unload(); + lm.act.unload(); + lm.qk.unload(); + lm.nm.unload(); + lm.g.deinit(); + } + + /// The pass's ids and positions [pos, pos + ids.len) on the device; the first position is the attention's. + pub fn positions(lm: *Lm, ids: []const u32, pos: usize) !void { + const rows = ids.len; + if (rows > lm.host_ids.len) return error.PassRows; + if (pos + rows > lm.cap) return error.ContextFull; + for (ids, lm.host_ids[0..rows], lm.host_pos[0..rows], 0..) |id, *x, *p, i| { + x.* = @intCast(id); + p.* = @intCast(pos + i); + } + try lm.s.synchronize(); // the last pass may still read them + try store.view(lm.d, lm.b.ids, 4 * rows).upload(0, std.mem.sliceAsBytes(lm.host_ids[0..rows])); + try store.view(lm.d, lm.b.pos, 4 * rows).upload(0, std.mem.sliceAsBytes(lm.host_pos[0..rows])); + try store.view(lm.d, lm.b.meta, 4).upload(0, std.mem.asBytes(&lm.host_pos[0])); + } + + 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); + } + + pub fn embed(lm: *Lm, table: u64, out: u64, rows: usize, hidden: usize) !void { + try lm.emb.bf16(lm.s, lm.b.ids, table, out, rows, hidden); + } + + pub fn copy(lm: *Lm, dst: u64, src: u64, n: usize) !void { + try store.view(lm.d, dst, n).copyFrom(0, src, n, lm.s.handle); + } + + /// h = bf16(x + res) (x when res is null), 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 { + try lm.nm.addRmsTail(lm.s, x, res, w, h, y, null, rows, lm.t.hidden, lm.t.eps, .{ .round = true }); + } + + pub fn gemm(lm: *Lm, x: u64, w: u64, y: u64, rows: usize, n: usize, k: usize) !void { + try lm.g.run(lm.s, x, w, y, rows, n, k, .bf16); + } + + 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; + const shape: cuda.qk_rows.Shape = .{ .norms = q_norm, .norm_k = k_norm, .norms_bf16 = true, .cos = b.cos, .sin = b.sin, .rot = t.head_dim, .eps = t.eps, .round = true }; + const out: cuda.qk_rows.Out = .{ .q = b.q, .k = b.k, .v = b.v, .kc = lm.kvAt(b.kc, layer), .vc = lm.kvAt(b.vc, layer), .len = lm.cap }; + try lm.qk.rows(lm.s, qkv, .{ .h = t.heads, .hk = t.kv_heads, .dim = t.head_dim }, shape, b.pos, null, out, rows); + } + + /// Causal GQA attention of the pass's q rows over layer's caches into out [rows, heads x dim]. + pub fn attention(lm: *Lm, layer: usize, out: u64, rows: usize) !void { + const t = lm.t; + const b = lm.b; + const qd = t.heads * t.head_dim; + const nch = lm.cap / chunk_keys; + const grp = t.heads / t.kv_heads; + const scale: f32 = @floatCast(1.0 / @sqrt(@as(f64, @floatFromInt(t.head_dim)))); + var a: cuda.Args = .{}; + for ([_]u64{ b.q, lm.kvAt(b.kc, layer), lm.kvAt(b.vc, layer), b.meta, b.po, b.pm, b.pl }) |x| a.add(x); + for ([_]usize{ qd, t.heads, t.kv_heads, grp, chunk_keys, nch }) |x| a.add(@as(c_int, @intCast(x))); + a.add(scale); + a.add(@as(u64, 0)); + a.add(@as(i64, 0)); + const f = if (rows > 1) lm.attn.chunk_pf else lm.attn.chunk; + const grid: cuda.launch.Dim3 = .{ .x = @intCast(rows), .y = @intCast(t.kv_heads), .z = @intCast(@min(nch, chunk_blocks)) }; + try cuda.launch.launch(f, .{ .grid = grid, .block = .{ .x = 256 } }, lm.s, &a); + var m: cuda.Args = .{}; + for ([_]u64{ b.po, b.pm, b.pl, b.meta, out, b.xs }) |x| m.add(x); + for ([_]usize{ t.heads, t.kv_heads, grp, chunk_keys, nch }) |x| m.add(@as(c_int, @intCast(x))); + try cuda.launch.launch(lm.attn.merge, .{ .grid = .{ .x = @intCast(rows), .y = @intCast(t.kv_heads), .z = 1 }, .block = .{ .x = 256 } }, lm.s, &m); + } + + /// out [rows, i] = bf16(silu(gate) up) of gu's [gate | up] rows. + pub fn swiglu(lm: *Lm, gu: u64, out: u64, rows: usize, i: usize) !void { + try lm.act.swiglu(lm.s, gu, 2 * i, gu + i * 2, 2 * i, out, null, rows, 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.g.run(lm.s, row, embed_table, lm.b.logits, 1, lm.t.vocab, lm.t.hidden, .bf16); + try store.view(lm.d, lm.b.logits, lm.logits.len * 2).downloadAsync(0, std.mem.sliceAsBytes(lm.logits), lm.s.handle); + try lm.s.synchronize(); + const best = shared.argmax(lm.logits); + lm.last_margin = shared.margin(lm.logits, best); + return best; + } +}; diff --git a/zig/src/families/qwen3_asr/cuda/model.zig b/zig/src/families/qwen3_asr/cuda/model.zig new file mode 100644 index 00000000000..1b3bf21a8fe --- /dev/null +++ b/zig/src/families/qwen3_asr/cuda/model.zig @@ -0,0 +1,91 @@ +//! Qwen3-ASR on CUDA: the shared tower and Qwen3 schedules over this directory's bindings, one allocation store. +const std = @import("std"); +const cuda = @import("cuda"); +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 ctower = @import("tower.zig"); +const clm = @import("lm.zig"); + +pub const Dump = ctower.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: ctower.Tower, + lr: clm.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, d: *const cuda.Driver, s: cuda.Stream, 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, .d = d }; + 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 ctower.Tower.init(gpa, d, s, c.audio, o.group, o.audio_rows, &m.st); + errdefer m.tr.deinit(); + m.lr = try clm.Lm.init(gpa, d, s, 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/cuda/store.zig b/zig/src/families/qwen3_asr/cuda/store.zig new file mode 100644 index 00000000000..81d4c8821c3 --- /dev/null +++ b/zig/src/families/qwen3_asr/cuda/store.zig @@ -0,0 +1,61 @@ +//! Device memory for the shared schedules: `put` and `taps` place tensors, `alloc` hands out scratch rows. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); + +/// A span another value owns, for one copy into or out of it. +pub fn view(d: *const cuda.Driver, ptr: u64, len: usize) cuda.DeviceBuffer { + return .{ .d = d, .ptr = ptr, .len = len, .borrowed = true }; +} + +/// 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, + d: *const cuda.Driver, + list: std.ArrayList(cuda.DeviceBuffer) = .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 cuda.DeviceBuffer.alloc(st.d, @max(n, 256)); + errdefer b.free(); + try st.list.append(st.gpa, b); + st.bytes += b.len; + return b.ptr; + } + + pub fn put(st: *Store, bytes: []const u8) !u64 { + const p = try st.alloc(bytes.len); + try view(st.d, p, bytes.len).upload(0, bytes); + return p; + } + + /// A conv's [co, k] taps with each row padded with zeros to `ld` (k to a multiple of 8: 16-byte rows for cuBLASLt). + pub fn taps(st: *Store, bytes: []const u8, co: usize, k: usize) !u64 { + const ld = tapsLd(k); + if (ld == k) return st.put(bytes); + const padded = try st.gpa.alloc(u8, co * ld * 2); + defer st.gpa.free(padded); + @memset(padded, 0); + for (0..co) |o| @memcpy(padded[o * ld * 2 ..][0 .. k * 2], bytes[o * k * 2 ..][0 .. k * 2]); + return st.put(padded); + } +}; + +/// The taps' row width a conv's columns use: k rounded up to 8 values. +pub fn tapsLd(k: usize) usize { + return std.mem.alignForward(usize, k, 8); +} diff --git a/zig/src/families/qwen3_asr/cuda/tower.zig b/zig/src/families/qwen3_asr/cuda/tower.zig new file mode 100644 index 00000000000..22a93325e9d --- /dev/null +++ b/zig/src/families/qwen3_asr/cuda/tower.zig @@ -0,0 +1,110 @@ +//! The audio tower's binding on CUDA: vit.cu's conv taps, LayerNorm and pointwise kernels, cuBLASLt, attention at 64. +const std = @import("std"); +const cuda = @import("cuda"); +const cfg = @import("../config.zig"); +const chunks = @import("../chunks.zig"); +const shared = @import("../tower.zig"); +const store = @import("store.zig"); +const vit = cuda.vit; + +/// 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, +}; + +pub const Tower = struct { + d: *const cuda.Driver, + s: cuda.Stream, + vk: vit.Kernels, + g: vit.Gemms, + att: vit.Attention, + cols: u64, // a conv's taps + tmp: u64, // a fused GEMM's bf16 output before its act and residual + acc: u64, // an unfused GEMM's f32 sums + zero: u64, // the bias of a Linear without one + sink: ?Dump = null, + + /// Kernels and scratch for `group` chunks a conv pass and up to `max_rows` rows. + pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, s: cuda.Stream, a: cfg.Audio, group: usize, max_rows: usize, st: *store.Store) !Tower { + var vk = try vit.Kernels.load(d); + errdefer vk.unload(); + var g = try vit.Gemms.init(gpa, d); + errdefer g.deinit(); + var att = try vit.Attention.load(d); + errdefer att.unload(); + const cf = a.chunkFrames(); + const p1 = group * ((a.mels - 1) / 2 + 1) * ((cf - 1) / 2 + 1); // conv1's output positions a group + const rows = @max(max_rows, group) + chunks.rows(cf); + const most = @max(p1 * a.conv, rows * @max(a.ffn, 3 * a.d, a.out)); + const wide = @max(a.d, a.out, a.ffn, a.conv); + const zero = try st.alloc(2 * wide); + try store.view(d, zero, 2 * wide).fill8(0, null); + return .{ + .d = d, + .s = s, + .vk = vk, + .g = g, + .att = att, + .cols = try st.alloc(2 * @max(p1 * store.tapsLd(9), (p1 / 4 + 1) * store.tapsLd(9 * a.conv))), + .tmp = try st.alloc(2 * most), + .acc = try st.alloc(4 * most), + .zero = zero, + }; + } + + pub fn deinit(t: *Tower) void { + t.att.unload(); + t.g.deinit(); + t.vk.unload(); + } + + pub fn upload(t: *Tower, dst: u64, bytes: []const u8) !void { + try store.view(t.d, dst, bytes.len).uploadAsync(0, bytes, t.s.handle); + } + + /// 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 ld = store.tapsLd(9 * c); + try t.vk.convCols(t.s, x, t.cols, n, fi, ti, c, ld); + const rows = n * ((fi - 1) / 2 + 1) * ((ti - 1) / 2 + 1); + try vit.linear(&t.g, &t.vk, t.s, t.acc, t.cols, w, b, y, rows, co, ld); + } + + 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 { + try t.vk.convFlatten(t.s, x, y, n, f, tt, c); + } + + /// y = bf16(act(bf16(x . w^T + b)) + res); a missing bias is zeros. + 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 bias = b orelse t.zero; + if (act == .none and res == null) return vit.linear(&t.g, &t.vk, t.s, t.acc, x, w, bias, y, rows, n, k); + const va: vit.Act = switch (act) { + .none => .none, + .gelu => .gelu, + }; + try vit.linearAct(&t.g, &t.vk, t.s, t.acc, x, w, bias, t.tmp, rows, n, k, res, y, va); + } + + pub fn layernorm(t: *Tower, x: u64, w: u64, b: u64, y: u64, rows: usize, d: usize) !void { + try t.vk.layerNorm(t.s, x, w, b, y, rows, d, 1e-5); + } + + /// Bidirectional attention over one window of `len` rows of [q | k | v] (heads x dim each). + pub fn attention(t: *Tower, qkv: u64, out: u64, len: usize, heads: usize, dim: usize) !void { + const scale: f32 = @floatCast(1.0 / @sqrt(@as(f64, @floatFromInt(dim)))); + try t.att.full(t.s, qkv, out, len, heads, dim, scale); + } + + pub fn gelu(t: *Tower, x: u64, y: u64, count: usize) !void { + try t.vk.pointwise(t.s, x, null, y, count, .gelu); + } + + pub fn sync(t: *Tower) !void { + try t.s.synchronize(); + } +}; diff --git a/zig/src/families/qwen3_asr/lm.zig b/zig/src/families/qwen3_asr/lm.zig index 74017b24c95..e0589f72b0b 100644 --- a/zig/src/families/qwen3_asr/lm.zig +++ b/zig/src/families/qwen3_asr/lm.zig @@ -91,30 +91,45 @@ pub fn forward(r: anytype, t: cfg.Text, w: *const Weights, b: Buffers, ids: []co if (sp.at < pos or sp.at + sp.n > pos + rows) return error.SpliceOutsidePass; try r.copy(b.e + (sp.at - pos) * t.hidden * 2, sp.ptr, sp.n * t.hidden * 2); } + try r.dump("lm_embed", b.e, rows, t.hidden); const qd = t.heads * t.head_dim; const kvd = t.kv_heads * t.head_dim; var x = b.e; var res: ?u64 = null; var cur: usize = 0; + var name: [24]u8 = undefined; for (w.layers, 0..) |l, i| { try r.addNorm(x, res, l.in_norm, b.h[cur], b.y, rows); + if (i > 0) try r.dump(try layerName(&name, i - 1), b.h[cur], rows, t.hidden); // h: the layer before's output + if (i == 0) try r.dump("lm0_norm", b.y, rows, t.hidden); // layer 0's steps, as the case taps them try r.gemm(b.y, l.qkv, b.qkv, rows, qd + 2 * kvd, t.hidden); try r.qkRope(b.qkv, l.q_norm, l.k_norm, i, rows); try r.attention(i, b.att, rows); + if (i == 0) try r.dump("lm0_attn", b.att, rows, qd); try r.gemm(b.att, l.o, b.o, rows, t.hidden, qd); - try r.addNorm(b.o, b.h[cur], l.post_norm, b.h[1 - cur], b.y, rows); + if (i == 0) try r.dump("lm0_o", b.o, rows, t.hidden); + const stream = if (res == null) x else b.h[cur]; // with no residual the norm leaves h unwritten: x is the stream + try r.addNorm(b.o, stream, l.post_norm, b.h[1 - cur], b.y, rows); + if (i == 0) try r.dump("lm0_post", b.y, rows, t.hidden); cur = 1 - cur; try r.gemm(b.y, l.gate_up, b.gu, rows, 2 * t.intermediate, t.hidden); try r.swiglu(b.gu, b.act, rows, t.intermediate); try r.gemm(b.act, l.down, b.dn, rows, t.hidden, t.intermediate); + if (i == 0) try r.dump("lm0_mlp", b.dn, rows, t.hidden); x = b.dn; res = b.h[cur]; cur = 1 - cur; } try r.addNorm(x, res, w.norm, b.h[cur], b.y, rows); + try r.dump(try layerName(&name, w.layers.len - 1), b.h[cur], rows, t.hidden); + try r.dump("lm_norm", b.y, rows, t.hidden); return r.greedy(b.y + (rows - 1) * t.hidden * 2, w.embed); } +fn layerName(buf: *[24]u8, i: usize) ![]const u8 { + return std.fmt.bufPrint(buf, "lm_layer{d}", .{i}); +} + /// The first largest bf16 logit (torch.argmax's tie rule); a NaN logit wins, as torch's max does. pub fn argmax(logits: []const u16) u32 { var best: usize = 0; @@ -130,6 +145,15 @@ pub fn argmax(logits: []const u16) u32 { return @intCast(best); } +/// The pick's lead over the best other logit (a greedy difference is listed with it). +pub fn margin(logits: []const u16, best: u32) f32 { + var other: f32 = -std.math.inf(f32); + for (logits, 0..) |bits, i| if (i != best) { + other = @max(other, @as(f32, @bitCast(@as(u32, bits) << 16))); + }; + return @as(f32, @bitCast(@as(u32, logits[best]) << 16)) - other; +} + /// RoPE's cos and sin at positions [0, n) as transformers stores them: fp32 angles, the values cast to bf16. pub fn ropeTables(t: cfg.Text, cs: []f32, sn: []f32, n: usize) void { const dim = t.head_dim; @@ -151,6 +175,10 @@ test "argmax: the first of equal logits, a NaN first" { try std.testing.expectEqual(@as(u32, 2), argmax(&.{ 0x3f80, 0x4000, 0x7fc0 })); } +test "margin: the lead over the runner-up" { + try std.testing.expectEqual(@as(f32, 1), margin(&.{ 0x3f80, 0x4000, 0x3f80 }, 1)); +} + test "ropeTables: position 0 is cos 1, sin 0; the halves repeat" { const t: cfg.Text = .{ .hidden = 8, .layers = 1, .heads = 1, .kv_heads = 1, .head_dim = 4, .intermediate = 8, .vocab = 4, .eps = 1e-6, .theta = 1e6, .context = 8 }; var cs: [8]f32 = undefined; diff --git a/zig/src/families/qwen3_asr/qwen3_asr_cuda.zig b/zig/src/families/qwen3_asr/qwen3_asr_cuda.zig new file mode 100644 index 00000000000..3a840342347 --- /dev/null +++ b/zig/src/families/qwen3_asr/qwen3_asr_cuda.zig @@ -0,0 +1,10 @@ +//! Qwen3-ASR on CUDA: cuda/ binds the shared schedules (tower.zig, lm.zig) to the kernels; tf-qwen3-asr drives it. +pub const host = @import("qwen3_asr.zig"); +pub const Model = @import("cuda/model.zig").Model; +pub const Options = @import("cuda/model.zig").Options; +pub const Dump = @import("cuda/model.zig").Dump; +pub const Splice = @import("cuda/model.zig").Splice; + +test { + _ = @import("cuda/model.zig"); +} diff --git a/zig/src/families/qwen3_asr/schedule_test.zig b/zig/src/families/qwen3_asr/schedule_test.zig index 66f3e75a4d8..1b41a2fb00d 100644 --- a/zig/src/families/qwen3_asr/schedule_test.zig +++ b/zig/src/families/qwen3_asr/schedule_test.zig @@ -293,6 +293,9 @@ const LmBounds = struct { try b.touch(gu, rows * 2 * i); try b.touch(out, rows * i); } + pub fn dump(b: *LmBounds, _: []const u8, ptr: u64, rows: usize, cols: usize) !void { + try b.touch(ptr, rows * cols); + } pub fn greedy(b: *LmBounds, row: u64, embed_table: u64) !u32 { try b.touch(row, b.t.hidden); try b.touch(embed_table, b.t.vocab * b.t.hidden); diff --git a/zig/tests/cuda/contract_family_sets.zig b/zig/tests/cuda/contract_family_sets.zig index 7a3f7891ff7..71fcd0954bf 100644 --- a/zig/tests/cuda/contract_family_sets.zig +++ b/zig/tests/cuda/contract_family_sets.zig @@ -16,6 +16,7 @@ pub const Sets = struct { inkling2: *@import("contract_inkling2.zig").Set, moss: *@import("contract_moss_image.zig").Set, nemo_audio: *@import("contract_nemo_audio.zig").Set, + qwen3_asr: *@import("contract_qwen3_asr.zig").Set, modelopt: *@import("contract_flashnext_modelopt.zig").Set, grouped: *Grouped, flashnext: *@import("contract_flashnext_more.zig").Set, @@ -42,6 +43,8 @@ pub const Sets = struct { errdefer moss.deinit(); const nemo_audio = try @import("contract_nemo_audio.zig").Set.init(gpu, s, a, list); errdefer nemo_audio.deinit(); + const qwen3_asr = try @import("contract_qwen3_asr.zig").Set.init(gpu, s, a, list); + errdefer qwen3_asr.deinit(); const modelopt = try @import("contract_flashnext_modelopt.zig").Set.init(gpu, s, a, list); errdefer modelopt.deinit(); const grouped = try gpu.gpa.create(Grouped); @@ -82,6 +85,7 @@ pub const Sets = struct { .inkling2 = inkling2, .moss = moss, .nemo_audio = nemo_audio, + .qwen3_asr = qwen3_asr, .modelopt = modelopt, .grouped = grouped, .flashnext = flashnext, @@ -110,6 +114,7 @@ pub const Sets = struct { sets.grouped.deinit(); sets.gpa.destroy(sets.grouped); sets.modelopt.deinit(); + sets.qwen3_asr.deinit(); sets.nemo_audio.deinit(); sets.moss.deinit(); sets.inkling2.deinit(); diff --git a/zig/tests/cuda/contract_qwen3_asr.zig b/zig/tests/cuda/contract_qwen3_asr.zig new file mode 100644 index 00000000000..4715da99731 --- /dev/null +++ b/zig/tests/cuda/contract_qwen3_asr.zig @@ -0,0 +1,218 @@ +//! Qwen3-ASR's tower kernels under the contract (qwen3-asr-contract): vit.cu's conv taps and flatten, attention at 64. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const check = @import("check.zig"); +const rig_ = @import("contract_rig.zig"); +const full = @import("contract_qwen3_asr_attn.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; + +const controls = struct { + pub const bytes align(16) = @embedFile("fatbin_contract_controls").*; +}; + +fn depth(_: c.Shape) usize { + return 0; +} + +/// A conv's geometry in a shape: rows the chunks, n the channels, k = fi 256 + ti. +fn geometry(s: c.Shape) struct { n: usize, c: usize, fi: usize, ti: usize } { + return .{ .n = s.rows, .c = s.n, .fi = s.k / 256, .ti = s.k % 256 }; +} + +/// The served convs (two chunks of each of the tower's three) and odd small grids for the padding's edges. +const conv_shapes = [_]c.Shape{ .{ .rows = 2, .n = 1, .k = 128 * 256 + 100 }, .{ .rows = 2, .n = 480, .k = 64 * 256 + 50 }, .{ .rows = 2, .n = 480, .k = 32 * 256 + 25 }, .{ .rows = 3, .n = 3, .k = 7 * 256 + 5 }, .{ .rows = 1, .n = 1, .k = 1 * 256 + 1 }, .{ .rows = 1, .n = 33, .k = 2 * 256 + 9 } }; +const flat_shapes = [_]c.Shape{ .{ .rows = 2, .n = 480, .k = 16 * 256 + 13 }, .{ .rows = 3, .n = 8, .k = 5 * 256 + 3 }, .{ .rows = 1, .n = 1, .k = 1 * 256 + 1 } }; + +pub fn spec(name: []const u8, served: []const c.Shape) c.Spec { + return .{ + .name = name, + .accum = .none, // copies: every output checked bit for bit against the host's replay + .depth = depth, + .out = .bf16, + .served = served, + }; +} + +/// tf_vit_conv_cols (`flatten` false) or tf_vit_conv_flatten on random bf16 rows, against the host's copy. +pub const Move = struct { + rig: rig_.Rig, + vk: *const cuda.vit.Kernels, + flatten: bool, + name: []const u8, + ctl: ?cuda.Function = null, + x: []u16 = &.{}, + want: []u16 = &.{}, + dev: [2]u64 = undefined, + shape: c.Shape = undefined, + msg: [160]u8 = undefined, + + pub fn deinit(self: *Move) void { + const a = self.rig.gpu.gpa; + a.free(self.x); + a.free(self.want); + self.rig.deinit(); + } + + const vt = g.hooks(Move); + + pub fn kernel(self: *Move) g.Kernel { + return .{ .spec = spec(self.name, if (self.flatten) &flat_shapes else &conv_shapes), .ctx = self, .vt = &vt, .control = if (self.ctl != null) .shapes else null }; + } + + fn ld(gm: anytype) usize { + return std.mem.alignForward(usize, 9 * gm.c, 8); + } + + /// Output rows and their width. + fn outShape(self: *const Move) [2]usize { + const gm = geometry(self.shape); + if (self.flatten) return .{ gm.n * gm.ti, gm.c * gm.fi }; + return .{ gm.n * ((gm.fi - 1) / 2 + 1) * ((gm.ti - 1) / 2 + 1), ld(gm) }; + } + + pub fn prepare(self: *Move, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + self.rig.reset(); + const gm = geometry(shape); + if (gm.n == 0 or gm.c == 0 or gm.fi == 0 or gm.ti == 0) return false; + self.shape = shape; + const a = self.rig.gpu.gpa; + a.free(self.x); + self.x = &.{}; + self.x = try a.alloc(u16, gm.n * gm.fi * gm.ti * gm.c); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + for (self.x) |*v| v.* = c.toBf16(rng.floatNorm(f32)); + if (fill == .nonfinite) { + self.x[0] = c.toBf16(std.math.nan(f32)); + self.x[self.x.len / 2] = c.toBf16(std.math.inf(f32)); + self.x[self.x.len - 1] = c.toBf16(-std.math.inf(f32)); + } + const o = self.outShape(); + a.free(self.want); + self.want = &.{}; + self.want = try a.alloc(u16, o[0] * o[1]); + self.replay(gm); + self.dev[0] = try self.rig.input(std.mem.sliceAsBytes(self.x)); + self.dev[1] = try self.rig.output(self.want.len * 2); + return true; + } + + /// The host's copy: zero where the conv's padding or the column tail is. + fn replay(self: *Move, gm: anytype) void { + if (self.flatten) { + for (0..gm.n) |n| for (0..gm.ti) |t| for (0..gm.c) |ci| for (0..gm.fi) |f| { + self.want[(n * gm.ti + t) * gm.c * gm.fi + ci * gm.fi + f] = self.x[((n * gm.fi + f) * gm.ti + t) * gm.c + ci]; + }; + return; + } + const fo = (gm.fi - 1) / 2 + 1; + const to = (gm.ti - 1) / 2 + 1; + const w = ld(gm); + for (0..gm.n) |n| for (0..fo) |f| for (0..to) |t| for (0..w) |j| { + var v: u16 = 0; + if (j < 9 * gm.c) { + const sf = @as(isize, @intCast(2 * f + j % 9 / 3)) - 1; + const st = @as(isize, @intCast(2 * t + j % 3)) - 1; + if (sf >= 0 and st >= 0 and sf < gm.fi and st < gm.ti) v = self.x[((n * gm.fi + @as(usize, @intCast(sf))) * gm.ti + @as(usize, @intCast(st))) * gm.c + j / 9]; + } + self.want[((n * fo + f) * to + t) * w + j] = v; + }; + } + + pub fn run(self: *Move) !void { + const gm = geometry(self.shape); + const s = self.rig.s; + if (self.ctl) |f| { + var a: cuda.Args = .{}; + a.add(self.dev[0]); + a.add(self.dev[1]); + const o = self.outShape(); + if (self.flatten) { + for ([_]usize{ gm.fi, gm.ti, gm.c }) |v| a.add(@as(c_int, @intCast(v))); + try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(o[0]) }, .block = .{ .x = 256 } }, s, &a); + } else { + for ([_]usize{ gm.fi, gm.ti, gm.c, o[1] }) |v| a.add(@as(c_int, @intCast(v))); + try cuda.launch.launch(f, .{ .grid = .{ .x = @intCast(o[0]), .y = @intCast((o[1] + 255) / 256) }, .block = .{ .x = 256 } }, s, &a); + } + } else if (self.flatten) { + try self.vk.convFlatten(s, self.dev[0], self.dev[1], gm.n, gm.fi, gm.ti, gm.c); + } else try self.vk.convCols(s, self.dev[0], self.dev[1], gm.n, gm.fi, gm.ti, gm.c, ld(gm)); + try s.synchronize(); + } + + pub fn count(self: *Move) usize { + return self.want.len; + } + + pub fn reference(self: *Move, out: []f64, mag: []f64) !void { + for (out, self.want) |*o, w| o.* = c.fromBf16(w); + @memset(mag, 0); + } + + /// Every output's bits equal to the host's copy (NaN payloads too). + pub fn check(self: *Move, _: g.Gate) !?[]const u8 { + const got = try self.rig.bytes(self.dev[1], self.want.len * 2); + for (self.want, 0..) |w, i| { + const v = std.mem.readInt(u16, got[2 * i ..][0..2], .little); + if (v != w) return try std.fmt.bufPrint(&self.msg, "output {d} has bits {x:0>4} where the copy has {x:0>4}", .{ i, v, w }); + } + return null; + } +}; + +/// Every registration, on the heap: the gates hold pointers to them. +pub const Set = struct { + gpa: std.mem.Allocator, + vk: cuda.vit.Kernels, + ctl: cuda.Module, + att: cuda.vit.Attention, + moves: [4]Move = undefined, + full: full.Full = undefined, + + /// The set, its kernels appended to `list` (each control after the kernel it breaks). + pub fn init(gpu: check.Gpu, s: cuda.Stream, a: std.mem.Allocator, list: *std.ArrayList(g.Kernel)) !*Set { + const set = try gpu.gpa.create(Set); + errdefer gpu.gpa.destroy(set); + var vk = try cuda.vit.Kernels.load(gpu.d); + errdefer vk.unload(); + var ctl = try cuda.Module.load(gpu.d, &controls.bytes); + errdefer ctl.unload(); + set.* = .{ .gpa = gpu.gpa, .vk = vk, .ctl = ctl, .att = try cuda.vit.Attention.load(gpu.d) }; + const rig: rig_.Rig = .{ .gpu = gpu, .s = s }; + set.moves[0] = .{ .rig = rig, .vk = &set.vk, .flatten = false, .name = "cuda vit tf_vit_conv_cols (Qwen3-ASR's 3x3 stride-2 conv taps)" }; + set.moves[1] = .{ .rig = rig, .vk = &set.vk, .flatten = false, .name = "control: tf_vit_conv_cols reads the clamped edge, not the zero padding", .ctl = try ctl.function("tf_ctl_vit_conv_cols_edge") }; + set.moves[2] = .{ .rig = rig, .vk = &set.vk, .flatten = true, .name = "cuda vit tf_vit_conv_flatten (Qwen3-ASR's conv_out rows)" }; + set.moves[3] = .{ .rig = rig, .vk = &set.vk, .flatten = true, .name = "control: tf_vit_conv_flatten writes f-major rows", .ctl = try ctl.function("tf_ctl_vit_conv_flatten_fc") }; + set.full = .{ .rig = rig, .att = &set.att }; + for (&set.moves) |*x| try list.append(a, x.kernel()); + try list.append(a, set.full.kernel()); + return set; + } + + pub fn deinit(set: *Set) void { + for (&set.moves) |*x| x.deinit(); + set.full.deinit(); + set.att.unload(); + set.ctl.unload(); + set.vk.unload(); + set.gpa.destroy(set); + } +}; + +/// The Qwen3-ASR tower kernels' gates 1-4 and their controls alone. +pub fn run(gpu: check.Gpu) !void { + const a = gpu.gpa; + var s = try cuda.Stream.init(gpu.d, false); + defer s.deinit(); + var list: std.ArrayList(g.Kernel) = .empty; + defer list.deinit(a); + const set = try Set.init(gpu, s, a, &list); + defer set.deinit(); + var t: g.Tally = .{}; + try g.runAll(a, list.items, 0x71776e33, &t); + std.debug.print("SUMMARY qwen3-asr: {d} kernels, {d} pass gates 1-4, {d} fail; {d} controls: {d} red as planted, {d} missed\n", .{ t.kernels, t.passed, t.failed, t.controls, t.caught, t.missed }); + try check.expect(t.problems() == 0, "qwen3-asr-contract: {d} gate failures, {d} controls missed", .{ t.failed, t.missed }); +} diff --git a/zig/tests/cuda/contract_qwen3_asr_attn.zig b/zig/tests/cuda/contract_qwen3_asr_attn.zig new file mode 100644 index 00000000000..60d1cba93ad --- /dev/null +++ b/zig/tests/cuda/contract_qwen3_asr_attn.zig @@ -0,0 +1,161 @@ +//! prefill_attention.cu's vision_kernel<64, 8> under the contract: Qwen3-ASR's tower attention over a window. +const std = @import("std"); +const cuda = @import("cuda"); +const core = @import("core"); +const rig_ = @import("contract_rig.zig"); +const attn = @import("contract_attn.zig"); + +const c = core.contract.spec; +const g = core.contract.gates; + +const D = 64; + +/// The P x V chain of a row: every key, a 64-key tile at a time. +fn keyChain(s: c.Shape) usize { + return s.k + 64; +} + +fn scale() f32 { + return 1.0 / @sqrt(@as(f32, D)); +} + +/// Shape: heads (rows), head width (n), a window's rows L (k): the 0.6B's 14 heads, the 1.7B's 16, windows to 104. +pub fn spec() c.Spec { + return .{ + .name = "cuda qwen3-asr vit vision_kernel<64, 8> (a window's full attention)", + .accum = .f32, + .depth = keyChain, + .ops = 1, + .out = .bf16, + .tiles = .{ .{}, .{}, .{ .size = 64 } }, + .served = &.{ .{ .rows = 14, .n = D, .k = 104 }, .{ .rows = 14, .n = D, .k = 70 }, .{ .rows = 14, .n = D, .k = 76 }, .{ .rows = 16, .n = D, .k = 104 }, .{ .rows = 16, .n = D, .k = 1 }, .{ .rows = 2, .n = D, .k = 13 } }, + .sums = .{ .why = attn.why }, + }; +} + +pub const Full = struct { + rig: rig_.Rig, + att: *const cuda.vit.Attention, + r: ?attn.Ref = null, + shape: c.Shape = undefined, + /// [L, 3 heads 64]: q heads, then k, then v (the fused q_proj | k_proj | v_proj rows) + qkv: []u16 = &.{}, + dev: u64 = 0, + out: u64 = 0, + + pub fn deinit(self: *Full) void { + self.rig.gpu.gpa.free(self.qkv); + if (self.r) |*r| r.deinit(); + self.rig.deinit(); + } + + pub fn kernel(self: *Full) g.Kernel { + return .{ .spec = spec(), .ctx = self, .vt = &vt }; + } + + const vt = g.hooks(Full); + + fn stride(self: *const Full) usize { + return 3 * self.shape.rows * D; + } + + fn at(self: *const Full, row: usize, which: usize, head: usize) []u16 { + return self.qkv[row * self.stride() + (which * self.shape.rows + head) * D ..][0..D]; + } + + pub fn prepare(self: *Full, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + self.rig.reset(); + if (shape.n != D or shape.rows == 0 or shape.k == 0) return false; + const a = self.rig.gpu.gpa; + self.shape = shape; + const L = shape.k; + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + if (self.r) |*r| r.deinit(); + self.r = null; + self.r = try attn.Ref.init(a, D, L); + a.free(self.qkv); + self.qkv = &.{}; + self.qkv = try a.alloc(u16, L * self.stride()); + for (self.qkv) |*e| e.* = attn.normal(rng); + switch (fill) { + .random => {}, + .nonfinite => self.plant(), + .stress => try self.stress(rng), + } + self.dev = try self.rig.input(std.mem.sliceAsBytes(self.qkv)); + self.out = try self.rig.output(L * shape.rows * D * 2); + return true; + } + + /// Head 0: NaN in row 0's query, +inf and -inf in values, both in one column; head 1: NaN in one key. + fn plant(self: *Full) void { + const L = self.shape.k; + const nan = c.toBf16(std.math.nan(f32)); + const inf = c.toBf16(std.math.inf(f32)); + const ninf = c.toBf16(-std.math.inf(f32)); + self.at(0, 0, 0)[3] = nan; + self.at(L - 1, 2, 0)[7] = inf; + self.at(L / 2, 2, 0)[9] = ninf; + if (L >= 3) { + self.at(1, 2, 0)[11] = inf; + self.at(2, 2, 0)[11] = ninf; + } + if (self.shape.rows > 1) self.at(L / 3, 1, 1)[5] = nan; + } + + /// Gate 4: every key one vector (each p is 1); each value column mirrored over the keys. + fn stress(self: *Full, rng: std.Random) !void { + const a = self.rig.gpu.gpa; + const L = self.shape.k; + const key = try a.alloc(u16, D); + defer a.free(key); + for (key) |*e| e.* = attn.normal(rng); + const col = try a.alloc(f32, L); + defer a.free(col); + for (0..self.shape.rows) |h| { + for (0..L) |j| @memcpy(self.at(j, 1, h), key); + for (0..D) |e| { + attn.mirrored(rng, col); + for (col, 0..) |y, j| self.at(j, 2, h)[e] = c.toBf16(y); + } + } + } + + pub fn run(self: *Full) !void { + try self.att.full(self.rig.s, self.dev, self.out, self.shape.k, self.shape.rows, D, scale()); + try self.rig.s.synchronize(); + } + + pub fn count(self: *Full) usize { + return self.shape.k * self.shape.rows * D; + } + + /// Output head i (row i / heads, head i % heads) over every row's key and value. + pub fn load(self: *Full, i: usize, hd: *attn.Head) !void { + const row = i / self.shape.rows; + const head = i % self.shape.rows; + for (hd.q, self.at(row, 0, head)) |*y, x| y.* = c.fromBf16(x); + for (0..self.shape.k) |j| for (0..D) |e| { + hd.k[j * D + e] = c.fromBf16(self.at(j, 1, head)[e]); + hd.v[j * D + e] = c.fromBf16(self.at(j, 2, head)[e]); + }; + hd.n = self.shape.k; + } + + fn heads(self: *Full) usize { + return self.shape.k * self.shape.rows; + } + + pub fn check(self: *Full, gate: g.Gate) !?[]const u8 { + return self.r.?.check(self, self.heads(), scale(), try self.rig.outputBytes(), gate); + } + + pub fn reference(self: *Full, want: []f64, mag: []f64) !void { + return self.r.?.reference(self, self.heads(), scale(), want, mag); + } + + pub fn simulate(self: *Full, acc: c.Accum, order: g.Order, out: []f64) !void { + return self.r.?.simulate(self, self.heads(), scale(), acc, order, out); + } +}; diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index 73de15d90aa..30576465f63 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -340,6 +340,7 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "moss-contract")) return @import("contract_moss_image.zig").run(gpu, rest); if (std.mem.eql(u8, cmd, "idol-decoder-contract")) return @import("contract_idol_decoder.zig").run(gpu); if (std.mem.eql(u8, cmd, "idol-contract")) return @import("contract_idol.zig").run(gpu); + if (std.mem.eql(u8, cmd, "qwen3-asr-contract")) return @import("contract_qwen3_asr.zig").run(gpu); if (std.mem.eql(u8, cmd, "tree")) return tree_tests.run(gpu); if (std.mem.eql(u8, cmd, "block")) return block_tests.run(gpu); if (std.mem.eql(u8, cmd, "window")) return window_tests.run(gpu); diff --git a/zig/tests/qwen3_asr_cuda.zig b/zig/tests/qwen3_asr_cuda.zig new file mode 100644 index 00000000000..5df662dc284 --- /dev/null +++ b/zig/tests/qwen3_asr_cuda.zig @@ -0,0 +1,199 @@ +//! tf-qwen3-asr: a clip through Qwen3-ASR on the first GPU, greedy, one stream; each stage against a reference case. +const std = @import("std"); +const cuda = @import("cuda"); +const qa = @import("qwen3_asr"); +const tok = @import("tokenizer"); +const host = qa.host; + +const usage = "usage: tf-qwen3-asr 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, + s: cuda.Stream, + d: *const cuda.Driver, + 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.s.synchronize(); + try c.d.check(c.d.api.cuMemcpyDtoH_v2(raw.ptr, ptr, raw.len * 2), "cuMemcpyDtoH"); + const vals = try c.gpa.alloc(f64, raw.len); + defer c.gpa.free(vals); + 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]); + }; + 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 { + const want = c.case.floats(c.gpa, stage) catch |e| return if (e == error.NoSuchStage) {} else e; // not every layer + 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, gathered over every chunk group, compared once whole. + fn finishConvs(c: *Compare) !void { + for ([_][]const u8{ "conv1", "conv2", "conv3" }) |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 cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var name_buf: [256]u8 = undefined; + var s = try cuda.Stream.init(&driver, false); + defer s.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, &driver, s, args[1], cfg, opts); + defer m.deinit(); + var rows_buf = try cuda.DeviceBuffer.alloc(&driver, plan.rows * cfg.audio.out * 2); + defer rows_buf.free(); + const gib = struct { + fn f(x: u64) f64 { + return @as(f64, @floatFromInt(x)) / (1 << 30); + } + }.f; + std.debug.print("GPU {s}: weights {d:.2} GiB, scratch {d:.2} GiB, load {d:.2} s\n", .{ ctx.name(&name_buf) catch "?", 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, .s = s, .d = &driver } 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 cuBLASLt plan creation or module load + _ = try m.encode(feats, rows_buf.ptr, null); + try s.synchronize(); + const t_tower = seconds(); + const rows = try m.encode(feats, rows_buf.ptr, null); + try s.synchronize(); + const tower_s = seconds() - t_tower; + if (cmp) |*c| if (!ids_only) { + _ = try m.encode(feats, rows_buf.ptr, .{ .ctx = c, .put = Compare.put }); + try c.finishConvs(); + }; + const t_prompt = seconds(); + const splice: qa.Splice = .{ .ptr = rows_buf.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 cuda: worst stage cosine {d:.9}, transcript {s}\n", .{ c.worst, if (same) "equal" else "different" }); + } + return 0; +} From 7e5a768b2584a9de144f7b79f391588a9be52a3e Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:49:57 +0000 Subject: [PATCH 06/28] Follow main extracted CUDA help for the original ASR contract command Follow main e54cb349293035edbf6a2128d6ae3beab9a9a7a4 (cuda tests: split command help to keep the runner under 600 lines). Keep every current usage entry and place original #2239 mail5 temporary ASR help beside them. The later original mail24 removes this command. --- zig/tests/cuda/main_usage.zig | 1 + 1 file changed, 1 insertion(+) diff --git a/zig/tests/cuda/main_usage.zig b/zig/tests/cuda/main_usage.zig index 0712cd8b62b..f643fdab23b 100644 --- a/zig/tests/cuda/main_usage.zig +++ b/zig/tests/cuda/main_usage.zig @@ -158,6 +158,7 @@ pub const usage = \\ moss-contract [ONLY..] MOSS-Image's own kernels, its decoder's unpack and its encoder's mixer, gates 1-4, controls red \\ idol-decoder-contract Idol's decoders' stem, to_kv, head norms and attention through gates 1-4, controls red \\ idol-contract Idol's denoiser glue and head-64 attention through gates 1-4, controls red + \\ qwen3-asr-contract Qwen3-ASR's conv taps, conv flatten and head-64 attention through gates 1-4, controls red \\ glm-exl3 | glm-exl3-items GLM's EXL3 routed experts, decode and prompt, against float64, and the item plan's decode against the plain decode, byte for byte (synthetic) \\ glm-kda-pad-split TF_GLM_KDA_PAD's padding of the bf16 and split KDA stacks at TP=3 (synthetic) \\ glm-exl3-layer one checkpoint layer's EXL3 experts through the GLM loader, against float64 From c4d4200dff1991a5ec2797a2998cad04626bcd7f 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:36:24 +0100 Subject: [PATCH 07/28] qwen3-asr: zig fmt --- zig/src/families/qwen3_asr/lm.zig | 4 ++-- zig/src/families/qwen3_asr/names.zig | 8 ++++---- zig/src/families/qwen3_asr/tower.zig | 6 +++--- zig/tests/qwen3_asr_cuda.zig | 4 ++-- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/zig/src/families/qwen3_asr/lm.zig b/zig/src/families/qwen3_asr/lm.zig index e0589f72b0b..db0096100c9 100644 --- a/zig/src/families/qwen3_asr/lm.zig +++ b/zig/src/families/qwen3_asr/lm.zig @@ -36,8 +36,8 @@ pub const Weights = struct { const gu = [2][]const u8{ try src.expect(try p(&nb[0], i, "mlp.gate_proj.weight"), &.{ t.intermediate, t.hidden }), try src.expect(try p(&nb[1], i, "mlp.up_proj.weight"), &.{ t.intermediate, t.hidden }) }; l.gate_up = try tower.joined(gpa, up, &gu); const one = .{ - .{ &l.in_norm, "input_layernorm.weight", &[_]usize{t.hidden} }, .{ &l.post_norm, "post_attention_layernorm.weight", &[_]usize{t.hidden} }, - .{ &l.o, "self_attn.o_proj.weight", &[_]usize{ t.hidden, qd } }, .{ &l.q_norm, "self_attn.q_norm.weight", &[_]usize{t.head_dim} }, + .{ &l.in_norm, "input_layernorm.weight", &[_]usize{t.hidden} }, .{ &l.post_norm, "post_attention_layernorm.weight", &[_]usize{t.hidden} }, + .{ &l.o, "self_attn.o_proj.weight", &[_]usize{ t.hidden, qd } }, .{ &l.q_norm, "self_attn.q_norm.weight", &[_]usize{t.head_dim} }, .{ &l.k_norm, "self_attn.k_norm.weight", &[_]usize{t.head_dim} }, .{ &l.down, "mlp.down_proj.weight", &[_]usize{ t.hidden, t.intermediate } }, }; inline for (one) |x| x[0].* = try up.put(try src.expect(try p(&nb[2], i, x[1]), x[2])); diff --git a/zig/src/families/qwen3_asr/names.zig b/zig/src/families/qwen3_asr/names.zig index 873636f7cf2..65a8c85034d 100644 --- a/zig/src/families/qwen3_asr/names.zig +++ b/zig/src/families/qwen3_asr/names.zig @@ -57,10 +57,10 @@ fn lmNames(list: *std.ArrayList(Want), arena: std.mem.Allocator, t: cfg.Text) !v for (0..t.layers) |i| { const p = try std.fmt.allocPrint(arena, lm ++ "layers.{d}.", .{i}); const parts = .{ - .{ "input_layernorm.weight", &[_]usize{t.hidden} }, .{ "post_attention_layernorm.weight", &[_]usize{t.hidden} }, - .{ "self_attn.q_proj.weight", &[_]usize{ qd, t.hidden } }, .{ "self_attn.k_proj.weight", &[_]usize{ kvd, t.hidden } }, - .{ "self_attn.v_proj.weight", &[_]usize{ kvd, t.hidden } }, .{ "self_attn.o_proj.weight", &[_]usize{ t.hidden, qd } }, - .{ "self_attn.q_norm.weight", &[_]usize{t.head_dim} }, .{ "self_attn.k_norm.weight", &[_]usize{t.head_dim} }, + .{ "input_layernorm.weight", &[_]usize{t.hidden} }, .{ "post_attention_layernorm.weight", &[_]usize{t.hidden} }, + .{ "self_attn.q_proj.weight", &[_]usize{ qd, t.hidden } }, .{ "self_attn.k_proj.weight", &[_]usize{ kvd, t.hidden } }, + .{ "self_attn.v_proj.weight", &[_]usize{ kvd, t.hidden } }, .{ "self_attn.o_proj.weight", &[_]usize{ t.hidden, qd } }, + .{ "self_attn.q_norm.weight", &[_]usize{t.head_dim} }, .{ "self_attn.k_norm.weight", &[_]usize{t.head_dim} }, .{ "mlp.gate_proj.weight", &[_]usize{ t.intermediate, t.hidden } }, .{ "mlp.up_proj.weight", &[_]usize{ t.intermediate, t.hidden } }, .{ "mlp.down_proj.weight", &[_]usize{ t.hidden, t.intermediate } }, }; diff --git a/zig/src/families/qwen3_asr/tower.zig b/zig/src/families/qwen3_asr/tower.zig index a2b09b1df96..8981f95fdc8 100644 --- a/zig/src/families/qwen3_asr/tower.zig +++ b/zig/src/families/qwen3_asr/tower.zig @@ -58,9 +58,9 @@ pub const Weights = struct { const qkv_b = [3][]const u8{ try src.expect(try p(&nb[0], i, "self_attn.q_proj.bias"), v), try src.expect(try p(&nb[1], i, "self_attn.k_proj.bias"), v), try src.expect(try p(&nb[2], i, "self_attn.v_proj.bias"), v) }; l.qkv_b = try joined(gpa, up, &qkv_b); const one = .{ - .{ &l.out, "self_attn.out_proj.weight", sq }, .{ &l.out_b, "self_attn.out_proj.bias", v }, - .{ &l.ln1, "self_attn_layer_norm.weight", v }, .{ &l.ln1_b, "self_attn_layer_norm.bias", v }, - .{ &l.ln2, "final_layer_norm.weight", v }, .{ &l.ln2_b, "final_layer_norm.bias", v }, + .{ &l.out, "self_attn.out_proj.weight", sq }, .{ &l.out_b, "self_attn.out_proj.bias", v }, + .{ &l.ln1, "self_attn_layer_norm.weight", v }, .{ &l.ln1_b, "self_attn_layer_norm.bias", v }, + .{ &l.ln2, "final_layer_norm.weight", v }, .{ &l.ln2_b, "final_layer_norm.bias", v }, .{ &l.fc1, "fc1.weight", &[_]usize{ a.ffn, a.d } }, .{ &l.fc1_b, "fc1.bias", &[_]usize{a.ffn} }, .{ &l.fc2, "fc2.weight", &[_]usize{ a.d, a.ffn } }, .{ &l.fc2_b, "fc2.bias", v }, }; diff --git a/zig/tests/qwen3_asr_cuda.zig b/zig/tests/qwen3_asr_cuda.zig index 5df662dc284..4c865dffbc0 100644 --- a/zig/tests/qwen3_asr_cuda.zig +++ b/zig/tests/qwen3_asr_cuda.zig @@ -188,8 +188,8 @@ pub fn main(init: std.process.Init) !u8 { 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, + 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, }); } From 8efe483a085f58fe3b3faa6427c4907fd1ad802b 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 13:57:25 +0100 Subject: [PATCH 08/28] qwen3-asr: mel.zig's comments describe the computation, not the reference's functions (#2105) --- zig/src/families/qwen3_asr/mel.zig | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/zig/src/families/qwen3_asr/mel.zig b/zig/src/families/qwen3_asr/mel.zig index 64b0bf00f00..78a367f22d8 100644 --- a/zig/src/families/qwen3_asr/mel.zig +++ b/zig/src/families/qwen3_asr/mel.zig @@ -1,4 +1,4 @@ -//! WhisperFeatureExtractor's log-mel rows in float64: a centered, reflect-padded STFT, slaney mel filters, log10. +//! Log-mel rows in float64: periodic Hann frames of a centered, reflect-padded STFT, slaney mel filters, log10. const std = @import("std"); const cfg = @import("config.zig"); @@ -14,7 +14,7 @@ fn melToHz(m: f64) f64 { return if (m >= 15.0) 1000.0 * @exp(logstep * (m - 15.0)) else 200.0 * m / 3.0; } -/// transformers' mel_filter_bank(201, mels, 0, 8000, 16000, "slaney", "slaney"): [bins][mels], float64. +/// Slaney-scale triangles over the 201 bins, 0 to 8 kHz, each area-normalized: [bins][mels], float64. pub fn filters(gpa: std.mem.Allocator, mels: usize) ![]f64 { const out = try gpa.alloc(f64, bins * mels); errdefer gpa.free(out); @@ -51,7 +51,7 @@ pub const Features = struct { } }; -/// Sample `i` of x reflect-padded by n_fft / 2 on each side (torch.stft's center=True, pad_mode="reflect"). +/// Sample `i` of x reflect-padded by n_fft / 2 on each side, the edge sample not repeated (frame t centered at t hop). fn padded(x: []const f32, i: isize) f64 { const n: isize = @intCast(x.len); var j = i - cfg.n_fft / 2; @@ -60,7 +60,7 @@ fn padded(x: []const f32, i: isize) f64 { return x[@intCast(j)]; } -/// Log-mel features of `x`, as the package's processor gives them for one clip (no padding to 30 s). +/// Log-mel features of `x`: log10 power floored at the clip's peak - 8, then (l + 4) / 4; no padding to 30 s. pub fn features(gpa: std.mem.Allocator, x: []const f32, mels: usize) !Features { if (x.len <= cfg.n_fft / 2) return error.AudioTooShort; const n_frames = x.len / cfg.hop; @@ -68,7 +68,7 @@ pub fn features(gpa: std.mem.Allocator, x: []const f32, mels: usize) !Features { defer gpa.free(fb); const window = try gpa.alloc(f64, cfg.n_fft); defer gpa.free(window); - // torch.hann_window(400): periodic + // periodic Hann window of n_fft samples for (window, 0..) |*w, i| w.* = 0.5 - 0.5 * @cos(2.0 * std.math.pi * @as(f64, @floatFromInt(i)) / cfg.n_fft); const twiddle = try gpa.alloc([2]f64, cfg.n_fft); defer gpa.free(twiddle); From 92002e432b50fe60c62d542410e555b4bfa8211d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Fri, 6 Nov 2026 06:00:56 +0100 Subject: [PATCH 09/28] qwen3-asr: a lone chunk under 100 frames is convolved at its own length (#2105) The package pads every chunk to the longest one, so a clip of one chunk shorter than 100 frames goes through the three convolutions at its own length; the right-edge conv2 and conv3 outputs then see no padded rows. The plan gives that length (chunk_frames), and the shared tower schedule and the float64 reference both take it. The schedule test runs 50- and 99-frame clips against the reference and checks the first convolution's length. On cases from qwen3_asr_case.py for a 0.5 s and a 0.99 s cut of a dev clip, the 0.6B's host check at torch's points gives audio_rows cosine 0.99984 and 0.99992, the conv stages at the package's shapes; at the parent commit the 50-frame case gave audio_rows 0.889 and stopped with StageSize at the conv stages. --- zig/src/families/qwen3_asr/chunks.zig | 9 +++++-- zig/src/families/qwen3_asr/schedule_test.zig | 25 +++++++++++++++----- zig/src/families/qwen3_asr/tower.zig | 15 ++++++------ zig/src/families/qwen3_asr/tower_ref.zig | 4 ++-- 4 files changed, 35 insertions(+), 18 deletions(-) diff --git a/zig/src/families/qwen3_asr/chunks.zig b/zig/src/families/qwen3_asr/chunks.zig index 583055b0e9c..03ed060d02b 100644 --- a/zig/src/families/qwen3_asr/chunks.zig +++ b/zig/src/families/qwen3_asr/chunks.zig @@ -1,4 +1,6 @@ //! The tower's chunk and window plan: 100-frame chunks through the convolutions, then attention over whole windows. +//! The package pads every chunk to the longest one, so a clip of one chunk under 100 frames is convolved at its own +//! length, and a clip of more chunks at 100 frames a chunk, the last one zero-padded. const std = @import("std"); const Audio = @import("config.zig").Audio; @@ -23,6 +25,7 @@ pub const Plan = struct { frames: usize, chunks: usize, last_frames: usize, // the last chunk's frames (a full chunk when frames divide) + chunk_frames: usize, // frames of the longest chunk: the convolutions' time length, every chunk padded to it rows: usize, chunk_rows: usize, // rows of the longest chunk: a row's position inside its chunk runs to this window_rows: usize, // rows an attention window spans @@ -32,8 +35,8 @@ pub const Plan = struct { const cf = a.chunkFrames(); const chunks = (n + cf - 1) / cf; const last = if (n % cf == 0) cf else n % cf; - const longest = if (chunks > 1) rows(cf) else rows(last); - return .{ .frames = n, .chunks = chunks, .last_frames = last, .rows = rows(n), .chunk_rows = longest, .window_rows = longest * (a.window_infer / cf) }; + const longest = if (chunks > 1) cf else last; + return .{ .frames = n, .chunks = chunks, .last_frames = last, .chunk_frames = longest, .rows = rows(n), .chunk_rows = rows(longest), .window_rows = rows(longest) * (a.window_infer / cf) }; } /// Rows chunk `i` leaves. @@ -70,7 +73,9 @@ test "plan: chunks, the short last chunk, windows of eight chunks" { var sum: usize = 0; for (0..p.chunks) |i| sum += p.rowsOf(i); try std.testing.expectEqual(p.rows, sum); + try std.testing.expectEqual(@as(usize, 100), p.chunk_frames); const short = try Plan.init(a, 60); + try std.testing.expectEqual(@as(usize, 60), short.chunk_frames); // a lone short chunk is not padded try std.testing.expectEqual(@as(usize, 8), short.chunk_rows); try std.testing.expectEqual(@as(usize, 64), short.window_rows); try std.testing.expectEqual(@as(usize, 1), short.windows()); diff --git a/zig/src/families/qwen3_asr/schedule_test.zig b/zig/src/families/qwen3_asr/schedule_test.zig index 1b41a2fb00d..67e25ac2591 100644 --- a/zig/src/families/qwen3_asr/schedule_test.zig +++ b/zig/src/families/qwen3_asr/schedule_test.zig @@ -52,6 +52,7 @@ const TowerHost = struct { m: *Mem, gpa: std.mem.Allocator, stages: std.StringHashMapUnmanaged([]f64) = .empty, + conv1_frames: usize = 0, // the first convolution's time length, as the schedule last passed it fn deinit(t: *TowerHost) void { var it = t.stages.iterator(); @@ -70,6 +71,7 @@ const TowerHost = struct { pub fn conv(t: *TowerHost, w: u64, b: u64, x: u64, y: u64, n: usize, fi: usize, ti: usize, c: usize, co: usize) !void { const fo = (fi - 1) / 2 + 1; const to = (ti - 1) / 2 + 1; + if (c == 1) t.conv1_frames = ti; const xs = try t.m.at(x, n * fi * ti * c); const ws = try t.m.at(w, co * c * 9); const bs = try t.m.at(b, co); @@ -207,27 +209,29 @@ fn cosine(a: []const f64, b: []const f64) f64 { const small: cfg.Audio = .{ .d = 8, .layers = 2, .heads = 2, .ffn = 16, .mels = 16, .conv = 4, .out = 6, .window = 50, .window_infer = 200, .positions = 1500, .conv_chunks = 500 }; -test "tower schedule: a host binding matches the float64 reference at torch's points, two windows, a short chunk" { +/// The schedule on the host binding against the float64 reference for a clip of `frames` frames, `group` chunks a pass. +fn towerCase(frames: usize, group: usize, want_windows: usize) !void { const gpa = std.testing.allocator; var mem: Mem = .{ .gpa = gpa }; defer mem.deinit(); var fake: Fake = .{ .gpa = gpa }; defer fake.deinit(); - var w = try tower.Weights.load(gpa, small, &fake, &mem, 3); // groups of 3 over 4 chunks: one short group + var w = try tower.Weights.load(gpa, small, &fake, &mem, group); defer w.deinit(gpa); - const frames = 350; const data = try gpa.alloc(f32, small.mels * frames); defer gpa.free(data); var rng: std.Random.DefaultPrng = .init(7); for (data) |*v| v.* = rng.random().floatNorm(f32); const feats: mel.Features = .{ .data = data, .mels = small.mels, .frames = frames }; const plan = try chunks.Plan.init(small, frames); - try std.testing.expectEqual(@as(usize, 2), plan.windows()); - const b = try tower.Buffers.alloc(small, 3, plan.rows, &mem); + try std.testing.expectEqual(want_windows, plan.windows()); + const b = try tower.Buffers.alloc(small, group, plan.rows, &mem); const out = try mem.alloc(2 * plan.rows * small.out); var host: TowerHost = .{ .m = &mem, .gpa = gpa }; defer host.deinit(); try std.testing.expectEqual(plan.rows, try tower.encode(&host, gpa, small, &w, b, feats, out)); + // a lone chunk under 100 frames is convolved at its own length (the package pads only to the longest chunk) + try std.testing.expectEqual(if (frames < small.chunkFrames()) frames else small.chunkFrames(), host.conv1_frames); var ref: Ref = .{ .gpa = gpa }; defer ref.deinit(); const want = try tower_ref.run(gpa, small, .torch, .{ .ctx = &fake, .get = Fake.get }, feats, .{ .ctx = &ref, .put = Ref.put }); @@ -239,12 +243,21 @@ test "tower schedule: a host binding matches the float64 reference at torch's po seen += 1; try std.testing.expectEqual(e.value_ptr.len, got.len); const c = cosine(got, e.value_ptr.*); - if (c < 0.9999) std.debug.print("stage {s}: cosine {d}\n", .{ e.key_ptr.*, c }); + if (c < 0.9999) std.debug.print("{d} frames, stage {s}: cosine {d}\n", .{ frames, e.key_ptr.*, c }); try std.testing.expect(c >= 0.9999); } try std.testing.expect(seen >= small.layers + 4); // embed, each layer, ln_post, proj1, audio_rows } +test "tower schedule: a host binding matches the float64 reference at torch's points, two windows, a short chunk" { + try towerCase(350, 3, 2); // groups of 3 over 4 chunks: one short group, a 50-frame last chunk padded to 100 +} + +test "tower schedule: a lone chunk of 50 or 99 frames, convolved at its own length" { + try towerCase(50, 3, 1); + try towerCase(99, 3, 1); +} + /// The LM's operators as extents only: every row an op touches lies inside the buffer it names. const LmBounds = struct { m: *Mem, diff --git a/zig/src/families/qwen3_asr/tower.zig b/zig/src/families/qwen3_asr/tower.zig index 8981f95fdc8..a2f82c4d01b 100644 --- a/zig/src/families/qwen3_asr/tower.zig +++ b/zig/src/families/qwen3_asr/tower.zig @@ -134,9 +134,8 @@ pub const Buffers = struct { } }; -/// The bf16 input of chunks [first, first + n) of `feats`: [n][mels][frames a chunk], zero past the clip. -fn input(a: cfg.Audio, feats: mel.Features, first: usize, n: usize, host: []u16) []u16 { - const cf = a.chunkFrames(); +/// The bf16 input of chunks [first, first + n) of `feats`: [n][mels][cf], zero past the clip. +fn input(a: cfg.Audio, feats: mel.Features, cf: usize, first: usize, n: usize, host: []u16) []u16 { const out = host[0 .. n * a.mels * cf]; @memset(out, 0); for (0..n) |i| for (0..a.mels) |m| for (0..cf) |j| { @@ -146,10 +145,10 @@ fn input(a: cfg.Audio, feats: mel.Features, first: usize, n: usize, host: []u16) return out; } -/// The convolutions over a group of chunks into rows of b.x from first * 13 on, positions added. -fn front(r: anytype, a: cfg.Audio, w: *const Weights, b: Buffers, feats: mel.Features, first: usize, n: usize, host: []u16) !void { - const cf = a.chunkFrames(); - try r.upload(b.in, std.mem.sliceAsBytes(input(a, feats, first, n, host))); +/// The convolutions over a group of chunks into rows of b.x from first * 13 on, positions added; each chunk is +/// convolved at the plan's chunk length (a lone short chunk at its own, as the package pads to the longest chunk). +fn front(r: anytype, a: cfg.Audio, w: *const Weights, b: Buffers, feats: mel.Features, cf: usize, first: usize, n: usize, host: []u16) !void { + try r.upload(b.in, std.mem.sliceAsBytes(input(a, feats, cf, first, n, host))); const f1 = (a.mels - 1) / 2 + 1; const t1 = (cf - 1) / 2 + 1; const f2 = (f1 - 1) / 2 + 1; @@ -178,7 +177,7 @@ pub fn encode(r: anytype, gpa: std.mem.Allocator, a: cfg.Audio, w: *const Weight defer gpa.free(host); var first: usize = 0; while (first < plan.chunks) : (first += w.group) { - try front(r, a, w, b, feats, first, @min(w.group, plan.chunks - first), host); + try front(r, a, w, b, feats, plan.chunk_frames, first, @min(w.group, plan.chunks - first), host); try r.sync(); // the host input is refilled for the next group } const rows = plan.rows; diff --git a/zig/src/families/qwen3_asr/tower_ref.zig b/zig/src/families/qwen3_asr/tower_ref.zig index b1d50509c40..27afb7d2f51 100644 --- a/zig/src/families/qwen3_asr/tower_ref.zig +++ b/zig/src/families/qwen3_asr/tower_ref.zig @@ -101,9 +101,9 @@ fn front(gpa: std.mem.Allocator, a: cfg.Audio, p: ops.Points, src: Source, feats defer gpa.free(b3); const wo = try src.take(gpa, t ++ "conv_out.weight"); defer gpa.free(wo); - const cf = a.chunkFrames(); + const cf = plan.chunk_frames; // the package pads every chunk to the longest one const bins = a.convBins(); - const crow = chunks.rows(cf); + const crow = plan.chunk_rows; const pos = try positions(gpa, p, crow, a.d); defer gpa.free(pos); const out = try gpa.alloc(f64, plan.rows * a.d); From afb65ef333f277b6526516943ec1bbf4640a1024 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Fri, 6 Nov 2026 06:01:59 +0100 Subject: [PATCH 10/28] qwen3-asr: tf-qwen3-asr-check opens a sharded checkpoint through core.Checkpoint (#2105) The host check mapped MODEL_DIR/model.safetensors only, so the released 1.7B (two shards and an index) failed with FileNotFound. It now opens the folder with core.Checkpoint.openModel, as the CUDA load does, and validates the names of every shard as one set. On the 1.7B: WEIGHTS ok (708 tensors), and the 50- and 99-frame cases give audio_rows cosine 0.99993 and 0.99992 at torch's points. --- zig/build/qwen3_asr_host.zig | 7 +++++-- zig/qwen3_asr_check.zig | 25 ++++++++++++------------- 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/zig/build/qwen3_asr_host.zig b/zig/build/qwen3_asr_host.zig index e5c3a75f572..181135671c6 100644 --- a/zig/build/qwen3_asr_host.zig +++ b/zig/build/qwen3_asr_host.zig @@ -7,14 +7,17 @@ pub fn steps(b: *std.Build, all: *std.Build.Step) void { const checks = b.step("test-qwen3-asr-host", "Qwen3-ASR config, tensor names, mel rows and reference ops"); checks.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = family })).step); all.dependOn(checks); - const st = b.createModule(.{ .root_source_file = b.path("zig/src/core/safetensors.zig"), .target = host, .link_libc = true }); const tokenizer = b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = host, .link_libc = true }); + // core for its Checkpoint: one checkpoint folder's shards (the 1.7B's two) as one name space, as the CUDA load opens it + const core = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = host, .link_libc = true }); + core.addImport("gpu_memory", @import("gpu_memory.zig").module(b, host)); + core.addImport("tokenizer", tokenizer); const tool = b.addExecutable(.{ .name = "tf-qwen3-asr-check", .root_module = b.createModule(.{ .root_source_file = b.path("zig/qwen3_asr_check.zig"), .target = host, .optimize = .ReleaseFast, .link_libc = true, - .imports = &.{ .{ .name = "qwen3_asr", .module = family }, .{ .name = "safetensors", .module = st }, .{ .name = "tokenizer", .module = tokenizer } }, + .imports = &.{ .{ .name = "qwen3_asr", .module = family }, .{ .name = "core", .module = core }, .{ .name = "tokenizer", .module = tokenizer } }, }) }); b.installArtifact(tool); b.step("tf-qwen3-asr-check", "Check a Qwen3-ASR checkpoint and its float64 tower against a tools/zig/qwen3_asr_case.py case") diff --git a/zig/qwen3_asr_check.zig b/zig/qwen3_asr_check.zig index 3c51cd6e566..6998cbf3196 100644 --- a/zig/qwen3_asr_check.zig +++ b/zig/qwen3_asr_check.zig @@ -1,18 +1,19 @@ //! tf-qwen3-asr-check: a Qwen3-ASR checkpoint's weights, tokenizer, mel rows and float64 tower against a case. const std = @import("std"); const qa = @import("qwen3_asr"); -const st = @import("safetensors"); +const core = @import("core"); const tok = @import("tokenizer"); const usage = "usage: tf-qwen3-asr-check MODEL_DIR CLIP.wav CASE_DIR [--points exact|torch] [--no-tower]\n"; +/// The checkpoint's shards as one name space (core.Checkpoint, as the CUDA load opens them). const Mapped = struct { - file: st.File, + ck: core.Checkpoint, fn get(ctx: *anyopaque, name: []const u8) ?[]const u8 { const m: *Mapped = @ptrCast(@alignCast(ctx)); - const t = m.file.get(name) orelse return null; - return t.bytes; + for (m.ck.files.items) |*f| if (f.get(name)) |t| return t.bytes; + return null; } }; @@ -57,19 +58,19 @@ const Compare = struct { } }; -fn checkWeights(gpa: std.mem.Allocator, cfg: qa.config.Config, file: *const st.File) !void { +fn checkWeights(gpa: std.mem.Allocator, cfg: qa.config.Config, m: *Mapped) !void { var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); const a = arena.allocator(); var have: std.ArrayList(qa.names.Have) = .empty; - for (file.names.keys(), file.names.values()) |name, *e| try have.append(a, .{ .name = name, .bf16 = e.dtype == .bf16, .shape = e.shape[0..e.rank] }); + for (m.ck.files.items) |*file| for (file.names.keys(), file.names.values()) |name, *e| try have.append(a, .{ .name = name, .bf16 = e.dtype == .bf16, .shape = e.shape[0..e.rank] }); var problem: []const u8 = ""; qa.names.validate(a, cfg, have.items, &problem) catch |err| { std.debug.print("WEIGHTS refused: {s} ({t})\n", .{ problem, err }); return err; }; - const head = file.get(qa.names.head).?.bytes; - const embed = file.get(qa.names.lm ++ "embed_tokens.weight").?.bytes; + const head = Mapped.get(m, qa.names.head).?; + const embed = Mapped.get(m, qa.names.lm ++ "embed_tokens.weight").?; if (!std.mem.eql(u8, head, embed)) return error.UntiedHead; std.debug.print("WEIGHTS ok: {d} tensors, all bf16 at the config's shapes; lm_head bit-equal to the embedding\n", .{have.items.len}); } @@ -114,11 +115,9 @@ pub fn main(init: std.process.Init) !u8 { } } const cfg = try qa.config.read(gpa, io, args[1]); - const path = try std.fs.path.join(gpa, &.{ args[1], "model.safetensors" }); - defer gpa.free(path); - var mapped: Mapped = .{ .file = try st.File.open(gpa, io, path) }; - defer mapped.file.close(io); - try checkWeights(gpa, cfg, &mapped.file); + var mapped: Mapped = .{ .ck = try core.Checkpoint.openModel(gpa, io, args[1]) }; + defer mapped.ck.close(); + try checkWeights(gpa, cfg, &mapped); var case = try qa.case.Case.open(gpa, io, args[3]); defer case.deinit(); const bytes = try std.Io.Dir.cwd().readFileAlloc(io, args[2], gpa, .limited(1 << 31)); From c8fae45a572b63e38148b98879196d5d15959535 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Fri, 6 Nov 2026 06:02:53 +0100 Subject: [PATCH 11/28] qwen3-asr: the host and CUDA checks are gates with a non-zero exit (#2105) tf-qwen3-asr-check exits 1 when the worst stage cosine is under --min-cos (default 0.995; a token or prompt mismatch already failed). tf-qwen3-asr with a case exits 1 when the prompt ids or the greedy transcript differ from the case's, or a compared stage's cosine is under --min-cos (default 0.99). The SUMMARY line names the gate and PASS or FAIL. --- zig/qwen3_asr_check.zig | 12 +++++++++--- zig/tests/qwen3_asr_cuda.zig | 16 ++++++++++++---- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/zig/qwen3_asr_check.zig b/zig/qwen3_asr_check.zig index 6998cbf3196..576fc223a25 100644 --- a/zig/qwen3_asr_check.zig +++ b/zig/qwen3_asr_check.zig @@ -4,7 +4,8 @@ const qa = @import("qwen3_asr"); const core = @import("core"); const tok = @import("tokenizer"); -const usage = "usage: tf-qwen3-asr-check MODEL_DIR CLIP.wav CASE_DIR [--points exact|torch] [--no-tower]\n"; +const usage = "usage: tf-qwen3-asr-check MODEL_DIR CLIP.wav CASE_DIR [--points exact|torch] [--no-tower] [--min-cos X]\n" ++ + " a gate: exit 1 when a stage's cosine to the case is under X (default 0.995) or the tokens differ\n"; /// The checkpoint's shards as one name space (core.Checkpoint, as the CUDA load opens them). const Mapped = struct { @@ -104,11 +105,15 @@ pub fn main(init: std.process.Init) !u8 { } var points: qa.ref_ops.Points = .torch; var tower = true; + var min_cos: f64 = 0.995; var i: usize = 4; while (i < args.len) : (i += 1) { if (std.mem.eql(u8, args[i], "--no-tower")) tower = false else if (std.mem.eql(u8, args[i], "--points") and i + 1 < args.len) { i += 1; points = std.meta.stringToEnum(qa.ref_ops.Points, args[i]) orelse return 2; + } else if (std.mem.eql(u8, args[i], "--min-cos") and i + 1 < args.len) { + i += 1; + min_cos = std.fmt.parseFloat(f64, args[i]) catch return 2; } else { std.debug.print(usage, .{}); return 2; @@ -141,6 +146,7 @@ pub fn main(init: std.process.Init) !u8 { gpa.free(out); } try cmp.finish(); - std.debug.print("SUMMARY qwen3-asr host ({t} points): worst stage cosine {d:.9}\n", .{ points, cmp.worst_cos }); - return 0; + const pass = cmp.worst_cos >= min_cos; // NaN fails + std.debug.print("SUMMARY qwen3-asr host ({t} points): worst stage cosine {d:.9} (gate {d}): {s}\n", .{ points, cmp.worst_cos, min_cos, if (pass) "PASS" else "FAIL" }); + return if (pass) 0 else 1; } diff --git a/zig/tests/qwen3_asr_cuda.zig b/zig/tests/qwen3_asr_cuda.zig index 4c865dffbc0..993f66f662e 100644 --- a/zig/tests/qwen3_asr_cuda.zig +++ b/zig/tests/qwen3_asr_cuda.zig @@ -5,7 +5,8 @@ const qa = @import("qwen3_asr"); const tok = @import("tokenizer"); const host = qa.host; -const usage = "usage: tf-qwen3-asr MODEL_DIR CLIP.wav [--case DIR [--ids-only]] [--tokens N]\n"; +const usage = "usage: tf-qwen3-asr MODEL_DIR CLIP.wav [--case DIR [--ids-only] [--min-cos X]] [--tokens N]\n" ++ + " with a case, a gate: exit 1 when the prompt or transcript differs or a stage's cosine is under X (default 0.99)\n"; const eos = [_]u32{ 151645, 151643 }; fn seconds() f64 { @@ -79,6 +80,7 @@ pub fn main(init: std.process.Init) !u8 { 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 min_cos: f64 = 0.99; var i: usize = 3; while (i < args.len) : (i += 2) { if (std.mem.eql(u8, args[i], "--ids-only")) { @@ -87,7 +89,9 @@ pub fn main(init: std.process.Init) !u8 { } 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")) { + } else if (std.mem.eql(u8, args[i], "--case")) case_dir = args[i + 1] else if (std.mem.eql(u8, args[i], "--min-cos")) { + min_cos = try std.fmt.parseFloat(f64, 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, .{}); @@ -136,10 +140,12 @@ pub fn main(init: std.process.Init) !u8 { 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, .s = s, .d = &driver } else null; + var same_prompt = true; 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"}); + same_prompt = std.mem.eql(u32, want, ids); + std.debug.print("PROMPT ids {s} the case's\n", .{if (same_prompt) "equal to" else "DIFFERENT from"}); } // a warm pass first: the timed pass after it sees no cuBLASLt plan creation or module load _ = try m.encode(feats, rows_buf.ptr, null); @@ -193,7 +199,9 @@ pub fn main(init: std.process.Init) !u8 { if (first < ref.len) ref[first] else 0, }); } - std.debug.print("SUMMARY qwen3-asr cuda: worst stage cosine {d:.9}, transcript {s}\n", .{ c.worst, if (same) "equal" else "different" }); + const pass = same_prompt and same and c.worst >= min_cos; // NaN fails + std.debug.print("SUMMARY qwen3-asr cuda: worst stage cosine {d:.9} (gate {d}), transcript {s}: {s}\n", .{ c.worst, min_cos, if (same) "equal" else "different", if (pass) "PASS" else "FAIL" }); + if (!pass) return 1; } return 0; } From 235b1bc19610d4e3377a4a75e54e536f32f6cc59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Fri, 6 Nov 2026 06:03:32 +0100 Subject: [PATCH 12/28] qwen3-asr: admission requires the tower's rows at the LM's width and a window of whole chunks; no empty group (#2105) The LM copies hidden-wide rows from the tower's output, so a config whose audio output_dim differs from the text hidden size is refused. n_window_infer under one chunk is refused by name (the modulo already refused it, as the integer fields are at least 1). tower.Weights.load refuses a group of 0 chunks, which encode steps through. The 1.7B's released geometry (24 tower layers, 16 heads of 64, output 2048 = hidden 2048) is admitted in a test. --- zig/src/families/qwen3_asr/config.zig | 8 +++--- zig/src/families/qwen3_asr/config_test.zig | 26 ++++++++++++++++++++ zig/src/families/qwen3_asr/schedule_test.zig | 9 +++++++ zig/src/families/qwen3_asr/tower.zig | 1 + 4 files changed, 41 insertions(+), 3 deletions(-) diff --git a/zig/src/families/qwen3_asr/config.zig b/zig/src/families/qwen3_asr/config.zig index d13d8174c89..46e64208768 100644 --- a/zig/src/families/qwen3_asr/config.zig +++ b/zig/src/families/qwen3_asr/config.zig @@ -114,8 +114,8 @@ fn audio(o: Object) !Audio { .conv_chunks = try integer(o, "conv_chunksize"), }; if (a.d % a.heads != 0 or a.d % 8 != 0 or a.ffn % 8 != 0 or a.conv % 8 != 0) return error.UnsupportedQwen3AsrGeometry; - // the package's per-chunk lengths assume a chunk of 100 frames (13 rows) and windows of whole chunks - if (a.chunkFrames() != 100 or a.window_infer % a.chunkFrames() != 0) return error.UnsupportedQwen3AsrGeometry; + // the package's per-chunk lengths assume a chunk of 100 frames (13 rows) and windows of one or more whole chunks + if (a.chunkFrames() != 100 or a.window_infer < a.chunkFrames() or a.window_infer % a.chunkFrames() != 0) return error.UnsupportedQwen3AsrGeometry; if (a.mels != 128) return error.UnsupportedQwen3AsrGeometry; return a; } @@ -162,13 +162,15 @@ pub fn parse(gpa: std.mem.Allocator, json: []const u8) !Config { const root = try object(doc.value); try expect(root, "model_type", "qwen3_asr"); const thinker = try object(root.get("thinker_config")); - return .{ + const c: Config = .{ .audio = try audio(try object(thinker.get("audio_config"))), .text = try text(try object(thinker.get("text_config"))), .audio_token = try id(thinker, "audio_token_id"), .audio_start = try id(thinker, "audio_start_token_id"), .audio_end = try id(thinker, "audio_end_token_id"), }; + if (c.audio.out != c.text.hidden) return error.UnsupportedQwen3AsrGeometry; // the audio rows splice in at the LM's width + return c; } /// `dir`/config.json, parsed and admitted. diff --git a/zig/src/families/qwen3_asr/config_test.zig b/zig/src/families/qwen3_asr/config_test.zig index 2b9ea526b45..b330d0160d3 100644 --- a/zig/src/families/qwen3_asr/config_test.zig +++ b/zig/src/families/qwen3_asr/config_test.zig @@ -37,6 +37,9 @@ test "refusals: another activation, M-RoPE sections not spanning the head, biase .{ "\"num_mel_bins\": 128", "\"num_mel_bins\": 80", "UnsupportedQwen3AsrGeometry" }, .{ "\"n_window\": 50", "\"n_window\": 40", "UnsupportedQwen3AsrGeometry" }, .{ "\"model_type\": \"qwen3_asr\"", "\"model_type\": \"qwen3\"", "UnsupportedQwen3AsrConfig" }, + .{ "\"output_dim\": 1024", "\"output_dim\": 2048", "UnsupportedQwen3AsrGeometry" }, // the tower's rows wider than the LM's + .{ "\"n_window_infer\": 800", "\"n_window_infer\": 50", "UnsupportedQwen3AsrGeometry" }, // a window under one chunk + .{ "\"n_window_infer\": 800", "\"n_window_infer\": 850", "UnsupportedQwen3AsrGeometry" }, }; for (cases) |x| { const text = try swapped(a, x[0], x[1]); @@ -44,3 +47,26 @@ test "refusals: another activation, M-RoPE sections not spanning the head, biase if (c.parse(a, text)) |_| return error.TestExpectedError else |err| try std.testing.expectEqualStrings(x[2], @errorName(err)); } } + +/// The released Qwen3-ASR-1.7B's config.json values where they differ from the 0.6B's. +const big_swaps = [_][2][]const u8{ + .{ "\"d_model\": 896", "\"d_model\": 1024" }, .{ "\"encoder_layers\": 18", "\"encoder_layers\": 24" }, + .{ "\"encoder_attention_heads\": 14", "\"encoder_attention_heads\": 16" }, .{ "\"encoder_ffn_dim\": 3584", "\"encoder_ffn_dim\": 4096" }, + .{ "\"output_dim\": 1024", "\"output_dim\": 2048" }, .{ "\"hidden_size\": 1024", "\"hidden_size\": 2048" }, + .{ "\"intermediate_size\": 3072", "\"intermediate_size\": 6144" }, +}; + +test "the 1.7B: admitted, the tower's rows at the LM's width" { + const a = std.testing.allocator; + var text = try a.dupe(u8, base); + defer a.free(text); + for (big_swaps) |s| { + const next = try std.mem.replaceOwned(u8, a, text, s[0], s[1]); + a.free(text); + text = next; + } + const cfg = try c.parse(a, text); + try std.testing.expectEqual(@as(usize, 64), cfg.audio.headDim()); + try std.testing.expectEqual(cfg.audio.out, cfg.text.hidden); + try std.testing.expectEqual(@as(usize, 128), cfg.text.head_dim); +} diff --git a/zig/src/families/qwen3_asr/schedule_test.zig b/zig/src/families/qwen3_asr/schedule_test.zig index 67e25ac2591..17c1cca4ddf 100644 --- a/zig/src/families/qwen3_asr/schedule_test.zig +++ b/zig/src/families/qwen3_asr/schedule_test.zig @@ -253,6 +253,15 @@ test "tower schedule: a host binding matches the float64 reference at torch's po try towerCase(350, 3, 2); // groups of 3 over 4 chunks: one short group, a 50-frame last chunk padded to 100 } +test "tower weights: a group of no chunks is refused" { + const gpa = std.testing.allocator; + var mem: Mem = .{ .gpa = gpa }; + defer mem.deinit(); + var fake: Fake = .{ .gpa = gpa }; + defer fake.deinit(); + try std.testing.expectError(error.EmptyChunkGroup, tower.Weights.load(gpa, small, &fake, &mem, 0)); +} + test "tower schedule: a lone chunk of 50 or 99 frames, convolved at its own length" { try towerCase(50, 3, 1); try towerCase(99, 3, 1); diff --git a/zig/src/families/qwen3_asr/tower.zig b/zig/src/families/qwen3_asr/tower.zig index a2f82c4d01b..481150ce057 100644 --- a/zig/src/families/qwen3_asr/tower.zig +++ b/zig/src/families/qwen3_asr/tower.zig @@ -32,6 +32,7 @@ pub const Weights = struct { /// `src.expect(name, shape)` gives a bf16 tensor's bytes; `up.put(bytes)` and `up.taps(bytes, co, k)` place them. pub fn load(gpa: std.mem.Allocator, a: cfg.Audio, src: anytype, up: anytype, group: usize) !Weights { + if (group == 0) return error.EmptyChunkGroup; // encode steps through the chunks `group` at a time const t = names.tower; const k = cfg.conv_taps; var w: Weights = undefined; From 79a1cbbe45d8b15b93580830b7707c1030cbb7bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Fri, 6 Nov 2026 06:03:45 +0100 Subject: [PATCH 13/28] qwen3-asr: drop prompt.split, which claimed parse_asr_output without its special-token, repetition and language handling (#2105) Only its own test used it; the tools compare token ids and the decoded reply. A parser matching the package's can come with the serving path that needs one. --- zig/src/families/qwen3_asr/prompt.zig | 20 +------------------- 1 file changed, 1 insertion(+), 19 deletions(-) diff --git a/zig/src/families/qwen3_asr/prompt.zig b/zig/src/families/qwen3_asr/prompt.zig index c7ab065dc7b..5f8dabf872e 100644 --- a/zig/src/families/qwen3_asr/prompt.zig +++ b/zig/src/families/qwen3_asr/prompt.zig @@ -1,4 +1,4 @@ -//! The package's ASR prompt (chat_template.json with one audio part) and the reply's "language X" split. +//! The package's ASR prompt: chat_template.json with one audio part. const std = @import("std"); pub const audio_pad = "<|audio_pad|>"; @@ -21,16 +21,6 @@ pub fn text(gpa: std.mem.Allocator, rows: usize, context: []const u8, language: return out.toOwnedSlice(gpa); } -/// A reply split as parse_asr_output splits it: "language Xbody" gives X and body, else no language. -pub fn split(reply: []const u8) struct { language: []const u8, body: []const u8 } { - const s = std.mem.trim(u8, reply, " \t\r\n"); - const at = std.mem.indexOf(u8, s, asr_text) orelse return .{ .language = "", .body = s }; - const meta = std.mem.trim(u8, s[0..at], " \t\r\n"); - const lang = if (std.mem.startsWith(u8, meta, "language ")) std.mem.trim(u8, meta["language ".len..], " ") else meta; - if (std.mem.eql(u8, lang, "None")) return .{ .language = "", .body = "" }; - return .{ .language = lang, .body = std.mem.trim(u8, s[at + asr_text.len ..], " \t\r\n") }; -} - test "text: the template's turns around the audio rows, and a forced language" { const a = std.testing.allocator; const t = try text(a, 2, "", null); @@ -40,11 +30,3 @@ test "text: the template's turns around the audio rows, and a forced language" { defer a.free(f); try std.testing.expect(std.mem.endsWith(u8, f, "assistant\nlanguage English")); } - -test "split: language and body, and the silent clip" { - const s = split("language EnglishMr. Quilter is the apostle."); - try std.testing.expectEqualStrings("English", s.language); - try std.testing.expectEqualStrings("Mr. Quilter is the apostle.", s.body); - try std.testing.expectEqualStrings("", split("language None").body); - try std.testing.expectEqualStrings("plain", split(" plain ").body); -} From 841d2e85aa2c12442fbb23b2661b399813746d76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Fri, 6 Nov 2026 06:04:23 +0100 Subject: [PATCH 14/28] qwen3-asr: tf-qwen3-asr-check --ids-only, as tf-qwen3-asr has (#2105) A case from qwen3_asr_case.py --ids-only holds no stage tensors, so the host check stopped at the missing mel stage. With --ids-only it checks the weights, the prompt ids and the reference reply's decode, and compares no stage. On the 1.7B's gate case 1089-134686-0001: PASS. --- zig/qwen3_asr_check.zig | 34 +++++++++++++++++++++------------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/zig/qwen3_asr_check.zig b/zig/qwen3_asr_check.zig index 576fc223a25..59a78db55ac 100644 --- a/zig/qwen3_asr_check.zig +++ b/zig/qwen3_asr_check.zig @@ -4,7 +4,8 @@ const qa = @import("qwen3_asr"); const core = @import("core"); const tok = @import("tokenizer"); -const usage = "usage: tf-qwen3-asr-check MODEL_DIR CLIP.wav CASE_DIR [--points exact|torch] [--no-tower] [--min-cos X]\n" ++ +const usage = "usage: tf-qwen3-asr-check MODEL_DIR CLIP.wav CASE_DIR [--points exact|torch] [--no-tower | --ids-only] [--min-cos X]\n" ++ + " --ids-only: a case of ids only (qwen3_asr_case.py --ids-only): the weights and tokens, no stage\n" ++ " a gate: exit 1 when a stage's cosine to the case is under X (default 0.995) or the tokens differ\n"; /// The checkpoint's shards as one name space (core.Checkpoint, as the CUDA load opens them). @@ -106,9 +107,12 @@ pub fn main(init: std.process.Init) !u8 { var points: qa.ref_ops.Points = .torch; var tower = true; var min_cos: f64 = 0.995; + var ids_only = false; var i: usize = 4; while (i < args.len) : (i += 1) { - if (std.mem.eql(u8, args[i], "--no-tower")) tower = false else if (std.mem.eql(u8, args[i], "--points") and i + 1 < args.len) { + if (std.mem.eql(u8, args[i], "--no-tower")) tower = false else if (std.mem.eql(u8, args[i], "--ids-only")) { + ids_only = true; + } else if (std.mem.eql(u8, args[i], "--points") and i + 1 < args.len) { i += 1; points = std.meta.stringToEnum(qa.ref_ops.Points, args[i]) orelse return 2; } else if (std.mem.eql(u8, args[i], "--min-cos") and i + 1 < args.len) { @@ -133,20 +137,24 @@ pub fn main(init: std.process.Init) !u8 { std.debug.print("CLIP {d} samples, {d} frames ({d} in the case), {d} chunks, {d} rows, {d} windows of {d}\n", .{ samples.len, plan.frames, case.frames, plan.chunks, plan.rows, plan.windows(), plan.window_rows }); if (plan.frames != case.frames) return error.FrameCount; try checkTokens(gpa, io, args[1], &case, plan.rows); - var feats = try qa.mel.features(gpa, samples, cfg.audio.mels); - defer feats.deinit(gpa); var cmp: Compare = .{ .gpa = gpa, .case = &case }; - const wide = try gpa.alloc(f64, feats.data.len); - defer gpa.free(wide); - for (wide, feats.data) |*w, f| w.* = f; - try Compare.put(&cmp, "mel", 0, wide); - if (tower) { - const src: qa.tower_ref.Source = .{ .ctx = &mapped, .get = Mapped.get }; - const out = try qa.tower_ref.run(gpa, cfg.audio, points, src, feats, .{ .ctx = &cmp, .put = Compare.put }); - gpa.free(out); + if (!ids_only) { // an ids-only case holds no stage: the weights and tokens above are its check + var feats = try qa.mel.features(gpa, samples, cfg.audio.mels); + defer feats.deinit(gpa); + const wide = try gpa.alloc(f64, feats.data.len); + defer gpa.free(wide); + for (wide, feats.data) |*w, f| w.* = f; + try Compare.put(&cmp, "mel", 0, wide); + if (tower) { + const src: qa.tower_ref.Source = .{ .ctx = &mapped, .get = Mapped.get }; + const out = try qa.tower_ref.run(gpa, cfg.audio, points, src, feats, .{ .ctx = &cmp, .put = Compare.put }); + gpa.free(out); + } } try cmp.finish(); const pass = cmp.worst_cos >= min_cos; // NaN fails - std.debug.print("SUMMARY qwen3-asr host ({t} points): worst stage cosine {d:.9} (gate {d}): {s}\n", .{ points, cmp.worst_cos, min_cos, if (pass) "PASS" else "FAIL" }); + if (ids_only) { + std.debug.print("SUMMARY qwen3-asr host (ids only): weights and tokens: PASS\n", .{}); + } else std.debug.print("SUMMARY qwen3-asr host ({t} points): worst stage cosine {d:.9} (gate {d}): {s}\n", .{ points, cmp.worst_cos, min_cos, if (pass) "PASS" else "FAIL" }); return if (pass) 0 else 1; } From 3e648eb9f04980b45ec803858e9d313e885e95c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Fri, 6 Nov 2026 06:05:15 +0100 Subject: [PATCH 15/28] qwen3-asr: the tower dumps conv_out, and tf-qwen3-asr compares it (#2105) The package taps conv_out before the positions are added, and the schedule fuses the add into conv_out's Linear. When a binding is dumping (a new dumping() on the binding), the schedule runs conv_out once more without the positions and dumps it; the timed pass is unchanged. tf-qwen3-asr gathers it over the chunk groups as it does the convs. The schedule test compares the host binding's conv_out with the float64 reference's. --- zig/src/families/qwen3_asr/cuda/tower.zig | 5 +++++ zig/src/families/qwen3_asr/schedule_test.zig | 14 ++++++++++++++ zig/src/families/qwen3_asr/tower.zig | 7 ++++++- zig/tests/qwen3_asr_cuda.zig | 19 ++++++++++++------- 4 files changed, 37 insertions(+), 8 deletions(-) diff --git a/zig/src/families/qwen3_asr/cuda/tower.zig b/zig/src/families/qwen3_asr/cuda/tower.zig index 22a93325e9d..c1685e56737 100644 --- a/zig/src/families/qwen3_asr/cuda/tower.zig +++ b/zig/src/families/qwen3_asr/cuda/tower.zig @@ -71,6 +71,11 @@ pub const Tower = struct { try vit.linear(&t.g, &t.vk, t.s, t.acc, t.cols, w, b, y, rows, co, ld); } + /// 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); } diff --git a/zig/src/families/qwen3_asr/schedule_test.zig b/zig/src/families/qwen3_asr/schedule_test.zig index 17c1cca4ddf..2103553b7af 100644 --- a/zig/src/families/qwen3_asr/schedule_test.zig +++ b/zig/src/families/qwen3_asr/schedule_test.zig @@ -53,8 +53,10 @@ const TowerHost = struct { gpa: std.mem.Allocator, stages: std.StringHashMapUnmanaged([]f64) = .empty, conv1_frames: usize = 0, // the first convolution's time length, as the schedule last passed it + conv_out: std.ArrayList(f64) = .empty, // gathered over the chunk groups fn deinit(t: *TowerHost) void { + t.conv_out.deinit(t.gpa); var it = t.stages.iterator(); while (it.next()) |e| { t.gpa.free(e.key_ptr.*); @@ -91,11 +93,16 @@ const TowerHost = struct { pub fn dump(t: *TowerHost, stage: []const u8, ptr: u64, rows: usize, cols: usize, conv_shape: ?[3]usize) !void { const v = try t.m.at(ptr, rows * cols); if (conv_shape != null) return; // the reference taps convs per chunk, channels first: extents only here + if (std.mem.eql(u8, stage, "conv_out")) return t.conv_out.appendSlice(t.gpa, v); const got = try t.stages.getOrPut(t.gpa, stage); if (got.found_existing) t.gpa.free(got.value_ptr.*) else got.key_ptr.* = try t.gpa.dupe(u8, stage); got.value_ptr.* = try t.gpa.dupe(f64, v); } + pub fn dumping(_: *const TowerHost) bool { + return true; + } + pub fn flatten(t: *TowerHost, x: u64, y: u64, n: usize, f: usize, tt: usize, c: usize) !void { const xs = try t.m.at(x, n * f * tt * c); const ys = try t.m.at(y, n * tt * c * f); @@ -178,14 +185,17 @@ const Fake = struct { const Ref = struct { gpa: std.mem.Allocator, stages: std.StringHashMapUnmanaged([]f64) = .empty, + conv_out: std.ArrayList(f64) = .empty, // a chunk at a time fn put(ctx: *anyopaque, stage: []const u8, offset: usize, values: []const f64) anyerror!void { const r: *Ref = @ptrCast(@alignCast(ctx)); + if (std.mem.eql(u8, stage, "conv_out")) return r.conv_out.appendSlice(r.gpa, values); if (offset != 0 or std.mem.startsWith(u8, stage, "conv")) return; try r.stages.put(r.gpa, try r.gpa.dupe(u8, stage), try r.gpa.dupe(f64, values)); } fn deinit(r: *Ref) void { + r.conv_out.deinit(r.gpa); var it = r.stages.iterator(); while (it.next()) |e| { r.gpa.free(e.key_ptr.*); @@ -247,6 +257,10 @@ fn towerCase(frames: usize, group: usize, want_windows: usize) !void { try std.testing.expect(c >= 0.9999); } try std.testing.expect(seen >= small.layers + 4); // embed, each layer, ln_post, proj1, audio_rows + // conv_out, before the positions, chunk after chunk at the plan's chunk rows + try std.testing.expectEqual(plan.chunks * plan.chunk_rows * small.d, host.conv_out.items.len); + try std.testing.expectEqual(ref.conv_out.items.len, host.conv_out.items.len); + try std.testing.expect(cosine(host.conv_out.items, ref.conv_out.items) >= 0.9999); } test "tower schedule: a host binding matches the float64 reference at torch's points, two windows, a short chunk" { diff --git a/zig/src/families/qwen3_asr/tower.zig b/zig/src/families/qwen3_asr/tower.zig index 481150ce057..91176177a73 100644 --- a/zig/src/families/qwen3_asr/tower.zig +++ b/zig/src/families/qwen3_asr/tower.zig @@ -167,7 +167,12 @@ fn front(r: anytype, a: cfg.Audio, w: *const Weights, b: Buffers, feats: mel.Fea try r.dump("conv3", b.c1, n * f3 * t3, a.conv, .{ n, f3, t3 }); try r.gelu(b.c1, b.c1, n * f3 * t3 * a.conv); try r.flatten(b.c1, b.wide, n, f3, t3, a.conv); - try r.linear(b.wide, w.conv_out, null, b.x + first * t3 * a.d * 2, n * t3, a.d, a.conv * f3, .none, w.positions); + const rows = b.x + first * t3 * a.d * 2; + if (r.dumping()) { // the package's conv_out tap is before the positions: one more pass for it, only when dumping + try r.linear(b.wide, w.conv_out, null, rows, n * t3, a.d, a.conv * f3, .none, null); + try r.dump("conv_out", rows, n * t3, a.d, null); + } + try r.linear(b.wide, w.conv_out, null, rows, n * t3, a.d, a.conv * f3, .none, w.positions); } /// The tower over `feats` into `out` [rows, a.out] bf16; the plan's rows returned. diff --git a/zig/tests/qwen3_asr_cuda.zig b/zig/tests/qwen3_asr_cuda.zig index 993f66f662e..bf9429b7209 100644 --- a/zig/tests/qwen3_asr_cuda.zig +++ b/zig/tests/qwen3_asr_cuda.zig @@ -36,11 +36,16 @@ const Compare = struct { try c.d.check(c.d.api.cuMemcpyDtoH_v2(raw.ptr, ptr, raw.len * 2), "cuMemcpyDtoH"); const vals = try c.gpa.alloc(f64, raw.len); defer c.gpa.free(vals); - 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]); - }; + 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); @@ -59,9 +64,9 @@ const Compare = struct { 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, gathered over every chunk group, compared once whole. + /// 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" }) |n| if (c.conv.getPtr(n)) |l| { + 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); }; From 09d6b199fef99c3f5dd5a752de35e8e562cbb10a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Fri, 6 Nov 2026 06:06:57 +0100 Subject: [PATCH 16/28] qwen3-asr: windowed attention is the decision, and a --global-attention case is checkable on the host (#2105) The tower runs attention within n_window_infer windows, as the package's vLLM backend and flash-attention-2 path do; the package's stock transformers SDPA path attends over every row. chunks.zig records that. The case's manifest names its attention, Plan.attending(.global) is one window over every row, and the float64 reference and tf-qwen3-asr-check run the case's kind. tf-qwen3-asr, which runs the windows, refuses a global case (exit 2). On dev clip 1272-128104-0004 (2940 frames, 4 windows) with the 0.6B: the global case passes at audio_rows cosine 0.99987 (worst stage 0.99979), the windowed case at 0.99989; the global case checked with windows gives 0.919 and fails the gate. --- zig/qwen3_asr_check.zig | 6 +++--- zig/src/families/qwen3_asr/case.zig | 3 +++ zig/src/families/qwen3_asr/chunks.zig | 17 +++++++++++++++++ zig/src/families/qwen3_asr/schedule_test.zig | 2 +- zig/src/families/qwen3_asr/tower_ref.zig | 6 +++--- zig/tests/qwen3_asr_cuda.zig | 4 ++++ 6 files changed, 31 insertions(+), 7 deletions(-) diff --git a/zig/qwen3_asr_check.zig b/zig/qwen3_asr_check.zig index 59a78db55ac..4ed7b23d58d 100644 --- a/zig/qwen3_asr_check.zig +++ b/zig/qwen3_asr_check.zig @@ -133,8 +133,8 @@ pub fn main(init: std.process.Init) !u8 { defer gpa.free(bytes); const samples = try qa.wav.decode(gpa, bytes); defer gpa.free(samples); - const plan = try qa.chunks.Plan.init(cfg.audio, qa.chunks.frames(samples.len)); - std.debug.print("CLIP {d} samples, {d} frames ({d} in the case), {d} chunks, {d} rows, {d} windows of {d}\n", .{ samples.len, plan.frames, case.frames, plan.chunks, plan.rows, plan.windows(), plan.window_rows }); + const plan = (try qa.chunks.Plan.init(cfg.audio, qa.chunks.frames(samples.len))).attending(case.attention); + std.debug.print("CLIP {d} samples, {d} frames ({d} in the case), {d} chunks, {d} rows, {d} windows of {d} ({t} attention, as the case)\n", .{ samples.len, plan.frames, case.frames, plan.chunks, plan.rows, plan.windows(), plan.window_rows, case.attention }); if (plan.frames != case.frames) return error.FrameCount; try checkTokens(gpa, io, args[1], &case, plan.rows); var cmp: Compare = .{ .gpa = gpa, .case = &case }; @@ -147,7 +147,7 @@ pub fn main(init: std.process.Init) !u8 { try Compare.put(&cmp, "mel", 0, wide); if (tower) { const src: qa.tower_ref.Source = .{ .ctx = &mapped, .get = Mapped.get }; - const out = try qa.tower_ref.run(gpa, cfg.audio, points, src, feats, .{ .ctx = &cmp, .put = Compare.put }); + const out = try qa.tower_ref.run(gpa, cfg.audio, points, case.attention, src, feats, .{ .ctx = &cmp, .put = Compare.put }); gpa.free(out); } } diff --git a/zig/src/families/qwen3_asr/case.zig b/zig/src/families/qwen3_asr/case.zig index 701f1ec9ba4..bb7037607a7 100644 --- a/zig/src/families/qwen3_asr/case.zig +++ b/zig/src/families/qwen3_asr/case.zig @@ -1,5 +1,6 @@ //! A reference case from tools/zig/qwen3_asr_case.py: manifest.json and one float32 or int32 file a stage. const std = @import("std"); +const Attention = @import("chunks.zig").Attention; pub const Stage = struct { shape: []const usize, int: bool }; @@ -10,6 +11,7 @@ pub const Case = struct { stages: std.StringArrayHashMapUnmanaged(Stage) = .empty, frames: usize = 0, text: []const u8 = "", + attention: Attention = .windows, // the tool's default; --global-attention cases say "global" pub fn open(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) !Case { var c: Case = .{ .arena = .init(gpa), .dir = undefined, .io = io }; @@ -33,6 +35,7 @@ pub const Case = struct { } if (doc.object.get("frames")) |f| c.frames = if (f == .integer and f.integer >= 0) @intCast(f.integer) else return error.BadCase; if (doc.object.get("text")) |t| c.text = if (t == .string) t.string else return error.BadCase; + if (doc.object.get("attention")) |t| c.attention = if (t == .string) std.meta.stringToEnum(Attention, t.string) orelse return error.BadCase else return error.BadCase; return c; } diff --git a/zig/src/families/qwen3_asr/chunks.zig b/zig/src/families/qwen3_asr/chunks.zig index 03ed060d02b..d32c98bf030 100644 --- a/zig/src/families/qwen3_asr/chunks.zig +++ b/zig/src/families/qwen3_asr/chunks.zig @@ -1,6 +1,9 @@ //! The tower's chunk and window plan: 100-frame chunks through the convolutions, then attention over whole windows. //! The package pads every chunk to the longest one, so a clip of one chunk under 100 frames is convolved at its own //! length, and a clip of more chunks at 100 frames a chunk, the last one zero-padded. +//! Attention runs within windows of n_window_infer frames, as the package's vLLM backend and its flash-attention-2 +//! path do; tf-qwen3-asr runs that. The package's stock transformers SDPA path attends over every row instead +//! (`Attention.global`); the float64 reference and tf-qwen3-asr-check run either, so both kinds of case stay checkable. const std = @import("std"); const Audio = @import("config.zig").Audio; @@ -20,6 +23,9 @@ pub fn rows(len: usize) usize { return @as(usize, @intCast(tail)) + (len / 100) * 13; } +/// How the tower's layers attend: within the plan's windows, or over every row. +pub const Attention = enum { windows, global }; + /// A clip's plan: its chunks' frames and rows, and the attention windows over the rows. pub const Plan = struct { frames: usize, @@ -39,6 +45,13 @@ pub const Plan = struct { return .{ .frames = n, .chunks = chunks, .last_frames = last, .chunk_frames = longest, .rows = rows(n), .chunk_rows = rows(longest), .window_rows = rows(longest) * (a.window_infer / cf) }; } + /// The plan with its attention as given: `global` is one window over every row. + pub fn attending(p: Plan, how: Attention) Plan { + var g = p; + if (how == .global) g.window_rows = p.rows; + return g; + } + /// Rows chunk `i` leaves. pub fn rowsOf(p: Plan, i: usize) usize { return rows(if (i + 1 == p.chunks) p.last_frames else 100); @@ -80,4 +93,8 @@ test "plan: chunks, the short last chunk, windows of eight chunks" { try std.testing.expectEqual(@as(usize, 64), short.window_rows); try std.testing.expectEqual(@as(usize, 1), short.windows()); try std.testing.expectError(error.EmptyClip, Plan.init(a, 0)); + const g = p.attending(.global); + try std.testing.expectEqual(@as(usize, 1), g.windows()); + try std.testing.expectEqual(p.rows, g.window(0).len); + try std.testing.expectEqual(p.window_rows, p.attending(.windows).window_rows); } diff --git a/zig/src/families/qwen3_asr/schedule_test.zig b/zig/src/families/qwen3_asr/schedule_test.zig index 2103553b7af..11df98bf1cd 100644 --- a/zig/src/families/qwen3_asr/schedule_test.zig +++ b/zig/src/families/qwen3_asr/schedule_test.zig @@ -244,7 +244,7 @@ fn towerCase(frames: usize, group: usize, want_windows: usize) !void { try std.testing.expectEqual(if (frames < small.chunkFrames()) frames else small.chunkFrames(), host.conv1_frames); var ref: Ref = .{ .gpa = gpa }; defer ref.deinit(); - const want = try tower_ref.run(gpa, small, .torch, .{ .ctx = &fake, .get = Fake.get }, feats, .{ .ctx = &ref, .put = Ref.put }); + const want = try tower_ref.run(gpa, small, .torch, .windows, .{ .ctx = &fake, .get = Fake.get }, feats, .{ .ctx = &ref, .put = Ref.put }); defer gpa.free(want); var it = ref.stages.iterator(); var seen: usize = 0; diff --git a/zig/src/families/qwen3_asr/tower_ref.zig b/zig/src/families/qwen3_asr/tower_ref.zig index 27afb7d2f51..545f96d6032 100644 --- a/zig/src/families/qwen3_asr/tower_ref.zig +++ b/zig/src/families/qwen3_asr/tower_ref.zig @@ -226,9 +226,9 @@ fn addLinear(gpa: std.mem.Allocator, p: ops.Points, src: Source, buf: []u8, i: u for (x, y) |*v, o| v.* = ops.round(p, v.* + ops.round(p, o)); } -/// The tower over `feats`: every stage to `sink`, the audio rows [plan.rows][out] returned. -pub fn run(gpa: std.mem.Allocator, a: cfg.Audio, p: ops.Points, src: Source, feats: mel.Features, sink: Sink) ![]f64 { - const plan = try chunks.Plan.init(a, feats.frames); +/// The tower over `feats`, attending as `how` says: every stage to `sink`, the audio rows [plan.rows][out] returned. +pub fn run(gpa: std.mem.Allocator, a: cfg.Audio, p: ops.Points, how: chunks.Attention, src: Source, feats: mel.Features, sink: Sink) ![]f64 { + const plan = (try chunks.Plan.init(a, feats.frames)).attending(how); const x = try front(gpa, a, p, src, feats, plan, sink); defer gpa.free(x); try sink.put(sink.ctx, "embed", 0, x); diff --git a/zig/tests/qwen3_asr_cuda.zig b/zig/tests/qwen3_asr_cuda.zig index bf9429b7209..739d9c7ab3e 100644 --- a/zig/tests/qwen3_asr_cuda.zig +++ b/zig/tests/qwen3_asr_cuda.zig @@ -144,6 +144,10 @@ pub fn main(init: std.process.Init) !u8 { 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(); + if (case) |c| if (c.attention != .windows) { // the tower here runs the windows: a global case is the host check's + std.debug.print("the case attends over every row (--global-attention); tf-qwen3-asr runs the windows\n", .{}); + return 2; + }; var cmp: ?Compare = if (case) |*c| .{ .gpa = gpa, .case = c, .s = s, .d = &driver } else null; var same_prompt = true; if (cmp) |*c| { From 18650a64c946e87b05e0f8652ab165eb2c42407b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Fri, 6 Nov 2026 06:08:53 +0100 Subject: [PATCH 17/28] qwen3-asr: one-line comments for the lean check (#2105) --- zig/build/qwen3_asr_host.zig | 2 +- zig/src/families/qwen3_asr/chunks.zig | 9 ++------- zig/src/families/qwen3_asr/tower.zig | 3 +-- 3 files changed, 4 insertions(+), 10 deletions(-) diff --git a/zig/build/qwen3_asr_host.zig b/zig/build/qwen3_asr_host.zig index 181135671c6..abf92997514 100644 --- a/zig/build/qwen3_asr_host.zig +++ b/zig/build/qwen3_asr_host.zig @@ -8,7 +8,7 @@ pub fn steps(b: *std.Build, all: *std.Build.Step) void { checks.dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = family })).step); all.dependOn(checks); const tokenizer = b.createModule(.{ .root_source_file = b.path("zig/src/core/tokenizer/tokenizer.zig"), .target = host, .link_libc = true }); - // core for its Checkpoint: one checkpoint folder's shards (the 1.7B's two) as one name space, as the CUDA load opens it + // core for its Checkpoint: a folder's shards (the 1.7B's two) as one name space, as the CUDA load opens them const core = b.createModule(.{ .root_source_file = b.path("zig/src/core/root.zig"), .target = host, .link_libc = true }); core.addImport("gpu_memory", @import("gpu_memory.zig").module(b, host)); core.addImport("tokenizer", tokenizer); diff --git a/zig/src/families/qwen3_asr/chunks.zig b/zig/src/families/qwen3_asr/chunks.zig index d32c98bf030..3d99fdc7dd0 100644 --- a/zig/src/families/qwen3_asr/chunks.zig +++ b/zig/src/families/qwen3_asr/chunks.zig @@ -1,9 +1,4 @@ //! The tower's chunk and window plan: 100-frame chunks through the convolutions, then attention over whole windows. -//! The package pads every chunk to the longest one, so a clip of one chunk under 100 frames is convolved at its own -//! length, and a clip of more chunks at 100 frames a chunk, the last one zero-padded. -//! Attention runs within windows of n_window_infer frames, as the package's vLLM backend and its flash-attention-2 -//! path do; tf-qwen3-asr runs that. The package's stock transformers SDPA path attends over every row instead -//! (`Attention.global`); the float64 reference and tf-qwen3-asr-check run either, so both kinds of case stay checkable. const std = @import("std"); const Audio = @import("config.zig").Audio; @@ -23,7 +18,7 @@ pub fn rows(len: usize) usize { return @as(usize, @intCast(tail)) + (len / 100) * 13; } -/// How the tower's layers attend: within the plan's windows, or over every row. +/// Windows of n_window_infer frames (vLLM's and flash-attention-2's, what tf-qwen3-asr runs) or SDPA's every row. pub const Attention = enum { windows, global }; /// A clip's plan: its chunks' frames and rows, and the attention windows over the rows. @@ -31,7 +26,7 @@ pub const Plan = struct { frames: usize, chunks: usize, last_frames: usize, // the last chunk's frames (a full chunk when frames divide) - chunk_frames: usize, // frames of the longest chunk: the convolutions' time length, every chunk padded to it + chunk_frames: usize, // the longest chunk's frames, every chunk padded to it: a lone short chunk is convolved as is rows: usize, chunk_rows: usize, // rows of the longest chunk: a row's position inside its chunk runs to this window_rows: usize, // rows an attention window spans diff --git a/zig/src/families/qwen3_asr/tower.zig b/zig/src/families/qwen3_asr/tower.zig index 91176177a73..ab40dda4c26 100644 --- a/zig/src/families/qwen3_asr/tower.zig +++ b/zig/src/families/qwen3_asr/tower.zig @@ -146,8 +146,7 @@ fn input(a: cfg.Audio, feats: mel.Features, cf: usize, first: usize, n: usize, h return out; } -/// The convolutions over a group of chunks into rows of b.x from first * 13 on, positions added; each chunk is -/// convolved at the plan's chunk length (a lone short chunk at its own, as the package pads to the longest chunk). +/// The convolutions over a group of chunks, `cf` frames each, into rows of b.x from first * 13 on, positions added. fn front(r: anytype, a: cfg.Audio, w: *const Weights, b: Buffers, feats: mel.Features, cf: usize, first: usize, n: usize, host: []u16) !void { try r.upload(b.in, std.mem.sliceAsBytes(input(a, feats, cf, first, n, host))); const f1 = (a.mels - 1) / 2 + 1; From a9270bd102b46818edb9a99a26a197c38239ffcb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Tue, 10 Nov 2026 12:15:45 +0100 Subject: [PATCH 18/28] qwen3-asr: a decode step's logits equal the prompt pass's rows, and a prompt in two passes equals one (#2105) The splice is cut to the pass, so a prompt can be split inside the audio rows. forwardHeads puts the head over a pass's last rows, the CUDA binding can keep each head row's logits and download its caches, and lm_test.zig checks both equalities on a computing host binding, with a planted cache slot that fails them. --- zig/src/families/qwen3_asr/cuda/lm.zig | 18 ++ zig/src/families/qwen3_asr/cuda/model.zig | 5 + zig/src/families/qwen3_asr/lm.zig | 30 ++- zig/src/families/qwen3_asr/lm_test.zig | 232 +++++++++++++++++++ zig/src/families/qwen3_asr/qwen3_asr.zig | 1 + zig/src/families/qwen3_asr/schedule_test.zig | 16 +- 6 files changed, 289 insertions(+), 13 deletions(-) create mode 100644 zig/src/families/qwen3_asr/lm_test.zig diff --git a/zig/src/families/qwen3_asr/cuda/lm.zig b/zig/src/families/qwen3_asr/cuda/lm.zig index 020ed87f28e..3b5f265f029 100644 --- a/zig/src/families/qwen3_asr/cuda/lm.zig +++ b/zig/src/families/qwen3_asr/cuda/lm.zig @@ -40,8 +40,12 @@ pub const Lm = struct { host_pos: []i32, logits: []u16, last_margin: f32 = 0, // the last pick's lead over the runner-up + keep: ?Keep = null, // each head row's logits, appended sink: ?@import("tower.zig").Dump = null, + /// Where the head's logits go, a row of vocab bf16 values at a time. + pub const Keep = struct { gpa: std.mem.Allocator, rows: *std.ArrayList(u16) }; + const Buffers = struct { ids: u64, pos: u64, meta: u64, q: u64, k: u64, v: u64, po: u64, pm: u64, pl: u64, xs: u64, logits: u64, cos: u64, sin: u64, kc: u64, vc: u64 }; /// Passes of up to `max_rows` rows over up to `span` positions. @@ -197,8 +201,22 @@ pub const Lm = struct { try lm.g.run(lm.s, row, embed_table, lm.b.logits, 1, lm.t.vocab, lm.t.hidden, .bf16); try store.view(lm.d, lm.b.logits, lm.logits.len * 2).downloadAsync(0, std.mem.sliceAsBytes(lm.logits), lm.s.handle); try lm.s.synchronize(); + if (lm.keep) |k| try k.rows.appendSlice(k.gpa, lm.logits); const best = shared.argmax(lm.logits); lm.last_margin = shared.margin(lm.logits, best); return best; } + + /// Positions [0, n) of every layer's k and v caches, downloaded: k rows then v rows, layer by layer. + pub fn cacheRows(lm: *Lm, gpa: std.mem.Allocator, n: usize) ![]u16 { + const row = lm.t.kv_heads * lm.t.head_dim; + const out = try gpa.alloc(u16, 2 * lm.t.layers * n * row); + errdefer gpa.free(out); + try lm.s.synchronize(); + for (0..lm.t.layers) |l| for ([_]u64{ lm.b.kc, lm.b.vc }, 0..) |base, j| { + const dst = out[(2 * l + j) * n * row ..][0 .. n * row]; + try lm.d.check(lm.d.api.cuMemcpyDtoH_v2(dst.ptr, lm.kvAt(base, l), dst.len * 2), "cuMemcpyDtoH"); + }; + return out; + } }; diff --git a/zig/src/families/qwen3_asr/cuda/model.zig b/zig/src/families/qwen3_asr/cuda/model.zig index 1b3bf21a8fe..f2684c71e1d 100644 --- a/zig/src/families/qwen3_asr/cuda/model.zig +++ b/zig/src/families/qwen3_asr/cuda/model.zig @@ -82,6 +82,11 @@ pub const Model = struct { return m.forwardDump(ids, pos, audio, null); } + /// forward with the head over the last `heads` rows: each row's logits to the binding's `keep` when set. + pub fn forwardHeads(m: *Model, ids: []const u32, pos: usize, audio: ?Splice, heads: usize) !u32 { + return lm.forwardHeads(&m.lr, m.c.text, &m.lw, m.lb, ids, pos, audio, heads); + } + /// 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/src/families/qwen3_asr/lm.zig b/zig/src/families/qwen3_asr/lm.zig index db0096100c9..908e7e90927 100644 --- a/zig/src/families/qwen3_asr/lm.zig +++ b/zig/src/families/qwen3_asr/lm.zig @@ -47,7 +47,18 @@ pub const Weights = struct { }; /// Audio rows spliced into a pass: `n` rows of the model's width at `ptr`, standing at positions [at, at + n). -pub const Splice = struct { ptr: u64, at: usize, n: usize }; +pub const Splice = struct { + ptr: u64, + at: usize, + n: usize, + + /// The rows standing in a pass over positions [pos, pos + rows): row `src` on, `len` of them, from pass row `dst`. + pub fn within(sp: Splice, pos: usize, rows: usize) ?struct { src: usize, dst: usize, len: usize } { + const lo = @max(sp.at, pos); + const hi = @min(sp.at + sp.n, pos + rows); + return if (lo < hi) .{ .src = lo - sp.at, .dst = lo - pos, .len = hi - lo } else null; + } +}; /// A pass's bf16 rows, each from the backend's `al.alloc(bytes)`; the KV caches are the binding's. pub const Buffers = struct { @@ -83,14 +94,19 @@ pub const Buffers = struct { /// One pass over `ids` at positions [pos, pos + ids.len), the audio rows spliced in: the last row's greedy pick. pub fn forward(r: anytype, t: cfg.Text, w: *const Weights, b: Buffers, ids: []const u32, pos: usize, audio: ?Splice) !u32 { + return forwardHeads(r, t, w, b, ids, pos, audio, 1); +} + +/// forward with the head over the pass's last `heads` rows, in order (a prompt run in passes splits its audio rows). +pub fn forwardHeads(r: anytype, t: cfg.Text, w: *const Weights, b: Buffers, ids: []const u32, pos: usize, audio: ?Splice, heads: usize) !u32 { const rows = ids.len; if (rows == 0 or rows > b.max_rows) return error.PassRows; + if (heads == 0 or heads > rows) return error.PassHeads; try r.positions(ids, pos); try r.embed(w.embed, b.e, rows, t.hidden); - if (audio) |sp| { - if (sp.at < pos or sp.at + sp.n > pos + rows) return error.SpliceOutsidePass; - try r.copy(b.e + (sp.at - pos) * t.hidden * 2, sp.ptr, sp.n * t.hidden * 2); - } + if (audio) |sp| if (sp.within(pos, rows)) |in| { + try r.copy(b.e + in.dst * t.hidden * 2, sp.ptr + in.src * t.hidden * 2, in.len * t.hidden * 2); + }; try r.dump("lm_embed", b.e, rows, t.hidden); const qd = t.heads * t.head_dim; const kvd = t.kv_heads * t.head_dim; @@ -123,7 +139,9 @@ pub fn forward(r: anytype, t: cfg.Text, w: *const Weights, b: Buffers, ids: []co try r.addNorm(x, res, w.norm, b.h[cur], b.y, rows); try r.dump(try layerName(&name, w.layers.len - 1), b.h[cur], rows, t.hidden); try r.dump("lm_norm", b.y, rows, t.hidden); - return r.greedy(b.y + (rows - 1) * t.hidden * 2, w.embed); + var pick: u32 = undefined; + for (rows - heads..rows) |i| pick = try r.greedy(b.y + i * t.hidden * 2, w.embed); + return pick; } fn layerName(buf: *[24]u8, i: usize) ![]const u8 { diff --git a/zig/src/families/qwen3_asr/lm_test.zig b/zig/src/families/qwen3_asr/lm_test.zig new file mode 100644 index 00000000000..23eb9267684 --- /dev/null +++ b/zig/src/families/qwen3_asr/lm_test.zig @@ -0,0 +1,232 @@ +//! The LM schedule's passes on a computing host binding: a decode step's logits and a prompt split in two passes. +const std = @import("std"); +const cfg = @import("config.zig"); +const ops = @import("ref_ops.zig"); +const lm = @import("lm.zig"); +const st = @import("schedule_test.zig"); + +const t: cfg.Text = .{ .hidden = 16, .layers = 2, .heads = 4, .kv_heads = 2, .head_dim = 8, .intermediate = 24, .vocab = 40, .eps = 1e-6, .theta = 1e6, .context = 64 }; +const qd = t.heads * t.head_dim; +const kvd = t.kv_heads * t.head_dim; +const cap = 32; + +/// Each op row by row in float64 at bf16 points, so a row's values never depend on the rows beside it in a pass. +const LmHost = struct { + m: *st.Mem, + gpa: std.mem.Allocator, + ids: [cap]u32 = undefined, + pos: usize = 0, + rows: usize = 0, + q: [cap * qd]f64 = undefined, + kc: [t.layers * cap * kvd]f64 = @splat(std.math.nan(f64)), + vc: [t.layers * cap * kvd]f64 = @splat(std.math.nan(f64)), + cs: [cap * t.head_dim]f32 = undefined, + sn: [cap * t.head_dim]f32 = undefined, + logits: std.ArrayList(f64) = .empty, + plant_slot: bool = false, // the planted fault: k and v written at the pass's row, not its position + + fn init(m: *st.Mem, gpa: std.mem.Allocator) LmHost { + var h: LmHost = .{ .m = m, .gpa = gpa }; + lm.ropeTables(t, &h.cs, &h.sn, cap); + return h; + } + + fn deinit(h: *LmHost) void { + h.logits.deinit(h.gpa); + } + + pub fn positions(h: *LmHost, ids: []const u32, pos: usize) !void { + if (pos + ids.len > cap) return error.ContextFull; + @memcpy(h.ids[0..ids.len], ids); + h.pos = pos; + h.rows = ids.len; + } + pub fn embed(h: *LmHost, table: u64, out: u64, rows: usize, hidden: usize) !void { + const tab = try h.m.at(table, t.vocab * hidden); + const o = try h.m.at(out, rows * hidden); + for (0..rows) |r| @memcpy(o[r * hidden ..][0..hidden], tab[h.ids[r] * hidden ..][0..hidden]); + } + pub fn copy(h: *LmHost, dst: u64, src: u64, n: usize) !void { + @memcpy(try h.m.at(dst, n / 2), try h.m.at(src, n / 2)); + } + fn rms(x: []const f64, w: []const f64, y: []f64) void { + var ss: f64 = 0; + for (x) |v| ss += v * v; + const inv = 1 / @sqrt(ss / @as(f64, @floatFromInt(x.len)) + t.eps); + for (y, x, w) |*o, v, g| o.* = ops.bf16(g * ops.bf16(v * inv)); + } + pub fn addNorm(h: *LmHost, x: u64, res: ?u64, w: u64, hb: u64, y: u64, rows: usize) !void { + const xs = try h.m.at(x, rows * t.hidden); + const ws = try h.m.at(w, t.hidden); + const ys = try h.m.at(y, rows * t.hidden); + const hs = if (res != null) try h.m.at(hb, rows * t.hidden) else xs; + if (res) |p| for (hs, xs, try h.m.at(p, rows * t.hidden)) |*o, a, b| { + o.* = ops.bf16(a + b); + }; + for (0..rows) |r| rms(hs[r * t.hidden ..][0..t.hidden], ws, ys[r * t.hidden ..][0..t.hidden]); + } + pub fn gemm(h: *LmHost, x: u64, w: u64, y: u64, rows: usize, n: usize, k: usize) !void { + const tmp = try h.gpa.alloc(f64, rows * n); + defer h.gpa.free(tmp); + ops.linear(tmp, try h.m.at(x, rows * k), try h.m.at(w, n * k), null, rows, n, k); + for (try h.m.at(y, rows * n), tmp) |*o, v| o.* = ops.bf16(v); + } + fn rope(h: *const LmHost, v: []f64, p: usize) void { + const half = t.head_dim / 2; + var tmp: [t.head_dim]f64 = undefined; + for (0..t.head_dim) |i| { + const other = if (i < half) -v[i + half] else v[i - half]; + tmp[i] = ops.bf16(v[i] * h.cs[p * t.head_dim + i] + other * h.sn[p * t.head_dim + i]); + } + @memcpy(v, &tmp); + } + pub fn qkRope(h: *LmHost, qkv: u64, qn: u64, kn: u64, layer: usize, rows: usize) !void { + const xs = try h.m.at(qkv, rows * (qd + 2 * kvd)); + const qw = try h.m.at(qn, t.head_dim); + const kw = try h.m.at(kn, t.head_dim); + for (0..rows) |r| { + const p = h.pos + r; + const row = xs[r * (qd + 2 * kvd) ..]; + for (0..t.heads) |i| { + const q = h.q[(r * t.heads + i) * t.head_dim ..][0..t.head_dim]; + rms(row[i * t.head_dim ..][0..t.head_dim], qw, q); + h.rope(q, p); + } + const slot = layer * cap + (if (h.plant_slot) r else p); + for (0..t.kv_heads) |i| { + const k = h.kc[slot * kvd + i * t.head_dim ..][0..t.head_dim]; + rms(row[qd + i * t.head_dim ..][0..t.head_dim], kw, k); + h.rope(k, p); + } + @memcpy(h.vc[slot * kvd ..][0..kvd], row[qd + kvd ..][0..kvd]); + } + } + pub fn attention(h: *LmHost, layer: usize, out: u64, rows: usize) !void { + const o = try h.m.at(out, rows * qd); + const scale = 1 / @sqrt(@as(f64, @floatFromInt(t.head_dim))); + var s: [cap]f64 = undefined; + for (0..rows) |r| for (0..t.heads) |i| { + const p = h.pos + r; + const g = i / (t.heads / t.kv_heads); + const q = h.q[(r * t.heads + i) * t.head_dim ..][0..t.head_dim]; + var top: f64 = -std.math.inf(f64); + for (0..p + 1) |j| { + const k = h.kc[(layer * cap + j) * kvd + g * t.head_dim ..][0..t.head_dim]; + var d: f64 = 0; + for (q, k) |a, b| d += a * b; + s[j] = d * scale; + top = @max(top, s[j]); + } + var sum: f64 = 0; + for (s[0 .. p + 1]) |*v| { + v.* = @exp(v.* - top); + sum += v.*; + } + for (0..t.head_dim) |c| { + var acc: f64 = 0; + for (0..p + 1) |j| acc += s[j] * h.vc[(layer * cap + j) * kvd + g * t.head_dim + c]; + o[r * qd + i * t.head_dim + c] = ops.bf16(acc / sum); + } + }; + } + pub fn swiglu(h: *LmHost, gu: u64, out: u64, rows: usize, i: usize) !void { + const x = try h.m.at(gu, rows * 2 * i); + const o = try h.m.at(out, rows * i); + for (0..rows) |r| for (0..i) |c| { + const g = x[r * 2 * i + c]; + o[r * i + c] = ops.bf16(ops.bf16(g / (1 + @exp(-g))) * x[r * 2 * i + i + c]); + }; + } + pub fn dump(_: *LmHost, _: []const u8, _: u64, _: usize, _: usize) !void {} + pub fn greedy(h: *LmHost, row: u64, table: u64) !u32 { + const x = try h.m.at(row, t.hidden); + const tab = try h.m.at(table, t.vocab * t.hidden); + var out: [t.vocab]f64 = undefined; + var best: u32 = 0; + for (&out, 0..) |*o, j| { + var d: f64 = 0; + for (x, tab[j * t.hidden ..][0..t.hidden]) |a, b| d += a * b; + o.* = ops.bf16(d); + if (o.* > out[best]) best = @intCast(j); + } + try h.logits.appendSlice(h.gpa, &out); + return best; + } +}; + +const Fixture = struct { + mem: st.Mem, + fake: st.Fake, + w: lm.Weights = undefined, + b: lm.Buffers = undefined, + audio: lm.Splice = undefined, + + fn init(f: *Fixture) !void { + const gpa = std.testing.allocator; + f.* = .{ .mem = .{ .gpa = gpa }, .fake = .{ .gpa = gpa } }; + const head = try f.fake.expect("thinker.model.embed_tokens.weight", &.{ t.vocab, t.hidden }); + try f.fake.map.put(gpa, try gpa.dupe(u8, "thinker.lm_head.weight"), try gpa.dupe(u8, head)); + f.w = try lm.Weights.load(gpa, t, &f.fake, &f.mem); + f.b = try lm.Buffers.alloc(t, 16, &f.mem); + const rows = try f.mem.alloc(2 * 4 * t.hidden); // four audio rows at positions [3, 7) + var rng: std.Random.DefaultPrng = .init(11); + for (try f.mem.at(rows, 4 * t.hidden)) |*v| v.* = ops.bf16(rng.random().floatNorm(f64)); + f.audio = .{ .ptr = rows, .at = 3, .n = 4 }; + } + + fn deinit(f: *Fixture) void { + f.w.deinit(std.testing.allocator); + f.fake.deinit(); + f.mem.deinit(); + } +}; + +const prompt = [_]u32{ 1, 2, 3, 9, 9, 9, 9, 4, 5, 6, 7, 8 }; + +/// Rows 7..11's logits by decode steps after a prompt pass over prompt[0..8], as tf-qwen3-asr runs a reply. +fn decoded(f: *Fixture, plant: bool) ![]f64 { + var h: LmHost = .init(&f.mem, std.testing.allocator); + defer h.deinit(); + h.plant_slot = plant; + _ = try lm.forward(&h, t, &f.w, f.b, prompt[0..8], 0, f.audio); + for (8..prompt.len) |p| _ = try lm.forward(&h, t, &f.w, f.b, prompt[p..][0..1], p, null); + return h.logits.toOwnedSlice(std.testing.allocator); +} + +test "lm schedule: each decode step's logits equal the prompt pass's for the same rows" { + var f: Fixture = undefined; + try f.init(); + defer f.deinit(); + var h: LmHost = .init(&f.mem, std.testing.allocator); + defer h.deinit(); + _ = try lm.forwardHeads(&h, t, &f.w, f.b, &prompt, 0, f.audio, 5); + const steps = try decoded(&f, false); + defer std.testing.allocator.free(steps); + try std.testing.expectEqualSlices(f64, h.logits.items, steps); + // the planted fault (k and v at the pass's row) moves a decode step: the comparison is not vacuous + const planted = try decoded(&f, true); + defer std.testing.allocator.free(planted); + try std.testing.expect(!std.mem.eql(f64, h.logits.items, planted)); +} + +test "lm schedule: a prompt in two passes, cut inside the audio rows, leaves the one pass's caches and logits" { + var f: Fixture = undefined; + try f.init(); + defer f.deinit(); + var one: LmHost = .init(&f.mem, std.testing.allocator); + defer one.deinit(); + _ = try lm.forward(&one, t, &f.w, f.b, &prompt, 0, f.audio); + for ([_]usize{ 5, 3, 7, 11 }) |cut| { + var two: LmHost = .init(&f.mem, std.testing.allocator); + defer two.deinit(); + _ = try lm.forward(&two, t, &f.w, f.b, prompt[0..cut], 0, f.audio); + two.logits.clearRetainingCapacity(); + _ = try lm.forward(&two, t, &f.w, f.b, prompt[cut..], cut, f.audio); + for (0..t.layers) |l| { + const at = l * cap * kvd; + try std.testing.expectEqualSlices(f64, one.kc[at..][0 .. prompt.len * kvd], two.kc[at..][0 .. prompt.len * kvd]); + try std.testing.expectEqualSlices(f64, one.vc[at..][0 .. prompt.len * kvd], two.vc[at..][0 .. prompt.len * kvd]); + } + try std.testing.expectEqualSlices(f64, one.logits.items, two.logits.items); + } +} diff --git a/zig/src/families/qwen3_asr/qwen3_asr.zig b/zig/src/families/qwen3_asr/qwen3_asr.zig index cb220dc9acb..1e0a756750b 100644 --- a/zig/src/families/qwen3_asr/qwen3_asr.zig +++ b/zig/src/families/qwen3_asr/qwen3_asr.zig @@ -25,4 +25,5 @@ test { _ = lm; _ = @import("config_test.zig"); _ = @import("schedule_test.zig"); + _ = @import("lm_test.zig"); } diff --git a/zig/src/families/qwen3_asr/schedule_test.zig b/zig/src/families/qwen3_asr/schedule_test.zig index 11df98bf1cd..17af4054c0d 100644 --- a/zig/src/families/qwen3_asr/schedule_test.zig +++ b/zig/src/families/qwen3_asr/schedule_test.zig @@ -9,11 +9,11 @@ const lm = @import("lm.zig"); const tower_ref = @import("tower_ref.zig"); /// Device memory on the host: an address is (allocation + 1) << 40 plus a byte offset, each value a bf16 slot. -const Mem = struct { +pub const Mem = struct { gpa: std.mem.Allocator, list: std.ArrayList([]f64) = .empty, - fn deinit(m: *Mem) void { + pub fn deinit(m: *Mem) void { for (m.list.items) |x| m.gpa.free(x); m.list.deinit(m.gpa); } @@ -37,7 +37,7 @@ const Mem = struct { } /// `n` values at `ptr`, refused unless they lie inside one allocation. - fn at(m: *Mem, ptr: u64, n: usize) ![]f64 { + pub fn at(m: *Mem, ptr: u64, n: usize) ![]f64 { const id = ptr >> 40; const off = ptr & ((1 << 40) - 1); if (id == 0 or id > m.list.items.len or off % 2 != 0) return error.BadAddress; @@ -147,12 +147,12 @@ const TowerHost = struct { }; /// Random bf16 tensors made on first ask, the same bytes for the schedule and the reference. -const Fake = struct { +pub const Fake = struct { gpa: std.mem.Allocator, rng: std.Random.DefaultPrng = .init(0x2105), map: std.StringHashMapUnmanaged([]u8) = .empty, - fn deinit(f: *Fake) void { + pub fn deinit(f: *Fake) void { var it = f.map.iterator(); while (it.next()) |e| { f.gpa.free(e.key_ptr.*); @@ -339,7 +339,7 @@ const LmBounds = struct { } }; -test "lm schedule: every op inside its buffers, the splice inside the pass, the head tied" { +test "lm schedule: every op inside its buffers, a splice cut to the pass, the head tied" { const gpa = std.testing.allocator; const t: cfg.Text = .{ .hidden = 16, .layers = 3, .heads = 4, .kv_heads = 2, .head_dim = 8, .intermediate = 24, .vocab = 32, .eps = 1e-6, .theta = 1e6, .context = 64 }; var mem: Mem = .{ .gpa = gpa }; @@ -358,6 +358,8 @@ test "lm schedule: every op inside its buffers, the splice inside the pass, the const ids = [_]u32{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; try std.testing.expectEqual(@as(u32, 7), try lm.forward(&bounds, t, &w, b, &ids, 0, .{ .ptr = rows, .at = 3, .n = 4 })); try std.testing.expectEqual(@as(u32, 7), try lm.forward(&bounds, t, &w, b, ids[0..1], 10, null)); - try std.testing.expectError(error.SpliceOutsidePass, lm.forward(&bounds, t, &w, b, &ids, 0, .{ .ptr = rows, .at = 8, .n = 4 })); + try std.testing.expectEqual(@as(u32, 7), try lm.forward(&bounds, t, &w, b, &ids, 0, .{ .ptr = rows, .at = 8, .n = 4 })); + try std.testing.expectError(error.OutOfBounds, lm.forward(&bounds, t, &w, b, &ids, 2, .{ .ptr = rows, .at = 0, .n = 5 })); + try std.testing.expectError(error.PassHeads, lm.forwardHeads(&bounds, t, &w, b, &ids, 0, null, 11)); try std.testing.expectError(error.PassRows, lm.forward(&bounds, t, &w, b, &(ids ++ ids), 0, null)); } From f575205c53c786619d8910b900f9d9ca459936e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Tue, 10 Nov 2026 12:15:45 +0100 Subject: [PATCH 19/28] qwen3-asr: tf-qwen3-asr-forced, the teacher-forced tie rule, and the case's bf16 and fp32 logits (#2105) Each clip runs on the reference's greedy ids to the end. A step whose top token differs passes only if the two tokens swap places and both margins are at most 0.25 logit; every such step is listed, anything else fails with exit 1. With logits_fp32 and logits_bf16 in the case (qwen3_asr_case.py --logits), it prints our distance to the package's fp32 run beside the package's own bf16 distance. --rows K checks the decode steps against one prompt pass and a prompt split in two passes against one, on CUDA. --- tools/zig/qwen3_asr_case.py | 21 ++- zig/build/qwen3_asr_cuda.zig | 6 +- zig/src/families/qwen3_asr/forced.zig | 62 +++++++ zig/src/families/qwen3_asr/qwen3_asr.zig | 2 + zig/tests/qwen3_asr_forced.zig | 201 +++++++++++++++++++++++ 5 files changed, 288 insertions(+), 4 deletions(-) create mode 100644 zig/src/families/qwen3_asr/forced.zig create mode 100644 zig/tests/qwen3_asr_forced.zig diff --git a/tools/zig/qwen3_asr_case.py b/tools/zig/qwen3_asr_case.py index 582c5c3078b..e7d1ea2a752 100644 --- a/tools/zig/qwen3_asr_case.py +++ b/tools/zig/qwen3_asr_case.py @@ -12,7 +12,8 @@ def save(out, manifest, name, t, kind="f32"): - if manifest.get("ids_only") and name not in ("prompt_ids", "greedy_ids", "greedy_top2", "greedy_margin"): + kept = ("prompt_ids", "greedy_ids", "greedy_top2", "greedy_margin", "logits_bf16", "logits_fp32") + if manifest.get("ids_only") and name not in kept: return a = t.detach().to(torch.float32 if kind == "f32" else torch.int32).cpu().numpy() a.astype(" widen(logits[a])) { + b = a; + a = @intCast(i); + } else if (b == null or v > widen(logits[b.?])) b = @intCast(i); + } + const second = b orelse a; + const m = widen(logits[a]) - widen(logits[second]); + return .{ .first = a, .second = second, .margin = if (nan) std.math.nan(f32) else m }; +} + +fn bf(x: f32) u16 { + return @intCast(@as(u32, @bitCast(x)) >> 16); +} + +test "top: the two best, the first of equals, the lead" { + const t = top(&.{ bf(1), bf(3), bf(2.5), bf(3) }); + try std.testing.expectEqual(Top{ .first = 1, .second = 3, .margin = 0 }, t); + try std.testing.expectEqual(Top{ .first = 0, .second = 2, .margin = 0.5 }, top(&.{ bf(4), bf(1), bf(3.5) })); + try std.testing.expect(std.math.isNan(top(&.{ bf(1), 0x7fc0 }).margin)); +} + +test "judge: a swap within 0.25 on both sides passes; a wider margin, a third token or a NaN fails" { + const ref: Top = .{ .first = 10, .second = 20, .margin = 0.125 }; + try std.testing.expectEqual(Step.same, judge(.{ .first = 10, .second = 30, .margin = 3 }, ref, bar)); + try std.testing.expectEqual(Step.swap, judge(.{ .first = 20, .second = 10, .margin = 0.25 }, ref, bar)); + try std.testing.expectEqual(Step.fail, judge(.{ .first = 20, .second = 10, .margin = 0.375 }, ref, bar)); + try std.testing.expectEqual(Step.fail, judge(.{ .first = 20, .second = 10, .margin = 0 }, .{ .first = 10, .second = 20, .margin = 0.5 }, bar)); + try std.testing.expectEqual(Step.fail, judge(.{ .first = 20, .second = 30, .margin = 0 }, ref, bar)); + try std.testing.expectEqual(Step.fail, judge(.{ .first = 30, .second = 10, .margin = 0 }, ref, bar)); + try std.testing.expectEqual(Step.fail, judge(.{ .first = 10, .second = 20, .margin = std.math.nan(f32) }, ref, bar)); +} diff --git a/zig/src/families/qwen3_asr/qwen3_asr.zig b/zig/src/families/qwen3_asr/qwen3_asr.zig index 1e0a756750b..d3225accb0a 100644 --- a/zig/src/families/qwen3_asr/qwen3_asr.zig +++ b/zig/src/families/qwen3_asr/qwen3_asr.zig @@ -10,6 +10,7 @@ pub const case = @import("case.zig"); pub const prompt = @import("prompt.zig"); pub const tower = @import("tower.zig"); pub const lm = @import("lm.zig"); +pub const forced = @import("forced.zig"); test { _ = config; @@ -24,6 +25,7 @@ test { _ = tower; _ = lm; _ = @import("config_test.zig"); + _ = forced; _ = @import("schedule_test.zig"); _ = @import("lm_test.zig"); } diff --git a/zig/tests/qwen3_asr_forced.zig b/zig/tests/qwen3_asr_forced.zig new file mode 100644 index 00000000000..e305b0487cb --- /dev/null +++ b/zig/tests/qwen3_asr_forced.zig @@ -0,0 +1,201 @@ +//! tf-qwen3-asr-forced: a clip on CUDA teacher-forced on a case's greedy ids, every step judged by the tie rule. +const std = @import("std"); +const cuda = @import("cuda"); +const qa = @import("qwen3_asr"); +const host = qa.host; +const forced = host.forced; + +const usage = "usage: tf-qwen3-asr-forced MODEL_DIR CLIP.wav --case DIR [--plant splice] [--rows K]\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" ++ + " --rows K: the prompt pass over the first K reply ids against the decode steps, and the prompt in two passes\n" ++ + " against one (caches and logits): exit 1 unless bit-equal. --plant splice: the audio rows one position late.\n"; + +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|. +fn compareRows(a: []const u16, b: []const u16, vocab: usize) Rows { + var r: Rows = .{ .equal = 0, .rows = a.len / vocab, .worst = 0 }; + for (0..r.rows) |i| { + const x = a[i * vocab ..][0..vocab]; + const y = b[i * vocab ..][0..vocab]; + if (std.mem.eql(u16, x, y)) r.equal += 1; + for (x, y) |p, q| r.worst = @max(r.worst, @abs(widen(p) - widen(q))); + } + return r; +} + +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 = false; + var check_rows: usize = 0; + 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], "--rows")) { + check_rows = try std.fmt.parseInt(usize, args[i + 1], 10); + } else if (std.mem.eql(u8, args[i], "--plant") and std.mem.eql(u8, args[i + 1], "splice")) plant = true 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; + check_rows = @min(check_rows, want.len - 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); + 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 cuda.Driver.open(); + defer driver.close(); + var ctx = try cuda.Context.init(&driver, 0); + defer ctx.deinit(); + var s = try cuda.Stream.init(&driver, false); + defer s.deinit(); + const opts: qa.Options = .{ .audio_rows = plan.rows, .pass_rows = ids.len + check_rows, .positions = ids.len + want.len + 1 }; + const m = try qa.Model.load(gpa, io, &driver, s, args[1], cfg, opts); + defer m.deinit(); + var rows_buf = try cuda.DeviceBuffer.alloc(&driver, plan.rows * cfg.audio.out * 2); + defer rows_buf.free(); + const n_rows = try m.encode(feats, rows_buf.ptr, null); + const splice: qa.Splice = .{ .ptr = rows_buf.ptr, .at = at + @intFromBool(plant), .n = n_rows }; + const vocab = cfg.text.vocab; + + // the prompt pass, then one decode step a reference id: every step's logits row kept + var steps: std.ArrayList(u16) = .empty; + defer steps.deinit(gpa); + m.lr.keep = .{ .gpa = gpa, .rows = &steps }; + _ = try m.forward(ids, 0, splice); + for (want[0 .. want.len - 1], 0..) |id, k| _ = try m.forward(&.{id}, ids.len + k, null); + m.lr.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: forced.Top = .{ .first = top2[2 * k], .second = top2[2 * k + 1], .margin = ref_margin[k] }; + if (ref.first != want[k]) return error.CaseTopIsNotGreedy; + 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) " (planted: audio rows one position late)" 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; + + if (check_rows > 0) { + // one prompt pass over the prompt and the first K reply ids, the head over its last K + 1 rows + const long = try std.mem.concat(gpa, u32, &.{ ids, want[0..check_rows] }); + defer gpa.free(long); + var pass: std.ArrayList(u16) = .empty; + defer pass.deinit(gpa); + m.lr.keep = .{ .gpa = gpa, .rows = &pass }; + _ = try m.forwardHeads(long, 0, splice, check_rows + 1); + m.lr.keep = null; + const dec = compareRows(pass.items, steps.items[0 .. (check_rows + 1) * vocab], vocab); + std.debug.print("ROWS {s}: the prompt pass's last {d} rows against the decode steps: {d} bit-equal, worst |diff| {d:.6}\n", .{ clip, dec.rows, dec.equal, dec.worst }); + ok = ok and dec.equal == dec.rows; + // the prompt in one pass, then in two cut inside the audio rows: caches and the last row's logits + var one: std.ArrayList(u16) = .empty; + defer one.deinit(gpa); + m.lr.keep = .{ .gpa = gpa, .rows = &one }; + _ = try m.forward(ids, 0, splice); + const c1 = try m.lr.cacheRows(gpa, ids.len); + defer gpa.free(c1); + const cut = at + n_rows / 2; + _ = try m.forward(ids[0..cut], 0, splice); + _ = try m.forward(ids[cut..], cut, splice); + m.lr.keep = null; + const c2 = try m.lr.cacheRows(gpa, ids.len); + defer gpa.free(c2); + var differ: usize = 0; + for (c1, c2) |x, y| differ += @intFromBool(x != y); + const lg = compareRows(one.items[0..vocab], one.items[2 * vocab ..][0..vocab], vocab); + std.debug.print("SPLIT {s}: cut at {d} of {d} (inside the audio rows {d}..{d}): {d} of {d} cache values differ, last logits {s} (worst |diff| {d:.6})\n", .{ clip, cut, ids.len, at, at + n_rows, differ, c1.len, if (lg.equal == 1) "bit-equal" else "differ", lg.worst }); + ok = ok and differ == 0 and lg.equal == 1; + } + std.debug.print("SUMMARY qwen3-asr forced {s}: {s}\n", .{ clip, if (ok) "PASS" else "FAIL" }); + return if (ok) 0 else 1; +} From 7b361dac679ef2b8504fd7347740229af8720dc5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Tue, 10 Nov 2026 12:23:54 +0100 Subject: [PATCH 20/28] qwen3-asr: tf-qwen3-asr-forced takes an exact reference tie either way round, plants swapped q and k norms, and --row-gemms (#2105) topk may list an exact tie (margin 0) in either order; the greedy id is the reference's pick. --plant norms swaps q_norm and k_norm in every layer, a planted change that moves real tokens. --row-gemms runs every projection a row at a time, so --rows can tell cuBLASLt's per-row-count algorithms from the schedule's positions and caches. --- zig/src/families/qwen3_asr/cuda/lm.zig | 8 ++++-- zig/tests/qwen3_asr_forced.zig | 39 ++++++++++++++++++++------ 2 files changed, 36 insertions(+), 11 deletions(-) diff --git a/zig/src/families/qwen3_asr/cuda/lm.zig b/zig/src/families/qwen3_asr/cuda/lm.zig index 3b5f265f029..e11bfc2a59d 100644 --- a/zig/src/families/qwen3_asr/cuda/lm.zig +++ b/zig/src/families/qwen3_asr/cuda/lm.zig @@ -41,6 +41,8 @@ pub const Lm = struct { logits: []u16, last_margin: f32 = 0, // the last pick's lead over the runner-up keep: ?Keep = null, // each head row's logits, appended + row_gemms: bool = false, // every projection a row at a time: one cuBLASLt algorithm at any pass size + plant_norms: bool = false, // a planted fault for tf-qwen3-asr-forced: q_norm and k_norm swapped sink: ?@import("tower.zig").Dump = null, /// Where the head's logits go, a row of vocab bf16 values at a time. @@ -152,7 +154,8 @@ pub const Lm = struct { } pub fn gemm(lm: *Lm, x: u64, w: u64, y: u64, rows: usize, n: usize, k: usize) !void { - try lm.g.run(lm.s, x, w, y, rows, n, k, .bf16); + if (!lm.row_gemms) return lm.g.run(lm.s, x, w, y, rows, n, k, .bf16); + for (0..rows) |r| try lm.g.run(lm.s, x + r * k * 2, w, y + r * n * 2, 1, n, k, .bf16); } fn kvAt(lm: *const Lm, base: u64, layer: usize) u64 { @@ -163,7 +166,8 @@ pub const Lm = struct { 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; - const shape: cuda.qk_rows.Shape = .{ .norms = q_norm, .norm_k = k_norm, .norms_bf16 = true, .cos = b.cos, .sin = b.sin, .rot = t.head_dim, .eps = t.eps, .round = true }; + const qn, const kn = if (lm.plant_norms) .{ k_norm, q_norm } else .{ q_norm, k_norm }; + const shape: cuda.qk_rows.Shape = .{ .norms = qn, .norm_k = kn, .norms_bf16 = true, .cos = b.cos, .sin = b.sin, .rot = t.head_dim, .eps = t.eps, .round = true }; const out: cuda.qk_rows.Out = .{ .q = b.q, .k = b.k, .v = b.v, .kc = lm.kvAt(b.kc, layer), .vc = lm.kvAt(b.vc, layer), .len = lm.cap }; try lm.qk.rows(lm.s, qkv, .{ .h = t.heads, .hk = t.kv_heads, .dim = t.head_dim }, shape, b.pos, null, out, rows); } diff --git a/zig/tests/qwen3_asr_forced.zig b/zig/tests/qwen3_asr_forced.zig index e305b0487cb..11179aa914a 100644 --- a/zig/tests/qwen3_asr_forced.zig +++ b/zig/tests/qwen3_asr_forced.zig @@ -5,11 +5,15 @@ const qa = @import("qwen3_asr"); const host = qa.host; const forced = host.forced; -const usage = "usage: tf-qwen3-asr-forced MODEL_DIR CLIP.wav --case DIR [--plant splice] [--rows K]\n" ++ +const usage = "usage: tf-qwen3-asr-forced MODEL_DIR CLIP.wav --case DIR [--plant splice|norms] [--rows K [--row-gemms]]\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" ++ " --rows K: the prompt pass over the first K reply ids against the decode steps, and the prompt in two passes\n" ++ - " against one (caches and logits): exit 1 unless bit-equal. --plant splice: the audio rows one position late.\n"; + " against one (caches and logits): exit 1 unless bit-equal; --row-gemms runs every projection a row at a time.\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 }; fn widen(bits: u16) f64 { return @as(f32, @bitCast(@as(u32, bits) << 16)); @@ -64,18 +68,28 @@ pub fn main(init: std.process.Init) !u8 { return 2; } var case_dir: ?[]const u8 = null; - var plant = false; + var plant: ?Plant = null; var check_rows: usize = 0; + var row_gemms = false; var i: usize = 3; - while (i + 1 < args.len) : (i += 2) { + while (i < args.len) : (i += 2) { + if (i + 1 >= args.len and !std.mem.eql(u8, args[i], "--row-gemms")) break; if (std.mem.eql(u8, args[i], "--case")) case_dir = args[i + 1] else if (std.mem.eql(u8, args[i], "--rows")) { check_rows = try std.fmt.parseInt(usize, args[i + 1], 10); - } else if (std.mem.eql(u8, args[i], "--plant") and std.mem.eql(u8, args[i + 1], "splice")) plant = true else { + } 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 if (std.mem.eql(u8, args[i], "--row-gemms")) { + row_gemms = true; + i -= 1; + } else { std.debug.print(usage, .{}); return 2; } } - if (i != args.len or case_dir == null) { + if (i < args.len or case_dir == null) { std.debug.print(usage, .{}); return 2; } @@ -116,7 +130,9 @@ pub fn main(init: std.process.Init) !u8 { var rows_buf = try cuda.DeviceBuffer.alloc(&driver, plan.rows * cfg.audio.out * 2); defer rows_buf.free(); const n_rows = try m.encode(feats, rows_buf.ptr, null); - const splice: qa.Splice = .{ .ptr = rows_buf.ptr, .at = at + @intFromBool(plant), .n = n_rows }; + const splice: qa.Splice = .{ .ptr = rows_buf.ptr, .at = at + @intFromBool(plant == .splice), .n = n_rows }; + m.lr.plant_norms = plant == .norms; + m.lr.row_gemms = row_gemms; const vocab = cfg.text.vocab; // the prompt pass, then one decode step a reference id: every step's logits row kept @@ -133,7 +149,9 @@ pub fn main(init: std.process.Init) !u8 { var fails: usize = 0; for (0..want.len) |k| { const ours = forced.top(steps.items[k * vocab ..][0..vocab]); - const ref: forced.Top = .{ .first = top2[2 * k], .second = top2[2 * k + 1], .margin = ref_margin[k] }; + var ref: forced.Top = .{ .first = top2[2 * k], .second = top2[2 * k + 1], .margin = ref_margin[k] }; + // an exact tie: topk may list the two either way round, the greedy id is the reference's pick + if (ref.first != want[k] and ref.second == want[k] and ref.margin == 0) std.mem.swap(u32, &ref.first, &ref.second); if (ref.first != want[k]) return error.CaseTopIsNotGreedy; switch (forced.judge(ours, ref, forced.bar)) { .same => same += 1, @@ -144,7 +162,10 @@ pub fn main(init: std.process.Init) !u8 { } } 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) " (planted: audio rows one position late)" else "" }); + 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) { + .splice => " (planted: the audio rows one position late)", + .norms => " (planted: q_norm and k_norm swapped in every layer)", + } else "" }); if (case.floats(gpa, "logits_fp32")) |fp32| { defer gpa.free(fp32); From 0f4ac8690813c1750e362d66543e64869372faa9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Tue, 10 Nov 2026 14:38:46 +0100 Subject: [PATCH 21/28] qwen3-asr: the exact-tie order of the reference's topk pair moves into forced.zig, with its test (#2105) forced.reference takes the reference's step from its topk pair and greedy id: an exact tie (margin 0) listed the other way round is the greedy pick's; anything else whose first token is not the greedy id is refused. Its test fails without the swap. --- zig/src/families/qwen3_asr/forced.zig | 17 +++++++++++++++++ zig/tests/qwen3_asr_forced.zig | 5 +---- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/zig/src/families/qwen3_asr/forced.zig b/zig/src/families/qwen3_asr/forced.zig index 5772dcff070..dc2843620c0 100644 --- a/zig/src/families/qwen3_asr/forced.zig +++ b/zig/src/families/qwen3_asr/forced.zig @@ -16,6 +16,13 @@ pub fn judge(ours: Top, ref: Top, max: f32) Step { return if (swapped and ours.margin <= max and ref.margin <= max) .swap else .fail; } +/// The reference's step from its topk pair and its greedy id: topk may list an exact tie (margin 0) either way round. +pub fn reference(first: u32, second: u32, margin: f32, greedy: u32) error{TopIsNotGreedy}!Top { + var r: Top = .{ .first = first, .second = second, .margin = margin }; + if (r.first != greedy and r.second == greedy and r.margin == 0) std.mem.swap(u32, &r.first, &r.second); + return if (r.first == greedy) r else error.TopIsNotGreedy; +} + fn widen(bits: u16) f32 { return @bitCast(@as(u32, bits) << 16); } @@ -60,3 +67,13 @@ test "judge: a swap within 0.25 on both sides passes; a wider margin, a third to try std.testing.expectEqual(Step.fail, judge(.{ .first = 30, .second = 10, .margin = 0 }, ref, bar)); try std.testing.expectEqual(Step.fail, judge(.{ .first = 10, .second = 20, .margin = std.math.nan(f32) }, ref, bar)); } + +test "reference: an exact tie listed the other way round is the greedy pick's; else the greedy id must lead" { + try std.testing.expectEqual(Top{ .first = 20, .second = 10, .margin = 0 }, try reference(10, 20, 0, 20)); + try std.testing.expectEqual(Top{ .first = 10, .second = 20, .margin = 0 }, try reference(10, 20, 0, 10)); + try std.testing.expectError(error.TopIsNotGreedy, reference(10, 20, 0.125, 20)); + try std.testing.expectError(error.TopIsNotGreedy, reference(10, 20, 0, 30)); + // as on 1.7B 1089-134686-0000 step 21: the tie decides a swap, not a fail + const ref = try reference(323, 11, 0, 11); + try std.testing.expectEqual(Step.swap, judge(.{ .first = 323, .second = 11, .margin = 0.25 }, ref, bar)); +} diff --git a/zig/tests/qwen3_asr_forced.zig b/zig/tests/qwen3_asr_forced.zig index 11179aa914a..5cfd4af8016 100644 --- a/zig/tests/qwen3_asr_forced.zig +++ b/zig/tests/qwen3_asr_forced.zig @@ -149,10 +149,7 @@ pub fn main(init: std.process.Init) !u8 { var fails: usize = 0; for (0..want.len) |k| { const ours = forced.top(steps.items[k * vocab ..][0..vocab]); - var ref: forced.Top = .{ .first = top2[2 * k], .second = top2[2 * k + 1], .margin = ref_margin[k] }; - // an exact tie: topk may list the two either way round, the greedy id is the reference's pick - if (ref.first != want[k] and ref.second == want[k] and ref.margin == 0) std.mem.swap(u32, &ref.first, &ref.second); - if (ref.first != want[k]) return error.CaseTopIsNotGreedy; + 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| { From aad03f1932d630e960106ba2d5db8b2af2a2a42d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Thu, 12 Nov 2026 03:18:32 +0100 Subject: [PATCH 22/28] qwen3-asr: the language model runs qwen3's CUDA pass (#2285) with a start position, an audio splice and a tied head over chosen rows (#2105) qwen3/cuda/lm.zig's forwardFrom takes an Extra: the input's first position, every layer's own k and v caches, rows spliced over the embedded ones, the final norm and the tied head over the pass's last rows, and stage taps. Each is read only when set: forward(.{}) issues the embeddings' launches with the same arguments. qwen3_asr/cuda/lm.zig (the schedule's CUDA binding) goes; the ASR checkpoint loads through weights.Model.fromCheckpoint under its thinker.model. scope, and the position and RoPE uploads are lm.tables, shared with the engine. tf-qwen3-asr-forced drops --row-gemms: every projection keeps one algorithm per (n, k). --- zig/build/qwen3_asr_cuda.zig | 4 +- zig/src/families/qwen3/cuda/engine.zig | 37 +-- zig/src/families/qwen3/cuda/lm.zig | 141 ++++++++++- zig/src/families/qwen3/cuda/weights.zig | 13 +- zig/src/families/qwen3/pass_cuda.zig | 4 + zig/src/families/qwen3_asr/cuda/lm.zig | 226 ------------------ zig/src/families/qwen3_asr/cuda/model.zig | 146 ++++++++--- zig/src/families/qwen3_asr/qwen3_asr_cuda.zig | 2 +- zig/tests/qwen3_asr_cuda.zig | 4 +- zig/tests/qwen3_asr_forced.zig | 31 +-- 10 files changed, 282 insertions(+), 326 deletions(-) create mode 100644 zig/src/families/qwen3/pass_cuda.zig delete mode 100644 zig/src/families/qwen3_asr/cuda/lm.zig diff --git a/zig/build/qwen3_asr_cuda.zig b/zig/build/qwen3_asr_cuda.zig index 28c84ae31c7..0c8a33f258c 100644 --- a/zig/build/qwen3_asr_cuda.zig +++ b/zig/build/qwen3_asr_cuda.zig @@ -2,7 +2,9 @@ const std = @import("std"); pub fn tool(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cuda: *std.Build.Module, core: *std.Build.Module, tokenizer: *std.Build.Module, strip: ?bool) void { - const family = b.createModule(.{ .root_source_file = b.path("zig/src/families/qwen3_asr/qwen3_asr_cuda.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core } } }); + // the Qwen3 layers: qwen3's CUDA pass, the one the embedding engine runs + const pass = b.createModule(.{ .root_source_file = b.path("zig/src/families/qwen3/pass_cuda.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core } } }); + const family = b.createModule(.{ .root_source_file = b.path("zig/src/families/qwen3_asr/qwen3_asr_cuda.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "core", .module = core }, .{ .name = "qwen3_pass", .module = pass } } }); const main = b.createModule(.{ .root_source_file = b.path("zig/tests/qwen3_asr_cuda.zig"), .target = target, .optimize = optimize, .link_libc = true, .strip = strip, .imports = &.{ .{ .name = "cuda", .module = cuda }, .{ .name = "qwen3_asr", .module = family }, .{ .name = "tokenizer", .module = tokenizer } } }); const exe = b.addExecutable(.{ .name = "tf-qwen3-asr", .root_module = main }); b.installArtifact(exe); diff --git a/zig/src/families/qwen3/cuda/engine.zig b/zig/src/families/qwen3/cuda/engine.zig index 1744331b5d6..1a67c75cd5c 100644 --- a/zig/src/families/qwen3/cuda/engine.zig +++ b/zig/src/families/qwen3/cuda/engine.zig @@ -109,8 +109,7 @@ pub const Engine = struct { errdefer e.scratch.free(); const cap = std.mem.alignForward(usize, window, lm.chunk_keys); e.a = sc.at(e.scratch.ptr); - try e.positions(cap); - try e.rope(cap); + try lm.tables(e.gpa, &e.d, e.a, e.m.spec, cap); e.ids_host = try cuda.HostBuffer.alloc(&e.d, 4 * window); errdefer e.ids_host.free(); e.rows_host = try cuda.HostBuffer.alloc(&e.d, 2 * max_inputs * e.m.spec.hidden); @@ -158,40 +157,6 @@ pub const Engine = struct { e.d.close(); e.gpa.destroy(e); } - - /// Positions 0 to cap - 1: each row's rotation angle, and the first position a row block's chunks read. - fn positions(e: *Engine, cap: usize) !void { - const pos = try e.gpa.alloc(i32, cap); - defer e.gpa.free(pos); - for (pos, 0..) |*x, i| x.* = @intCast(i); - try store.view(&e.d, e.a.pos, cap * 4).upload(0, std.mem.sliceAsBytes(pos)); - } - - /// The RoPE table [cap, head_dim] of fp32 cosines and sines, each half of a head rotating by the same angle. - fn rope(e: *Engine, cap: usize) !void { - const hd = e.m.spec.head_dim; - const theta: f64 = e.m.spec.theta; - const cs = try e.gpa.alloc(f32, cap * hd); - defer e.gpa.free(cs); - const sn = try e.gpa.alloc(f32, cap * hd); - defer e.gpa.free(sn); - var i: usize = 0; - while (i < hd / 2) : (i += 1) { - const inv = 1.0 / std.math.pow(f64, theta, @as(f64, @floatFromInt(2 * i)) / @as(f64, @floatFromInt(hd))); - var p: usize = 0; - while (p < cap) : (p += 1) { - const angle = @as(f64, @floatFromInt(p)) * inv; - const c: f32 = @floatCast(@cos(angle)); - const s: f32 = @floatCast(@sin(angle)); - for ([_]usize{ i, i + hd / 2 }) |col| { - cs[p * hd + col] = c; - sn[p * hd + col] = s; - } - } - } - try store.view(&e.d, e.a.cos, cs.len * 4).upload(0, std.mem.sliceAsBytes(cs)); - try store.view(&e.d, e.a.sin, sn.len * 4).upload(0, std.mem.sliceAsBytes(sn)); - } }; test "the scratch the count reports is the block size, and its sections never share a unit" { diff --git a/zig/src/families/qwen3/cuda/lm.zig b/zig/src/families/qwen3/cuda/lm.zig index 6dfb43b56d9..cae12339dd7 100644 --- a/zig/src/families/qwen3/cuda/lm.zig +++ b/zig/src/families/qwen3/cuda/lm.zig @@ -7,6 +7,7 @@ const store = @import("store.zig"); const weights = @import("weights.zig"); const Driver = cuda.Driver; +const Allocator = std.mem.Allocator; /// nemotron_attention.cu's chunk: keys a partial covers, and the most chunk blocks a row launches. pub const chunk_keys = 512; @@ -122,6 +123,46 @@ pub const Addrs = struct { rows: u64 = 0, }; +/// The position table and the RoPE table for `cap` positions, uploaded into the block at `a`. +pub fn tables(gpa: Allocator, d: *const Driver, a: Addrs, spec: config.Spec, cap: usize) !void { + try positions(gpa, d, a, cap); + try rope(gpa, d, a, spec, cap); +} + +/// Positions 0 to cap - 1: each row's rotation angle, and the first position a row block's chunks read. +fn positions(gpa: Allocator, d: *const Driver, a: Addrs, cap: usize) !void { + const pos = try gpa.alloc(i32, cap); + defer gpa.free(pos); + for (pos, 0..) |*x, i| x.* = @intCast(i); + try store.view(d, a.pos, cap * 4).upload(0, std.mem.sliceAsBytes(pos)); +} + +/// The RoPE table [cap, head_dim] of fp32 cosines and sines, each half of a head rotating by the same angle. +fn rope(gpa: Allocator, d: *const Driver, a: Addrs, spec: config.Spec, cap: usize) !void { + const hd = spec.head_dim; + const theta: f64 = spec.theta; + const cs = try gpa.alloc(f32, cap * hd); + defer gpa.free(cs); + const sn = try gpa.alloc(f32, cap * hd); + defer gpa.free(sn); + var i: usize = 0; + while (i < hd / 2) : (i += 1) { + const inv = 1.0 / std.math.pow(f64, theta, @as(f64, @floatFromInt(2 * i)) / @as(f64, @floatFromInt(hd))); + var p: usize = 0; + while (p < cap) : (p += 1) { + const angle = @as(f64, @floatFromInt(p)) * inv; + const c: f32 = @floatCast(@cos(angle)); + const s: f32 = @floatCast(@sin(angle)); + for ([_]usize{ i, i + hd / 2 }) |col| { + cs[p * hd + col] = c; + sn[p * hd + col] = s; + } + } + } + try store.view(d, a.cos, cs.len * 4).upload(0, std.mem.sliceAsBytes(cs)); + try store.view(d, a.sin, sn.len * 4).upload(0, std.mem.sliceAsBytes(sn)); +} + /// `n` bytes at the block's cursor, a section unit in. fn cut(cursor: *usize, n: usize) usize { cursor.* = store.up(cursor.*); @@ -129,6 +170,42 @@ fn cut(cursor: *usize, n: usize) usize { return cursor.*; } +/// Rows from elsewhere over the embedded ones: `n` rows of hidden at `ptr`, standing at positions [at, at + n). +pub const Splice = struct { + ptr: u64, + at: usize, + n: usize, + + /// The rows standing in a pass over positions [pos, pos + rows): row `src` on, `len` of them, from pass row `dst`. + pub fn within(sp: Splice, pos: usize, rows: usize) ?struct { src: usize, dst: usize, len: usize } { + const lo = @max(sp.at, pos); + const hi = @min(sp.at + sp.n, pos + rows); + return if (lo < hi) .{ .src = lo - sp.at, .dst = lo - pos, .len = hi - lo } else null; + } +}; + +/// Every layer's k and v caches of `cap` positions, in place of the scratch's one: layer i's at kc + i * stride. +pub const Cache = struct { kc: u64, vc: u64, stride: usize }; + +/// The final norm over the pass's last `rows` rows, then the tied head's logits [rows, vocab] into `logits`. +pub const Head = struct { rows: usize, logits: u64 }; + +/// A stage's rows (lm_embed, lm0_norm, lm0_attn, lm0_o, lm0_post, lm0_mlp, lm_layer{i}, lm_norm), after its launch. +pub const Tap = struct { + ctx: *anyopaque, + put: *const fn (ctx: *anyopaque, stage: []const u8, ptr: u64, rows: usize, cols: usize) anyerror!void, +}; + +/// What a resumed or spliced pass adds; each field is read only when set, so `.{}` is forward's call. +pub const Extra = struct { + /// The `at` the input's rows stand from: the pass continues a `cache` holding [0, start), one input, no trunk. + start: usize = 0, + cache: ?Cache = null, + splice: ?Splice = null, + head: ?Head = null, + tap: ?Tap = null, +}; + /// Which of the CUDA kernels' geometry limits a spec breaks: the attention's heads, the row kernels' widths, or none. pub const Geometry = enum { ok, heads, widths }; @@ -231,9 +308,24 @@ pub const Lm = struct { /// Every input's final-normed last row into `rows`: after a shared `trunk` of rows, inputs end at `ends`. pub fn forward(lm: *Lm, m: *const weights.Model, a: Addrs, cap: usize, trunk: usize, ends: []const u32) !void { + return lm.forwardFrom(m, a, cap, trunk, ends, .{}); + } + + /// forward with `x`'s start, caches, splice, head and taps; refused before any launch when they do not fit. + pub fn forwardFrom(lm: *Lm, m: *const weights.Model, a: Addrs, cap: usize, trunk: usize, ends: []const u32, x: Extra) !void { const s = m.spec; - try lm.emb.bf16(lm.s, a.ids, m.embed, a.x, ends[ends.len - 1], s.hidden); - for (m.layers, 0..) |*l, i| try layerRows(lm, m, l, a, cap, trunk, ends, ends[ends.len - 1], i == 0); + const total = ends[ends.len - 1]; + if ((x.start > 0 or x.head != null) and (ends.len != 1 or x.cache == null or trunk > 0)) return error.InvalidBatch; + if (x.start + total > cap) return error.ContextFull; + if (x.head) |h| if (h.rows == 0 or h.rows > total) return error.InvalidBatch; + try lm.emb.bf16(lm.s, a.ids, m.embed, a.x, total, s.hidden); + if (x.splice) |sp| if (sp.within(x.start, total)) |in| { + const row = s.hidden * 2; + try store.view(lm.d, a.x + in.dst * row, in.len * row).copyFrom(0, sp.ptr + in.src * row, in.len * row, lm.s.handle); + }; + if (x.tap) |t| try t.put(t.ctx, "lm_embed", a.x, total, s.hidden); + for (m.layers, 0..) |*l, i| try layerRows(lm, m, l, a, cap, trunk, ends, total, i, x); + if (x.head) |h| return lm.head(m, a, total, h, x.tap); for (ends, 0..) |e, i| { // the last layer's residual add and the final norm, for the one row an input pools const row = (e - 1) * s.hidden * 2; @@ -241,10 +333,24 @@ pub const Lm = struct { } } + /// The final norm over the head's rows (every row when tapped), then their logits by the tied embedding table. + fn head(lm: *Lm, m: *const weights.Model, a: Addrs, total: usize, h: Head, tap: ?Tap) !void { + const s = m.spec; + const rows = if (tap == null) h.rows else total; + const at = (total - rows) * s.hidden * 2; + try lm.nm.addRmsH(lm.s, a.z + at, a.x + at, m.final_norm, .f32, a.x + at, a.normed + at, null, rows, s.hidden, @floatCast(s.eps)); + if (tap) |t| { + var name: [24]u8 = undefined; + try t.put(t.ctx, try std.fmt.bufPrint(&name, "lm_layer{d}", .{m.layers.len - 1}), a.x, total, s.hidden); + try t.put(t.ctx, "lm_norm", a.normed, total, s.hidden); + } + try lm.g.run(lm.s, a.normed + (total - h.rows) * s.hidden * 2, m.embed, h.logits, h.rows, s.vocab, s.hidden); + } + /// The chunk partials of a row block's `q`, over every chunk below its last key. - fn chunks(lm: *Lm, s: config.Spec, q: u64, a: Addrs, pos: u64, rows: usize, nch: usize, scale: f32) !void { + fn chunks(lm: *Lm, s: config.Spec, q: u64, kc: u64, vc: u64, a: Addrs, pos: u64, rows: usize, nch: usize, scale: f32) !void { var args: cuda.Args = .{}; - for ([_]u64{ q, a.kc, a.vc, pos, a.po, a.pm, a.pl }) |x| args.add(x); + for ([_]u64{ q, kc, vc, pos, a.po, a.pm, a.pl }) |x| args.add(x); for ([_]usize{ s.heads * s.head_dim, s.heads, s.kv_heads, s.heads / s.kv_heads, chunk_keys, nch }) |x| args.add(@as(c_int, @intCast(x))); args.add(scale); args.add(@as(u64, 0)); @@ -262,35 +368,46 @@ pub const Lm = struct { } }; -/// One decoder layer over every row; `first` is layer 0, whose residual is the embedding rows themselves. -fn layerRows(lm: *Lm, m: *const weights.Model, l: *const weights.Layer, a: Addrs, cap: usize, trunk: usize, ends: []const u32, total: usize, first: bool) !void { +/// Decoder layer `li` over every row; layer 0's residual is the embedding rows themselves. +fn layerRows(lm: *Lm, m: *const weights.Model, l: *const weights.Layer, a: Addrs, cap: usize, trunk: usize, ends: []const u32, total: usize, li: usize, x: Extra) !void { const s = m.spec; const qw = s.heads * s.head_dim; const kvw = s.kv_heads * s.head_dim; const eps: f32 = @floatCast(s.eps); + const first = li == 0; try lm.nm.addRmsH(lm.s, a.x, if (first) null else a.z, l.input_norm, .f32, a.x, a.normed, null, total, s.hidden, eps); + const tap0 = if (first) x.tap else null; // layer 0's steps, as a case taps them + if (x.tap) |t| if (!first) { + var name: [24]u8 = undefined; + try t.put(t.ctx, try std.fmt.bufPrint(&name, "lm_layer{d}", .{li - 1}), a.x, total, s.hidden); + }; + if (tap0) |t| try t.put(t.ctx, "lm0_norm", a.normed, total, s.hidden); // the projected q goes to a.q, and the attention's rotated rows to a.attn, which the o_proj then reads try lm.g.run(lm.s, a.normed, l.q, a.q, total, qw, s.hidden); try lm.g.run(lm.s, a.normed, l.k, a.k, total, kvw, s.hidden); try lm.g.run(lm.s, a.normed, l.v, a.v, total, kvw, s.hidden); // the trunk's keys stay in the cache's first rows; each input after it attends to them and its own, from there - if (trunk > 0) try attention(lm, m, l, a, cap, 0, trunk, 0); + if (trunk > 0) try attention(lm, m, l, a, cap, 0, trunk, x.start, li, x); var begin: usize = trunk; for (ends) |e| { defer begin = e; - try attention(lm, m, l, a, cap, begin, e, trunk); + try attention(lm, m, l, a, cap, begin, e, x.start + trunk, li, x); } + if (tap0) |t| try t.put(t.ctx, "lm0_attn", a.attn, total, qw); try lm.g.run(lm.s, a.attn, l.o, a.z, total, s.hidden, qw); + if (tap0) |t| try t.put(t.ctx, "lm0_o", a.z, total, s.hidden); try lm.nm.addRmsH(lm.s, a.z, a.x, l.post_norm, .f32, a.x, a.normed, null, total, s.hidden, eps); + if (tap0) |t| try t.put(t.ctx, "lm0_post", a.normed, total, s.hidden); try lm.g.run(lm.s, a.normed, l.gate, a.gate, total, s.inter, s.hidden); try lm.g.run(lm.s, a.normed, l.up, a.up, total, s.inter, s.hidden); // in place into gate: each thread reads its 8 values of gate and up before it writes them try lm.act.swiglu(lm.s, a.gate, s.inter, a.up, s.inter, a.gate, null, total, s.inter); try lm.g.run(lm.s, a.gate, l.down, a.z, total, s.hidden, s.inter); + if (tap0) |t| try t.put(t.ctx, "lm0_mlp", a.z, total, s.hidden); } /// Rows [begin, end) standing at positions from `at`: QK norm, RoPE and the cache write, then causal attention. -fn attention(lm: *Lm, m: *const weights.Model, l: *const weights.Layer, a: Addrs, cap: usize, begin: usize, end: usize, at: usize) !void { +fn attention(lm: *Lm, m: *const weights.Model, l: *const weights.Layer, a: Addrs, cap: usize, begin: usize, end: usize, at: usize, li: usize, x: Extra) !void { const s = m.spec; const hd = s.head_dim; const qw = s.heads * hd; @@ -300,6 +417,8 @@ fn attention(lm: *Lm, m: *const weights.Model, l: *const weights.Layer, a: Addrs const heads: cuda.qk_rows.Heads = .{ .h = s.heads, .hk = s.kv_heads, .dim = hd }; const shape: cuda.qk_rows.Shape = .{ .norms = l.q_norm, .norm_k = l.k_norm, .cos = a.cos, .sin = a.sin, .rot = hd, .eps = @floatCast(s.eps) }; const len = end - begin; + // layer li's own caches when the pass keeps them, else the scratch's one, rewritten by every layer + const kc, const vc = if (x.cache) |c| .{ c.kc + li * c.stride, c.vc + li * c.stride } else .{ a.kc, a.vc }; var p: usize = 0; while (p < len) : (p += attn_rows) { const rows = @min(attn_rows, len - p); @@ -309,11 +428,11 @@ fn attention(lm: *Lm, m: *const weights.Model, l: *const weights.Layer, a: Addrs const kld: i64 = @intCast(kvw); const hd64: i64 = @intCast(hd); const src: cuda.qk_rows.Src = .{ .q = a.q + (begin + p) * qw * 2, .q_ld = ld, .q_hs = hd64, .k = a.k + k, .k_ld = kld, .k_hs = hd64, .v = a.v + k, .v_ld = kld, .v_hs = hd64 }; - const dst: cuda.qk_rows.Out = .{ .q = out, .k = a.kb, .v = a.kb + attn_rows * kvw * 2, .kc = a.kc, .vc = a.vc, .len = cap }; + const dst: cuda.qk_rows.Out = .{ .q = out, .k = a.kb, .v = a.kb + attn_rows * kvw * 2, .kc = kc, .vc = vc, .len = cap }; // a block's first row stands at position at + p: the position table is the meta the chunks read, shifted too const pos = a.pos + 4 * (at + p); try lm.qk.rowsFrom(lm.s, src, heads, shape, pos, null, dst, rows); - try lm.chunks(s, dst.q, a, pos, rows, nch, scale); + try lm.chunks(s, dst.q, kc, vc, a, pos, rows, nch, scale); try lm.merge(s, out, a, pos, rows, nch); } } diff --git a/zig/src/families/qwen3/cuda/weights.zig b/zig/src/families/qwen3/cuda/weights.zig index 5793445d250..e3119b82399 100644 --- a/zig/src/families/qwen3/cuda/weights.zig +++ b/zig/src/families/qwen3/cuda/weights.zig @@ -41,12 +41,17 @@ pub const Model = struct { var ck = try Checkpoint.openModel(gpa, io, dir); defer ck.close(); ck.scope = names.scopeOf(&ck); - var m: Model = .{ .gpa = gpa, .spec = spec, .head = names.headKey(spec.tied, ck.scope), .embed = 0, .final_norm = 0, .layers = &.{}, .st = .{ .gpa = gpa, .d = d } }; + return fromCheckpoint(gpa, d, &ck, spec, names.headKey(spec.tied, ck.scope)); + } + + /// `spec`'s tensors from an open checkpoint under its scope (a model whose Qwen3 sits beside other parts). + pub fn fromCheckpoint(gpa: Allocator, d: *const cuda.Driver, ck: *Checkpoint, spec: config.Spec, head: []const u8) !Model { + var m: Model = .{ .gpa = gpa, .spec = spec, .head = head, .embed = 0, .final_norm = 0, .layers = &.{}, .st = .{ .gpa = gpa, .d = d } }; errdefer m.deinit(); - m.embed = try projection(&ck, &m.st, "embed_tokens.weight", spec.vocab, spec.hidden); - m.final_norm = try norm(&ck, &m.st, "norm.weight", spec.hidden); + m.embed = try projection(ck, &m.st, "embed_tokens.weight", spec.vocab, spec.hidden); + m.final_norm = try norm(ck, &m.st, "norm.weight", spec.hidden); m.layers = try gpa.alloc(Layer, spec.layers); - for (m.layers, 0..) |*l, i| l.* = try layer(&ck, &m.st, spec, i); + for (m.layers, 0..) |*l, i| l.* = try layer(ck, &m.st, spec, i); return m; } diff --git a/zig/src/families/qwen3/pass_cuda.zig b/zig/src/families/qwen3/pass_cuda.zig new file mode 100644 index 00000000000..66501189b84 --- /dev/null +++ b/zig/src/families/qwen3/pass_cuda.zig @@ -0,0 +1,4 @@ +//! The Qwen3 dense pass on CUDA alone, for a family that runs Qwen3 layers inside a larger model (Qwen3-ASR). +pub const config = @import("config.zig"); +pub const lm = @import("cuda/lm.zig"); +pub const weights = @import("cuda/weights.zig"); diff --git a/zig/src/families/qwen3_asr/cuda/lm.zig b/zig/src/families/qwen3_asr/cuda/lm.zig deleted file mode 100644 index e11bfc2a59d..00000000000 --- a/zig/src/families/qwen3_asr/cuda/lm.zig +++ /dev/null @@ -1,226 +0,0 @@ -//! The Qwen3 language model's binding on CUDA's shared rows: RMS norms, QK norm with RoPE, Nemotron's GQA attention. -const std = @import("std"); -const cuda = @import("cuda"); -const cfg = @import("../config.zig"); -const shared = @import("../lm.zig"); -const store = @import("store.zig"); - -/// nemotron_attention.cu's chunk: keys a partial covers, and the most chunk blocks a row launches. -const chunk_keys = 512; -const chunk_blocks = 64; - -const Attn = struct { - mod: cuda.Module, - chunk: cuda.Function, - chunk_pf: cuda.Function, - merge: cuda.Function, - - fn load(d: *const cuda.Driver) !Attn { - if (!cuda.kernels.available) return error.BuiltWithoutKernels; - var mod = try cuda.Module.load(d, cuda.kernels.nemotron_attention); - errdefer mod.unload(); - const f = .{ try mod.function("tf_nemo_attn_chunk"), try mod.function("tf_nemo_attn_chunk_pf"), try mod.function("tf_nemo_attn_merge") }; - return .{ .mod = mod, .chunk = f[0], .chunk_pf = f[1], .merge = f[2] }; - } -}; - -pub const Lm = struct { - t: cfg.Text, - d: *const cuda.Driver, - s: cuda.Stream, - g: cuda.vit.Gemms, - nm: cuda.norms.Norms, - qk: cuda.qk_rows.QkRows, - act: cuda.act_rows.ActRows, - emb: cuda.embed_rows.EmbedRows, - attn: Attn, - cap: usize, // positions the caches hold - b: Buffers, - host_ids: []i32, - host_pos: []i32, - logits: []u16, - last_margin: f32 = 0, // the last pick's lead over the runner-up - keep: ?Keep = null, // each head row's logits, appended - row_gemms: bool = false, // every projection a row at a time: one cuBLASLt algorithm at any pass size - plant_norms: bool = false, // a planted fault for tf-qwen3-asr-forced: q_norm and k_norm swapped - sink: ?@import("tower.zig").Dump = null, - - /// Where the head's logits go, a row of vocab bf16 values at a time. - pub const Keep = struct { gpa: std.mem.Allocator, rows: *std.ArrayList(u16) }; - - const Buffers = struct { ids: u64, pos: u64, meta: u64, q: u64, k: u64, v: u64, po: u64, pm: u64, pl: u64, xs: u64, logits: u64, cos: u64, sin: u64, kc: u64, vc: u64 }; - - /// Passes of up to `max_rows` rows over up to `span` positions. - pub fn init(gpa: std.mem.Allocator, d: *const cuda.Driver, s: cuda.Stream, t: cfg.Text, max_rows: usize, span: usize, st: *store.Store) !Lm { - if (t.head_dim != 128 or t.heads % t.kv_heads != 0 or t.heads / t.kv_heads > 16) return error.UnsupportedQwen3AsrGeometry; - const cap = std.mem.alignForward(usize, span, chunk_keys); - if (cap > t.context) return error.ContextTooLong; - var lm: Lm = undefined; - lm.t = t; - lm.d = d; - lm.s = s; - lm.cap = cap; - lm.g = try cuda.vit.Gemms.init(gpa, d); - errdefer lm.g.deinit(); - lm.nm = try cuda.norms.Norms.load(d); - errdefer lm.nm.unload(); - lm.qk = try cuda.qk_rows.QkRows.load(d); - errdefer lm.qk.unload(); - lm.act = try cuda.act_rows.ActRows.load(d); - errdefer lm.act.unload(); - lm.emb = try cuda.embed_rows.EmbedRows.load(d); - errdefer lm.emb.unload(); - lm.attn = try Attn.load(d); - errdefer lm.attn.mod.unload(); - const r = max_rows; - const qd = t.heads * t.head_dim; - const kvd = t.kv_heads * t.head_dim; - const nch = cap / chunk_keys; - const kv = t.layers * cap * kvd * 2; - lm.b = .{ - .ids = try st.alloc(4 * r), - .pos = try st.alloc(4 * r), - .meta = try st.alloc(4), - .q = try st.alloc(2 * r * qd), - .k = try st.alloc(2 * r * kvd), - .v = try st.alloc(2 * r * kvd), - .po = try st.alloc(4 * r * nch * qd), - .pm = try st.alloc(4 * r * nch * t.heads), - .pl = try st.alloc(4 * r * nch * t.heads), - .xs = try st.alloc(4 * r * qd / 64), - .logits = try st.alloc(2 * t.vocab), - .cos = try st.alloc(4 * cap * t.head_dim), - .sin = try st.alloc(4 * cap * t.head_dim), - .kc = try st.alloc(kv), - .vc = try st.alloc(kv), - }; - const cs = try gpa.alloc(f32, cap * t.head_dim); - defer gpa.free(cs); - const sn = try gpa.alloc(f32, cap * t.head_dim); - defer gpa.free(sn); - shared.ropeTables(t, cs, sn, cap); - try store.view(d, lm.b.cos, cs.len * 4).upload(0, std.mem.sliceAsBytes(cs)); - try store.view(d, lm.b.sin, sn.len * 4).upload(0, std.mem.sliceAsBytes(sn)); - lm.host_ids = try gpa.alloc(i32, r); - errdefer gpa.free(lm.host_ids); - lm.host_pos = try gpa.alloc(i32, r); - errdefer gpa.free(lm.host_pos); - 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.host_pos); - gpa.free(lm.host_ids); - lm.attn.mod.unload(); - lm.emb.unload(); - lm.act.unload(); - lm.qk.unload(); - lm.nm.unload(); - lm.g.deinit(); - } - - /// The pass's ids and positions [pos, pos + ids.len) on the device; the first position is the attention's. - pub fn positions(lm: *Lm, ids: []const u32, pos: usize) !void { - const rows = ids.len; - if (rows > lm.host_ids.len) return error.PassRows; - if (pos + rows > lm.cap) return error.ContextFull; - for (ids, lm.host_ids[0..rows], lm.host_pos[0..rows], 0..) |id, *x, *p, i| { - x.* = @intCast(id); - p.* = @intCast(pos + i); - } - try lm.s.synchronize(); // the last pass may still read them - try store.view(lm.d, lm.b.ids, 4 * rows).upload(0, std.mem.sliceAsBytes(lm.host_ids[0..rows])); - try store.view(lm.d, lm.b.pos, 4 * rows).upload(0, std.mem.sliceAsBytes(lm.host_pos[0..rows])); - try store.view(lm.d, lm.b.meta, 4).upload(0, std.mem.asBytes(&lm.host_pos[0])); - } - - 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); - } - - pub fn embed(lm: *Lm, table: u64, out: u64, rows: usize, hidden: usize) !void { - try lm.emb.bf16(lm.s, lm.b.ids, table, out, rows, hidden); - } - - pub fn copy(lm: *Lm, dst: u64, src: u64, n: usize) !void { - try store.view(lm.d, dst, n).copyFrom(0, src, n, lm.s.handle); - } - - /// h = bf16(x + res) (x when res is null), 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 { - try lm.nm.addRmsTail(lm.s, x, res, w, h, y, null, rows, lm.t.hidden, lm.t.eps, .{ .round = true }); - } - - pub fn gemm(lm: *Lm, x: u64, w: u64, y: u64, rows: usize, n: usize, k: usize) !void { - if (!lm.row_gemms) return lm.g.run(lm.s, x, w, y, rows, n, k, .bf16); - for (0..rows) |r| try lm.g.run(lm.s, x + r * k * 2, w, y + r * n * 2, 1, n, k, .bf16); - } - - 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; - const qn, const kn = if (lm.plant_norms) .{ k_norm, q_norm } else .{ q_norm, k_norm }; - const shape: cuda.qk_rows.Shape = .{ .norms = qn, .norm_k = kn, .norms_bf16 = true, .cos = b.cos, .sin = b.sin, .rot = t.head_dim, .eps = t.eps, .round = true }; - const out: cuda.qk_rows.Out = .{ .q = b.q, .k = b.k, .v = b.v, .kc = lm.kvAt(b.kc, layer), .vc = lm.kvAt(b.vc, layer), .len = lm.cap }; - try lm.qk.rows(lm.s, qkv, .{ .h = t.heads, .hk = t.kv_heads, .dim = t.head_dim }, shape, b.pos, null, out, rows); - } - - /// Causal GQA attention of the pass's q rows over layer's caches into out [rows, heads x dim]. - pub fn attention(lm: *Lm, layer: usize, out: u64, rows: usize) !void { - const t = lm.t; - const b = lm.b; - const qd = t.heads * t.head_dim; - const nch = lm.cap / chunk_keys; - const grp = t.heads / t.kv_heads; - const scale: f32 = @floatCast(1.0 / @sqrt(@as(f64, @floatFromInt(t.head_dim)))); - var a: cuda.Args = .{}; - for ([_]u64{ b.q, lm.kvAt(b.kc, layer), lm.kvAt(b.vc, layer), b.meta, b.po, b.pm, b.pl }) |x| a.add(x); - for ([_]usize{ qd, t.heads, t.kv_heads, grp, chunk_keys, nch }) |x| a.add(@as(c_int, @intCast(x))); - a.add(scale); - a.add(@as(u64, 0)); - a.add(@as(i64, 0)); - const f = if (rows > 1) lm.attn.chunk_pf else lm.attn.chunk; - const grid: cuda.launch.Dim3 = .{ .x = @intCast(rows), .y = @intCast(t.kv_heads), .z = @intCast(@min(nch, chunk_blocks)) }; - try cuda.launch.launch(f, .{ .grid = grid, .block = .{ .x = 256 } }, lm.s, &a); - var m: cuda.Args = .{}; - for ([_]u64{ b.po, b.pm, b.pl, b.meta, out, b.xs }) |x| m.add(x); - for ([_]usize{ t.heads, t.kv_heads, grp, chunk_keys, nch }) |x| m.add(@as(c_int, @intCast(x))); - try cuda.launch.launch(lm.attn.merge, .{ .grid = .{ .x = @intCast(rows), .y = @intCast(t.kv_heads), .z = 1 }, .block = .{ .x = 256 } }, lm.s, &m); - } - - /// out [rows, i] = bf16(silu(gate) up) of gu's [gate | up] rows. - pub fn swiglu(lm: *Lm, gu: u64, out: u64, rows: usize, i: usize) !void { - try lm.act.swiglu(lm.s, gu, 2 * i, gu + i * 2, 2 * i, out, null, rows, 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.g.run(lm.s, row, embed_table, lm.b.logits, 1, lm.t.vocab, lm.t.hidden, .bf16); - try store.view(lm.d, lm.b.logits, lm.logits.len * 2).downloadAsync(0, std.mem.sliceAsBytes(lm.logits), lm.s.handle); - try lm.s.synchronize(); - if (lm.keep) |k| try k.rows.appendSlice(k.gpa, lm.logits); - const best = shared.argmax(lm.logits); - lm.last_margin = shared.margin(lm.logits, best); - return best; - } - - /// Positions [0, n) of every layer's k and v caches, downloaded: k rows then v rows, layer by layer. - pub fn cacheRows(lm: *Lm, gpa: std.mem.Allocator, n: usize) ![]u16 { - const row = lm.t.kv_heads * lm.t.head_dim; - const out = try gpa.alloc(u16, 2 * lm.t.layers * n * row); - errdefer gpa.free(out); - try lm.s.synchronize(); - for (0..lm.t.layers) |l| for ([_]u64{ lm.b.kc, lm.b.vc }, 0..) |base, j| { - const dst = out[(2 * l + j) * n * row ..][0 .. n * row]; - try lm.d.check(lm.d.api.cuMemcpyDtoH_v2(dst.ptr, lm.kvAt(base, l), dst.len * 2), "cuMemcpyDtoH"); - }; - return out; - } -}; diff --git a/zig/src/families/qwen3_asr/cuda/model.zig b/zig/src/families/qwen3_asr/cuda/model.zig index f2684c71e1d..b8f767978c5 100644 --- a/zig/src/families/qwen3_asr/cuda/model.zig +++ b/zig/src/families/qwen3_asr/cuda/model.zig @@ -1,70 +1,117 @@ -//! Qwen3-ASR on CUDA: the shared tower and Qwen3 schedules over this directory's bindings, one allocation store. +//! Qwen3-ASR on CUDA: the shared tower schedule over this directory's binding, the Qwen3 layers through qwen3's pass. const std = @import("std"); const cuda = @import("cuda"); const core = @import("core"); +const q3 = @import("qwen3_pass"); const cfg = @import("../config.zig"); const mel = @import("../mel.zig"); +const names = @import("../names.zig"); const tower = @import("../tower.zig"); -const lm = @import("../lm.zig"); +const shared = @import("../lm.zig"); const store = @import("store.zig"); const ctower = @import("tower.zig"); -const clm = @import("lm.zig"); pub const Dump = ctower.Dump; -pub const Splice = lm.Splice; +pub const Splice = q3.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 + head_rows: usize = 1, // the most rows a pass's head scores }; +/// The Qwen3 spec of the checkpoint's text config: tied, as the loader checks. +pub fn spec(t: cfg.Text) q3.config.Spec { + return .{ .layers = t.layers, .hidden = t.hidden, .heads = t.heads, .kv_heads = t.kv_heads, .head_dim = t.head_dim, .inter = t.intermediate, .vocab = t.vocab, .eps = t.eps, .theta = t.theta, .max_positions = t.context, .tied = true }; +} + pub const Model = struct { gpa: std.mem.Allocator, + d: *const cuda.Driver, + s: cuda.Stream, c: cfg.Config, st: store.Store, weight_bytes: u64, tw: tower.Weights, - lw: lm.Weights, tb: tower.Buffers, - lb: lm.Buffers, tr: ctower.Tower, - lr: clm.Lm, + qm: q3.weights.Model, + lm: q3.lm.Lm, + a: q3.lm.Addrs, + cap: usize, // positions the caches hold + pass_rows: usize, + head_rows: usize, + cache: q3.lm.Cache, + logits_dev: u64, + logits: []u16, + ids: []u32, + last_margin: f32 = 0, // the last pick's lead over the runner-up + keep: ?Keep = null, // each head row's logits, appended + sink: ?Dump = null, + + /// Where the head's logits go, a row of vocab bf16 values at a time. + pub const Keep = struct { gpa: std.mem.Allocator, rows: *std.ArrayList(u16) }; /// 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, d: *const cuda.Driver, s: cuda.Stream, dir: []const u8, c: cfg.Config, o: Options) !*Model { + const sp = spec(c.text); + const cap = std.mem.alignForward(usize, o.positions, q3.lm.chunk_keys); + if (cap > c.text.context) return error.ContextTooLong; + if (o.pass_rows == 0 or o.pass_rows > o.positions or o.head_rows == 0 or o.head_rows > o.pass_rows) return error.PassRows; const m = try gpa.create(Model); errdefer gpa.destroy(m); - m.gpa = gpa; - m.c = c; - m.st = .{ .gpa = gpa, .d = d }; + m.* = .{ .gpa = gpa, .d = d, .s = s, .c = c, .st = .{ .gpa = gpa, .d = d }, .weight_bytes = 0, .tw = undefined, .tb = undefined, .tr = undefined, .qm = undefined, .lm = undefined, .a = .{}, .cap = cap, .pass_rows = o.pass_rows, .head_rows = o.head_rows, .cache = undefined, .logits_dev = 0, .logits = &.{}, .ids = &.{} }; 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); + m.tw = try tower.Weights.load(gpa, c.audio, store.Source{ .ck = &ck }, &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); + ck.scope = names.lm; + // the head's rows, as stored: the embedding table, which the device head reads (tied) + m.qm = try q3.weights.Model.fromCheckpoint(gpa, d, &ck, sp, names.lm ++ "embed_tokens.weight"); + errdefer m.qm.deinit(); + ck.scope = ""; + // the tied head: the stored lm_head must be the embedding table, bit for bit + const embed = (try ck.expect(names.lm ++ "embed_tokens.weight", .bf16, &.{ sp.vocab, sp.hidden })).bytes; + if (!std.mem.eql(u8, embed, (try ck.expect(names.head, .bf16, &.{ sp.vocab, sp.hidden })).bytes)) return error.UntiedHead; if (ck.unused() != 0) return error.UnexpectedTensors; } errdefer m.tw.deinit(gpa); - errdefer m.lw.deinit(gpa); - m.weight_bytes = m.st.bytes; + errdefer m.qm.deinit(); + for (m.qm.st.list.items) |b| m.weight_bytes += b.len; + 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 ctower.Tower.init(gpa, d, s, c.audio, o.group, o.audio_rows, &m.st); errdefer m.tr.deinit(); - m.lr = try clm.Lm.init(gpa, d, s, c.text, o.pass_rows, o.positions, &m.st); + m.lm = try q3.lm.Lm.init(gpa, d, s, sp); + errdefer m.lm.deinit(); + try m.lm.prepare(sp); + try m.lm.g.prepare(&.{.{ sp.vocab, sp.hidden }}); // the tied head: one more (n, k), which embeddings never run + try m.lm.g.checkRows(1); + try m.lm.g.checkRows(o.pass_rows); + // the scratch block sized to the positions: its RoPE and position tables and the chunk partials cover the caches + const sc = q3.lm.Scratch.of(sp, cap, 1); + m.a = sc.at(try m.st.alloc(sc.total)); + try q3.lm.tables(gpa, d, m.a, sp, cap); + const stride = cap * sp.kv_heads * sp.head_dim * 2; + m.cache = .{ .kc = try m.st.alloc(sp.layers * stride), .vc = try m.st.alloc(sp.layers * stride), .stride = stride }; + m.logits_dev = try m.st.alloc(2 * o.head_rows * sp.vocab); + m.logits = try gpa.alloc(u16, o.head_rows * sp.vocab); + errdefer gpa.free(m.logits); + m.ids = try gpa.alloc(u32, o.pass_rows); return m; } pub fn deinit(m: *Model) void { - m.lr.deinit(m.gpa); + m.s.synchronize() catch {}; + m.gpa.free(m.ids); + m.gpa.free(m.logits); + m.lm.deinit(); + m.qm.deinit(); m.tr.deinit(); - m.lw.deinit(m.gpa); m.tw.deinit(m.gpa); m.st.deinit(); m.gpa.destroy(m); @@ -79,18 +126,63 @@ pub const Model = struct { /// 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); + return m.pass(ids, pos, audio, 1, null); } - /// forward with the head over the last `heads` rows: each row's logits to the binding's `keep` when set. + /// forward with the head over the last `heads` rows: each row's logits to `keep` when set. pub fn forwardHeads(m: *Model, ids: []const u32, pos: usize, audio: ?Splice, heads: usize) !u32 { - return lm.forwardHeads(&m.lr, m.c.text, &m.lw, m.lb, ids, pos, audio, heads); + return m.pass(ids, pos, audio, heads, null); } - /// forward with its stages (lm_embed, lm_layer{i}, lm_norm) to `sink`. + /// forward with its stages (lm_embed, lm0_*, 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); + m.sink = sink; + defer m.sink = null; + return m.pass(ids, pos, audio, 1, if (sink != null) .{ .ctx = m, .put = tapPut } else null); + } + + fn tapPut(ctx: *anyopaque, stage: []const u8, ptr: u64, rows: usize, cols: usize) anyerror!void { + const m: *Model = @ptrCast(@alignCast(ctx)); + if (m.sink) |dm| try dm.put(dm.ctx, stage, ptr, rows, cols, null); + } + + fn pass(m: *Model, ids: []const u32, pos: usize, audio: ?Splice, heads: usize, tap: ?q3.lm.Tap) !u32 { + const rows = ids.len; + if (rows == 0 or rows > m.pass_rows) return error.PassRows; + if (heads == 0 or heads > rows or heads > m.head_rows) return error.PassHeads; + if (pos + rows > m.cap) return error.ContextFull; + for (ids) |t| if (t >= m.c.text.vocab) return error.InvalidBatch; + try m.s.synchronize(); // the last pass may still read them + @memcpy(m.ids[0..rows], ids); + try store.view(m.d, m.a.ids, 4 * rows).upload(0, std.mem.sliceAsBytes(m.ids[0..rows])); + const x: q3.lm.Extra = .{ .start = pos, .cache = m.cache, .splice = audio, .head = .{ .rows = heads, .logits = m.logits_dev }, .tap = tap }; + try m.lm.forwardFrom(&m.qm, m.a, m.cap, 0, &.{@intCast(rows)}, x); + const got = m.logits[0 .. heads * m.c.text.vocab]; + try store.view(m.d, m.logits_dev, got.len * 2).downloadAsync(0, std.mem.sliceAsBytes(got), m.s.handle); + try m.s.synchronize(); + if (m.keep) |k| try k.rows.appendSlice(k.gpa, got); + const last = got[(heads - 1) * m.c.text.vocab ..]; + const best = shared.argmax(last); + m.last_margin = shared.margin(last, best); + return best; + } + + /// A planted fault for tf-qwen3-asr-forced: every layer's q_norm and k_norm swapped (again: back). + pub fn swapQkNorms(m: *Model) void { + for (m.qm.layers) |*l| std.mem.swap(u64, &l.q_norm, &l.k_norm); + } + + /// Positions [0, n) of every layer's k and v caches, downloaded: k rows then v rows, layer by layer. + pub fn cacheRows(m: *Model, gpa: std.mem.Allocator, n: usize) ![]u16 { + const t = m.c.text; + const row = t.kv_heads * t.head_dim; + const out = try gpa.alloc(u16, 2 * t.layers * n * row); + errdefer gpa.free(out); + try m.s.synchronize(); + for (0..t.layers) |l| for ([_]u64{ m.cache.kc, m.cache.vc }, 0..) |base, j| { + const dst = out[(2 * l + j) * n * row ..][0 .. n * row]; + try m.d.check(m.d.api.cuMemcpyDtoH_v2(dst.ptr, base + l * m.cache.stride, dst.len * 2), "cuMemcpyDtoH"); + }; + return out; } }; diff --git a/zig/src/families/qwen3_asr/qwen3_asr_cuda.zig b/zig/src/families/qwen3_asr/qwen3_asr_cuda.zig index 3a840342347..1d6ac9e31f2 100644 --- a/zig/src/families/qwen3_asr/qwen3_asr_cuda.zig +++ b/zig/src/families/qwen3_asr/qwen3_asr_cuda.zig @@ -1,4 +1,4 @@ -//! Qwen3-ASR on CUDA: cuda/ binds the shared schedules (tower.zig, lm.zig) to the kernels; tf-qwen3-asr drives it. +//! Qwen3-ASR on CUDA: cuda/ binds the tower schedule; the Qwen3 layers run qwen3's CUDA pass; tf-qwen3-asr drives it. pub const host = @import("qwen3_asr.zig"); pub const Model = @import("cuda/model.zig").Model; pub const Options = @import("cuda/model.zig").Options; diff --git a/zig/tests/qwen3_asr_cuda.zig b/zig/tests/qwen3_asr_cuda.zig index 739d9c7ab3e..8dd26ab9429 100644 --- a/zig/tests/qwen3_asr_cuda.zig +++ b/zig/tests/qwen3_asr_cuda.zig @@ -175,7 +175,7 @@ pub fn main(init: std.process.Init) !u8 { defer out.deinit(gpa); var margins: std.ArrayList(f32) = .empty; defer margins.deinit(gpa); - try margins.append(gpa, m.lr.last_margin); + try margins.append(gpa, m.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 }); }; @@ -184,7 +184,7 @@ pub fn main(init: std.process.Init) !u8 { 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); + try margins.append(gpa, m.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; diff --git a/zig/tests/qwen3_asr_forced.zig b/zig/tests/qwen3_asr_forced.zig index 5cfd4af8016..80389571891 100644 --- a/zig/tests/qwen3_asr_forced.zig +++ b/zig/tests/qwen3_asr_forced.zig @@ -5,11 +5,11 @@ const qa = @import("qwen3_asr"); const host = qa.host; const forced = host.forced; -const usage = "usage: tf-qwen3-asr-forced MODEL_DIR CLIP.wav --case DIR [--plant splice|norms] [--rows K [--row-gemms]]\n" ++ +const usage = "usage: tf-qwen3-asr-forced MODEL_DIR CLIP.wav --case DIR [--plant splice|norms] [--rows K]\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" ++ " --rows K: the prompt pass over the first K reply ids against the decode steps, and the prompt in two passes\n" ++ - " against one (caches and logits): exit 1 unless bit-equal; --row-gemms runs every projection a row at a time.\n" ++ + " against one (caches and logits): exit 1 unless bit-equal.\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. @@ -70,10 +70,9 @@ pub fn main(init: std.process.Init) !u8 { var case_dir: ?[]const u8 = null; var plant: ?Plant = null; var check_rows: usize = 0; - var row_gemms = false; var i: usize = 3; while (i < args.len) : (i += 2) { - if (i + 1 >= args.len and !std.mem.eql(u8, args[i], "--row-gemms")) break; + if (i + 1 >= args.len) break; if (std.mem.eql(u8, args[i], "--case")) case_dir = args[i + 1] else if (std.mem.eql(u8, args[i], "--rows")) { check_rows = try std.fmt.parseInt(usize, args[i + 1], 10); } else if (std.mem.eql(u8, args[i], "--plant")) { @@ -81,9 +80,6 @@ pub fn main(init: std.process.Init) !u8 { std.debug.print(usage, .{}); return 2; }; - } else if (std.mem.eql(u8, args[i], "--row-gemms")) { - row_gemms = true; - i -= 1; } else { std.debug.print(usage, .{}); return 2; @@ -124,24 +120,23 @@ pub fn main(init: std.process.Init) !u8 { defer ctx.deinit(); var s = try cuda.Stream.init(&driver, false); defer s.deinit(); - const opts: qa.Options = .{ .audio_rows = plan.rows, .pass_rows = ids.len + check_rows, .positions = ids.len + want.len + 1 }; + const opts: qa.Options = .{ .audio_rows = plan.rows, .pass_rows = ids.len + check_rows, .positions = ids.len + want.len + 1, .head_rows = check_rows + 1 }; const m = try qa.Model.load(gpa, io, &driver, s, args[1], cfg, opts); defer m.deinit(); var rows_buf = try cuda.DeviceBuffer.alloc(&driver, plan.rows * cfg.audio.out * 2); defer rows_buf.free(); const n_rows = try m.encode(feats, rows_buf.ptr, null); const splice: qa.Splice = .{ .ptr = rows_buf.ptr, .at = at + @intFromBool(plant == .splice), .n = n_rows }; - m.lr.plant_norms = plant == .norms; - m.lr.row_gemms = row_gemms; + if (plant == .norms) m.swapQkNorms(); const vocab = cfg.text.vocab; // the prompt pass, then one decode step a reference id: every step's logits row kept var steps: std.ArrayList(u16) = .empty; defer steps.deinit(gpa); - m.lr.keep = .{ .gpa = gpa, .rows = &steps }; + m.keep = .{ .gpa = gpa, .rows = &steps }; _ = try m.forward(ids, 0, splice); for (want[0 .. want.len - 1], 0..) |id, k| _ = try m.forward(&.{id}, ids.len + k, null); - m.lr.keep = null; + m.keep = null; const clip = std.fs.path.basename(case_dir.?); var same: usize = 0; @@ -189,24 +184,24 @@ pub fn main(init: std.process.Init) !u8 { defer gpa.free(long); var pass: std.ArrayList(u16) = .empty; defer pass.deinit(gpa); - m.lr.keep = .{ .gpa = gpa, .rows = &pass }; + m.keep = .{ .gpa = gpa, .rows = &pass }; _ = try m.forwardHeads(long, 0, splice, check_rows + 1); - m.lr.keep = null; + m.keep = null; const dec = compareRows(pass.items, steps.items[0 .. (check_rows + 1) * vocab], vocab); std.debug.print("ROWS {s}: the prompt pass's last {d} rows against the decode steps: {d} bit-equal, worst |diff| {d:.6}\n", .{ clip, dec.rows, dec.equal, dec.worst }); ok = ok and dec.equal == dec.rows; // the prompt in one pass, then in two cut inside the audio rows: caches and the last row's logits var one: std.ArrayList(u16) = .empty; defer one.deinit(gpa); - m.lr.keep = .{ .gpa = gpa, .rows = &one }; + m.keep = .{ .gpa = gpa, .rows = &one }; _ = try m.forward(ids, 0, splice); - const c1 = try m.lr.cacheRows(gpa, ids.len); + const c1 = try m.cacheRows(gpa, ids.len); defer gpa.free(c1); const cut = at + n_rows / 2; _ = try m.forward(ids[0..cut], 0, splice); _ = try m.forward(ids[cut..], cut, splice); - m.lr.keep = null; - const c2 = try m.lr.cacheRows(gpa, ids.len); + m.keep = null; + const c2 = try m.cacheRows(gpa, ids.len); defer gpa.free(c2); var differ: usize = 0; for (c1, c2) |x, y| differ += @intFromBool(x != y); From 83dd8c329b844055443d1e4b84711e8d9a502eba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Thu, 12 Nov 2026 03:19:38 +0100 Subject: [PATCH 23/28] qwen3 cuda: forwardFrom refuses a start or head without one input and its caches before any launch, with its tests lm.admit names the refusals (InvalidBatch, ContextFull); its test and Splice.within's run in test-qwen3-cuda-host. --- zig/src/families/qwen3/cuda/lm.zig | 43 +++++++++++++++++++++-- zig/src/families/qwen3/qwen3_cuda.zig | 2 ++ zig/src/families/qwen3_asr/cuda/model.zig | 2 +- 3 files changed, 43 insertions(+), 4 deletions(-) diff --git a/zig/src/families/qwen3/cuda/lm.zig b/zig/src/families/qwen3/cuda/lm.zig index cae12339dd7..254f3b4085e 100644 --- a/zig/src/families/qwen3/cuda/lm.zig +++ b/zig/src/families/qwen3/cuda/lm.zig @@ -206,6 +206,45 @@ pub const Extra = struct { tap: ?Tap = null, }; +/// Refuses a start or head on several inputs, a trunk or no caches, a head over 0 or too many rows, positions past cap. +pub fn admit(x: Extra, trunk: usize, ends: []const u32, cap: usize) !void { + if (ends.len == 0) return error.InvalidBatch; + const total = ends[ends.len - 1]; + if ((x.start > 0 or x.head != null) and (ends.len != 1 or x.cache == null or trunk > 0)) return error.InvalidBatch; + if (x.start + total > cap) return error.ContextFull; + if (x.head) |h| if (h.rows == 0 or h.rows > total) return error.InvalidBatch; +} + +test "admit: forward's call passes; a start or head needs one input, no trunk and its caches, and stays in them" { + const c: Cache = .{ .kc = 256, .vc = 512, .stride = 256 }; + try admit(.{}, 0, &.{ 3, 7 }, 512); + try admit(.{}, 2, &.{ 3, 7 }, 512); // the reranker's trunk + try admit(.{ .start = 5, .cache = c, .head = .{ .rows = 7, .logits = 0 } }, 0, &.{7}, 512); + try std.testing.expectError(error.InvalidBatch, admit(.{ .start = 5 }, 0, &.{7}, 512)); // no caches to resume + try std.testing.expectError(error.InvalidBatch, admit(.{ .start = 5, .cache = c }, 0, &.{ 3, 7 }, 512)); + try std.testing.expectError(error.InvalidBatch, admit(.{ .start = 5, .cache = c }, 2, &.{7}, 512)); // a trunk too + try std.testing.expectError(error.InvalidBatch, admit(.{ .cache = c, .head = .{ .rows = 1, .logits = 0 } }, 2, &.{7}, 512)); + try std.testing.expectError(error.InvalidBatch, admit(.{ .head = .{ .rows = 1, .logits = 0 } }, 0, &.{7}, 512)); + try std.testing.expectError(error.InvalidBatch, admit(.{ .cache = c, .head = .{ .rows = 8, .logits = 0 } }, 0, &.{7}, 512)); + try std.testing.expectError(error.InvalidBatch, admit(.{ .cache = c, .head = .{ .rows = 0, .logits = 0 } }, 0, &.{7}, 512)); + try std.testing.expectError(error.ContextFull, admit(.{ .start = 506, .cache = c }, 0, &.{7}, 512)); + try admit(.{ .start = 505, .cache = c }, 0, &.{7}, 512); +} + +test "a splice is cut to the pass: the rows inside its positions, none outside" { + const sp: Splice = .{ .ptr = 0, .at = 3, .n = 4 }; // positions 3..6 + const in = sp.within(0, 10).?; + try std.testing.expectEqual(@as(usize, 0), in.src); + try std.testing.expectEqual(@as(usize, 3), in.dst); + try std.testing.expectEqual(@as(usize, 4), in.len); + const tail = sp.within(5, 1).?; // a one-row pass at position 5: the splice's row 2 + try std.testing.expectEqual(@as(usize, 2), tail.src); + try std.testing.expectEqual(@as(usize, 0), tail.dst); + try std.testing.expectEqual(@as(usize, 1), tail.len); + try std.testing.expect(sp.within(7, 3) == null); + try std.testing.expect(sp.within(0, 3) == null); +} + /// Which of the CUDA kernels' geometry limits a spec breaks: the attention's heads, the row kernels' widths, or none. pub const Geometry = enum { ok, heads, widths }; @@ -314,10 +353,8 @@ pub const Lm = struct { /// forward with `x`'s start, caches, splice, head and taps; refused before any launch when they do not fit. pub fn forwardFrom(lm: *Lm, m: *const weights.Model, a: Addrs, cap: usize, trunk: usize, ends: []const u32, x: Extra) !void { const s = m.spec; + try admit(x, trunk, ends, cap); // before any launch: a refused pass queues nothing const total = ends[ends.len - 1]; - if ((x.start > 0 or x.head != null) and (ends.len != 1 or x.cache == null or trunk > 0)) return error.InvalidBatch; - if (x.start + total > cap) return error.ContextFull; - if (x.head) |h| if (h.rows == 0 or h.rows > total) return error.InvalidBatch; try lm.emb.bf16(lm.s, a.ids, m.embed, a.x, total, s.hidden); if (x.splice) |sp| if (sp.within(x.start, total)) |in| { const row = s.hidden * 2; diff --git a/zig/src/families/qwen3/qwen3_cuda.zig b/zig/src/families/qwen3/qwen3_cuda.zig index 87d2fd773e2..fb66da6434a 100644 --- a/zig/src/families/qwen3/qwen3_cuda.zig +++ b/zig/src/families/qwen3/qwen3_cuda.zig @@ -7,6 +7,7 @@ pub const lane = @import("lane.zig"); pub const score = @import("score.zig"); pub const gemm = @import("cuda/gemm.zig"); pub const engine = @import("cuda/engine.zig"); +pub const pass = @import("cuda/lm.zig"); pub const native = @import("cuda/native.zig"); test { @@ -18,4 +19,5 @@ test { _ = gemm; _ = engine; _ = native; + _ = pass; } diff --git a/zig/src/families/qwen3_asr/cuda/model.zig b/zig/src/families/qwen3_asr/cuda/model.zig index b8f767978c5..c6a2928057a 100644 --- a/zig/src/families/qwen3_asr/cuda/model.zig +++ b/zig/src/families/qwen3_asr/cuda/model.zig @@ -92,7 +92,7 @@ pub const Model = struct { try m.lm.g.prepare(&.{.{ sp.vocab, sp.hidden }}); // the tied head: one more (n, k), which embeddings never run try m.lm.g.checkRows(1); try m.lm.g.checkRows(o.pass_rows); - // the scratch block sized to the positions: its RoPE and position tables and the chunk partials cover the caches + // the scratch sized to the positions: its RoPE, position tables and chunk partials cover the caches const sc = q3.lm.Scratch.of(sp, cap, 1); m.a = sc.at(try m.st.alloc(sc.total)); try q3.lm.tables(gpa, d, m.a, sp, cap); From d5a2f81140dab59f22ad13ebf6bd413da376ccb2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Thu, 12 Nov 2026 15:56:18 +0100 Subject: [PATCH 24/28] tests: re-pin prefill_attention.cu, vit.cu and vit.zig for Qwen3-ASR's audio tower (#2105) The three pinned serving sources gain only new code: a vision_kernel<64, 8> instance, tf_vit_conv_cols and tf_vit_conv_flatten, and their wrappers. The existing kernels' SASS is unchanged on sm_80/86/89/120/121. --- zig/dense_serving_test.zig | 4 ++-- zig/tests/fixtures/gradient-serving.tsv | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/zig/dense_serving_test.zig b/zig/dense_serving_test.zig index 94dc62daccc..a99df4ad4e0 100644 --- a/zig/dense_serving_test.zig +++ b/zig/dense_serving_test.zig @@ -11,8 +11,8 @@ test "dense serving: owned CUDA images retain their reviewed lane and decode byt try std.testing.expectEqualStrings("5f325dc6d8134624b30b5e99c5764f75beb3c344b5f949d38bfaa41bc8dfe5dc", &hash(@embedFile("kernels/cuda/experts_prefill.cu"))); try std.testing.expectEqualStrings("e5ef9dcce75c478e59e476d2fa8747baee2317bd283b0756f125ea050dad9228", &hash(@embedFile("kernels/cuda/gdn.cu"))); try std.testing.expectEqualStrings("dba5aae94115571ed48933d80f646fff31b2a7da226569867c74a1dc061d2ca2", &hash(@embedFile("kernels/cuda/lane_gemv.cu"))); - // 191061381's bytes: 82f3dde92 and 191061381 (#2609) add pattn_kernel instances; 94a9a48d6 moves helpers out - try std.testing.expectEqualStrings("905fff2c9018d778557a60ed2c81c24ce220adf5b092c8c32f8a1782963f9f28", &hash(@embedFile("kernels/cuda/prefill_attention.cu"))); + // #2239 adds vision_kernel<64, 8> for Qwen3-ASR's tower; every function main had keeps its SASS (sm_80 to sm_121) + try std.testing.expectEqualStrings("4227f0a9b7a89ac296388a7dcd9e49cd0dd487ed09ee46cc1d4eda94ab8e3741", &hash(@embedFile("kernels/cuda/prefill_attention.cu"))); const group = @embedFile("kernels/cuda/qmm_group.cu"); try std.testing.expectEqualStrings("ceff4ee13e97b5aa93cbe7a1edc9a524c78aaa145dd1e5c82dcb05a3011aae23", &hash(group[0..16095])); try std.testing.expectEqualStrings("8780fd710be3ce2f04e53fa1e69eb062809d3bec6391d9bd49983d0588e374d0", &hash(group)); diff --git a/zig/tests/fixtures/gradient-serving.tsv b/zig/tests/fixtures/gradient-serving.tsv index 19b03df27b1..559b1a89298 100644 --- a/zig/tests/fixtures/gradient-serving.tsv +++ b/zig/tests/fixtures/gradient-serving.tsv @@ -46,7 +46,7 @@ zig/kernels/cuda/nemotron_route.cu 65da41432442f9fd99f73abefe87f34cf3c46b4971afe zig/kernels/cuda/norms.cu 89d3c6cea39fe3e1bf8d5a2fe60465f7ae272548f14711abb59ddac709d2d1db raw main d4541b00e0 (rms_scale shared; same SASS) zig/kernels/cuda/nvfp4_experts.cu cb54357e2c06252cc594cd1223401170dadefd995b0c67db0cae5edf628719d0 raw #2266 (decode cp.async rings, GB10 SASS unchanged) zig/kernels/cuda/nvfp4q.cuh 5fe4fa58568f2293bb72ccfa58b362ba2783b21a781e56946a5a2c328303d111 raw -zig/kernels/cuda/prefill_attention.cu 905fff2c9018d778557a60ed2c81c24ce220adf5b092c8c32f8a1782963f9f28 raw main 82f3dde92 (pattn_kernel<64, 8, 4, 8> over paged caches), 94a9a48d6 (helpers to prefill_attention.cuh, SASS unchanged), 191061381 (#2609: two new pattn_kernel instances at two query heads a block, head dims 128 and 64; existing instances unchanged) +zig/kernels/cuda/prefill_attention.cu 4227f0a9b7a89ac296388a7dcd9e49cd0dd487ed09ee46cc1d4eda94ab8e3741 raw main 82f3dde92 (pattn_kernel<64, 8, 4, 8> over paged caches), 94a9a48d6 (helpers to prefill_attention.cuh, SASS unchanged), 191061381 (#2609: two new pattn_kernel instances at two query heads a block, head dims 128 and 64; existing instances unchanged), #2239 (a vision_kernel<64, 8> instance for Qwen3-ASR's audio tower; existing instances unchanged) zig/kernels/cuda/prefill_attention_rows.cuh 21975248a7ec9efd199a28324bba837e7b78f066a63b426ab26587cba38fda5e raw main 94a9a48d6 (helpers shared with the contract controls, SASS unchanged) zig/kernels/cuda/probe.cu 94a3118894b3066e0f0f6fc1cfc3c03828d291077cb26c437b62fcc9b177a210 raw glm-pdl-order's slow writer, planted early reader and glm_pdl::enter() reader zig/kernels/cuda/prompt16.cu 2da3c4ea23de0fa9b2536db0fa66f07bb2d5b45db36c2f9cb321e039ebeac7c2 raw #3252: the lean gate/up SwiGLU pair launch for a dense MLP prompt @@ -79,7 +79,7 @@ zig/kernels/cuda/torch_ops/nucleus.cu c3328dc3ad1fb28c820c343f22c10dd1b4f9a9d8c8 zig/kernels/cuda/torch_ops/pointwise.cu 3d3118159265538679968e56a8c4b5d61b01c07487530e95e4f93ba8662f98c8 raw zig/kernels/cuda/torch_ops/topk.cu 0b5ddb5b02af2ebd9a3992cb11bb80eefd7547c32d6dfdafdf216ab484dd1627 raw zig/kernels/cuda/train_mixers.cuh cec88446cede27c941da254d94f81afa1c92c6880e63bfd66a0efcdc7f95aa13 raw -zig/kernels/cuda/vit.cu 516fbc7ec65afafd3a368d593c85d21d5ffa0da858703f257c4779745ebc239e raw +zig/kernels/cuda/vit.cu 5bdb9bb4e247c1deb6d5e30bc65aa7976786b1a3f55569e1729a87717d2e37b3 raw #2239 (tf_vit_conv_cols and tf_vit_conv_flatten for Qwen3-ASR's audio tower; existing kernels unchanged) zig/src/cuda/abi.zig fef21a6302d1863001496b3765899a265470cfdf78678d7f73fa7fd3115d2a93 raw commits ef23b5934; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate zig/src/cuda/aot.zig bd4e41f32eebf8e75e6f40e036847aaca2900aee7628167552c661824c79d62b raw commits 9349e38bb; series patches 14-runtime-foundation.patch, 45-runtime-one-fallback.patch, 46-preserve-nospec-and-capture.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate; main 3a7e6fac7 (identity export for persisted serving states) zig/src/cuda/carveout.zig 5ebe77d420ec42d1494fbe7259ce12e20e56427d8f7d931d672b7ca1240b1759 raw main 6a1feb26e (malformed TF_CUDA_CARVEOUT settings refused by name) @@ -113,7 +113,7 @@ zig/src/cuda/stream.zig 02c1879e72a35927466ab462d6b2a461691d1f5196da770decd1125d zig/src/cuda/tp_group.zig 1a2acbdf2de6b827218deb45df5b5845beecde4eb718a4e4b3966582db51d7a7 raw commits b8d45ded3, 80afaf959; series patches 14-runtime-foundation.patch; HELD: must be re-qualified by the LW device gates on the 1.1.1 candidate; main c8ad9872da (#2205: RoCE small gathers at any world up to roce.max_world when every rank asks; TF_ROCE's default unchanged, two ranks on, three or more on NCCL), 61a2651577 (#2789: a call failing after the group's abort ends as Aborted, not fatally); #2918 (communicator abort through its owner) zig/src/cuda/tp_watch.zig 19ed1d12bc56f804b5d207d04226e9f6131a517aaf7aec4c4b2d0bd5f468ace3 raw main 13d7450fd (#2354), 7ead07c92 (bounded peer warm-up, #2512) zig/src/cuda/triton.zig 256323865c6a4676b8b75aae9e32d2d9732cf2623efedb9462cf6f95302c3e83 raw -zig/src/cuda/vit.zig 72c4301251f50d0f25907f0d8ad03a943281b234c506a455e413627a3ffe09c0 raw +zig/src/cuda/vit.zig 0a9200b161e331cf3f5937ff5dcc5c65bcb15e3de8127c277f6a31595d2e5296 raw #2239 (convCols, convFlatten and the head-64 full attention for Qwen3-ASR's audio tower; existing paths unchanged) zig/src/families/flashnext/cuda_attn.zig 99dfe79f919a8599490f1cdba0bec20d6e73ccbeafe26d5848419a465fdfa0d0 raw zig/src/families/flashnext/cuda_batch.zig f1c5ab1478497ab2c0abdf77776dfed36fa9092579d4306e4320a32cfadf6910 raw main 42ff6c510f (disk states keyed by the resolved prompt passes; serving unchanged); #XXXX: the scratch test's ceiling restated at the 3,072-row default, #3413 (TF_FLASHNEXT_READOUT_FUSED's prompt read-out; unchanged when unset) zig/src/families/flashnext/cuda_batch_state.zig 493ee0dc5bc832b9344d16de92ab33f5de15574b4d9a81f283558c4d729c6db6 raw y and moe_f32 take one spare row for a --tp 2 prompt pass's padded rank block; replies unchanged; #XXXX: the default prompt chunk is 3,072 rows; the shared pass takes the pooled n-gram gather first (TF_FLASHNEXT_GATHER_EARLY); replies unchanged From 970ad6a93e1fff21a72a3a14bda5e794effad922 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:44:34 +0100 Subject: [PATCH 25/28] tests/cuda: Qwen3-ASR's contract set runs under kernel-contract's words, so main.zig stays within 600 lines (#2105) --- zig/tests/cuda/contract_qwen3_asr.zig | 17 +---------------- zig/tests/cuda/main.zig | 1 - 2 files changed, 1 insertion(+), 17 deletions(-) diff --git a/zig/tests/cuda/contract_qwen3_asr.zig b/zig/tests/cuda/contract_qwen3_asr.zig index 4715da99731..9663993d551 100644 --- a/zig/tests/cuda/contract_qwen3_asr.zig +++ b/zig/tests/cuda/contract_qwen3_asr.zig @@ -1,4 +1,4 @@ -//! Qwen3-ASR's tower kernels under the contract (qwen3-asr-contract): vit.cu's conv taps and flatten, attention at 64. +//! Qwen3-ASR's conv taps, flatten and attention at 64, in kernel-contract: `kernel-contract tf_vit_conv qwen3-asr`. const std = @import("std"); const cuda = @import("cuda"); const core = @import("core"); @@ -201,18 +201,3 @@ pub const Set = struct { set.gpa.destroy(set); } }; - -/// The Qwen3-ASR tower kernels' gates 1-4 and their controls alone. -pub fn run(gpu: check.Gpu) !void { - const a = gpu.gpa; - var s = try cuda.Stream.init(gpu.d, false); - defer s.deinit(); - var list: std.ArrayList(g.Kernel) = .empty; - defer list.deinit(a); - const set = try Set.init(gpu, s, a, &list); - defer set.deinit(); - var t: g.Tally = .{}; - try g.runAll(a, list.items, 0x71776e33, &t); - std.debug.print("SUMMARY qwen3-asr: {d} kernels, {d} pass gates 1-4, {d} fail; {d} controls: {d} red as planted, {d} missed\n", .{ t.kernels, t.passed, t.failed, t.controls, t.caught, t.missed }); - try check.expect(t.problems() == 0, "qwen3-asr-contract: {d} gate failures, {d} controls missed", .{ t.failed, t.missed }); -} diff --git a/zig/tests/cuda/main.zig b/zig/tests/cuda/main.zig index 30576465f63..73de15d90aa 100644 --- a/zig/tests/cuda/main.zig +++ b/zig/tests/cuda/main.zig @@ -340,7 +340,6 @@ fn run(gpu: check.Gpu, cmd: []const u8, rest: []const [:0]const u8) !void { if (std.mem.eql(u8, cmd, "moss-contract")) return @import("contract_moss_image.zig").run(gpu, rest); if (std.mem.eql(u8, cmd, "idol-decoder-contract")) return @import("contract_idol_decoder.zig").run(gpu); if (std.mem.eql(u8, cmd, "idol-contract")) return @import("contract_idol.zig").run(gpu); - if (std.mem.eql(u8, cmd, "qwen3-asr-contract")) return @import("contract_qwen3_asr.zig").run(gpu); if (std.mem.eql(u8, cmd, "tree")) return tree_tests.run(gpu); if (std.mem.eql(u8, cmd, "block")) return block_tests.run(gpu); if (std.mem.eql(u8, cmd, "window")) return window_tests.run(gpu); From f0eb1c6202d51985468ed916f8b186e3c5506662 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 09:51:03 +0000 Subject: [PATCH 26/28] Follow main extracted CUDA help when the original ASR command retires Follow main e54cb349293035edbf6a2128d6ae3beab9a9a7a4 (cuda tests: split command help to keep the runner under 600 lines). Original #2239 mail24 removes its standalone contract command in favor of the existing kernel-contract words; remove only its temporary help row from the current module. --- zig/tests/cuda/main_usage.zig | 1 - 1 file changed, 1 deletion(-) diff --git a/zig/tests/cuda/main_usage.zig b/zig/tests/cuda/main_usage.zig index f643fdab23b..0712cd8b62b 100644 --- a/zig/tests/cuda/main_usage.zig +++ b/zig/tests/cuda/main_usage.zig @@ -158,7 +158,6 @@ pub const usage = \\ moss-contract [ONLY..] MOSS-Image's own kernels, its decoder's unpack and its encoder's mixer, gates 1-4, controls red \\ idol-decoder-contract Idol's decoders' stem, to_kv, head norms and attention through gates 1-4, controls red \\ idol-contract Idol's denoiser glue and head-64 attention through gates 1-4, controls red - \\ qwen3-asr-contract Qwen3-ASR's conv taps, conv flatten and head-64 attention through gates 1-4, controls red \\ glm-exl3 | glm-exl3-items GLM's EXL3 routed experts, decode and prompt, against float64, and the item plan's decode against the plain decode, byte for byte (synthetic) \\ glm-kda-pad-split TF_GLM_KDA_PAD's padding of the bf16 and split KDA stacks at TP=3 (synthetic) \\ glm-exl3-layer one checkpoint layer's EXL3 experts through the GLM loader, against float64 From 9aa14207f623ce6e1440c70d14f2536c08e54787 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Schmied?= <600316+jschmied@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:44:34 +0100 Subject: [PATCH 27/28] qwen3-asr: tower_ref.zig's header and chunks.zig's rows test describe the computation (#2105) --- zig/src/families/qwen3_asr/chunks.zig | 2 +- zig/src/families/qwen3_asr/tower_ref.zig | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/zig/src/families/qwen3_asr/chunks.zig b/zig/src/families/qwen3_asr/chunks.zig index 3d99fdc7dd0..4592686fd42 100644 --- a/zig/src/families/qwen3_asr/chunks.zig +++ b/zig/src/families/qwen3_asr/chunks.zig @@ -63,7 +63,7 @@ pub const Plan = struct { } }; -test "rows: the package's _get_feat_extract_output_lengths" { +test "rows: three halvings of a chunk's remainder, rounding up, plus 13 a whole chunk of 100 frames" { // values printed by qwen-asr 0.0.6's formula for these frame counts const cases = [_][2]usize{ .{ 1, 1 }, .{ 7, 1 }, .{ 8, 1 }, .{ 9, 2 }, .{ 99, 13 }, .{ 100, 13 }, .{ 101, 14 }, .{ 481, 63 }, .{ 585, 76 }, .{ 2940, 382 }, .{ 3000, 390 } }; for (cases) |c| try std.testing.expectEqual(c[1], rows(c[0])); diff --git a/zig/src/families/qwen3_asr/tower_ref.zig b/zig/src/families/qwen3_asr/tower_ref.zig index 545f96d6032..1972fa995bf 100644 --- a/zig/src/families/qwen3_asr/tower_ref.zig +++ b/zig/src/families/qwen3_asr/tower_ref.zig @@ -1,4 +1,4 @@ -//! The audio tower in float64, stage by stage as the package's Qwen3ASRAudioEncoder runs it: the check's reference. +//! The audio tower in float64, stage by stage: convs, positions, windowed layers, final norm, two projections. const std = @import("std"); const cfg = @import("config.zig"); const chunks = @import("chunks.zig"); From 1fa23a86d6a7465cfc6ec82e3bf29258d284f217 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sun, 22 Nov 2026 02:27:15 +0000 Subject: [PATCH 28/28] changelog: #2239 under Unreleased --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 759cd3f1316..04408ac5618 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Qwen3-ASR on CUDA (tools only, not served yet): `tf-qwen3-asr` runs a WAV clip through the 0.6B or 1.7B checkpoint (the audio tower, then greedy decode through the Qwen3 CUDA pass the embedding engine runs), `tf-qwen3-asr-forced` teacher-forces a clip on a reference case, and `test-qwen3-asr-host` and `tf-qwen3-asr-check` cover config admission, tensor names, log-mel rows and a float64 tower without a GPU (#2239, refs #2105). Thanks to @jschmied. + - GLM TP=2 prefill on CUDA: `TF_GLM_INDEX_SPLIT=32768` keeps indexer scores, pools and token rows local on each rank below that position (no blocking all-gathers) and own partials are read in place; outputs are unchanged and the default stays 2048 (#4510). - GLM at TP=2 on CUDA prefill: dense attention runs only on the rows sparse attention leaves untouched when a chunk crosses the dense limit, and prefill skips projections nothing reads (MTP proposal and query-side work); outputs are unchanged (#4499).