From 7f8a286b1c4c819d3e40863761426e2ac1f3ee3e Mon Sep 17 00:00:00 2001 From: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> Date: Sun, 15 Nov 2026 04:09:38 -0600 Subject: [PATCH] gpu: raise the Vulkan qwen3.5 context ceiling from 7168 to 8192 keys The bf16 SDPA kernel stages f32 scores in shared memory: 7168 keys with the query row and reduction tree fill the 30720 B budget, and Apple's Vulkan limit is 32768 B, so 8192 keys cannot sit in shared memory. Add a -DSTREAM_GLOBAL twin of the kernel that stages scores in a coherent f32 storage buffer (one total-keys region per workgroup, memoryBarrierBuffer at the two write-to-read points). Same arithmetic and order as the shared arm. attend() picks the twin only when total keys exceed 7168; forward.zig allocates the stream from scratch only then. The shared-memory images below 7168 keys are byte-identical to the previous SPIR-V. max_visible_keys and the engine capacity become 8192; the scratch arena grows to 32 MiB. Contract cases cover 7169, 8192 decode and 64 rows ending at 8192. Signed-off-by: Joshua Warren <816217+joshuaswarren@users.noreply.github.com> --- zig/build/vulkan.zig | 4 ++ zig/kernels/vulkan/sdpa_decode_native.comp | 37 ++++++++++-- .../qwen3_5/backend/vulkan/backend.zig | 14 ++--- .../qwen3_5/backend/vulkan/engine.zig | 26 +++++---- .../qwen3_5/backend/vulkan/forward.zig | 7 ++- .../families/qwen3_5/backend/vulkan/state.zig | 4 +- zig/src/native/vulkan.zig | 4 +- zig/src/vulkan/attention.zig | 57 ++++++++++++++----- zig/tests/vulkan/contract_attention.zig | 37 ++++++++---- zig/tests/vulkan/contract_attention_main.zig | 44 ++++++++++++-- zig/tests/vulkan/qwen35_model_probe.zig | 16 +++--- zig/tests/vulkan/stage3_probe.zig | 6 +- 12 files changed, 188 insertions(+), 68 deletions(-) diff --git a/zig/build/vulkan.zig b/zig/build/vulkan.zig index 3845549d651..e10d2bde44e 100644 --- a/zig/build/vulkan.zig +++ b/zig/build/vulkan.zig @@ -139,20 +139,24 @@ pub const stage2_shaders_src = pub const stage3_variants = [_]ShaderVariant{ .{ .name = "rope_bf16", .src = "zig/kernels/vulkan/fast_rope.comp", .defines = &.{ "-DUSE_BF16", "-DORACLE_QWEN35" } }, .{ .name = "sdpa_rows_bf16", .src = "zig/kernels/vulkan/sdpa_decode_native.comp", .defines = &.{ "-DBF16_IO", "-DSDPA_DIM=256", "-DSDPA_ROWS" } }, + .{ .name = "sdpa_rows_bf16_long", .src = "zig/kernels/vulkan/sdpa_decode_native.comp", .defines = &.{ "-DBF16_IO", "-DSDPA_DIM=256", "-DSDPA_ROWS", "-DSTREAM_GLOBAL" } }, .{ .name = "gate_bf16", .src = "zig/kernels/vulkan/attention_gate.comp", .defines = &.{} }, .{ .name = "rope_f32", .src = "zig/kernels/vulkan/fast_rope.comp", .defines = &.{"-DORACLE_QWEN35"} }, .{ .name = "rope_f32_kcache", .src = "zig/kernels/vulkan/fast_rope.comp", .defines = &.{ "-DORACLE_QWEN35", "-DACT_OUT_BF16" } }, .{ .name = "sdpa_rows_f32q", .src = "zig/kernels/vulkan/sdpa_decode_native.comp", .defines = &.{ "-DBF16_IO", "-DF32_Q", "-DF32_OUT", "-DSDPA_DIM=256", "-DSDPA_ROWS" } }, + .{ .name = "sdpa_rows_f32q_long", .src = "zig/kernels/vulkan/sdpa_decode_native.comp", .defines = &.{ "-DBF16_IO", "-DF32_Q", "-DF32_OUT", "-DSDPA_DIM=256", "-DSDPA_ROWS", "-DSTREAM_GLOBAL" } }, .{ .name = "gate_f32", .src = "zig/kernels/vulkan/attention_gate.comp", .defines = &.{"-DACT_F32"} }, }; pub const stage3_shaders_src = \\pub const rope_bf16 align(4) = @embedFile("rope_bf16.spv").*; \\pub const sdpa_rows_bf16 align(4) = @embedFile("sdpa_rows_bf16.spv").*; + \\pub const sdpa_rows_bf16_long align(4) = @embedFile("sdpa_rows_bf16_long.spv").*; \\pub const gate_bf16 align(4) = @embedFile("gate_bf16.spv").*; \\pub const rope_f32 align(4) = @embedFile("rope_f32.spv").*; \\pub const rope_f32_kcache align(4) = @embedFile("rope_f32_kcache.spv").*; \\pub const sdpa_rows_f32q align(4) = @embedFile("sdpa_rows_f32q.spv").*; + \\pub const sdpa_rows_f32q_long align(4) = @embedFile("sdpa_rows_f32q_long.spv").*; \\pub const gate_f32 align(4) = @embedFile("gate_f32.spv").*; ; diff --git a/zig/kernels/vulkan/sdpa_decode_native.comp b/zig/kernels/vulkan/sdpa_decode_native.comp index a846c245c10..626a1c822e6 100644 --- a/zig/kernels/vulkan/sdpa_decode_native.comp +++ b/zig/kernels/vulkan/sdpa_decode_native.comp @@ -7,9 +7,21 @@ // softmax, then a per-dimension weighted V sum over 16-key blocks. // Shared usage: 7168*4 + 256*4 + 256*4 = 30720 bytes, at the host's // declared limit, so the served context is capped by kStreamKeys. +// -DSTREAM_GLOBAL moves the score stream to a coherent f32 storage +// buffer (binding 4, one total-keys region per workgroup); the host +// selects that image only when total keys exceed kStreamKeys. const uint kStreamKeys = 7168u; +#ifdef STREAM_GLOBAL +layout(set = 0, binding = 4, std430) coherent buffer Stream { + float values[]; +} stream_data; +#define STREAM(i) stream_data.values[stream_base + i] +#else +#define STREAM(i) scores[i] +#endif + #ifndef SDPA_DIM #define SDPA_DIM 256 #endif @@ -67,7 +79,9 @@ layout(set = 0, binding = 3, std430) writeonly buffer Y { float v[]; } ybuf; layout(set = 0, binding = 3, std430) writeonly buffer Y { uint16_t v[]; } ybuf; #endif +#ifndef STREAM_GLOBAL shared float scores[kStreamKeys]; +#endif shared float red[256]; shared float qs[256]; @@ -77,9 +91,16 @@ void main() { const uint thread = gl_LocalInvocationID.x; const uint D = SDPA_DIM; +#ifdef STREAM_GLOBAL + // Row * heads + head names this row-head's matrix_k-word (total-keys) + // score region; the causal bound alone caps the stream. + const uint stream_base = (gl_WorkGroupID.y * gl_NumWorkGroups.x + gl_WorkGroupID.x) * params.matrix_k; + uint key_end = params.matrix_k - params.dims + row + 1u; +#else // The causal bound the served shapes ride, capped by the shared score // buffer. uint key_end = min(params.matrix_k - params.dims + row + 1u, kStreamKeys); +#endif uint kv_head = head / (params.matrix_m / params.matrix_n); uint k_row_stride = params.shape[2]; uint k_head_base = kv_head * params.shape[1]; @@ -101,9 +122,12 @@ void main() { for (uint d = 0u; d < D; ++d) { s += qs[d] * bf16_to_f32(uint(kbuf.v[kbase + d])); } - scores[index] = s; + STREAM(index) = s; lmax = nan_max(lmax, s); } +#ifdef STREAM_GLOBAL + memoryBarrierBuffer(); +#endif red[thread] = lmax; barrier(); for (uint stride = 128u; stride > 0u; stride >>= 1u) { @@ -128,10 +152,13 @@ void main() { float lsum = 0.0; for (uint index = thread; index < key_end; index += 256u) { - float w = exp(scores[index] - m); - scores[index] = w; + float w = exp(STREAM(index) - m); + STREAM(index) = w; lsum += w; } +#ifdef STREAM_GLOBAL + memoryBarrierBuffer(); +#endif red[thread] = lsum; barrier(); for (uint stride = 128u; stride > 0u; stride >>= 1u) { @@ -146,12 +173,12 @@ void main() { for (; key + 16u <= key_end; key += 16u) { float b = 0.0; for (uint j = 0u; j < 16u; ++j) { - b += scores[key + j] * bf16_to_f32(uint(vbuf.v[k_head_base + (key + j) * k_row_stride + thread])); + b += STREAM(key + j) * bf16_to_f32(uint(vbuf.v[k_head_base + (key + j) * k_row_stride + thread])); } acc += b; } for (; key < key_end; ++key) { - acc += scores[key] * bf16_to_f32(uint(vbuf.v[k_head_base + key * k_row_stride + thread])); + acc += STREAM(key) * bf16_to_f32(uint(vbuf.v[k_head_base + key * k_row_stride + thread])); } #if defined(F32_OUT) ybuf.v[obase] = acc / denom; diff --git a/zig/src/families/qwen3_5/backend/vulkan/backend.zig b/zig/src/families/qwen3_5/backend/vulkan/backend.zig index 3b31ad0e5a7..7748028849b 100644 --- a/zig/src/families/qwen3_5/backend/vulkan/backend.zig +++ b/zig/src/families/qwen3_5/backend/vulkan/backend.zig @@ -213,11 +213,11 @@ test "prompt validation bounds: whole requests to the ceiling, never past, real var oov_last: [65]u32 = @splat(7); oov_last[oov_last.len - 1] = pinned.vocab; // valid length, OOV beyond the first chunk try std.testing.expect(!validPrompt(&oov_last)); - const over: [max_capacity + 1]u32 = @splat(7); // 7169 ids: one past the ceiling + const over: [max_capacity + 1]u32 = @splat(7); // 8193 ids: one past the ceiling try std.testing.expect(!validPrompt(&over)); - const at_cap: [max_capacity]u32 = @splat(7); // 7168 ids: exactly the ceiling + const at_cap: [max_capacity]u32 = @splat(7); // 8192 ids: exactly the ceiling try std.testing.expect(validPrompt(&at_cap)); - const buf: [7168]u32 = @splat(7); + const buf: [8192]u32 = @splat(7); for ([_]usize{ 1, 31, 32, 33, 63, 64, 65, 7105 }) |len| { try std.testing.expect(validPrompt(buf[0..len])); } @@ -225,12 +225,12 @@ test "prompt validation bounds: whole requests to the ceiling, never past, real test "the whole-request plan gates exact fit and one past, with checked arithmetic" { const cap: usize = max_capacity; - for ([_]usize{ 1, 31, 32, 33, 63, 64, 65, 7105, 7168 }) |len| { + for ([_]usize{ 1, 31, 32, 33, 63, 64, 65, 8129, 8192 }) |len| { try engine_mod.planFor(cap, 0, len, 1); // prompt-only: last draw reads a written row } - try engine_mod.planFor(cap, 0, 7167, 2); // 7167 rows + 1 decode = exact fit - try std.testing.expectError(error.ContextTooLong, engine_mod.planFor(cap, 0, 7168, 2)); // one past - try std.testing.expectError(error.ContextTooLong, engine_mod.planFor(cap, 0, 7169, 1)); + try engine_mod.planFor(cap, 0, 8191, 2); // 8191 rows + 1 decode = exact fit + try std.testing.expectError(error.ContextTooLong, engine_mod.planFor(cap, 0, 8192, 2)); // one past + try std.testing.expectError(error.ContextTooLong, engine_mod.planFor(cap, 0, 8193, 1)); try std.testing.expectError(error.UnsupportedPrompt, engine_mod.planFor(cap, 0, 0, 1)); // empty try std.testing.expectError(error.UnsupportedPrompt, engine_mod.planFor(cap, 0, 1, 0)); try std.testing.expectError(error.ContextTooLong, engine_mod.planFor(cap, std.math.maxInt(u64) - 2, 2, 2)); diff --git a/zig/src/families/qwen3_5/backend/vulkan/engine.zig b/zig/src/families/qwen3_5/backend/vulkan/engine.zig index ded4fd34cd9..7c6bb24f1a8 100644 --- a/zig/src/families/qwen3_5/backend/vulkan/engine.zig +++ b/zig/src/families/qwen3_5/backend/vulkan/engine.zig @@ -18,8 +18,8 @@ pub fn chunkEnd(done: usize, total: usize) usize { // The staged-transfer buffer: 8 MiB so the load's ~27k tensors stream in large chunks instead of one 64 KiB fence each. pub const staging_bytes: u64 = 8 << 20; -// The 16 MiB scratch arena holds persistent windows (~2.6 MB) and worst-layer prefill transients (~11.1 MB at 64 rows). -pub const arena_bytes: u64 = 16 << 20; +// The 32 MiB scratch arena: persistent windows ~2.6 MB, prefill transients ~11.1 MB, f32 score stream 16 MiB. +pub const arena_bytes: u64 = 32 << 20; // Step errors include dispatch.Error; Timeout exits 124 and InFlight exits 1 inside `vk.orExit`, before teardown. pub const Error = vk.dispatch.Error || @@ -85,7 +85,7 @@ pub const Engine = struct { base_mark: u64, poisoned: bool, - // Pinned-model admission runs inside the weights load before GPU work; SDPA arm limit is 7168; probe uses 256. + // Pinned-model admission runs inside the weights load before GPU work; the key cap is 8192 (probe: 256). pub fn init( gpa: Allocator, io: std.Io, @@ -377,17 +377,17 @@ test "the canonical cut ends every whole-request length at 64-row boundaries" { } test "the plan admits whole requests up to the capacity ceiling and refuses one past" { - const cap: usize = 7168; - for ([_]usize{ 1, 31, 32, 33, 63, 64, 65, 7105, 7168 }) |len| { + const cap: usize = state.max_capacity; + for ([_]usize{ 1, 31, 32, 33, 63, 64, 65, 8129, 8192 }) |len| { try planFor(cap, 0, len, 1); // a prompt-only request always fits at or under the ceiling } - try testing.expectError(error.ContextTooLong, planFor(cap, 0, 7169, 1)); // one past the ceiling - try planFor(cap, 0, 7168, 1); // exact fit prompt + one draw reads a written row - try testing.expectError(error.ContextTooLong, planFor(cap, 0, 7168, 2)); // one past with a decode - try planFor(cap, 0, 7105, 64); // the frozen long case ends at exactly 7168 writes - try testing.expectError(error.ContextTooLong, planFor(cap, 0, 7106, 64)); + try testing.expectError(error.ContextTooLong, planFor(cap, 0, 8193, 1)); // one past the ceiling + try planFor(cap, 0, 8192, 1); // exact fit prompt + one draw reads a written row + try testing.expectError(error.ContextTooLong, planFor(cap, 0, 8192, 2)); // one past with a decode + try planFor(cap, 0, 8129, 64); // the frozen long case ends at exactly 8192 writes + try testing.expectError(error.ContextTooLong, planFor(cap, 0, 8130, 64)); try testing.expectError(error.ContextTooLong, planFor(cap + 1, 0, 1, 1)); - try planFor(cap, 0, 7167, 2); // 7167 + 2 - 1 = 7168: exact fit + try planFor(cap, 0, 8191, 2); // 8191 + 2 - 1 = 8192: exact fit } test "the wide store policy covers exactly layers 0-3 of the 24-layer model" { @@ -407,7 +407,9 @@ test "the arena holds the persistent windows plus the worst transient layer" { const full = 4 * rows * (2 * 8 * 256 + 5 * 8 * 256 + 3 * 2 * 256); // the MLP in f32: gate + up + act const mlp = 12 * pinned.intermediate * rows; - const worst = @max(linear, @max(full, mlp)); + // the long-attention f32 score stream rides the full-attention layer's scratch window: 8 heads x rows x capacity + const stream = 4 * 8 * rows * state.max_capacity; + const worst = @max(linear, @max(full + stream, mlp)); try testing.expect(worst > 0); try testing.expectEqual(fwd.actKind(0), vk.tensor.Kind.f32); // the wide layers the buffers size for try testing.expectEqual(fwd.actKind(fwd.wide_layers), vk.tensor.Kind.bf16); // the first narrow layer diff --git a/zig/src/families/qwen3_5/backend/vulkan/forward.zig b/zig/src/families/qwen3_5/backend/vulkan/forward.zig index be354963c7b..b849ca10a74 100644 --- a/zig/src/families/qwen3_5/backend/vulkan/forward.zig +++ b/zig/src/families/qwen3_5/backend/vulkan/forward.zig @@ -99,7 +99,12 @@ pub const Core = struct { try vk.orExit(c.acc.attn.ropeQueries(c.cmds, queries, qn, rows, c.timeout_ns)); try vk.orExit(c.acc.attn.cacheKV(c.cmds, s.keysFor(slot), s.valuesFor(slot), kn, v, rows, base, s.capacity, c.timeout_ns)); const y = try c.scratch.alloc(act, q.elements); - try vk.orExit(c.acc.attn.attend(c.cmds, y, queries, s.keysFor(slot), s.valuesFor(slot), base, rows, s.capacity, c.timeout_ns)); + // Past the shared-memory stream cap, scores stage in an f32 scratch stream: 8 query heads x rows x total keys. + const stream: ?View = if (base + rows > vk.attention.shared_stream_keys) + try c.scratch.alloc(.f32, rows * pinned.query_heads * (base + rows)) + else + null; + try vk.orExit(c.acc.attn.attend(c.cmds, y, queries, s.keysFor(slot), s.valuesFor(slot), stream, base, rows, s.capacity, c.timeout_ns)); const mix = try c.scratch.alloc(act, rows * hidden); try vk.orExit(c.acc.attn.gateOutput(c.cmds, mix, y, qraw, rows, c.timeout_ns)); try c.project(r_out, mix, layer.o); diff --git a/zig/src/families/qwen3_5/backend/vulkan/state.zig b/zig/src/families/qwen3_5/backend/vulkan/state.zig index 45edb8c7a83..5695c380d86 100644 --- a/zig/src/families/qwen3_5/backend/vulkan/state.zig +++ b/zig/src/families/qwen3_5/backend/vulkan/state.zig @@ -15,8 +15,8 @@ pub const Error = vk.runtime.Error || error{ContextTooLong}; pub const full_layers: usize = pinned.layers / 4; pub const linear_layers: usize = pinned.layers - full_layers; -// SDPA shared memory admits visible prefixes up to 7168 keys. -pub const max_capacity: usize = 7168; +// The shared-memory stream serves visible prefixes to 7168 keys; the -DSTREAM_GLOBAL arm extends the cap to 8192. +pub const max_capacity: usize = 8192; pub const kv_heads: usize = pinned.kv_heads; // 2 pub const head_dim: usize = pinned.head_dim; // 256 diff --git a/zig/src/native/vulkan.zig b/zig/src/native/vulkan.zig index fa12ff8ccea..391047f0de0 100644 --- a/zig/src/native/vulkan.zig +++ b/zig/src/native/vulkan.zig @@ -108,10 +108,12 @@ fn bundle() fam.engine.ShaderBundle { .attention = .{ .rope_bf16 = &sh.rope_bf16, .sdpa_rows_bf16 = &sh.sdpa_rows_bf16, + .sdpa_rows_bf16_long = &sh.sdpa_rows_bf16_long, .gate_bf16 = &sh.gate_bf16, .rope_f32 = &sh.rope_f32, .rope_f32_kcache = &sh.rope_f32_kcache, .sdpa_rows_f32q = &sh.sdpa_rows_f32q, + .sdpa_rows_f32q_long = &sh.sdpa_rows_f32q_long, .gate_f32 = &sh.gate_f32, }, .gdn = .{ @@ -266,7 +268,7 @@ test "the pinned checkpoint's wide native window clamps by default, and an expli defer arena.deinit(); const a = arena.allocator(); var problem: []const u8 = ""; - // config.json names 262144 (the pinned checkpoint's): a default open serves the arm's 7168. + // config.json names 262144 (the pinned checkpoint's): a default open serves the arm's 8192. try std.testing.expectEqual(@as(usize, fam.backend.max_capacity), try contextFor(a, .{ .dir = "d", .model_type = "qwen3_5" }, 262144, &problem)); try std.testing.expectError(error.Refused, contextFor(a, .{ .dir = "d", .model_type = "qwen3_5", .context = 262144 }, 262144, &problem)); } diff --git a/zig/src/vulkan/attention.zig b/zig/src/vulkan/attention.zig index 401a75582f2..118ecfa9aa5 100644 --- a/zig/src/vulkan/attention.zig +++ b/zig/src/vulkan/attention.zig @@ -26,19 +26,22 @@ pub const rotary_pairs: u64 = 32; pub const theta: f32 = 1e7; /// head_dim^-1/2 as the oracle passes it: e.setValue(1.0 / 16.0, 3). pub const scale: f32 = 1.0 / 16.0; -// bf16 stages kStreamKeys f32 slots; long prefixes refuse, not truncate; p1/p2 is not wired. -pub const max_visible_keys: u64 = 7168; -/// s_qrow (256) + s_stream (7168) + s_tree (256) f32 words. +// Totals past shared_stream_keys run the -DSTREAM_GLOBAL images with the f32 score stream; never truncate. +pub const max_visible_keys: u64 = 8192; +/// kStreamKeys: s_qrow (256) + s_stream (7168) + s_tree (256) fit shared memory; the stream arm stages scores past it. +pub const shared_stream_keys: u64 = 7168; const sdpa_shared_bytes: u64 = 30720; // The compiled shader images Attention runs; every field is a real SPIR-V image of the named variant. pub const Shaders = struct { rope_bf16: []align(4) const u8, sdpa_rows_bf16: []align(4) const u8, + sdpa_rows_bf16_long: []align(4) const u8, gate_bf16: []align(4) const u8, rope_f32: []align(4) const u8, rope_f32_kcache: []align(4) const u8, sdpa_rows_f32q: []align(4) const u8, + sdpa_rows_f32q_long: []align(4) const u8, gate_f32: []align(4) const u8, }; @@ -59,10 +62,12 @@ pub const Attention = struct { ops: *Ops, rope_bf16: dispatch.Pipeline, sdpa_bf16: dispatch.Pipeline, + sdpa_bf16_long: dispatch.Pipeline, gate_bf16: dispatch.Pipeline, rope_f32: dispatch.Pipeline, rope_f32_kcache: dispatch.Pipeline, sdpa_f32q: dispatch.Pipeline, + sdpa_f32q_long: dispatch.Pipeline, gate_f32: dispatch.Pipeline, // The i32 base position is read by each rope dispatch; setBasePosition writes it between operations. offsets: Buffer, @@ -76,10 +81,12 @@ pub const Attention = struct { .ops = ops, .rope_bf16 = undefined, .sdpa_bf16 = undefined, + .sdpa_bf16_long = undefined, .gate_bf16 = undefined, .rope_f32 = undefined, .rope_f32_kcache = undefined, .sdpa_f32q = undefined, + .sdpa_f32q_long = undefined, .gate_f32 = undefined, .offsets = try Buffer.init(dev, .device, 4), }; @@ -89,6 +96,8 @@ pub const Attention = struct { errdefer a.rope_bf16.deinit(); a.sdpa_bf16 = try dispatch.Pipeline.init(dev, shaders.sdpa_rows_bf16, .{ .bindings = 4, .push_bytes = params.push_bytes, .writes = 1 << 3 }); errdefer a.sdpa_bf16.deinit(); + a.sdpa_bf16_long = try dispatch.Pipeline.init(dev, shaders.sdpa_rows_bf16_long, .{ .bindings = 5, .push_bytes = params.push_bytes, .writes = (1 << 3) | (1 << 4) }); + errdefer a.sdpa_bf16_long.deinit(); a.gate_bf16 = try dispatch.Pipeline.init(dev, shaders.gate_bf16, .{ .bindings = 3, .push_bytes = gate_push_bytes, .writes = 1 << 2 }); errdefer a.gate_bf16.deinit(); a.rope_f32 = try dispatch.Pipeline.init(dev, shaders.rope_f32, .{ .bindings = 3, .push_bytes = params.push_bytes, .writes = 1 << 1 }); @@ -97,6 +106,8 @@ pub const Attention = struct { errdefer a.rope_f32_kcache.deinit(); a.sdpa_f32q = try dispatch.Pipeline.init(dev, shaders.sdpa_rows_f32q, .{ .bindings = 4, .push_bytes = params.push_bytes, .writes = 1 << 3 }); errdefer a.sdpa_f32q.deinit(); + a.sdpa_f32q_long = try dispatch.Pipeline.init(dev, shaders.sdpa_rows_f32q_long, .{ .bindings = 5, .push_bytes = params.push_bytes, .writes = (1 << 3) | (1 << 4) }); + errdefer a.sdpa_f32q_long.deinit(); a.gate_f32 = try dispatch.Pipeline.init(dev, shaders.gate_f32, .{ .bindings = 3, .push_bytes = gate_push_bytes, .writes = 1 << 2 }); return a; } @@ -105,10 +116,12 @@ pub const Attention = struct { pub fn deinit(a: *Attention) void { a.rope_bf16.deinit(); a.sdpa_bf16.deinit(); + a.sdpa_bf16_long.deinit(); a.gate_bf16.deinit(); a.rope_f32.deinit(); a.rope_f32_kcache.deinit(); a.sdpa_f32q.deinit(); + a.sdpa_f32q_long.deinit(); a.gate_f32.deinit(); a.offsets.deinit(); } @@ -169,13 +182,21 @@ pub const Attention = struct { try vpipe.run(cmds, std.mem.asBytes(&p), try groups(copy.elements, vpipe.local[0], a.dev.properties.limits.maxComputeWorkGroupCount[0]), timeout_ns); } - // SDPA scales q once, streams f32 scores; Metal scales per-score in 128-key chunks. No bit-exact/performance claim. - pub fn attend(a: *Attention, cmds: *Commands, y: View, queries: View, cache_keys: View, cache_values: View, prefix: u64, rows: u64, capacity: u64, timeout_ns: u64) Error!void { - const plan = try attendPlan(prefix, rows, capacity, queries.elements, y.elements, cache_keys.elements, cache_values.elements); + // q scales once (Metal: per-score chunks, not bit-exact); past shared_stream_keys, f32 scores stage in the stream. + pub fn attend(a: *Attention, cmds: *Commands, y: View, queries: View, cache_keys: View, cache_values: View, stream: ?View, prefix: u64, rows: u64, capacity: u64, timeout_ns: u64) Error!void { + const plan = try attendPlan(prefix, rows, capacity, queries.elements, y.elements, cache_keys.elements, cache_values.elements, if (stream) |s| s.elements else 0); try attendKinds(y, queries, cache_keys, cache_values); if (y.overlaps(queries) or y.overlaps(cache_keys) or y.overlaps(cache_values)) return error.Aliased; - const pipe = if (queries.kind == .f32) &a.sdpa_f32q else &a.sdpa_bf16; - try pipe.bind(&.{ queries.bind(), cache_keys.bind(), cache_values.bind(), y.bind() }); + const long = plan.total_keys > shared_stream_keys; + var bindings: [5]dispatch.Binding = .{ queries.bind(), cache_keys.bind(), cache_values.bind(), y.bind(), undefined }; + const pipe = if (long) blk: { + const s = stream orelse return error.Invalid; + if (s.kind != .f32) return error.Invalid; + if (s.overlaps(y) or s.overlaps(queries) or s.overlaps(cache_keys) or s.overlaps(cache_values)) return error.Aliased; + bindings[4] = s.bind(); + break :blk if (queries.kind == .f32) &a.sdpa_f32q_long else &a.sdpa_bf16_long; + } else if (queries.kind == .f32) &a.sdpa_f32q else &a.sdpa_bf16; + try pipe.bind(if (long) bindings[0..5] else bindings[0..4]); var p: params.Params = .{ .matrix_m = @intCast(query_heads), // repeats = 8/2 = 4 .matrix_n = @intCast(kv_heads), @@ -278,7 +299,7 @@ pub fn vCopyPlan(rows: u64, capacity: u64, v_elements: u64) Error!VCopyPlan { // Causal SDPA row r sees prefix+r+1 keys, including its own; later keys are unread. Pure and host-tested. pub const AttendPlan = struct { rows: u32, total_keys: u32 }; -pub fn attendPlan(prefix: u64, rows: u64, capacity: u64, q_elements: u64, y_elements: u64, k_elements: u64, v_elements: u64) Error!AttendPlan { +pub fn attendPlan(prefix: u64, rows: u64, capacity: u64, q_elements: u64, y_elements: u64, k_elements: u64, v_elements: u64, stream_elements: u64) Error!AttendPlan { if (rows == 0 or rows > std.math.maxInt(u32)) return error.Invalid; const total = std.math.add(u64, prefix, rows) catch return error.TooLarge; if (capacity == 0 or total > capacity) return error.OutOfRange; @@ -288,6 +309,7 @@ pub fn attendPlan(prefix: u64, rows: u64, capacity: u64, q_elements: u64, y_elem const cache_elems = kv_heads *| capacity *| head_dim; if (k_elements != cache_elems or v_elements != cache_elems) return error.Invalid; if (capacity *| head_dim > std.math.maxInt(u32)) return error.TooLarge; + if (total > shared_stream_keys and stream_elements < rows *| query_heads *| total) return error.Invalid; return .{ .rows = @intCast(rows), .total_keys = try ops_mod.cast32(total) }; } @@ -334,14 +356,19 @@ test "ropePlan derives the word count and refuses torn or foreign shapes" { test "attendPlan keeps the causal prefix and refuses long or torn contexts" { // rows > 1: each row's visible count is prefix + row + 1. - const plan = try attendPlan(100, 3, 128, 3 * 8 * 256, 3 * 8 * 256, 2 * 128 * 256, 2 * 128 * 256); + const plan = try attendPlan(100, 3, 128, 3 * 8 * 256, 3 * 8 * 256, 2 * 128 * 256, 2 * 128 * 256, 0); try testing.expectEqual(@as(u32, 103), plan.total_keys); try testing.expectEqual(@as(u32, 3), plan.rows); - try testing.expectError(error.OutOfRange, attendPlan(126, 3, 128, 3 * 2048, 3 * 2048, 2 * 128 * 256, 2 * 128 * 256)); - try testing.expectError(error.ContextTooLong, attendPlan(max_visible_keys, 1, max_visible_keys + 1, 2048, 2048, 2 * (max_visible_keys + 1) * 256, 2 * (max_visible_keys + 1) * 256)); - try testing.expectError(error.Invalid, attendPlan(0, 3, 128, 2 * 2048, 3 * 2048, 2 * 128 * 256, 2 * 128 * 256)); - try testing.expectError(error.Invalid, attendPlan(0, 3, 128, 3 * 2048, 3 * 2048, 2 * 127 * 256, 2 * 128 * 256)); - try testing.expectError(error.TooLarge, attendPlan(0, 1, 1 << 25, 2048, 2048, 2 * (1 << 25) * 256, 2 * (1 << 25) * 256)); + try testing.expectError(error.OutOfRange, attendPlan(126, 3, 128, 3 * 2048, 3 * 2048, 2 * 128 * 256, 2 * 128 * 256, 0)); + try testing.expectError(error.ContextTooLong, attendPlan(max_visible_keys, 1, max_visible_keys + 1, 2048, 2048, 2 * (max_visible_keys + 1) * 256, 2 * (max_visible_keys + 1) * 256, 0)); + try testing.expectError(error.Invalid, attendPlan(0, 3, 128, 2 * 2048, 3 * 2048, 2 * 128 * 256, 2 * 128 * 256, 0)); + try testing.expectError(error.Invalid, attendPlan(0, 3, 128, 3 * 2048, 3 * 2048, 2 * 127 * 256, 2 * 128 * 256, 0)); + try testing.expectError(error.TooLarge, attendPlan(0, 1, 1 << 25, 2048, 2048, 2 * (1 << 25) * 256, 2 * (1 << 25) * 256, 0)); + // Past the shared stream the f32 stream view must cover 8 * rows * total keys. + try testing.expectEqual(@as(u32, 7169), (try attendPlan(7168, 1, 8192, 2048, 2048, 2 * 8192 * 256, 2 * 8192 * 256, 8 * 7169)).total_keys); + try testing.expectError(error.Invalid, attendPlan(7168, 1, 8192, 2048, 2048, 2 * 8192 * 256, 2 * 8192 * 256, 8 * 7169 - 1)); + try testing.expectEqual(@as(u32, 8192), (try attendPlan(8191, 1, 8192, 2048, 2048, 2 * 8192 * 256, 2 * 8192 * 256, 8 * 8192)).total_keys); + try testing.expectError(error.ContextTooLong, attendPlan(max_visible_keys, 2, max_visible_keys + 2, 2 * 2048, 2 * 2048, 2 * (max_visible_keys + 2) * 256, 2 * (max_visible_keys + 2) * 256, 8 * 2 * (max_visible_keys + 2))); } test "vCopyPlan refuses rows past capacity and caches past u32 offsets" { diff --git a/zig/tests/vulkan/contract_attention.zig b/zig/tests/vulkan/contract_attention.zig index b2d006ea288..a23d9cd5c66 100644 --- a/zig/tests/vulkan/contract_attention.zig +++ b/zig/tests/vulkan/contract_attention.zig @@ -1,4 +1,4 @@ -// Host-only rope/SDPA contract vs f64; fixture caps at 8 keys; shader SDPA uses 256 lanes and 7168-key limit. +// Host-only rope/SDPA contract vs f64; fixture caps at 8 keys; shader SDPA uses 256 lanes and the 8192-key ceiling. const std = @import("std"); const contract = @import("contract"); const c = contract.spec; @@ -13,7 +13,8 @@ pub const tree_levels: u64 = 8; // log2(lanes) binary-tree levels pub const dot_terms: u64 = fx.head_dim; // 256 ascending-d score FMAs pub const key_tile: u64 = 16; // 16-key output tiles / load batches pub const key_stride: u64 = 1024; // threads striding the score scan -pub const max_visible_keys: u64 = 7168; // kStreamKeys: the shared-memory stream +pub const max_visible_keys: u64 = 8192; // the arm's ceiling: attendPlan refuses past it +pub const shared_stream_keys: u64 = 7168; // kStreamKeys: the shared-memory stream; totals past it ride the f32 stream // For n keys, denominator depth is ceil(n/256)+8: 256 lanes, 8 tree levels, and 36 at n=7168. pub fn softmaxDepth(n: u64) u64 { @@ -76,7 +77,7 @@ pub fn visibleKeys(case: SdpaCase, r: u64) u64 { return case.prefix + r + 1; } -// Cases test n=1,15/16/17,255/256/257,1023/1024/1025,7167/7168 and rows 17/64 at 1024/7168 limits. +// Cases test n=1,15/16/17,255/256/257,1023/1024/1025,7167/7168,7169/8192 and rows 17/32/64 at 1024/7168/8192 limits. pub const served_cases = [_]SdpaCase{ .{ .name = "decode n=1", .rows = 1, .prefix = 0 }, .{ .name = "decode n=16 tile", .rows = 1, .prefix = 15 }, @@ -88,9 +89,12 @@ pub const served_cases = [_]SdpaCase{ .{ .name = "decode n=1025 stride+1", .rows = 1, .prefix = 1024 }, .{ .name = "decode n=7167 stream-1", .rows = 1, .prefix = 7166 }, .{ .name = "decode n=7168 stream", .rows = 1, .prefix = 7167 }, + .{ .name = "decode n=7169 long stream", .rows = 1, .prefix = 7168 }, + .{ .name = "decode n=8192 long stream", .rows = 1, .prefix = 8191 }, .{ .name = "prefill rows64 n1..64", .rows = 64, .prefix = 0 }, .{ .name = "prefill rows17 across 1024", .rows = 17, .prefix = 1007 }, .{ .name = "prefill rows64 to 7168", .rows = 64, .prefix = 7104 }, + .{ .name = "prefill rows64 to 8192", .rows = 64, .prefix = 8128 }, }; // Attend f64 dots/max/softmax/output for n=prefix+r+1 in (kv_head,capacity,head_dim); matches fx.Attend.init order. @@ -108,7 +112,7 @@ pub fn attendRef( const row_elems: usize = @intCast(fx.heads * fx.head_dim); const cap: usize = @intCast(capacity); const kh_span: usize = @intCast(fx.heads / fx.kv_heads); // repeats: 8/2 - // Per-(row, head) score scratch; capacity <= 7168 (attendPlan's bound). + // Per-(row, head) score scratch; capacity <= 8192 (attendPlan's bound). const scores = try a.alloc(f64, cap); defer a.free(scores); for (0..@intCast(case.rows)) |r| { @@ -297,7 +301,8 @@ test "softmax depth is the shader's chain plus tree, never the plain key sum" { try testing.expectEqual(@as(u64, 12), softmaxDepth(1024)); try testing.expectEqual(@as(u64, 13), softmaxDepth(1025)); try testing.expectEqual(@as(u64, 36), softmaxDepth(7168)); - // The point of the derivation: 36, not 7168. + try testing.expectEqual(@as(u64, 40), softmaxDepth(8192)); + // The point of the derivation: 40, not 8192. try testing.expect(softmaxDepth(max_visible_keys) < max_visible_keys / 100); } @@ -307,7 +312,8 @@ test "sdpaBound covers a planted wrong finite and grows with the honest depths" try testing.expect(b1 > 0); try testing.expect(sdpaBound(257, m, 1) > sdpaBound(256, m, 1)); // chain edge try testing.expect(sdpaBound(7168, m, 1) > sdpaBound(1025, m, 1)); // output depth - try testing.expect(sdpaBound(7168, m, 1) < 1 << 20); // 2^31 plants are refused + try testing.expect(sdpaBound(8192, m, 1) > sdpaBound(7168, m, 1)); // output depth at the ceiling + try testing.expect(sdpaBound(8192, m, 1) < 1 << 20); // 2^31 plants are refused try testing.expect(sdpaBound(1, .{}, 0) > 0); // finite on zeros } @@ -345,12 +351,12 @@ test "served cases stay inside the engine's shapes and hit every reduction edge" for (served_cases) |case| { try testing.expect(case.rows == 1 or case.rows <= 64); // decode rows 1, prefill <= max_prefill_rows (64) const capacity = capacityOf(case); - try testing.expect(capacity <= max_visible_keys); // kStreamKeys + try testing.expect(capacity <= max_visible_keys); // the arm's ceiling try testing.expectEqual(visibleKeys(case, case.rows - 1), capacity); // exact fit try testing.expect(visibleKeys(case, 0) >= 1); } // The named edges all appear as some decode case's single-row count. - const decode_edges = [_]u64{ 1, 16, 17, 256, 257, 1024, 1025, 7168 }; + const decode_edges = [_]u64{ 1, 16, 17, 256, 257, 1024, 1025, 7168, 7169, 8192 }; for (decode_edges) |n| { var found = false; for (served_cases) |case| { @@ -358,9 +364,14 @@ test "served cases stay inside the engine's shapes and hit every reduction edge" } try testing.expect(found); // every claimed edge is actually served } - // Multi-row prefill crosses the 1024 stride and fills 7168. - try testing.expect(served_cases[11].prefix < key_stride and capacityOf(served_cases[11]) >= key_stride); + // Multi-row prefill crosses the 1024 stride and fills 7168 and 8192. + try testing.expect(served_cases[13].prefix < key_stride and capacityOf(served_cases[13]) >= key_stride); try testing.expectEqual(max_visible_keys, capacityOf(served_cases[served_cases.len - 1])); + var long_count: usize = 0; + for (served_cases) |case| { + if (capacityOf(case) > shared_stream_keys) long_count += 1; + } + try testing.expectEqual(@as(usize, 3), long_count); // the 7169/8192 decodes and the row-64 prefill to 8192 ride the long arm } test "sdpa checkers accept the honest bf16 output and refuse planted ones" { @@ -428,4 +439,10 @@ test "depth derivation is pinned to the shader source this contract reads" { try testing.expect(std.mem.indexOf(u8, src, "params.matrix_k - params.dims + row + 1u") != null); // The shared-memory bound that caps the served context. try testing.expect(std.mem.indexOf(u8, src, "kStreamKeys = 7168u") != null); + // The long arm: binding 4 replaces the shared stream, one total_keys region per workgroup. + try testing.expect(std.mem.indexOf(u8, src, "#define STREAM(i) s_stream[i]") != null); + try testing.expect(std.mem.indexOf(u8, src, "#define STREAM(i) stream_data.values[stream_base + i]") != null); + try testing.expect(std.mem.indexOf(u8, src, "coherent buffer Stream") != null); + try testing.expect(std.mem.indexOf(u8, src, "gl_WorkGroupID.y * gl_NumWorkGroups.x + gl_WorkGroupID.x") != null); + try testing.expect(std.mem.indexOf(u8, src, "memoryBarrierBuffer()") != null); } diff --git a/zig/tests/vulkan/contract_attention_main.zig b/zig/tests/vulkan/contract_attention_main.zig index fa71fe6a173..f605340bc40 100644 --- a/zig/tests/vulkan/contract_attention_main.zig +++ b/zig/tests/vulkan/contract_attention_main.zig @@ -1,4 +1,4 @@ -// The attention gate checks rope_bf16, sdpa_rows_bf16 and sdpa_rows_f32q: decode=1, prefill<=64, keys=1..7168. +// Attention gate checks rope_bf16 + sdpa_rows_{bf16,f32q}(+_long): decode=1, prefill<=64, keys<=8192; exit 0/1/2/124. const std = @import("std"); const vk = @import("vulkan"); const shaders = @import("stage3_shaders"); @@ -26,7 +26,7 @@ const Elapsed = struct { const repeats = 3; // Large FINITE bf16 planted over non-visible keys: an uncausal read turns the output huge and fails every check. const finite_poison: u16 = 0x7f7f; -/// 1 MiB: the 7168-key cache buffers (7.3 MB each) upload in few chunks. +/// 1 MiB: the 8192-key cache buffers (8.4 MB each) upload in few chunks. const staging_bytes = 1 << 20; pub fn main(init: std.process.Init) !u8 { @@ -100,10 +100,12 @@ fn probe(a: std.mem.Allocator, clock: Elapsed, vendor: ?u32, timeout: u64) !bool var attn = try vk.Attention.init(&dev, .{ .rope_bf16 = &shaders.rope_bf16, .sdpa_rows_bf16 = &shaders.sdpa_rows_bf16, + .sdpa_rows_bf16_long = &shaders.sdpa_rows_bf16_long, .gate_bf16 = &shaders.gate_bf16, .rope_f32 = &shaders.rope_f32, .rope_f32_kcache = &shaders.rope_f32_kcache, .sdpa_rows_f32q = &shaders.sdpa_rows_f32q, + .sdpa_rows_f32q_long = &shaders.sdpa_rows_f32q_long, .gate_f32 = &shaders.gate_f32, }, &ops); defer attn.deinit(); @@ -344,6 +346,18 @@ fn sdpaGate(a: std.mem.Allocator, clock: Elapsed, dev: *const vk.Device, cmds: * defer keys.deinit(); var values = try upload16(dev, cmds, staging, f.v_bits, timeout); defer values.deinit(); + // Long cases stage scores in an f32 stream: 8 heads x rows x keys words, zero-filled once (write-before-read). + const total_keys = ca.capacityOf(case); + var stream_buf: ?vk.Buffer = null; + defer if (stream_buf) |*b| b.deinit(); + const stream_words: u64 = fx.heads * case.rows * total_keys; + if (total_keys > ca.shared_stream_keys) { + const zeros = try a.alloc(u32, @intCast(stream_words)); + defer a.free(zeros); + @memset(zeros, 0); + stream_buf = try upload32(dev, cmds, staging, zeros, timeout); + } + const stream_view: ?vk.tensor.View = if (stream_buf) |*b| try vk.tensor.View.init(b, .f32, 0, stream_words) else null; // Poison every output word so missing writes cannot inherit a reference. const out_len: usize = @intCast(case.rows * row_elems); const out_shell = try a.alloc(u16, out_len + fx.tail); @@ -362,7 +376,7 @@ fn sdpaGate(a: std.mem.Allocator, clock: Elapsed, dev: *const vk.Device, cmds: * const bits = full_bits[0..out_len]; for (0..repeats) |rep| { try vk.orExit(vk.upload(cmds, out, 0, staging, std.mem.sliceAsBytes(out_shell), timeout)); - try vk.orExit(attn.attend(cmds, y_view, q_view, keys_view, values_view, case.prefix, case.rows, f.capacity, timeout)); + try vk.orExit(attn.attend(cmds, y_view, q_view, keys_view, values_view, stream_view, case.prefix, case.rows, f.capacity, timeout)); try fetch(cmds, staging, out, std.mem.sliceAsBytes(full_bits), timeout); for (full_bits[out_len..]) |g_elem| { if (g_elem != fx.poison16) { @@ -410,8 +424,11 @@ fn sdpaGate(a: std.mem.Allocator, clock: Elapsed, dev: *const vk.Device, cmds: * defer a.free(one_bits); for (0..@intCast(case.rows)) |r| { const q_row = try q_view.slice(@intCast(r * row_elems), @intCast(row_elems)); + // A row decoded alone gets its own total; long totals slice the front of the same stream buffer. + const row_total = case.prefix + @as(u64, r) + 1; + const row_stream: ?vk.tensor.View = if (row_total > ca.shared_stream_keys) try stream_view.?.slice(0, fx.heads * row_total) else null; try vk.orExit(vk.upload(cmds, one, 0, staging, std.mem.sliceAsBytes(one_shell), timeout)); - try vk.orExit(attn.attend(cmds, one_view, q_row, keys_view, values_view, case.prefix + @as(u64, r), 1, f.capacity, timeout)); + try vk.orExit(attn.attend(cmds, one_view, q_row, keys_view, values_view, row_stream, case.prefix + @as(u64, r), 1, f.capacity, timeout)); try fetch(cmds, staging, one, std.mem.sliceAsBytes(one_bits), timeout); if (std.mem.indexOfDiff(u16, one_bits, bits[@intCast(r * row_elems)..][0..one_len])) |at| { std.debug.print("FAIL sdpa case=\"{s}\": row {d} decoded alone differs at element {d}\n", .{ case.name, r, at }); @@ -441,6 +458,18 @@ fn sdpaF32Gate(a: std.mem.Allocator, clock: Elapsed, dev: *const vk.Device, cmds defer keys.deinit(); var values = try upload16(dev, cmds, staging, f.v_bits, timeout); defer values.deinit(); + // Long cases stage scores in an f32 stream: 8 heads x rows x keys words, zero-filled once (write-before-read). + const total_keys = ca.capacityOf(case); + var stream_buf: ?vk.Buffer = null; + defer if (stream_buf) |*b| b.deinit(); + const stream_words: u64 = fx.heads * case.rows * total_keys; + if (total_keys > ca.shared_stream_keys) { + const zeros = try a.alloc(u32, @intCast(stream_words)); + defer a.free(zeros); + @memset(zeros, 0); + stream_buf = try upload32(dev, cmds, staging, zeros, timeout); + } + const stream_view: ?vk.tensor.View = if (stream_buf) |*b| try vk.tensor.View.init(b, .f32, 0, stream_words) else null; const out_len: usize = @intCast(case.rows * row_elems); const out_shell = try a.alloc(u32, out_len + fx.tail); defer a.free(out_shell); @@ -458,7 +487,7 @@ fn sdpaF32Gate(a: std.mem.Allocator, clock: Elapsed, dev: *const vk.Device, cmds const bits = full_bits[0..out_len]; for (0..repeats) |rep| { try vk.orExit(vk.upload(cmds, out, 0, staging, std.mem.sliceAsBytes(out_shell), timeout)); - try vk.orExit(attn.attend(cmds, y_view, q_view, keys_view, values_view, case.prefix, case.rows, f.capacity, timeout)); + try vk.orExit(attn.attend(cmds, y_view, q_view, keys_view, values_view, stream_view, case.prefix, case.rows, f.capacity, timeout)); try fetch(cmds, staging, out, std.mem.sliceAsBytes(full_bits), timeout); for (full_bits[out_len..]) |g_elem| { if (g_elem != poison32) { @@ -505,8 +534,11 @@ fn sdpaF32Gate(a: std.mem.Allocator, clock: Elapsed, dev: *const vk.Device, cmds defer a.free(one_bits); for (0..@intCast(case.rows)) |r| { const q_row = try q_view.slice(@intCast(r * row_elems), @intCast(row_elems)); + // A row decoded alone gets its own total; long totals slice the front of the same stream buffer. + const row_total = case.prefix + @as(u64, r) + 1; + const row_stream: ?vk.tensor.View = if (row_total > ca.shared_stream_keys) try stream_view.?.slice(0, fx.heads * row_total) else null; try vk.orExit(vk.upload(cmds, one, 0, staging, std.mem.sliceAsBytes(one_shell), timeout)); - try vk.orExit(attn.attend(cmds, one_view, q_row, keys_view, values_view, case.prefix + @as(u64, r), 1, f.capacity, timeout)); + try vk.orExit(attn.attend(cmds, one_view, q_row, keys_view, values_view, row_stream, case.prefix + @as(u64, r), 1, f.capacity, timeout)); try fetch(cmds, staging, one, std.mem.sliceAsBytes(one_bits), timeout); if (std.mem.indexOfDiff(u32, one_bits, bits[@intCast(r * row_elems)..][0..one_len])) |at| { std.debug.print("FAIL sdpa_f32q case=\"{s}\": row {d} decoded alone differs at element {d}\n", .{ case.name, r, at }); diff --git a/zig/tests/vulkan/qwen35_model_probe.zig b/zig/tests/vulkan/qwen35_model_probe.zig index 05d317dc261..af225071e22 100644 --- a/zig/tests/vulkan/qwen35_model_probe.zig +++ b/zig/tests/vulkan/qwen35_model_probe.zig @@ -1,4 +1,4 @@ -// Qwen3.5-2B: context 1-7168 (256 default); 2 exact-ID runs, lowest ties; exits 0/1/2/124; teacher-forced per-step. +// Qwen3.5-2B: context 1-8192 (256 default); 2 exact-ID runs, lowest ties; exits 0/1/2/124; teacher-forced per-step. const std = @import("std"); const q35v = @import("qwen35_vulkan"); const engine_mod = q35v.engine; @@ -18,7 +18,7 @@ const usage = "usage: tf-qwen35-model [--vendor ID] [--timeout-ms MS] [--context " --help show this text and exit without opening a loader or device\n" ++ " --vendor ID refuse a device whose Vulkan vendorID differs (decimal or 0x hex; no default)\n" ++ " --timeout-ms MS bound on every fence wait, 1 to 300000 (default 10000); a timeout ends the process\n" ++ - " --context N KV context capacity to request, 1 to 7168 (default 256)\n" ++ + " --context N KV context capacity to request, 1 to 8192 (default 256)\n" ++ " --teacher-forced feed each scored step's oracle id as the next input (labelled per-step mode; default off)\n" ++ " --sequential-prefill prefill one prompt token per Engine.prefill call (test-only; default is the canonical whole-prompt 64-row chunking)\n"; @@ -232,10 +232,12 @@ fn bundle() engine_mod.ShaderBundle { .attention = .{ .rope_bf16 = &q35s.rope_bf16, .sdpa_rows_bf16 = &q35s.sdpa_rows_bf16, + .sdpa_rows_bf16_long = &q35s.sdpa_rows_bf16_long, .gate_bf16 = &q35s.gate_bf16, .rope_f32 = &q35s.rope_f32, .rope_f32_kcache = &q35s.rope_f32_kcache, .sdpa_rows_f32q = &q35s.sdpa_rows_f32q, + .sdpa_rows_f32q_long = &q35s.sdpa_rows_f32q_long, .gate_f32 = &q35s.gate_f32, }, .gdn = .{ @@ -511,15 +513,15 @@ test "parseArgs context and mode flags keep the anchor default and bound the con try testing.expect(!plain.teacher_forced); try testing.expect(!plain.sequential_prefill); - // the boundary sizes the corpus runs: 33, 65, 7105 all parse - for ([_][]const u8{ "33", "65", "7105", "7168" }) |n| { + // the boundary sizes the corpus runs: 33, 65, 8129 all parse + for ([_][]const u8{ "33", "65", "8129", "8192" }) |n| { const o = parseArgs(&.{ "--context", n, "--teacher-forced", "--sequential-prefill", "/m", "/i", "/o", "/out" }).?; try testing.expect(o.teacher_forced); try testing.expect(o.sequential_prefill); } // one past the backend's capacity is refused at the CLI, no device - try testing.expectEqual(@as(usize, 7168), q35v.backend.max_capacity); - try testing.expect(parseArgs(&.{ "--context", "7169", "/m", "/i", "/o", "/out" }) == null); + try testing.expectEqual(@as(usize, 8192), q35v.backend.max_capacity); + try testing.expect(parseArgs(&.{ "--context", "8193", "/m", "/i", "/o", "/out" }) == null); try testing.expect(parseArgs(&.{ "--context", "0", "/m", "/i", "/o", "/out" }) == null); try testing.expect(parseArgs(&.{ "--context", "-1", "/m", "/i", "/o", "/out" }) == null); try testing.expect(parseArgs(&.{ "--context", "abc", "/m", "/i", "/o", "/out" }) == null); @@ -534,7 +536,7 @@ test "chunkCount spans the canonical 64-row chunks without a configurable size" try testing.expectEqual(@as(usize, 2), chunkCount(65)); // boundary: two chunks try testing.expectEqual(@as(usize, 2), chunkCount(128)); try testing.expectEqual(@as(usize, 3), chunkCount(129)); // boundary: three chunks - try testing.expectEqual(@as(usize, 112), chunkCount(7168)); // full context + try testing.expectEqual(@as(usize, 128), chunkCount(8192)); // full context } test "parseNpy takes exactly a v1 LE u32 rank-1 array" { diff --git a/zig/tests/vulkan/stage3_probe.zig b/zig/tests/vulkan/stage3_probe.zig index 80cc695e33c..73c093084c0 100644 --- a/zig/tests/vulkan/stage3_probe.zig +++ b/zig/tests/vulkan/stage3_probe.zig @@ -96,10 +96,12 @@ fn probe(a: std.mem.Allocator, clock: Elapsed, vendor: ?u32, timeout: u64) !bool var attn = try vk.Attention.init(&dev, .{ .rope_bf16 = &shaders.rope_bf16, .sdpa_rows_bf16 = &shaders.sdpa_rows_bf16, + .sdpa_rows_bf16_long = &shaders.sdpa_rows_bf16_long, .gate_bf16 = &shaders.gate_bf16, .rope_f32 = &shaders.rope_f32, .rope_f32_kcache = &shaders.rope_f32_kcache, .sdpa_rows_f32q = &shaders.sdpa_rows_f32q, + .sdpa_rows_f32q_long = &shaders.sdpa_rows_f32q_long, .gate_f32 = &shaders.gate_f32, }, &ops); defer attn.deinit(); @@ -315,7 +317,7 @@ fn attendGate(a: std.mem.Allocator, clock: Elapsed, dev: *const vk.Device, cmds: for (0..repeats) |rep| { try vk.orExit(vk.upload(cmds, ybuf, 0, staging, std.mem.sliceAsBytes(y_init), timeout)); - try vk.orExit(attn.attend(cmds, y_view, rotated_view, keys_view, values_view, ac.prefix, rows, cc.capacity, timeout)); + try vk.orExit(attn.attend(cmds, y_view, rotated_view, keys_view, values_view, null, ac.prefix, rows, cc.capacity, timeout)); try fetch(cmds, staging, ybuf, std.mem.sliceAsBytes(ybits), timeout); if (first) |x| { if (std.mem.indexOfDiff(u16, x, ybits)) |at| { @@ -354,7 +356,7 @@ fn attendGate(a: std.mem.Allocator, clock: Elapsed, dev: *const vk.Device, cmds: const q_row_view = try vk.tensor.View.init(&rotated, .bf16, row_byte_offset, qrow_elems); const y_row_view = try vk.tensor.View.init(&ybuf, .bf16, row_byte_offset, qrow_elems); try vk.orExit(vk.upload(cmds, ybuf, 0, staging, std.mem.sliceAsBytes(y_init), timeout)); - try vk.orExit(attn.attend(cmds, y_row_view, q_row_view, alt_view, values_view, ac.prefix + @as(u64, @intCast(r)), 1, cc.capacity, timeout)); + try vk.orExit(attn.attend(cmds, y_row_view, q_row_view, alt_view, values_view, null, ac.prefix + @as(u64, @intCast(r)), 1, cc.capacity, timeout)); try vk.orExit(vk.download(cmds, ybuf, row_byte_offset, staging, std.mem.sliceAsBytes(y_row_bits), timeout)); const baseline_row = first.?[r * @as(usize, @intCast(qrow_elems)) ..][0..@intCast(qrow_elems)]; if (std.mem.indexOfDiff(u16, baseline_row, y_row_bits)) |at| {