Skip to content
Open
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
6 changes: 6 additions & 0 deletions docs/vulkan-shader-specs/spec-core-attn-gdn-17.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,12 @@
- Passthrough tail: copy `in[in_base + d]` -> `out[out_base + d]` bit-exact when BF16->BF16 or F32->F32, and RNE `f32_to_bf16` when F32->BF16 (`rope_f32_kcache`).

### 3.3 `sdpa_decode_native.comp`
- BF16 chunks of 2..64 rows may use `sdpa_prefill_tile.comp`: shared scores, in-place exponentials plus stats, then shared V.
- The tile keeps the fused 256-lane softmax tree and 16-key output partials, including the scalar tail and finite single-key transport.
- FP32 queries always retain the fused shared/global routes; future keys never participate in an earlier row's products.
- `GLOBAL_SCORES` variants extend admission to 8192 using an explicit coherent F32 workspace at binding 4.
- Workspace regions are disjoint `(row * 8 + head) * total_keys` spans; both write/read transitions fence buffer memory.
- Shared variants retain the 7168-key cap; both variants keep main's unnormalized exponentials, 16-key partials and final division.
- **Variants**:
- `sdpa_rows_bf16`: `-DBF16_IO -DSDPA_DIM=256 -DSDPA_ROWS` (Q/K/V/Out all BF16)
- `sdpa_rows_f32q`: `-DBF16_IO -DF32_Q -DF32_OUT -DSDPA_DIM=256 -DSDPA_ROWS` (Q/Out F32, K/V cache BF16)
Expand Down
16 changes: 16 additions & 0 deletions zig/build/vulkan.zig
Original file line number Diff line number Diff line change
Expand Up @@ -137,23 +137,39 @@ pub const stage2_shaders_src =

/// Stage 3's images: the ORACLE_QWEN35 rope variant, the causal multi-row SDPA decode arm, the output gate.
pub const stage3_variants = [_]ShaderVariant{
.{ .name = "sdpa_global_bf16", .src = "zig/kernels/vulkan/sdpa_decode_native.comp", .defines = &.{"-DGLOBAL_SCORES"} },
.{ .name = "sdpa_global_f32", .src = "zig/kernels/vulkan/sdpa_decode_native.comp", .defines = &.{ "-DGLOBAL_SCORES", "-DF32_Q", "-DF32_OUT" } },
.{ .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 = "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 = "gate_f32", .src = "zig/kernels/vulkan/attention_gate.comp", .defines = &.{"-DACT_F32"} },
.{ .name = "prefill_scores", .src = "zig/kernels/vulkan/sdpa_prefill_tile.comp", .defines = &.{"-DTILE_SCORES"} },
.{ .name = "prefill_softmax", .src = "zig/kernels/vulkan/sdpa_prefill_tile.comp", .defines = &.{"-DTILE_SOFTMAX"} },
.{ .name = "prefill_values", .src = "zig/kernels/vulkan/sdpa_prefill_tile.comp", .defines = &.{"-DTILE_VALUES"} },
.{ .name = "prefill_scores_bad", .src = "zig/kernels/vulkan/sdpa_prefill_tile.comp", .defines = &.{ "-DTILE_SCORES", "-DTILE_CONTROL" } },
.{ .name = "prefill_softmax_bad", .src = "zig/kernels/vulkan/sdpa_prefill_tile.comp", .defines = &.{ "-DTILE_SOFTMAX", "-DTILE_CONTROL" } },
.{ .name = "prefill_values_bad", .src = "zig/kernels/vulkan/sdpa_prefill_tile.comp", .defines = &.{ "-DTILE_VALUES", "-DTILE_CONTROL" } },
};

pub const stage3_shaders_src =
\\pub const sdpa_global_bf16 align(4) = @embedFile("sdpa_global_bf16.spv").*;
\\pub const sdpa_global_f32 align(4) = @embedFile("sdpa_global_f32.spv").*;
\\pub const rope_bf16 align(4) = @embedFile("rope_bf16.spv").*;
\\pub const sdpa_rows_bf16 align(4) = @embedFile("sdpa_rows_bf16.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 gate_f32 align(4) = @embedFile("gate_f32.spv").*;
\\pub const prefill_scores align(4) = @embedFile("prefill_scores.spv").*;
\\pub const prefill_softmax align(4) = @embedFile("prefill_softmax.spv").*;
\\pub const prefill_values align(4) = @embedFile("prefill_values.spv").*;
\\pub const prefill_scores_bad align(4) = @embedFile("prefill_scores_bad.spv").*;
\\pub const prefill_softmax_bad align(4) = @embedFile("prefill_softmax_bad.spv").*;
\\pub const prefill_values_bad align(4) = @embedFile("prefill_values_bad.spv").*;
;

/// Stage 4's images: GDN conv, gate split, prefill scan, decode, RMSNorm epilogue and the bf16 copy, all -DUSE_BF16.
Expand Down
37 changes: 29 additions & 8 deletions zig/kernels/vulkan/sdpa_decode_native.comp
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@
// Causal multi-row SDPA decode. One workgroup of 256 threads per
// (query head, row): scores for keys 0..key_end-1 in shared memory,
// 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.
// Shared scores use 30720 bytes; GLOBAL_SCORES keeps the same arithmetic with an explicit f32 workspace.

const uint kStreamKeys = 7168u;

Expand Down Expand Up @@ -67,7 +66,23 @@ 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

#ifdef GLOBAL_SCORES
layout(set = 0, binding = 4, std430) coherent buffer ScoreWorkspace { float v[]; } workspace;
const uint score_limit = 8192u;
float read_score(uint i) {
uint base = (gl_WorkGroupID.y * params.matrix_m + gl_WorkGroupID.x) * params.matrix_k;
return workspace.v[base + i];
}
void write_score(uint i, float value) {
uint base = (gl_WorkGroupID.y * params.matrix_m + gl_WorkGroupID.x) * params.matrix_k;
workspace.v[base + i] = value;
}
#else
shared float scores[kStreamKeys];
const uint score_limit = kStreamKeys;
float read_score(uint i) { return scores[i]; }
void write_score(uint i, float value) { scores[i] = value; }
#endif
shared float red[256];
shared float qs[256];

Expand All @@ -79,7 +94,7 @@ void main() {

// 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);
uint key_end = min(params.matrix_k - params.dims + row + 1u, score_limit);
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,10 +116,13 @@ void main() {
for (uint d = 0u; d < D; ++d) {
s += qs[d] * bf16_to_f32(uint(kbuf.v[kbase + d]));
}
scores[index] = s;
write_score(index, s);
lmax = nan_max(lmax, s);
}
red[thread] = lmax;
#ifdef GLOBAL_SCORES
memoryBarrierBuffer();
#endif
barrier();
for (uint stride = 128u; stride > 0u; stride >>= 1u) {
if (thread < stride) red[thread] = nan_max(red[thread], red[thread + stride]);
Expand All @@ -128,11 +146,14 @@ 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(read_score(index) - m);
write_score(index, w);
lsum += w;
}
red[thread] = lsum;
#ifdef GLOBAL_SCORES
memoryBarrierBuffer();
#endif
barrier();
for (uint stride = 128u; stride > 0u; stride >>= 1u) {
if (thread < stride) red[thread] += red[thread + stride];
Expand All @@ -146,12 +167,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 += read_score(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 += read_score(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
152 changes: 152 additions & 0 deletions zig/kernels/vulkan/sdpa_prefill_tile.comp
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
#version 450
#extension GL_EXT_shader_16bit_storage : require
#extension GL_EXT_shader_explicit_arithmetic_types_int16 : require

// BF16 row sharing around main's score dot, softmax tree, 16-key PV partials and final division.
layout(push_constant) uniform PrefillArgs {
uint rows; uint query_heads; uint kv_heads; uint total_keys;
uint capacity; uint head_dim; float scale; uint pad;
} p;

float widen(uint16_t x) { return uintBitsToFloat(uint(x) << 16u); }
uint16_t narrow(float x) {
uint bits = floatBitsToUint(x);
if ((bits & 0x7fffffffu) > 0x7f800000u) return uint16_t((bits >> 16u) | 0x40u);
return uint16_t((bits + 0x7fffu + ((bits >> 16u) & 1u)) >> 16u);
}
float maximum(float a, float b) { return isnan(a) ? a : (isnan(b) ? b : max(a, b)); }

#if defined(TILE_SCORES)
layout(local_size_x = 8, local_size_y = 16) in;
layout(set = 0, binding = 0, std430) readonly buffer Query { uint16_t x[]; } q;
layout(set = 0, binding = 1, std430) readonly buffer Key { uint16_t x[]; } k;
layout(set = 0, binding = 2, std430) writeonly buffer Scores { float x[]; } out_scores;
shared float query_tile[16 * 256];
shared float key_tile[8 * 256];

void main() {
uint lid = gl_LocalInvocationIndex;
uint kh = gl_WorkGroupID.z;
uint row0 = gl_WorkGroupID.y * 4u;
uint key0 = gl_WorkGroupID.x * 8u;
for (uint i = lid; i < 16u * 256u; i += 128u) {
uint h = kh * 4u + (i / 256u) / 4u;
uint row = row0 + (i / 256u) % 4u;
query_tile[i] = 0.0;
if (row < p.rows) query_tile[i] = p.scale * widen(q.x[(row * 8u + h) * 256u + i % 256u]);
}
for (uint i = lid; i < 8u * 256u; i += 128u) {
uint key = key0 + i / 256u;
key_tile[i] = 0.0;
if (key < p.total_keys) key_tile[i] = widen(k.x[(kh * p.capacity + key) * 256u + i % 256u]);
}
barrier();
uint qr = gl_LocalInvocationID.y;
uint row = row0 + qr % 4u;
uint h = kh * 4u + qr / 4u;
uint key = key0 + gl_LocalInvocationID.x;
uint end = p.total_keys - p.rows + row + 1u;
if (row < p.rows && key < end) {
float s = 0.0;
for (uint d = 0u; d < 256u; ++d) s += query_tile[qr * 256u + d] * key_tile[gl_LocalInvocationID.x * 256u + d];
#ifdef TILE_CONTROL
if (key == 0u) s += 1024.0;
#endif
out_scores.x[(row * 8u + h) * p.total_keys + key] = s;
}
}
#elif defined(TILE_SOFTMAX)
layout(local_size_x = 256) in;
layout(set = 0, binding = 0, std430) buffer Weights { float x[]; } w;
layout(set = 0, binding = 1, std430) writeonly buffer Statistics { float x[]; } st;
shared float reduction[256];

void main() {
uint group = gl_WorkGroupID.y * 8u + gl_WorkGroupID.x;
uint end = p.total_keys - p.rows + gl_WorkGroupID.y + 1u;
uint tid = gl_LocalInvocationID.x;
uint base = group * p.total_keys;
float m = -3.4028234663852886e38;
for (uint key = tid; key < end; key += 256u) m = maximum(m, w.x[base + key]);
reduction[tid] = m;
barrier();
for (uint stride = 128u; stride > 0u; stride >>= 1u) {
if (tid < stride) reduction[tid] = maximum(reduction[tid], reduction[tid + stride]);
barrier();
}
m = reduction[0];
float sum = 0.0;
for (uint key = tid; key < end; key += 256u) {
float e = exp(w.x[base + key] - m);
w.x[base + key] = e;
sum += e;
}
reduction[tid] = sum;
barrier();
for (uint stride = 128u; stride > 0u; stride >>= 1u) {
if (tid < stride) reduction[tid] += reduction[tid + stride];
barrier();
}
if (tid == 0u) {
st.x[group * 2u] = m;
#ifdef TILE_CONTROL
st.x[group * 2u + 1u] = reduction[0] + 1.0;
#else
st.x[group * 2u + 1u] = reduction[0];
#endif
}
}
#elif defined(TILE_VALUES)
layout(local_size_x = 16, local_size_y = 16) in;
layout(set = 0, binding = 0, std430) readonly buffer Weights { float x[]; } w;
layout(set = 0, binding = 1, std430) readonly buffer Statistics { float x[]; } st;
layout(set = 0, binding = 2, std430) readonly buffer Values { uint16_t x[]; } v;
layout(set = 0, binding = 3, std430) writeonly buffer Output { uint16_t x[]; } y;
shared float weight_tile[16 * 16];
shared float value_tile[16 * 16];

void main() {
uint qr = gl_LocalInvocationID.y;
uint dim = gl_WorkGroupID.x * 16u + gl_LocalInvocationID.x;
uint kh = gl_WorkGroupID.z;
uint row0 = gl_WorkGroupID.y * 4u;
uint row = row0 + qr % 4u;
uint h = kh * 4u + qr / 4u;
uint prefix = p.total_keys - p.rows;
uint end = prefix + row + 1u;
uint group = row * 8u + h;
float m = 0.0;
float denom = 1.0;
if (row < p.rows) { m = st.x[group * 2u]; denom = st.x[group * 2u + 1u]; }
bool transport = end == 1u && !isnan(m) && !isinf(m);
float acc = 0.0;
uint stop = prefix + min(row0 + 4u, p.rows);
for (uint key0 = 0u; key0 < stop; key0 += 16u) {
uint lane = gl_LocalInvocationID.x;
uint key = key0 + lane;
weight_tile[qr * 16u + lane] = 0.0;
if (row < p.rows && key < end) weight_tile[qr * 16u + lane] = w.x[group * p.total_keys + key];
uint vk = key0 + qr;
value_tile[qr * 16u + lane] = 0.0;
if (vk < p.total_keys) value_tile[qr * 16u + lane] = widen(v.x[(kh * p.capacity + vk) * 256u + dim]);
barrier();
if (row < p.rows && !transport && key0 < end) {
if (key0 + 16u <= end) {
float block_sum = 0.0;
for (uint j = 0u; j < 16u; ++j) block_sum += weight_tile[qr * 16u + j] * value_tile[j * 16u + lane];
acc += block_sum;
} else {
for (uint j = 0u; j < end - key0; ++j) acc += weight_tile[qr * 16u + j] * value_tile[j * 16u + lane];
}
}
barrier();
}
if (row < p.rows) {
uint16_t result = transport ? v.x[kh * p.capacity * 256u + dim] : narrow(acc / denom);
#ifdef TILE_CONTROL
if (row == 0u && h == 0u && dim == 0u) result = uint16_t(uint(result) ^ 1u);
#endif
y.x[(row * 8u + h) * 256u + dim] = result;
}
}
#endif
10 changes: 9 additions & 1 deletion zig/src/core/contract/vulkan_records.zig
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ pub const devices = [_]limits.VulkanDeviceLimits{
};

pub const records = [_]Record{
.{ .launch = .{ .name = "sdpa_global_bf16", .local_size = .{ 256, 1, 1 }, .shared_bytes = 2048 } },
.{ .launch = .{ .name = "sdpa_global_f32", .local_size = .{ 256, 1, 1 }, .shared_bytes = 2048 } },
.{ .launch = .{ .name = "qmm_bf16", .local_size = .{ 256, 1, 1 } } },
.{ .launch = .{ .name = "qmm_f32", .local_size = .{ 256, 1, 1 } } },
.{ .launch = .{ .name = "qmm_q4_vec4", .local_size = .{ 256, 1, 1 } } },
Expand All @@ -36,6 +38,12 @@ pub const records = [_]Record{
.{ .launch = .{ .name = "control:drop_tail", .local_size = .{ 256, 1, 1 } }, .control_gate = 3 },
.{ .launch = .{ .name = "control:fp16_accum", .local_size = .{ 256, 1, 1 } }, .control_gate = 4 },
.{ .launch = .{ .name = "control:over_limit", .local_size = .{ 2048, 1, 1 } }, .control_gate = 5 },
.{ .launch = .{ .name = "prefill_scores", .local_size = .{ 8, 16, 1 }, .shared_bytes = 24576 } },
.{ .launch = .{ .name = "prefill_softmax", .local_size = .{ 256, 1, 1 }, .shared_bytes = 1024 } },
.{ .launch = .{ .name = "prefill_values", .local_size = .{ 16, 16, 1 }, .shared_bytes = 2048 } },
.{ .launch = .{ .name = "prefill_scores_bad", .local_size = .{ 8, 16, 1 }, .shared_bytes = 24576 }, .control_gate = 3 },
.{ .launch = .{ .name = "prefill_softmax_bad", .local_size = .{ 256, 1, 1 }, .shared_bytes = 1024 }, .control_gate = 3 },
.{ .launch = .{ .name = "prefill_values_bad", .local_size = .{ 16, 16, 1 }, .shared_bytes = 2048 }, .control_gate = 3 },
};

/// Every row must be measured before records can be considered audited.
Expand Down Expand Up @@ -63,7 +71,7 @@ test "every served chip fits every real launch and rejects only the planted over
}

test "the planted controls stay registered, one per gate, in gate order" {
const expected_gates = [_]u8{ 1, 2, 2, 3, 4, 5 };
const expected_gates = [_]u8{ 1, 2, 2, 3, 4, 5, 3, 3, 3 };
var control_index: usize = 0;
for (records) |record| if (record.control_gate) |gate| {
try std.testing.expectEqual(expected_gates[control_index], gate);
Expand Down
16 changes: 8 additions & 8 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); // 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); // exactly the ceiling
try std.testing.expect(validPrompt(&at_cap));
const buf: [7168]u32 = @splat(7);
for ([_]usize{ 1, 31, 32, 33, 63, 64, 65, 7105 }) |len| {
const buf: [max_capacity]u32 = @splat(7);
for ([_]usize{ 1, 31, 32, 33, 63, 64, 65, 7105, 7169, 8192 }) |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, 7105, 7168, 7169, 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, cap - 1, 2); // exact fit
try std.testing.expectError(error.ContextTooLong, engine_mod.planFor(cap, 0, cap, 2)); // one past
try std.testing.expectError(error.ContextTooLong, engine_mod.planFor(cap, 0, cap + 1, 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
Loading
Loading