Skip to content
Closed
Changes from 1 commit
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
bda4834
DeepSeek V4.1: the Engram token map built in Zig, byte-identical to t…
akol1 Oct 14, 2026
b1effbb
DeepSeek V4.1 Flash: configuration, Engram tables and resident weight…
akol1 Oct 13, 2026
c51e6aa
DeepSeek V4.1 Flash: Metal operators with fp64-dot references and the…
akol1 Oct 13, 2026
2a22d68
THIRD_PARTY_NOTICES: the native DS4.1 reference follows DeepSeek-V4.1…
akol1 Oct 13, 2026
c408cb7
DeepSeek V4.1 load: a shard contributes only the tensors the index ma…
akol1 Oct 13, 2026
d52f9cd
DeepSeek V4.1 load: the router gate and bias ride the pack's dtypes
akol1 Oct 13, 2026
73eb0fb
DeepSeek V4.1 load: the Engram gate weights ride f32 or bf16
akol1 Oct 13, 2026
e630d73
DeepSeek V4.1: the kept-dense EXL3 form, for rank-split repacks
akol1 Oct 13, 2026
9fe64f8
DeepSeek V4.1 reference: the kept-dense apply
akol1 Oct 13, 2026
a6d7f86
DeepSeek V4.1 load: the shard-plan tests pass the index-ownership arg…
akol1 Oct 14, 2026
84386c9
DeepSeek V4.1: the rebase residue — one counters binding, the state-w…
akol1 Oct 14, 2026
d3c94ee
mHC fp64 ideal reference: the mix at rounding level, 1-ULP noise atte…
akol1 Oct 14, 2026
bb4cbc3
CSA2 reference: FP64-ideal parameterization of the pool, RMS and spar…
akol1 Oct 14, 2026
7b19ae1
csa2: FP64 stage harness, compressor pool + RMS, six adversarial inpu…
akol1 Oct 14, 2026
20e3880
csa2: FP64 stage harness over the sparse attention kernel, with kerne…
akol1 Oct 14, 2026
16e101b
csa2: indexer stage harness — FP32/FP64 score comparison and top-k se…
akol1 Oct 14, 2026
4bbb896
csa2: indexer stage receipts — carry the BF16 einsum/score boundaries…
akol1 Oct 14, 2026
585cd5a
csa2: sparse stage reads its own FP32 rounding level before the BF16 …
akol1 Oct 14, 2026
d33f74c
csa2: per-stage harnesses for sinks, tile denominators, output mix an…
akol1 Oct 14, 2026
75cbd19
csa2: measure how much score noise the top-k selection absorbs
akol1 Oct 14, 2026
edf9c7a
The fp64 harness ports: dedupe the shared math helpers, fix the shard…
akol1 Oct 14, 2026
1f0aed0
The oracle records the indexer's selection margins while it teaches
akol1 Oct 14, 2026
ed7ba76
The indexer-margin capture at depth: one diagnostic token's selection…
akol1 Oct 14, 2026
4006c85
DeepSeek V4.1: lane slots, each with its own caches and Engram cursor
akol1 Oct 13, 2026
10026d4
tf-dsv41-run: the counters read the full rusage_info_v4
akol1 Oct 13, 2026
c1f7e63
DeepSeek V4.1: the lane backend, a stream a slot
akol1 Oct 13, 2026
7ba5fa6
DeepSeek V4.1: the lane host behind the native server
akol1 Oct 13, 2026
34811b7
serve: --engram-table-dir reaches the native engine
akol1 Oct 13, 2026
b51503d
DeepSeek V4.1: the lane host builds the token map when it is missing
akol1 Oct 14, 2026
5f62bb6
DeepSeek V4.1: the family guide
akol1 Oct 14, 2026
9e8269a
the operator harnesses through zig fmt
akol1 Oct 14, 2026
81b013b
DeepSeek V4.1: the token map ships its table generator and its unit t…
akol1 Oct 18, 2026
a2a2874
DeepSeek V4.1 reference: the operator harnesses split at their seams
akol1 Oct 18, 2026
589937c
DeepSeek V4.1: the reference, family, native and Metal comments on on…
akol1 Oct 18, 2026
b7b23ba
DeepSeek V4.1: the lane runner accepts and documents its context argu…
akol1 Oct 18, 2026
1ccd7bc
DeepSeek V4.1: the FP32 and FP64 oracles run side by side
akol1 Oct 19, 2026
99c7c54
DeepSeek V4.1 reference: the FP64 narrowing keeps NaN, and the FP32 o…
akol1 Oct 19, 2026
34d6eb9
DeepSeek V4.1 reference: the index tie fixture broadcasts row 0 into …
akol1 Oct 21, 2026
c55c246
DeepSeek V4.1 reference: the FP32 sign packing matches the consumer w…
akol1 Oct 21, 2026
c379221
Pass the span metadata the counter recorder now requires
akol1 Oct 21, 2026
3032baa
DeepSeek V4.1: Metal targets onto 1.1.2's build modules
akol1 Oct 21, 2026
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
Prev Previous commit
Next Next commit
csa2: indexer stage harness — FP32/FP64 score comparison and top-k se…
…lection agreement
  • Loading branch information
akol1 committed Oct 21, 2026
commit 16e101b136d6334259fb42bd31d246d6d49b004c
191 changes: 191 additions & 0 deletions zig/tests/deepseek_v41_reference/operator_csa2_fp64.zig
Original file line number Diff line number Diff line change
Expand Up @@ -718,6 +718,197 @@ test "sparse attention stages sit at rounding level against the FP64 ideal" {
}
}

/// One indexer-score row set: 32 heads of 128 FP4-index columns each, scored against packed keys.
const IndexSpec = struct { name: []const u8, rows: usize, keys: usize, topk: usize };

fn packIndexRow(values: []const f32, out: []u8) void {
@memset(out[0 .. 128 / 2 + 128 / 32], 0);
for (0..128 / 32) |block| {
var a: f32 = 6.0 * 0x1p-126;
for (values[block * 32 ..][0..32]) |v| a = @max(a, @abs(v));
const bits: u32 = @bitCast(a / 6.0);
const unbiased: i32 = @as(i32, @intCast((bits >> 23) & 255)) - 127 + @intFromBool((bits & 0x7fffff) != 0);
const scale = std.math.ldexp(@as(f32, 1.0), unbiased);
out[64 + block] = @intCast(unbiased + 127);
for (0..32) |j| {
const code = e2Code(values[block * 32 + j] / scale);
const at = block * 16 + j / 2;
if ((j & 1) != 0) out[at] |= code << 4 else out[at] |= code;
}
}
}

fn decodeIndexRow(bytes: []const u8) [128]u16 {
var row: [128]u16 = undefined;
for (0..128) |d| {
const nibble: u8 = if ((d & 1) != 0) bytes[d / 2] >> 4 else bytes[d / 2] & 15;
const scale: f32 = @bitCast(@as(u32, bytes[64 + d / 32]) << 23);
row[d] = math.b(e2(nibble) * scale);
}
return row;
}

fn indexCase(device: mtl.Device, queue: mtl.Queue, p: *const tf.deepseek_v41.csa2_index.Pipelines,
spec: IndexSpec, q: []const u16, weights: []const u16, key_values: []const []const f32,
) !void {
var b = Buffers{ .device = device };
defer b.deinit();
var scratch = try tf.deepseek_v41.csa2_index.Scratch.init(device, @intCast(spec.rows));
defer scratch.deinit();
const q_gpu = try b.get(u16, spec.rows * 32 * 128);
const weights_gpu = try b.get(u16, spec.rows * 32);
const keys_gpu = try b.get(u8, spec.keys * 68);
@memcpy(q_gpu.slice(u16, spec.rows * 32 * 128), q);
@memcpy(weights_gpu.slice(u16, spec.rows * 32), weights);

// Both sides read the same decoded keys; the references differ only in their arithmetic.
const decoded = try std.testing.allocator.alloc(u16, spec.keys * 128);
defer std.testing.allocator.free(decoded);
for (key_values, 0..) |values, row| {
const bytes = try std.testing.allocator.alloc(u8, 68);
defer std.testing.allocator.free(bytes);
packIndexRow(values, bytes);
@memcpy(keys_gpu.slice(u8, spec.keys * 68)[row * 68 ..][0..68], bytes);
const decoded_row = decodeIndexRow(bytes);
@memcpy(decoded[row * 128 ..][0..128], &decoded_row);
}
const cb = queue.commandBuffer();
const enc = cb.compute(.serial);
try p.encode(enc, view(q_gpu), view(weights_gpu), view(keys_gpu), scratch, .{
.rows = @intCast(spec.rows),
.keys = @intCast(spec.keys),
.q_stride = 32 * 128,
.weight_stride = 32,
.position = @intCast(spec.keys),
.ratio = 1,
});
enc.end();
cb.commit();
cb.wait();
if (cb.failure() != null) return error.Csa2Fp64GpuFailure;

const kernel_scores = scratch.scores().buffer.slice(f32, spec.rows * 4096);
const kernel_positions = scratch.positions().buffer.slice(i32, spec.rows * 512);
var ref32 = try std.testing.allocator.alloc(f32, spec.keys);
defer std.testing.allocator.free(ref32);
var ref64 = try std.testing.allocator.alloc(f64, spec.keys);
defer std.testing.allocator.free(ref64);
const w_scale: f32 = 1 / @sqrt(@as(f32, 128 * 32));
for (0..spec.keys) |row| {
const key = decoded[row * 128 ..][0..128];
var ideal: f64 = 0;
var narrow32: f32 = 0;
for (0..32) |head| {
var dot: f64 = 0;
for (0..128) |d| dot += @as(f64, math.f(key[d])) * @as(f64, math.f(q[head * 128 + d]));
const rectified: f64 = @max(@min(dot, 1e38), 0);
const weight: f32 = math.f(weights[head]);
const scaled_weight = math.f(math.b(weight * w_scale));
const weighted = math.f(math.b(@as(f32, @floatCast(rectified)) * scaled_weight));
ideal += weighted;
narrow32 += @as(f32, @floatCast(weighted));
}
ref64[row] = ideal;
ref32[row] = math.f(math.b(narrow32));
}
var ideal_cells: [1024]f64 = undefined;
const shown = @min(spec.keys, ideal_cells.len);
for (0..shown) |row| ideal_cells[row] = ref64[row];
printF32(spec.name, "index_score", "metal_vs_ideal", deltaF32VsF64(
kernel_scores[0..shown], ideal_cells[0..shown]));
printF32(spec.name, "index_score", "f32_vs_ideal", deltaF32VsF64(ref32[0..shown], ideal_cells[0..shown]));

// Selection: which keys land in the top-k. Ties are decided by the merge's comparator on the
// kernel side and by ascending index in the reference; the sets can therefore differ.
var chosen = try std.testing.allocator.alloc(bool, spec.keys);
defer std.testing.allocator.free(chosen);
@memset(chosen, false);
var scores_copy = try std.testing.allocator.alloc(f32, spec.keys);
defer std.testing.allocator.free(scores_copy);
@memcpy(scores_copy, ref32[0..spec.keys]);
var reference_picks: [512]u32 = undefined;
const picks = @min(spec.topk, spec.keys);
for (0..picks) |pick| {
var best: usize = 0;
for (0..spec.keys) |i| {
if (scores_copy[i] > scores_copy[best]) best = i;
}
reference_picks[pick] = @intCast(best);
scores_copy[best] = -std.math.inf(f32);
}
std.mem.sort(u32, reference_picks[0..picks], {}, std.sort.asc(u32));
var overlap: usize = 0;
for (reference_picks[0..picks]) |at| chosen[at] = true;
var min_selected: f32 = std.math.inf(f32);
var max_unselected: f32 = -std.math.inf(f32);
for (0..spec.keys) |row| {
if (chosen[row]) {
overlap += 1;
min_selected = @min(min_selected, ref32[row]);
} else max_unselected = @max(max_unselected, ref32[row]);
}
var kernel_only: usize = 0;
for (0..picks) |i| {
const slot = kernel_positions[i];
if (slot < 0 or slot >= @as(i32, @intCast(spec.keys))) continue;
if (!chosen[@intCast(slot)]) kernel_only += 1;
}
std.debug.print(
\\CSA64 {{"case":"{s}","stage":"index_select","side":"metal","keys":{d},"picks":{d},"reference_only":{d},"kernel_only":{d},"lowest_selected":{d},"highest_unselected":{d}}}
, .{ spec.name, spec.keys, picks, picks - overlap, kernel_only, min_selected, max_unselected });
}

test "indexer scoring and selection sit at rounding level against the FP64 ideal" {
var arena_instance = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_instance.deinit();
const gpa = arena_instance.allocator();
const device = mtl.Device.init() catch return error.SkipZigTest;
defer device.deinit();
const pool = mtl.objc.Pool.push();
defer pool.pop();
const queue = try device.queue();
defer queue.deinit();
var p = try tf.deepseek_v41.csa2_index.Pipelines.load(device);
defer p.deinit();

var rng = Lcg{ .state = 0x1234_5678_9abc_def0 };
var amplitude: f32 = 1;
for ([_]IndexSpec{
.{ .name = "index_random", .rows = 1, .keys = 1024, .topk = 512 },
.{ .name = "index_random_4k", .rows = 1, .keys = 4096, .topk = 512 },
.{ .name = "index_ties", .rows = 1, .keys = 1024, .topk = 512 },
.{ .name = "index_boundary", .rows = 1, .keys = 1024, .topk = 512 },
}, 0..) |spec, case_index| {
_ = case_index;
const q = try gpa.alloc(u16, 32 * 128);
defer gpa.free(q);
const weights = try gpa.alloc(u16, 32);
defer gpa.free(weights);
const cells = try gpa.alloc(f32, spec.keys * 128);
defer gpa.free(cells);
const keys = try gpa.alloc([]const f32, spec.keys);
defer gpa.free(keys);
for (q) |*cell| cell.* = math.b(rng.scale(1.0));
for (weights) |*cell| cell.* = math.b(rng.scale(1.0));
for (cells, 0..) |*v, i| {
v.* = rng.scale(1.0);
keys[i / 128] = cells[i / 128 * 128 ..][0..128];
}
// Identical keys: every score is the same value, so the whole selection is tie-driven.
if (std.mem.eql(u8, spec.name, "index_ties")) {
for (cells[128..], cells[0..128]) |*dst, src| dst.* = src;
}
// A score cliff just inside the selection boundary: half the keys sit on the boundary.
if (std.mem.eql(u8, spec.name, "index_boundary")) {
for (cells, 0..) |*v, i| {
if ((i % 128) == 0) amplitude = (if (i / 128 < 512) @as(f32, 1.000001) else @as(f32, 1.0));
v.* = rng.scale(amplitude);
}
}
try indexCase(device, queue, &p, spec, q, weights, keys);
}
}

fn weightCells(gpa: std.mem.Allocator, rng: *Lcg) ![]u16 {
const out = try gpa.alloc(u16, width);
for (out) |*cell| {
Expand Down