Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions zig/build/vulkan.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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").*;
;

Expand Down
37 changes: 32 additions & 5 deletions zig/kernels/vulkan/sdpa_decode_native.comp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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];

Expand All @@ -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];
Expand All @@ -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) {
Expand All @@ -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) {
Expand All @@ -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;
Expand Down
14 changes: 7 additions & 7 deletions zig/src/families/qwen3_5/backend/vulkan/backend.zig
Original file line number Diff line number Diff line change
Expand Up @@ -213,24 +213,24 @@ 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]));
}
}

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));
Expand Down
26 changes: 14 additions & 12 deletions zig/src/families/qwen3_5/backend/vulkan/engine.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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 ||
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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" {
Expand All @@ -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
Expand Down
7 changes: 6 additions & 1 deletion zig/src/families/qwen3_5/backend/vulkan/forward.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
4 changes: 2 additions & 2 deletions zig/src/families/qwen3_5/backend/vulkan/state.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion zig/src/native/vulkan.zig
Original file line number Diff line number Diff line change
Expand Up @@ -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 = .{
Expand Down Expand Up @@ -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));
}
Expand Down
Loading
Loading