From b513303d89bf020964338f46d1433ba2d7a7b8bf Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:36:42 +0800 Subject: [PATCH 01/14] inkling2 metal: run greedy DSpark holds step-major across streams --- zig/kernels/metal/inkling2/dspark.metal | 145 ++++++++++++++---- zig/src/families/inkling2/metal/dspark.zig | 128 ++++++++++++---- .../inkling2/metal/dspark_kernels.zig | 129 +++++++++++++++- .../families/inkling2/metal/dspark_state.zig | 72 +++++++++ 4 files changed, 415 insertions(+), 59 deletions(-) diff --git a/zig/kernels/metal/inkling2/dspark.metal b/zig/kernels/metal/inkling2/dspark.metal index be21a1f33c5..5a85b42c58e 100644 --- a/zig/kernels/metal/inkling2/dspark.metal +++ b/zig/kernels/metal/inkling2/dspark.metal @@ -18,9 +18,16 @@ struct DsparkTokenArgs { uint token; }; struct DsparkResidualArgs { uint init; }; struct DsparkCountArgs { uint count; }; struct DsparkBaseArgs { uint rows, vocab; }; +struct DsparkCohortArgs { uint streams; uint row; }; +struct DsparkPackArgs { uint active[7]; uint first, count; }; +constant constexpr uint DSP_TILE = 28; -kernel void tf_ink2_dspark_init_rows(const device bfloat* anchor [[buffer(0)]], const device bfloat* mask [[buffer(1)]], device bfloat* rows [[buffer(2)]], uint row [[threadgroup_position_in_grid]], uint t [[thread_position_in_threadgroup]]) { - for (uint d = t; d < DSP_H; d += 256) { +// Threadgroup (row, stream): row zero copies the stream's normalized anchor, the other seven the raw mask embedding. +kernel void tf_ink2_dspark_init_rows(const device bfloat* anchors [[buffer(0)]], const device bfloat* mask [[buffer(1)]], device bfloat* blocks [[buffer(2)]], uint2 tg [[threadgroup_position_in_grid]], uint2 t [[thread_position_in_threadgroup]]) { + const uint row = tg.x; + const device bfloat* anchor = anchors + size_t(tg.y) * DSP_H; + device bfloat* rows = blocks + size_t(tg.y) * 8 * DSP_H; + for (uint d = t.x; d < DSP_H; d += 256) { const device bfloat* src = row == 0 ? anchor : mask; rows[row * DSP_H + d] = src[d]; } @@ -61,39 +68,50 @@ static inline float dspark_rope_angle(uint d, uint position) { return float(position) * frequency; } -kernel void tf_ink2_dspark_block_qkv(const device bfloat* q_raw [[buffer(0)]], const device bfloat* k_raw [[buffer(1)]], const device bfloat* v_raw [[buffer(2)]], const device bfloat* q_weight [[buffer(3)]], const device bfloat* k_weight [[buffer(4)]], device bfloat* q [[buffer(5)]], device bfloat* k [[buffer(6)]], device bfloat* v [[buffer(7)]], constant DsparkPositionArgs& a [[buffer(8)]], uint group [[threadgroup_position_in_grid]], uint d [[thread_position_in_threadgroup]]) { - const uint row = group / 40, work = group % 40; - threadgroup float scale; +// One block row at `position`: work 0..31 a query, then a key head; 32..39 a value head's unchanged 128 threads. +static inline void dspark_block_qkv(const device bfloat* q_raw, const device bfloat* k_raw, const device bfloat* v_raw, const device bfloat* q_weight, const device bfloat* k_weight, device bfloat* q, device bfloat* k, device bfloat* v, threadgroup float* scale, uint position, uint work, uint d) { if (work < 32 && d == 0) { float sum = 0.0f; if (work < 24) { const uint h = work; - for (uint i = 0; i < DSP_HEAD; ++i) { const float x = float(q_raw[row * DSP_Q + h * DSP_HEAD + i]); sum += x * x; } + for (uint i = 0; i < DSP_HEAD; ++i) { const float x = float(q_raw[h * DSP_HEAD + i]); sum += x * x; } } else { const uint h = work - 24; - for (uint i = 0; i < DSP_HEAD; ++i) { const float x = float(k_raw[row * DSP_KV + h * DSP_HEAD + i]); sum += x * x; } + for (uint i = 0; i < DSP_HEAD; ++i) { const float x = float(k_raw[h * DSP_HEAD + i]); sum += x * x; } } - scale = rsqrt(sum / float(DSP_HEAD) + DSP_EPS); + scale[0] = rsqrt(sum / float(DSP_HEAD) + DSP_EPS); } threadgroup_barrier(mem_flags::mem_threadgroup); if (work >= 32) { const uint h = work - 32; - v[row * DSP_KV + h * DSP_HEAD + d] = v_raw[row * DSP_KV + h * DSP_HEAD + d]; + v[h * DSP_HEAD + d] = v_raw[h * DSP_HEAD + d]; return; } const bool query = work < 24; const uint h = query ? work : work - 24; - const uint at = row * (query ? DSP_Q : DSP_KV) + h * DSP_HEAD + d; - const float x = float(bfloat(float(query ? q_raw[at] : k_raw[at]) * scale * float(query ? q_weight[d] : k_weight[d]))); + const uint at = h * DSP_HEAD + d; + const float x = float(bfloat(float(query ? q_raw[at] : k_raw[at]) * scale[0] * float(query ? q_weight[d] : k_weight[d]))); const uint partner = d < 64 ? d + 64 : d - 64; - const uint other_at = row * (query ? DSP_Q : DSP_KV) + h * DSP_HEAD + partner; - const float other = float(bfloat(float(query ? q_raw[other_at] : k_raw[other_at]) * scale * float(query ? q_weight[partner] : k_weight[partner]))); - const float angle = dspark_rope_angle(d, a.base + row); + const float other = float(bfloat(float(query ? q_raw[h * DSP_HEAD + partner] : k_raw[h * DSP_HEAD + partner]) * scale[0] * float(query ? q_weight[partner] : k_weight[partner]))); + const float angle = dspark_rope_angle(d, position); const float cs = cos(angle), sn = sin(angle); const float rotated = d < 64 ? x * cs - other * sn : other * sn + x * cs; if (query) q[at] = bfloat(rotated); else k[at] = bfloat(rotated); } +kernel void tf_ink2_dspark_block_qkv(const device bfloat* q_raw [[buffer(0)]], const device bfloat* k_raw [[buffer(1)]], const device bfloat* v_raw [[buffer(2)]], const device bfloat* q_weight [[buffer(3)]], const device bfloat* k_weight [[buffer(4)]], device bfloat* q [[buffer(5)]], device bfloat* k [[buffer(6)]], device bfloat* v [[buffer(7)]], constant DsparkPositionArgs& a [[buffer(8)]], uint group [[threadgroup_position_in_grid]], uint d [[thread_position_in_threadgroup]]) { + threadgroup float scale; + const uint row = group / 40, work = group % 40; + dspark_block_qkv(q_raw + size_t(row) * DSP_Q, k_raw + size_t(row) * DSP_KV, v_raw + size_t(row) * DSP_KV, q_weight, k_weight, q + size_t(row) * DSP_Q, k + size_t(row) * DSP_KV, v + size_t(row) * DSP_KV, &scale, a.base + row, work, d); +} + +// The cohort's: threadgroup (work, row) over blocks of eight rows, each block at its own entry of `anchors`. +kernel void tf_ink2_dspark_cohort_qkv(const device bfloat* q_raw [[buffer(0)]], const device bfloat* k_raw [[buffer(1)]], const device bfloat* v_raw [[buffer(2)]], const device bfloat* q_weight [[buffer(3)]], const device bfloat* k_weight [[buffer(4)]], device bfloat* q [[buffer(5)]], device bfloat* k [[buffer(6)]], device bfloat* v [[buffer(7)]], const device uint* anchors [[buffer(8)]], uint2 tg [[threadgroup_position_in_grid]], uint2 d [[thread_position_in_threadgroup]]) { + threadgroup float scale; + const uint work = tg.x, row = tg.y; + dspark_block_qkv(q_raw + size_t(row) * DSP_Q, k_raw + size_t(row) * DSP_KV, v_raw + size_t(row) * DSP_KV, q_weight, k_weight, q + size_t(row) * DSP_Q, k + size_t(row) * DSP_KV, v + size_t(row) * DSP_KV, &scale, anchors[row / 8] + row % 8, work, d.x); +} + kernel void tf_ink2_dspark_context_kv(const device bfloat* k_raw [[buffer(0)]], const device bfloat* v_raw [[buffer(1)]], const device bfloat* weight [[buffer(2)]], device bfloat* keys [[buffer(3)]], device bfloat* values [[buffer(4)]], constant DsparkContextArgs& a [[buffer(5)]], uint group [[threadgroup_position_in_grid]], uint d [[thread_position_in_threadgroup]]) { const uint row = group / 8, h = group % 8; threadgroup float scale; @@ -239,11 +257,14 @@ kernel void tf_ink2_dspark_chain_step(const device bfloat* state [[buffer(0)]], dspark_recurrent_step(state, kappa, rnn_weight, markov, z, next_state, lambda, held[a.token], i); } -// held[a.token + 1] = the first greatest of the 200,058 logits; a NaN is never chosen unless logit 0 is one. -[[max_total_threads_per_threadgroup(1024)]] -kernel void tf_ink2_dspark_chain_pick(const device bfloat* logits [[buffer(0)]], device uint* held [[buffer(1)]], constant DsparkTokenArgs& a [[buffer(2)]], uint t [[thread_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { - threadgroup float values[32]; - threadgroup uint places[32]; +// A depth's recurrent step, a threadgroup a stream: stream s takes kappa row 7s + a.row after the token held[8s + a.row]. +[[max_total_threads_per_threadgroup(256)]] +kernel void tf_ink2_dspark_cohort_step(const device bfloat* state [[buffer(0)]], const device float* kappa [[buffer(1)]], const device bfloat* rnn_weight [[buffer(2)]], const device bfloat* markov [[buffer(3)]], device bfloat* z [[buffer(4)]], device bfloat* next_state [[buffer(5)]], device bfloat* lambda [[buffer(6)]], constant DsparkCohortArgs& a [[buffer(7)]], const device uint* held [[buffer(8)]], uint s [[threadgroup_position_in_grid]], uint i [[thread_position_in_threadgroup]]) { + dspark_recurrent_step(state + s * DSP_RANK, kappa + (s * 7 + a.row) * DSP_RNN, rnn_weight, markov, z + s * 3 * DSP_RANK, next_state + s * DSP_RANK, lambda + s * DSP_RANK, held[s * 8 + a.row], i); +} + +// The first greatest of one row of 200,058 logits for a 1,024-thread group: the lower id of equals, a NaN never. +static inline uint dspark_first_greatest(const device bfloat* logits, uint t, uint lane, uint sg, threadgroup float* values, threadgroup uint* places) { float best = -INFINITY; uint at = 0xffffffffu; for (uint i = t; i < 200058u; i += 1024u) { @@ -258,30 +279,55 @@ kernel void tf_ink2_dspark_chain_pick(const device bfloat* logits [[buffer(0)]], } if (lane == 0) { values[sg] = best; places[sg] = at; } threadgroup_barrier(mem_flags::mem_threadgroup); - if (t != 0) return; + if (t != 0) return 0xffffffffu; for (uint g = 0; g < 32; ++g) if (values[g] > best || (values[g] == best && places[g] < at)) { best = values[g]; at = places[g]; } - held[a.token + 1] = isnan(float(logits[0])) ? 0u : at; + return at; } -// A simdgroup an id: eight columns a lane a step, every row sharing the read of unembed[id]; rounded once to BF16. +// held[a.token + 1] = the first greatest of the 200,058 logits; a NaN is never chosen unless logit 0 is one. +[[max_total_threads_per_threadgroup(1024)]] +kernel void tf_ink2_dspark_chain_pick(const device bfloat* logits [[buffer(0)]], device uint* held [[buffer(1)]], constant DsparkTokenArgs& a [[buffer(2)]], uint t [[thread_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float values[32]; + threadgroup uint places[32]; + const uint at = dspark_first_greatest(logits, t, lane, sg, values, places); + if (t == 0) held[a.token + 1] = isnan(float(logits[0])) ? 0u : at; +} + +// A depth's picks, a threadgroup a stream: held[8s + a.row + 1] is the first greatest of logits row s. +[[max_total_threads_per_threadgroup(1024)]] +kernel void tf_ink2_dspark_cohort_pick(const device bfloat* logits [[buffer(0)]], device uint* held [[buffer(1)]], constant DsparkCohortArgs& a [[buffer(2)]], uint s [[threadgroup_position_in_grid]], uint t [[thread_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]], uint sg [[simdgroup_index_in_threadgroup]]) { + threadgroup float values[32]; + threadgroup uint places[32]; + const device bfloat* row = logits + size_t(s) * 200058u; + const uint at = dspark_first_greatest(row, t, lane, sg, values, places); + if (t == 0) held[s * 8 + a.row + 1] = isnan(float(row[0])) ? 0u : at; +} + +// A simdgroup an id: eight columns a lane a row; the rows share the read of unembed[id] and round once to BF16. [[max_total_threads_per_threadgroup(256)]] kernel void tf_ink2_dspark_base(const device bfloat* unembed [[buffer(0)]], const device bfloat* y [[buffer(1)]], device bfloat* out [[buffer(2)]], constant DsparkBaseArgs& a [[buffer(3)]], uint tg [[threadgroup_position_in_grid]], uint sg [[simdgroup_index_in_threadgroup]], uint lane [[thread_index_in_simdgroup]]) { const uint id = tg * 8 + sg; if (id >= a.vocab) return; const device bfloat* w = unembed + size_t(id) * DSP_H; - float acc[7] = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}; + float acc[DSP_TILE]; + #pragma unroll + for (uint row = 0; row < DSP_TILE; ++row) acc[row] = 0.0f; for (uint i = 8 * lane; i < DSP_H; i += 256) { const float4 w0 = float4(*(const device bfloat4*)(w + i)), w1 = float4(*(const device bfloat4*)(w + i + 4)); - for (uint row = 0; row < a.rows; ++row) { - const device bfloat* x = y + size_t(row) * DSP_H + i; - acc[row] += dot(w0, float4(*(const device bfloat4*)x)) + dot(w1, float4(*(const device bfloat4*)(x + 4))); + #pragma unroll + for (uint row = 0; row < DSP_TILE; ++row) { + if (row < a.rows) { + const device bfloat* x = y + size_t(row) * DSP_H + i; + acc[row] += dot(w0, float4(*(const device bfloat4*)x)) + dot(w1, float4(*(const device bfloat4*)(x + 4))); + } } } - for (uint row = 0; row < a.rows; ++row) { + #pragma unroll + for (uint row = 0; row < DSP_TILE; ++row) { const float sum = simd_sum(acc[row]); - if (lane == 0) out[size_t(row) * a.vocab + id] = bfloat(sum); + if (row < a.rows && lane == 0) out[size_t(row) * a.vocab + id] = bfloat(sum); } } @@ -293,3 +339,46 @@ kernel void tf_ink2_dspark_logits(const device bfloat* base [[buffer(0)]], const const bfloat logit = bfloat(float(base[i]) + float(bias)); out[i] = bfloat(30.0f * tanh(float(logit) / 30.0f)); } + +// A vocabulary id's logits for `streams` rows: phi's row is read once, each row keeping its own serial 256-sum. +template +inline void dspark_cohort_logits(const device bfloat* base, const device bfloat* phi, const device bfloat* beta, const device bfloat* lambda, device bfloat* out, uint streams, uint i) { + float dot[N]; + #pragma unroll + for (uint s = 0; s < N; ++s) dot[s] = 0.0f; + for (uint d = 0; d < DSP_RANK; ++d) { + const float p = float(phi[size_t(i) * DSP_RANK + d]); + #pragma unroll + for (uint s = 0; s < N; ++s) { + if (s < streams) dot[s] += p * float(lambda[size_t(s) * DSP_RANK + d]); + } + } + #pragma unroll + for (uint s = 0; s < N; ++s) { + if (s < streams) { + const bfloat bias = bfloat(float(beta[i]) + dot[s]); + const bfloat logit = bfloat(float(base[size_t(s) * 200058u + i]) + float(bias)); + out[size_t(s) * 200058u + i] = bfloat(30.0f * tanh(float(logit) / 30.0f)); + } + } +} + +// A depth's final logits for streams 0 .. a.streams: base rows a.row .., lambda row s, out row s. +kernel void tf_ink2_dspark_cohort_logits(const device bfloat* base [[buffer(0)]], const device bfloat* phi [[buffer(1)]], const device bfloat* beta [[buffer(2)]], const device bfloat* lambda [[buffer(3)]], device bfloat* out [[buffer(4)]], constant DsparkCohortArgs& a [[buffer(5)]], uint i [[thread_position_in_grid]]) { + if (i >= 200058u) return; + const device bfloat* rows = base + size_t(a.row) * 200058u; + if (a.streams <= 4) dspark_cohort_logits<4>(rows, phi, beta, lambda, out, a.streams, i); + else if (a.streams <= 8) dspark_cohort_logits<8>(rows, phi, beta, lambda, out, a.streams, i); + else dspark_cohort_logits<16>(rows, phi, beta, lambda, out, a.streams, i); +} + +// The packed unembed rows a.first .. a.first + a.count: draft row tg.y + 1 of the first active[tg.y] streams, a row a stream. +kernel void tf_ink2_dspark_cohort_pack(const device bfloat* x [[buffer(0)]], device bfloat* out [[buffer(1)]], constant DsparkPackArgs& a [[buffer(2)]], uint2 tg [[threadgroup_position_in_grid]], uint2 t [[thread_position_in_threadgroup]]) { + if (tg.x >= a.active[tg.y]) return; + uint row = tg.x; + for (uint j = 0; j < tg.y; ++j) row += a.active[j]; + if (row < a.first || row - a.first >= a.count) return; + const device bfloat4* src = (const device bfloat4*)(x + size_t(tg.x * 8 + tg.y + 1) * DSP_H); + device bfloat4* dst = (device bfloat4*)(out + size_t(row - a.first) * DSP_H); + for (uint d = t.x; d < DSP_H / 4; d += 256) dst[d] = src[d]; +} diff --git a/zig/src/families/inkling2/metal/dspark.zig b/zig/src/families/inkling2/metal/dspark.zig index 31909c6b0d7..d3817d74409 100644 --- a/zig/src/families/inkling2/metal/dspark.zig +++ b/zig/src/families/inkling2/metal/dspark.zig @@ -17,8 +17,6 @@ const Ref = k.Ref; const tap_list = [_]u32{ 5, 23, 41, 48 }; /// Drafts a hold offers at most: the block after its anchor. The depth rule prices how many a round takes. const hold_depth: u32 = state.block - 1; -/// Streams one greedy hold can chain on the GPU; a wider hold samples on the host as sampled streams do. -const chain_streams = 16; fn at(buf: mtl.Buffer, off: usize) Ref { return .{ .buf = buf, .off = off }; @@ -40,11 +38,14 @@ pub const Drafter = struct { weights: weight_loader.Loaded, pipelines: k.Pipelines, scratch: state.Scratch, - /// Scratch for the second and later streams of one hold; the first uses `scratch`, as absorb does. + /// Scratch for the second and later streams of a sampled hold; the first uses `scratch`, as absorb does. more: std.ArrayList(state.Scratch) = .empty, - /// The greedy chain's kernels, and each held stream's eight tokens: the anchor, then its drafts. + /// The solo timing kernels and eight held tokens per cohort slot. chain: k.Chain = undefined, chain_tokens: mtl.Buffer = undefined, + /// Shared greedy block rows, packed unembed inputs and base rows. + cohort: k.Cohort = undefined, + cohort_state: state.Cohort = undefined, scores: ?mtl.Buffer = null, /// The block attention's tensor-unit kernels, on the chips that have the units. units: ?k.Units = null, @@ -71,9 +72,15 @@ pub const Drafter = struct { errdefer d.pipelines.deinit(); d.scratch = try state.Scratch.init(device); errdefer d.scratch.deinit(); - d.chain = try k.Chain.load(device, @import("inkling2_metal").inkling2_dspark); + const lib = try mtl.Library.fromSource(device, @import("inkling2_metal").inkling2_dspark, mtl.CompileOptions.mlx()); + defer lib.deinit(); + d.chain = try k.Chain.fromLibrary(device, lib); errdefer d.chain.deinit(); - d.chain_tokens = try device.buffer(chain_streams * 8 * @sizeOf(u32), mtl.ResourceOptions.shared); + d.cohort = try k.Cohort.fromLibrary(device, lib); + errdefer d.cohort.deinit(); + d.cohort_state = try state.Cohort.init(device); + errdefer d.cohort_state.deinit(); + d.chain_tokens = try device.buffer(k.cohort_streams * 8 * @sizeOf(u32), mtl.ResourceOptions.shared); errdefer d.chain_tokens.deinit(); if (device.tensorUnits()) d.units = try k.Units.load(device, @import("inkling2_metal").inkling2_dspark_units); return d; @@ -85,6 +92,8 @@ pub const Drafter = struct { d.contexts.deinit(d.gpa); if (d.scores) |scores| scores.deinit(); if (d.units) |*u| u.deinit(); + d.cohort_state.deinit(); + d.cohort.deinit(); d.chain_tokens.deinit(); d.chain.deinit(); for (d.more.items) |*extra| extra.deinit(); @@ -96,7 +105,7 @@ pub const Drafter = struct { } pub fn fixedBytes(d: *const Drafter) u64 { - return d.weights.fixedBytes() + state.scratchBytes(); + return d.weights.fixedBytes() + state.scratchBytes() + state.cohortBytes(); } pub fn scoreBytes(capacity: usize) u64 { @@ -340,33 +349,94 @@ pub const Drafter = struct { d.step_ms = ms / @as(f64, @floatFromInt(hold_depth)); } - /// Greedy streams: the blocks and every step in one command buffer, each draft picked on the GPU for the next. - fn holdChained(d: *Drafter, items: []const dr.Hold) !void { - const tokens = d.chain_tokens.slice(u32, chain_streams * 8); + /// Every stream's block in the cohort's launches, then its kappa and the drafts' packed unembed rows. + fn encodeCohort(d: *Drafter, e: mtl.ComputeEncoder, items: []const dr.Hold, order: *const k.Order) void { + const c = &d.cohort_state; + const p = &d.pipelines; + const streams: u32 = @intCast(order.active[0]); + const slots = order.slots[0..streams]; + const rows = streams * state.block; + const anchors = c.anchors.slice(u32, k.cohort_streams); + const tokens = d.chain_tokens.slice(u32, k.cohort_streams * 8); + for (slots, 0..) |item, s| { + anchors[s] = @intCast(items[item].position - 1); + c.ids.slice(u32, k.cohort_streams)[s] = items[item].pending; + tokens[s * 8] = items[item].pending; + } + @memset(c.state.slice(u16, k.cohort_streams * state.rank), 0); + glue.embedNorm(&d.target.glue, e, at(c.ids, 0), r(d.target.weights.embed), r(d.target.weights.embed_norm), at(c.tile, 0), streams); + k.cohortInitializeRows(p, e, at(c.tile, 0), r(d.weights.weights.mask), at(c.x, 0), streams); + k.residualNorm(p, e, at(c.x, 0), at(c.resid, 0), r(d.weights.weights.layers[0].input_norm), at(c.resid, 0), at(c.x, 0), rows, true); + for (d.weights.weights.layers, 0..) |layer, i| { + fwd.dense(d.target, e, layer.q, at(c.x, 0), at(c.q_raw, 0), rows); + fwd.dense(d.target, e, layer.k, at(c.x, 0), at(c.k_raw, 0), rows); + fwd.dense(d.target, e, layer.v, at(c.x, 0), at(c.v_raw, 0), rows); + k.cohortQkv(&d.cohort, e, at(c.q_raw, 0), at(c.k_raw, 0), at(c.v_raw, 0), r(layer.q_norm), r(layer.k_norm), at(c.q, 0), at(c.kb, 0), at(c.vb, 0), at(c.anchors, 0), streams); + for (slots, 0..) |item, s| { + const lane = d.contexts.getPtr(items[item].stream).?; + const q = at(c.q, s * state.block * state.query * 2); + const kb = at(c.kb, s * state.block * state.kv * 2); + const vb = at(c.vb, s * state.block * state.kv * 2); + const attn = at(c.attn, s * state.block * state.query * 2); + if (d.units) |*u| k.attendUnits(u, e, q, kb, vb, at(lane.k[i], 0), at(lane.v[i], 0), at(d.scores.?, 0), attn, @intCast(lane.end), @intCast(lane.rings[i]), i != 1, @intCast(lane.from)) else k.attend(p, e, q, kb, vb, at(lane.k[i], 0), at(lane.v[i], 0), at(d.scores.?, 0), attn, @intCast(lane.end), @intCast(lane.rings[i]), i != 1, @intCast(lane.from)); + } + fwd.dense(d.target, e, layer.o, at(c.attn, 0), at(c.y, 0), rows); + k.residualNorm(p, e, at(c.y, 0), at(c.resid, 0), r(layer.post_norm), at(c.next_resid, 0), at(c.x, 0), rows, false); + fwd.dense(d.target, e, layer.gate, at(c.x, 0), at(c.gate, 0), rows); + fwd.dense(d.target, e, layer.up, at(c.x, 0), at(c.up, 0), rows); + k.swiglu(p, e, at(c.gate, 0), at(c.up, 0), at(c.act, 0), rows * state.intermediate); + fwd.dense(d.target, e, layer.down, at(c.act, 0), at(c.y, 0), rows); + const next_norm = if (i + 1 < d.weights.weights.layers.len) d.weights.weights.layers[i + 1].input_norm else d.weights.weights.norm; + k.residualNorm(p, e, at(c.y, 0), at(c.next_resid, 0), r(next_norm), at(c.resid, 0), at(c.x, 0), rows, false); + } + for (slots, 0..) |item, s| { + const lane = d.contexts.getPtr(items[item].stream).?; + const y = at(c.x, (s * state.block + 1) * state.hidden * 2); + const out = at(c.kappa, s * (state.block - 1) * 3 * state.rank * 4); + k.kappa(p, e, y, at(lane.newest, 0), r(d.weights.weights.rnn), r(d.weights.weights.rnn_bias), out, @min(items[item].depth, hold_depth)); + } + var first: usize = 0; + while (first < order.rows) { + const count: u32 = @intCast(@min(@as(usize, k.tile_rows), order.rows - first)); + const args = k.PackArgs{ .active = order.active, .first = @intCast(first), .count = count }; + k.cohortPack(&d.cohort, e, at(c.x, 0), at(c.tile, 0), args); + k.base(p, e, r(d.target.weights.unembed), at(c.tile, 0), at(c.base, first * state.vocabulary * 2), count, state.vocabulary); + first += count; + } + } + + /// Share block and unembed launches before stepping across all greedy streams. + fn holdCohort(d: *Drafter, items: []const dr.Hold) !void { + var depths: [k.cohort_streams]u32 = undefined; + for (items, 0..) |item, i| depths[i] = @min(item.depth, hold_depth); + const order = k.Order.sort(depths[0..items.len]); + const tokens = d.chain_tokens.slice(u32, k.cohort_streams * 8); const pool = mtl.objc.Pool.push(); defer pool.pop(); const cb = d.target.queue.commandBuffer(); const e = cb.compute(.serial); - for (items, 0..) |item, i| { - const depth: usize = @min(item.depth, 7); - const s = try d.slot(i); - const lane = d.contexts.getPtr(item.stream).?; - const held = Ref{ .buf = d.chain_tokens, .off = i * 8 * @sizeOf(u32) }; - tokens[i * 8] = item.pending; - d.encodeChain(e, s, lane, held, item.pending, item.position - 1, depth); + d.encodeCohort(e, items, &order); + const c = &d.cohort_state; + const held = Ref{ .buf = d.chain_tokens, .off = 0 }; + for (order.active, 0..) |streams, step| { + if (streams == 0) break; + const current = if (step % 2 == 0) c.state else c.next_state; + const next = if (step % 2 == 0) c.next_state else c.state; + k.cohortStep(&d.cohort, e, at(current, 0), at(c.kappa, 0), r(d.weights.weights.rnn), r(d.weights.weights.markov_w1), at(c.z, 0), at(next, 0), at(c.lambda, 0), held, @intCast(step), streams); + k.cohortLogits(&d.cohort, e, at(c.base, 0), at(d.weights.phi, 0), at(d.weights.beta, 0), at(c.lambda, 0), at(c.logits, 0), @intCast(order.first[step]), streams); + k.cohortPick(&d.cohort, e, at(c.logits, 0), held, @intCast(step), streams); } e.end(); cb.commit(); - try failed(cb, "chained block"); - for (items, 0..) |item, i| { - const depth: usize = @min(item.depth, 7); - const lane = d.contexts.getPtr(item.stream).?; - for (0..depth) |step| { - const token = tokens[i * 8 + step + 1]; + try failed(cb, "cohort hold"); + for (order.slots[0..items.len], 0..) |item, s| { + const lane = d.contexts.getPtr(items[item].stream).?; + for (0..depths[item]) |step| { + const token = tokens[s * 8 + step + 1]; if (token >= state.vocabulary) return error.DraftNonfinite; lane.held[step] = token; } - lane.held_len = @intCast(depth); + lane.held_len = depths[item]; } } @@ -375,16 +445,16 @@ pub const Drafter = struct { const d = cast(ptr); if (items.len == 0) return; var deepest: usize = 0; - for (items, 0..) |item, i| { + var greedy = items.len <= k.cohort_streams; + for (items) |item| { const lane = d.contexts.getPtr(item.stream) orelse return error.DraftStreamUnknown; if (item.depth == 0 or item.position == 0) return error.DraftDepth; if (lane.end != item.position - 1) return error.DraftContextGap; deepest = @max(deepest, @min(item.depth, 7)); - @memset((try d.slot(i)).state.slice(u16, state.rank), 0); + greedy = greedy and item.sampling == null; } - var greedy = items.len <= chain_streams; - for (items) |item| greedy = greedy and item.sampling == null; - if (greedy) return d.holdChained(items); + if (greedy) return d.holdCohort(items); + for (items, 0..) |_, i| @memset((try d.slot(i)).state.slice(u16, state.rank), 0); const previous = try d.gpa.alloc(u32, items.len); defer d.gpa.free(previous); const values = try d.gpa.alloc(f32, state.vocabulary); diff --git a/zig/src/families/inkling2/metal/dspark_kernels.zig b/zig/src/families/inkling2/metal/dspark_kernels.zig index d6d65528338..adc5dda4076 100644 --- a/zig/src/families/inkling2/metal/dspark_kernels.zig +++ b/zig/src/families/inkling2/metal/dspark_kernels.zig @@ -21,6 +21,14 @@ pub const units_chunk: u32 = 256; pub const TokenArgs = extern struct { token: u32 }; pub const CountArgs = extern struct { count: u32 }; pub const BaseArgs = extern struct { rows: u32, vocab: u32 }; +pub const CohortArgs = extern struct { streams: u32, row: u32 }; +pub const PackArgs = extern struct { active: [steps]u32, first: u32, count: u32 }; +/// Drafts a block's rows 1..7 hold: the recurrent steps' depths. +pub const steps: u32 = block_rows - 1; +/// Streams one greedy hold's cohort takes; a wider hold samples on the host as sampled streams do. +pub const cohort_streams: u32 = 16; +/// Rows one unembed launch takes: four streams' drafts share each weight row's read. +pub const tile_rows: u32 = 4 * steps; /// Round through binary32 and nearest-even BF16, returning an exactly representable FP64 value. pub fn roundBf16(v: anytype) f64 { @@ -131,6 +139,9 @@ pub const Chain = struct { pub fn load(device: mtl.Device, text: []const u8) !Chain { const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); defer lib.deinit(); + return fromLibrary(device, lib); + } + pub fn fromLibrary(device: mtl.Device, lib: mtl.Library) !Chain { const step = try mtl.Pipeline.init(device, lib, "tf_ink2_dspark_chain_step", false); errdefer step.deinit(); return .{ .step = step, .pick = try mtl.Pipeline.init(device, lib, "tf_ink2_dspark_chain_pick", false) }; @@ -142,6 +153,67 @@ pub const Chain = struct { } }; +/// The greedy cohort's five kernels, outside `Pipelines`: one launch each over the hold's active streams. +pub const Cohort = struct { + qkv: mtl.Pipeline, + step: mtl.Pipeline, + pick: mtl.Pipeline, + logits: mtl.Pipeline, + pack: mtl.Pipeline, + + pub fn fromLibrary(device: mtl.Device, lib: mtl.Library) !Cohort { + const qkv = try mtl.Pipeline.init(device, lib, "tf_ink2_dspark_cohort_qkv", false); + errdefer qkv.deinit(); + const step = try mtl.Pipeline.init(device, lib, "tf_ink2_dspark_cohort_step", false); + errdefer step.deinit(); + const pick = try mtl.Pipeline.init(device, lib, "tf_ink2_dspark_cohort_pick", false); + errdefer pick.deinit(); + const logits = try mtl.Pipeline.init(device, lib, "tf_ink2_dspark_cohort_logits", false); + errdefer logits.deinit(); + return .{ .qkv = qkv, .step = step, .pick = pick, .logits = logits, .pack = try mtl.Pipeline.init(device, lib, "tf_ink2_dspark_cohort_pack", false) }; + } + pub fn deinit(c: *Cohort) void { + c.pack.deinit(); + c.logits.deinit(); + c.pick.deinit(); + c.step.deinit(); + c.qkv.deinit(); + c.* = undefined; + } +}; + +/// A cohort's slot order, deepest first: each depth's active slots are then a prefix of `slots`. +pub const Order = struct { + /// The hold's item at each slot; the first `active[0]` are used. + slots: [cohort_streams]usize, + /// Slots with a draft after depth v, so depth v runs streams 0 .. active[v]. + active: [steps]u32, + /// The first packed base row of each depth. + first: [steps]usize, + /// Base rows the drafts pack into: every slot's. + rows: usize, + + /// Slots deepest first, input order kept among equals; each depth at most `steps`. + pub fn sort(depths: []const u32) Order { + std.debug.assert(depths.len > 0 and depths.len <= cohort_streams); + var out: Order = .{ .slots = undefined, .active = @splat(0), .first = @splat(0), .rows = 0 }; + for (depths, 0..) |depth, item| { + std.debug.assert(depth <= steps); + var place = item; + while (place > 0 and depths[out.slots[place - 1]] < depth) : (place -= 1) out.slots[place] = out.slots[place - 1]; + out.slots[place] = item; + } + for (out.slots[0..depths.len]) |item| { + for (0..depths[item]) |v| out.active[v] += 1; + } + for (0..steps) |v| { + out.first[v] = out.rows; + out.rows += out.active[v]; + } + return out; + } +}; + /// The block attention on the tensor units, outside `Pipelines`: a chunk's partial sums, then their fold. pub const Units = struct { partials: mtl.Pipeline, @@ -259,7 +331,7 @@ pub fn residualNorm(p: *const Pipelines, e: mtl.ComputeEncoder, x: Ref, residual /// Gate and up projections are BF16 rows with 9216 entries; only this SwiGLU product is stored here. pub fn swiglu(p: *const Pipelines, e: mtl.ComputeEncoder, gate: Ref, up: Ref, out: Ref, count: u32) void { - std.debug.assert(count == 8 * intermediate); + std.debug.assert(count % (8 * intermediate) == 0); e.setPipeline(p.swiglu); bind(e, &.{ gate, up, out }); e.setValue(CountArgs{ .count = count }, 3); @@ -306,7 +378,7 @@ pub fn base(p: *const Pipelines, e: mtl.ComputeEncoder, unembed: Ref, y: Ref, ou e.setPipeline(p.base); bind(e, &.{ unembed, y, out }); e.setValue(BaseArgs{ .rows = rows, .vocab = vocabulary_count }, 3); - std.debug.assert(rows <= 7); + std.debug.assert(rows <= tile_rows); groups(e, (@as(usize, vocabulary_count) + 7) / 8, 256); } /// Folded Phi/beta correction and target-style 30 tanh softcap, restricted to Mini's 200058 logits. @@ -316,3 +388,56 @@ pub fn finalLogits(p: *const Pipelines, e: mtl.ComputeEncoder, base_values: Ref, e.setValue(CountArgs{ .count = vocab }, 5); threads(e, vocab, 256); } + +/// The cohort's row zero of each block copies its embedded anchor; `anchors` holds `streams` contiguous rows. +pub fn cohortInitializeRows(p: *const Pipelines, e: mtl.ComputeEncoder, anchors: Ref, mask_embed: Ref, out: Ref, streams: u32) void { + std.debug.assert(streams > 0 and streams <= cohort_streams); + e.setPipeline(p.init_rows); + bind(e, &.{ anchors, mask_embed, out }); + e.dispatchGroups(mtl.Size.of(block_rows, streams, 1), mtl.Size.of(256, 1, 1)); +} + +/// `blockQkv` over `streams` eight-row blocks: each block's rows take `anchors[stream]` as their first position. +pub fn cohortQkv(c: *const Cohort, e: mtl.ComputeEncoder, q_raw: Ref, k_raw: Ref, v_raw: Ref, q_norm: Ref, k_norm: Ref, q: Ref, k: Ref, v: Ref, anchors: Ref, streams: u32) void { + std.debug.assert(streams > 0 and streams <= cohort_streams); + e.setPipeline(c.qkv); + bind(e, &.{ q_raw, k_raw, v_raw, q_norm, k_norm, q, k, v, anchors }); + e.dispatchGroups(mtl.Size.of(40, streams * block_rows, 1), mtl.Size.of(128, 1, 1)); +} + +/// The cohort's unembed input: packed rows `first` .. `first` + `count`, a draft row a stream a depth. +pub fn cohortPack(c: *const Cohort, e: mtl.ComputeEncoder, x: Ref, out: Ref, args: PackArgs) void { + std.debug.assert(args.count > 0 and args.first + args.count <= steps * cohort_streams); + e.setPipeline(c.pack); + bind(e, &.{ x, out }); + e.setValue(args, 2); + e.dispatchGroups(mtl.Size.of(cohort_streams, steps, 1), mtl.Size.of(256, 1, 1)); +} + +/// Depth `row` for streams 0 .. `streams`: stream s takes kappa row 7s + row after the token held[8s + row]. +pub fn cohortStep(c: *const Cohort, e: mtl.ComputeEncoder, state: Ref, kappa_rows: Ref, rnn_weight: Ref, markov_w1: Ref, z: Ref, next_state: Ref, lambda: Ref, held: Ref, row: u32, streams: u32) void { + std.debug.assert(row < steps and streams > 0 and streams <= cohort_streams); + e.setPipeline(c.step); + bind(e, &.{ state, kappa_rows, rnn_weight, markov_w1, z, next_state, lambda }); + e.setValue(CohortArgs{ .streams = streams, .row = row }, 7); + e.setBuffer(held.buf, held.off, 8); + groups(e, streams, 256); +} + +/// Final logits of base rows `row` .. for streams 0 .. `streams`: lambda row s, out row s. +pub fn cohortLogits(c: *const Cohort, e: mtl.ComputeEncoder, base_values: Ref, phi: Ref, beta: Ref, lambda: Ref, out: Ref, row: u32, streams: u32) void { + std.debug.assert(streams > 0 and streams <= cohort_streams); + e.setPipeline(c.logits); + bind(e, &.{ base_values, phi, beta, lambda, out }); + e.setValue(CohortArgs{ .streams = streams, .row = row }, 5); + threads(e, vocab, 256); +} + +/// Depth `row`'s picks for streams 0 .. `streams`: held[8s + row + 1] is the first greatest of logits row s. +pub fn cohortPick(c: *const Cohort, e: mtl.ComputeEncoder, logits: Ref, held: Ref, row: u32, streams: u32) void { + std.debug.assert(row < steps and streams > 0 and streams <= cohort_streams); + e.setPipeline(c.pick); + bind(e, &.{ logits, held }); + e.setValue(CohortArgs{ .streams = streams, .row = row }, 2); + groups(e, streams, 1024); +} diff --git a/zig/src/families/inkling2/metal/dspark_state.zig b/zig/src/families/inkling2/metal/dspark_state.zig index c27eb93b554..d127e003708 100644 --- a/zig/src/families/inkling2/metal/dspark_state.zig +++ b/zig/src/families/inkling2/metal/dspark_state.zig @@ -39,6 +39,78 @@ pub fn scratchBytes() usize { return bytes; } +const cohort_fields = [_][]const u8{ + "ids", "anchors", "state", "next_state", "z", "lambda", "x", "y", "resid", "next_resid", "q_raw", "k_raw", + "v_raw", "q", "kb", "vb", "attn", "gate", "up", "act", "kappa", "tile", "base", "logits", +}; + +fn cohortSizes() [cohort_fields.len]usize { + const s: usize = kernels.cohort_streams; + const rows = s * block; + const drafts = s * (block - 1); + const b = 2; + return .{ + s * 4, s * 4, s * rank * b, s * rank * b, + s * 3 * rank * b, s * rank * b, rows * hidden * b, rows * hidden * b, + rows * hidden * b, rows * hidden * b, rows * query * b, rows * kv * b, + rows * kv * b, rows * query * b, rows * kv * b, rows * kv * b, + rows * query * b, rows * intermediate * b, rows * intermediate * b, rows * intermediate * b, + drafts * 3 * rank * 4, kernels.tile_rows * hidden * b, drafts * vocabulary * b, s * vocabulary * b, + }; +} + +pub fn cohortBytes() usize { + var bytes: usize = 0; + for (cohortSizes()) |n| bytes += n; + return bytes; +} + +/// One greedy hold's cohort: every stream's eight block rows, the drafts' packed unembed input and their base rows. +pub const Cohort = struct { + ids: mtl.Buffer, + anchors: mtl.Buffer, + state: mtl.Buffer, + next_state: mtl.Buffer, + z: mtl.Buffer, + lambda: mtl.Buffer, + x: mtl.Buffer, + y: mtl.Buffer, + resid: mtl.Buffer, + next_resid: mtl.Buffer, + q_raw: mtl.Buffer, + k_raw: mtl.Buffer, + v_raw: mtl.Buffer, + q: mtl.Buffer, + kb: mtl.Buffer, + vb: mtl.Buffer, + attn: mtl.Buffer, + gate: mtl.Buffer, + up: mtl.Buffer, + act: mtl.Buffer, + kappa: mtl.Buffer, + tile: mtl.Buffer, + base: mtl.Buffer, + logits: mtl.Buffer, + + pub fn init(device: mtl.Device) !Cohort { + @setEvalBranchQuota(10_000); + const ns = cohortSizes(); + var c: Cohort = undefined; + var made: usize = 0; + errdefer inline for (cohort_fields, 0..) |f, i| if (i < made) @field(c, f).deinit(); + inline for (cohort_fields, 0..) |f, i| { + @field(c, f) = try device.buffer(ns[i], mtl.ResourceOptions.shared); + made += 1; + } + return c; + } + + pub fn deinit(c: *Cohort) void { + inline for (cohort_fields) |f| @field(c, f).deinit(); + c.* = undefined; + } +}; + pub const Scratch = struct { ids: mtl.Buffer, resid: mtl.Buffer, From 0911e37e58dd8d34f49d35ad0115d2ad02534b12 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:36:42 +0800 Subject: [PATCH 02/14] inkling2 metal: cover cohort depths and solo token equality --- ...nkling-2-mini-on-mac-all-streams-dspark.md | 4 + .../inkling2/metal/dspark_kernels_test.zig | 13 ++ .../families/inkling2/metal/serving_test.zig | 150 +++++++++++++++++- 3 files changed, 163 insertions(+), 4 deletions(-) create mode 100644 changelog.d/235-inkling-2-mini-on-mac-all-streams-dspark.md diff --git a/changelog.d/235-inkling-2-mini-on-mac-all-streams-dspark.md b/changelog.d/235-inkling-2-mini-on-mac-all-streams-dspark.md new file mode 100644 index 00000000000..c3f601b65f7 --- /dev/null +++ b/changelog.d/235-inkling-2-mini-on-mac-all-streams-dspark.md @@ -0,0 +1,4 @@ +# Inkling 2 Mini on Metal: shared DSpark holds across streams + +- Schedule greedy DSpark holds by block and recurrent step across active streams, batching the unembedding weight read for each cohort rather than completing one stream's draft chain before starting the next. +- Check greedy draft-token equality against solo holds with unequal depths, streams joining or leaving, and 16-stream cohorts. diff --git a/zig/src/families/inkling2/metal/dspark_kernels_test.zig b/zig/src/families/inkling2/metal/dspark_kernels_test.zig index 6da89b8b598..e9a217774fc 100644 --- a/zig/src/families/inkling2/metal/dspark_kernels_test.zig +++ b/zig/src/families/inkling2/metal/dspark_kernels_test.zig @@ -154,6 +154,19 @@ test "folded correction rounds bias then logits before the thirty softcap" { try t.expect(saturated <= 30 and saturated > 29.9); } +test "DSpark cohort depth order packs each active prefix without losing a stream" { + const depths = [_]u32{ 2, 7, 1, 4, 7 }; + const order = k.Order.sort(&depths); + try t.expectEqualSlices(usize, &.{ 1, 4, 3, 0, 2 }, order.slots[0..depths.len]); + try t.expectEqualSlices(u32, &.{ 5, 4, 3, 3, 2, 2, 2 }, &order.active); + try t.expectEqualSlices(usize, &.{ 0, 5, 9, 12, 15, 17, 19 }, &order.first); + try t.expectEqual(@as(usize, 21), order.rows); + for (order.active, 0..) |active, step| { + for (order.slots[0..active]) |item| try t.expect(depths[item] > step); + for (order.slots[active..depths.len]) |item| try t.expect(depths[item] <= step); + } +} + test "the tensor-unit attention spans the kept keys in whole chunks, and none without a key" { try t.expectEqual(@as(u32, 0), k.unitsSpan(0, false, 0).chunks); try t.expectEqual(@as(u32, 0), k.unitsSpan(700, false, 700).chunks); diff --git a/zig/src/families/inkling2/metal/serving_test.zig b/zig/src/families/inkling2/metal/serving_test.zig index 5e759627839..0d27e0f4e89 100644 --- a/zig/src/families/inkling2/metal/serving_test.zig +++ b/zig/src/families/inkling2/metal/serving_test.zig @@ -170,13 +170,13 @@ fn serve(native_opened: api.Opened, id: api.Id, request: *const api.Request) !Re return reply; } -fn opened(dir: []const u8, drafter: ?[]const u8, cache_gib: ?f64) !api.Opened { +fn opened(dir: []const u8, drafter: ?[]const u8, cache_gib: ?f64, stream_count: u32) !api.Opened { var why: []const u8 = ""; const result = try native.open(gpa, gpa, io, .{ .dir = dir, .model_type = "inkling2_loop", .context = context, - .lanes = 1, + .lanes = stream_count, .drafts = drafter != null, .drafter = drafter, .prompt_cache_gib = cache_gib, @@ -257,7 +257,7 @@ test "Mini Metal serving matches the host reference token for token" { for (refs.first.tap) |byte| tap_nonzero = tap_nonzero or byte != 0; try std.testing.expect(tap_nonzero); - const opened_once = try opened(dir, null, 1); + const opened_once = try opened(dir, null, 1, 1); defer opened_once.close(opened_once.ctx); try std.testing.expectEqual(@as(?f64, 0.5), opened_once.engine.info().decode_share); const keepalive = opened_once.engine.keepaliveTarget() orelse return error.MissingMiniKeepalive; @@ -285,7 +285,7 @@ test "Mini Metal opt-in DSpark drafting preserves target tokens and rolls back e const refs = try withReference(dir, &ids, &turn); try transactions(dir, drafter, &ids, &refs.first); - const opened_once = try opened(dir, drafter, 1); + const opened_once = try opened(dir, drafter, 1, 1); defer opened_once.close(opened_once.ctx); var plain = try serve(opened_once, 10, &.{ .prompt = &ids, .max_tokens = made, .drafts = false, .logprobs = 3, .history_len = ids.len }); defer plain.deinit(); @@ -306,6 +306,148 @@ test "Mini Metal opt-in DSpark drafting preserves target tokens and rolls back e try expectTokens(&refs.second.?, &restored); } +const AbsorbSink = struct { + d: lanes.drafter.Drafter, + + fn take(ptr: *anyopaque, s: *lanes.Stream, f: lanes.backend.Features, start: u64) !void { + const self: *AbsorbSink = @ptrCast(@alignCast(ptr)); + const ids = s.prompt(); + const last = ids.len - 1; + if (start >= last) return; + var rows = f; + rows.rows = @intCast(@min(f.rows, last - start)); + try self.d.absorb(&.{.{ .stream = s, .features = rows, .start = start, .follow = ids[@intCast(start + 1)..][0..rows.rows] }}); + } +}; + +fn prepareHold(b: lanes.backend.Backend, d: lanes.drafter.Drafter, s: *lanes.Stream) !u32 { + try d.open(s); + errdefer d.release(s); + var sink: AbsorbSink = .{ .d = d }; + try b.vtable.prefill_features.?(b.ptr, s, d.taps(), .{ .ptr = &sink, .take = AbsorbSink.take }); + errdefer b.release(s); + const ids = s.prompt(); + const pending = try b.read(try b.first(s, ids.len)); + const last = try b.features(s, d.taps(), ids.len - 1, 1); + const follow = [1]u32{pending}; + try d.absorb(&.{.{ .stream = s, .features = last, .start = ids.len - 1, .follow = &follow }}); + return pending; +} + +fn holdAlone(b: lanes.backend.Backend, d: lanes.drafter.Drafter, ids: []const u32, depth: u32, out: []u32) !void { + var s = try lanes.Stream.init(gpa, .{ .id = "solo-hold", .prompt = ids, .max_new = made, .drafts = true }); + defer s.deinit(gpa); + const pending = try prepareHold(b, d, &s); + defer b.release(&s); + defer d.release(&s); + try d.hold(&.{.{ .stream = &s, .pending = pending, .position = ids.len + 1, .depth = depth }}); + try d.held(&.{&s}, &.{out}); +} + +test "Mini Metal DSpark sixteen-stream chain preserves solo holds at unequal depths" { + const dir = try checkpoint(); + const drafter_dir = @import("sys").getenv("TF_INKLING2_DSPARK_DIR") orelse return error.SkipZigTest; + const depths = [_]u32{ 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 3, 6 }; + var ids: [16][history]u32 = undefined; + for (&ids, 0..) |*p, i| p.* = prompt(history, @intCast(40 + i)); + + const model = try Model.load(gpa, io, dir); + defer model.deinit(); + const target = try backend.Metal.init(gpa, model, .{ .capacity = context, .streams = 16, .budget = 16 * st.cacheBytes(context) }); + defer target.deinit(); + const draft_head = try dspark.Drafter.init(gpa, io, model.device, model, drafter_dir); + defer draft_head.deinit(); + try draft_head.setContext(context); + const b = target.backend(); + const d = draft_head.drafter(); + try b.vtable.prepare_features.?(b.ptr, d.taps()); + var want: [16][7]u32 = undefined; + for (0..16) |i| try holdAlone(b, d, &ids[i], depths[i], want[i][0..depths[i]]); + + var streams: [16]lanes.Stream = undefined; + var initialized: usize = 0; + defer for (streams[0..initialized]) |*s| s.deinit(gpa); + for (&streams, 0..) |*s, i| { + s.* = try lanes.Stream.init(gpa, .{ .id = "chain-hold", .prompt = &ids[i], .max_new = made, .drafts = true }); + initialized += 1; + } + var prepared: usize = 0; + defer for (streams[0..prepared]) |*s| b.release(s); + defer for (streams[0..prepared]) |*s| d.release(s); + var holds: [16]lanes.drafter.Hold = undefined; + for (&streams, 0..) |*s, i| { + const pending = try prepareHold(b, d, s); + prepared += 1; + holds[i] = .{ .stream = s, .pending = pending, .position = history + 1, .depth = depths[i] }; + } + var got: [16][7]u32 = undefined; + var ptrs: [16]*lanes.Stream = undefined; + var outs: [16][]u32 = undefined; + for (0..16) |i| { + ptrs[i] = &streams[i]; + outs[i] = got[i][0..depths[i]]; + } + try d.hold(holds[0..4]); + try d.held(ptrs[0..4], outs[0..4]); + for (0..4) |i| try std.testing.expectEqualSlices(u32, want[i][0..depths[i]], outs[i]); + try d.hold(&holds); + try d.held(&ptrs, &outs); + for (0..16) |i| try std.testing.expectEqualSlices(u32, want[i][0..depths[i]], outs[i]); +} + +test "Mini Metal DSpark four prompts equal solos through a leave and join" { + const dir = try checkpoint(); + const drafter = @import("sys").getenv("TF_INKLING2_DSPARK_DIR") orelse return error.SkipZigTest; + const opened_wide = try opened(dir, drafter, 0, 4); + defer opened_wide.close(opened_wide.ctx); + var ids: [4][history]u32 = undefined; + var requests: [4]api.Request = undefined; + for (0..4) |i| { + ids[i] = prompt(history, @intCast(70 + i)); + // Null sampling is the native request's temperature-zero, greedy representation. + requests[i] = .{ .prompt = &ids[i], .max_tokens = made, .sampling = null, .drafts = true }; + } + var solo: [4]Reply = .{ .{}, .{}, .{}, .{} }; + defer for (&solo) |*r| r.deinit(); + for (0..4) |i| solo[i] = try serve(opened_wide, 200 + i, &requests[i]); + + var batched: [4]Reply = .{ .{}, .{}, .{}, .{} }; + defer for (&batched) |*r| r.deinit(); + var drafted: u64 = 0; + var accepted: u64 = 0; + for (0..4) |i| try opened_wide.engine.submit(210 + i, &requests[i], .{ .ctx = &batched[i], .event = Reply.event }); + for (0..4) |i| try std.testing.expectEqual(api.Reason.length, try batched[i].wait()); + for (0..4) |i| { + try std.testing.expectEqual(@as(usize, made), batched[i].tokens.items.len); + try std.testing.expectEqualSlices(u32, solo[i].tokens.items, batched[i].tokens.items); + drafted += batched[i].drafted; + accepted += batched[i].accepted; + } + for (0..4) |i| { + var previous = batched[i]; + batched[i] = .{}; + previous.deinit(); + } + const lengths = [_]u32{ 6, 12, made, made }; + for (0..3) |i| { + requests[i].max_tokens = lengths[i]; + try opened_wide.engine.submit(220 + i, &requests[i], .{ .ctx = &batched[i], .event = Reply.event }); + } + try std.testing.expectEqual(api.Reason.length, try batched[0].wait()); + try std.testing.expectEqual(@as(usize, 6), batched[0].tokens.items.len); + try opened_wide.engine.submit(223, &requests[3], .{ .ctx = &batched[3], .event = Reply.event }); + try std.testing.expectEqual(api.Reason.length, try batched[1].wait()); + for (2..4) |i| try std.testing.expectEqual(api.Reason.length, try batched[i].wait()); + for (0..4) |i| { + try std.testing.expectEqual(@as(usize, lengths[i]), batched[i].tokens.items.len); + try std.testing.expectEqualSlices(u32, solo[i].tokens.items[0..lengths[i]], batched[i].tokens.items); + drafted += batched[i].drafted; + accepted += batched[i].accepted; + } + try std.testing.expect(drafted > 0); + try std.testing.expect(accepted > 0); +} + test "Mini Metal fills a prompt a chunk a call to the whole pass's first row and features" { const dir = try checkpoint(); const ids = prompt(64, 5); From ea994bd02d27b53b4b2b0f8e97ba0552512093b2 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:50:12 +0800 Subject: [PATCH 03/14] inkling2 metal: reduce only active DSpark unembed rows --- zig/kernels/metal/inkling2/dspark.metal | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/zig/kernels/metal/inkling2/dspark.metal b/zig/kernels/metal/inkling2/dspark.metal index 5a85b42c58e..92dbc059bf8 100644 --- a/zig/kernels/metal/inkling2/dspark.metal +++ b/zig/kernels/metal/inkling2/dspark.metal @@ -325,9 +325,9 @@ kernel void tf_ink2_dspark_base(const device bfloat* unembed [[buffer(0)]], cons } } #pragma unroll - for (uint row = 0; row < DSP_TILE; ++row) { + for (uint row = 0; row < a.rows; ++row) { const float sum = simd_sum(acc[row]); - if (row < a.rows && lane == 0) out[size_t(row) * a.vocab + id] = bfloat(sum); + if (lane == 0) out[size_t(row) * a.vocab + id] = bfloat(sum); } } From 7c5106906455952131d328970b4c2c4ccede5627 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:04:56 +0800 Subject: [PATCH 04/14] inkling2 metal: keep a lone greedy DSpark hold on its solo chain --- zig/src/families/inkling2/metal/dspark.zig | 35 ++++++++++++++-------- 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/zig/src/families/inkling2/metal/dspark.zig b/zig/src/families/inkling2/metal/dspark.zig index d3817d74409..f7159ff70ec 100644 --- a/zig/src/families/inkling2/metal/dspark.zig +++ b/zig/src/families/inkling2/metal/dspark.zig @@ -405,7 +405,8 @@ pub const Drafter = struct { } } - /// Share block and unembed launches before stepping across all greedy streams. + /// Share block and unembed launches before stepping across all greedy streams; a lone stream keeps the chain the + /// depth rule measured, which skips the cohort's packing launches. fn holdCohort(d: *Drafter, items: []const dr.Hold) !void { var depths: [k.cohort_streams]u32 = undefined; for (items, 0..) |item, i| depths[i] = @min(item.depth, hold_depth); @@ -415,17 +416,12 @@ pub const Drafter = struct { defer pool.pop(); const cb = d.target.queue.commandBuffer(); const e = cb.compute(.serial); - d.encodeCohort(e, items, &order); - const c = &d.cohort_state; - const held = Ref{ .buf = d.chain_tokens, .off = 0 }; - for (order.active, 0..) |streams, step| { - if (streams == 0) break; - const current = if (step % 2 == 0) c.state else c.next_state; - const next = if (step % 2 == 0) c.next_state else c.state; - k.cohortStep(&d.cohort, e, at(current, 0), at(c.kappa, 0), r(d.weights.weights.rnn), r(d.weights.weights.markov_w1), at(c.z, 0), at(next, 0), at(c.lambda, 0), held, @intCast(step), streams); - k.cohortLogits(&d.cohort, e, at(c.base, 0), at(d.weights.phi, 0), at(d.weights.beta, 0), at(c.lambda, 0), at(c.logits, 0), @intCast(order.first[step]), streams); - k.cohortPick(&d.cohort, e, at(c.logits, 0), held, @intCast(step), streams); - } + if (items.len == 1) { + @memset(d.scratch.state.slice(u16, state.rank), 0); + tokens[0] = items[0].pending; + const lane = d.contexts.getPtr(items[0].stream).?; + d.encodeChain(e, &d.scratch, lane, .{ .buf = d.chain_tokens, .off = 0 }, items[0].pending, items[0].position - 1, depths[0]); + } else d.encodeSteps(e, items, &order); e.end(); cb.commit(); try failed(cb, "cohort hold"); @@ -440,6 +436,21 @@ pub const Drafter = struct { } } + /// The cohort's shared block and unembed launches, then one step, logits and pick launch set per recurrent depth. + fn encodeSteps(d: *Drafter, e: mtl.ComputeEncoder, items: []const dr.Hold, order: *const k.Order) void { + d.encodeCohort(e, items, order); + const c = &d.cohort_state; + const held = Ref{ .buf = d.chain_tokens, .off = 0 }; + for (order.active, 0..) |streams, step| { + if (streams == 0) break; + const current = if (step % 2 == 0) c.state else c.next_state; + const next = if (step % 2 == 0) c.next_state else c.state; + k.cohortStep(&d.cohort, e, at(current, 0), at(c.kappa, 0), r(d.weights.weights.rnn), r(d.weights.weights.markov_w1), at(c.z, 0), at(next, 0), at(c.lambda, 0), held, @intCast(step), streams); + k.cohortLogits(&d.cohort, e, at(c.base, 0), at(d.weights.phi, 0), at(d.weights.beta, 0), at(c.lambda, 0), at(c.logits, 0), @intCast(order.first[step]), streams); + k.cohortPick(&d.cohort, e, at(c.logits, 0), held, @intCast(step), streams); + } + } + /// Every stream's block and first step in one command buffer, then one command buffer a later step for all of them. fn holdFn(ptr: *anyopaque, items: []const dr.Hold) anyerror!void { const d = cast(ptr); From 46219d6c45b2592292305823d435026bd0f2fdeb Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Tue, 24 Nov 2026 02:04:56 +0800 Subject: [PATCH 05/14] docs: card 235's step-major DSpark receipt and engine comparison on M5 Ultra --- ...nkling-2-mini-on-mac-all-streams-dspark.md | 3 +- .../inkling-2-mini-metal-235/README.md | 60 +++++++++++++++++++ .../inkling-2-mini-metal-235/bench.sh | 17 ++++++ .../inkling-2-mini-metal-235/cells.jsonl | 36 +++++++++++ .../inkling-2-mini-metal-235/engines.sh | 29 +++++++++ 5 files changed, 144 insertions(+), 1 deletion(-) create mode 100644 docs/receipts/inkling-2-mini-metal-235/README.md create mode 100755 docs/receipts/inkling-2-mini-metal-235/bench.sh create mode 100644 docs/receipts/inkling-2-mini-metal-235/cells.jsonl create mode 100755 docs/receipts/inkling-2-mini-metal-235/engines.sh diff --git a/changelog.d/235-inkling-2-mini-on-mac-all-streams-dspark.md b/changelog.d/235-inkling-2-mini-on-mac-all-streams-dspark.md index c3f601b65f7..9b0615b51f4 100644 --- a/changelog.d/235-inkling-2-mini-on-mac-all-streams-dspark.md +++ b/changelog.d/235-inkling-2-mini-on-mac-all-streams-dspark.md @@ -1,4 +1,5 @@ # Inkling 2 Mini on Metal: shared DSpark holds across streams -- Schedule greedy DSpark holds by block and recurrent step across active streams, batching the unembedding weight read for each cohort rather than completing one stream's draft chain before starting the next. +- Schedule greedy DSpark holds by block and recurrent step across active streams, batching the unembedding weight read for each cohort rather than completing one stream's draft chain before starting the next; a lone stream keeps its solo chain. - Check greedy draft-token equality against solo holds with unequal depths, streams joining or leaving, and 16-stream cohorts. +- On the M5 Ultra, greedy DSpark reaches 310 / 257 tok/s at four streams (code / chat, up 14% / 37% on the better control) and 344 / 235 at sixteen, with acceptance unchanged; `docs/receipts/inkling-2-mini-metal-235` also holds the 1, 4 and 64-stream receipt against oMLX 0.8.2 on the same machine. diff --git a/docs/receipts/inkling-2-mini-metal-235/README.md b/docs/receipts/inkling-2-mini-metal-235/README.md new file mode 100644 index 00000000000..0ed48c1ba6c --- /dev/null +++ b/docs/receipts/inkling-2-mini-metal-235/README.md @@ -0,0 +1,60 @@ +# Inkling 2 Mini on Metal, M5 Ultra: card 235's receipt + +Apple M5 Ultra, 256 GB, macOS 27.0; the official checkpoint (`Inkling-2-Mini`, its own `mtp.safetensors` as the +DSpark drafter); `tensorfold-native` from `zig build native -Doptimize=ReleaseFast`, `--context 65536`. Control is +card 210's head (781eeab52), candidate this branch. Every run held `/tmp/tensorfold-model.lock` inside the Desk's Mac +GPU window, one server at a time. Other agents' builds kept the load average between 14 and 40, which moves the +controls by up to 30%; the candidate ran between them. + +## Step-major holds + +`bench.sh` (`tools/bench_concurrent.py --levels 1,2,4,16 --reps 3 --tokens 256 --temperatures 0 --alone`), medians +of three reps, aggregate tok/s. Control, candidate, control: + +| code / chat | control | **candidate** | control again | tokens a round (all three) | +|---|---|---|---|---| +| 1 stream | 123.2 / 67.5 | **121.7 / 90.5** | 112.2 / 82.4 | 3.37 / 2.29-2.56 | +| 2 streams | 188.9 / 121.9 | **205.6 / 170.1** | 186.4 / 139.5 | 2.81 / 2.33 | +| 4 streams | 271.2 / 136.5 | **310.3 / 256.5** | 239.6 / 187.8 | 2.81 / 2.33 | +| 16 streams | 262.2 / 130.5 | **344.1 / 234.6** | 243.9 / 222.0 | 2.81 / 2.33 | + +- Against the better control: +8.8% / +21.9% at two streams, +14.4% / +36.6% at four, +31.2% / +5.7% at sixteen. One + stream keeps the solo chain (−1.2% on code, inside the controls' spread). +- Acceptance: at every depth the drafts equal the control's, so tokens a round agree cell for cell from two streams on + (one stream's chunking varies with timing). Accepted over drafted across each session: 21,844 / 42,709 (51.1%), + candidate 21,833 / 42,386 (51.5%), control 21,870 / 43,100 (50.7%). +- 0 failed requests; every concurrent reply equal to its run alone (3, 6, 12 and 48 of each in every session). + +## Against the fastest other engine here + +`engines.sh` (`--levels 1,4,64 --reps 3 --tokens 256 --temperatures 0`), end-to-end tok/s (a reply that arrives as +one text piece has no decode time, so the aggregate column reads 0 for it), medians of three: + +| code / chat | TensorFold, DSpark | oMLX 0.8.2, MTP | ratio | +|---|---|---|---| +| 1 stream | **112.3 / 90.7** | 45.1 / 8.3 | 2.5x / 10.9x | +| 4 streams | **292.0 / 256.4** | 107.0 / 79.1 | 2.7x / 3.2x | +| 64 streams | **341.8 / 232.8** | 209.3 / 227.6 | 1.6x / 1.02x | + +- oMLX serves its own 4-bit build (`Inkling-2-Mini-oQ4e-mtp`, about 17 GB) with MTP drafting on; TensorFold serves the + official NVFP4/MXFP8 checkpoint. oMLX's chat reps vary 4.5x at one stream (6.9-37.7); its best rep is still 2.4x + under ours. At 64 chat streams the two tie within the reps' spread (ours 210.9-277.3, oMLX 207.7-282.8). +- Not runnable here: Strata (no binary or weights; v0.2.19 publishes 108.9-114.5 tok/s at one stream on M5 Max), + llama.cpp (no `llama-server`, no Inkling GGUF), mlx-lm `mlx_lm.server` (installed with Inkling support, but oMLX + wraps the same kernels with batching, so it is the stronger of the two). + +## Exactness + +`TF_INKLING2_METAL_DIR` and `TF_INKLING2_DSPARK_DIR` set to the checkpoint, the `test-inkling2-metal-host` test +binary runs on the device: + +- `Mini Metal DSpark sixteen-stream chain preserves solo holds at unequal depths`: depths 1-7, four streams then all + sixteen in one hold, each equal to its own solo hold; +- `Mini Metal DSpark four prompts equal solos through a leave and join`: four greedy replies equal four solo replies + token for token while a stream leaves and another joins; +- `Mini Metal opt-in DSpark drafting preserves target tokens and rolls back exactly`. + +## Files + +`cells.jsonl`: each cell of the five sessions; `bench.sh` and `engines.sh` reproduce them (`MODEL` names the +checkpoint, `OUT` the scratch folder, `OMLX` the oMLX binary). diff --git a/docs/receipts/inkling-2-mini-metal-235/bench.sh b/docs/receipts/inkling-2-mini-metal-235/bench.sh new file mode 100755 index 00000000000..f02e6ef5b33 --- /dev/null +++ b/docs/receipts/inkling-2-mini-metal-235/bench.sh @@ -0,0 +1,17 @@ +#!/bin/bash +# bench.sh LABEL BINARY: one DSpark server session from BINARY, bench_concurrent at 1, 2, 4 and 16 streams, greedy, +# 3 reps. Run it under `lockf -k /tmp/tensorfold-model.lock`, one at a time; LEVELS overrides the stream counts. +set -euo pipefail +label=$1 bin=$2 +wt=$(git -C "$(dirname "$0")" rev-parse --show-toplevel) +model=${MODEL:-$HOME/models/Inkling-2-Mini} +out=${OUT:-/tmp/ink2-bench} +mkdir -p "$out" +[ -e /Users/Shared/agent-work/mac-gpu-window ] || { echo "no Mac GPU window" >&2; exit 3; } +"$bin" serve "$model" --port 18235 --context 65536 --drafter "$model" >"$out/$label.server.log" 2>&1 & +pid=$! +trap 'kill -INT $pid 2>/dev/null; wait $pid 2>/dev/null' EXIT +for _ in $(seq 240); do curl -sf http://127.0.0.1:18235/v1/models >/dev/null && break; sleep 1; done +/opt/homebrew/bin/python3.13 "$wt/tools/bench_concurrent.py" http://127.0.0.1:18235 Inkling-2-Mini \ + --levels "${LEVELS:-1,2,4,16}" --reps 3 --tokens 256 --temperatures 0 --label "$label" --alone \ + --output "$out/$label.json" 2>&1 | tail -n 6 diff --git a/docs/receipts/inkling-2-mini-metal-235/cells.jsonl b/docs/receipts/inkling-2-mini-metal-235/cells.jsonl new file mode 100644 index 00000000000..e3c6c83170c --- /dev/null +++ b/docs/receipts/inkling-2-mini-metal-235/cells.jsonl @@ -0,0 +1,36 @@ +{"label": "c2-ctl-a", "prompt": "code", "streams": 1, "aggregate_tps": 123.2, "end_to_end_tps": 120.0, "tokens_per_round": 3.368, "failed": 0, "alone": {"equal": 3, "unequal": 0, "failed": 0}} +{"label": "c2-ctl-a", "prompt": "code", "streams": 2, "aggregate_tps": 188.9, "end_to_end_tps": 185.2, "tokens_per_round": 2.813, "failed": 0, "alone": {"equal": 6, "unequal": 0, "failed": 0}} +{"label": "c2-ctl-a", "prompt": "code", "streams": 4, "aggregate_tps": 271.2, "end_to_end_tps": 267.6, "tokens_per_round": 2.813, "failed": 0, "alone": {"equal": 12, "unequal": 0, "failed": 0}} +{"label": "c2-ctl-a", "prompt": "code", "streams": 16, "aggregate_tps": 262.2, "end_to_end_tps": 262.0, "tokens_per_round": 2.813, "failed": 0, "alone": {"equal": 48, "unequal": 0, "failed": 0}} +{"label": "c2-ctl-a", "prompt": "chat", "streams": 1, "aggregate_tps": 67.5, "end_to_end_tps": 65.8, "tokens_per_round": 2.286, "failed": 0, "alone": {"equal": 3, "unequal": 0, "failed": 0}} +{"label": "c2-ctl-a", "prompt": "chat", "streams": 2, "aggregate_tps": 121.9, "end_to_end_tps": 118.7, "tokens_per_round": 2.327, "failed": 0, "alone": {"equal": 6, "unequal": 0, "failed": 0}} +{"label": "c2-ctl-a", "prompt": "chat", "streams": 4, "aggregate_tps": 136.5, "end_to_end_tps": 134.4, "tokens_per_round": 2.327, "failed": 0, "alone": {"equal": 12, "unequal": 0, "failed": 0}} +{"label": "c2-ctl-a", "prompt": "chat", "streams": 16, "aggregate_tps": 130.5, "end_to_end_tps": 130.5, "tokens_per_round": 2.327, "failed": 0, "alone": {"equal": 48, "unequal": 0, "failed": 0}} +{"label": "c2-cand", "prompt": "code", "streams": 1, "aggregate_tps": 121.7, "end_to_end_tps": 118.7, "tokens_per_round": 3.368, "failed": 0, "alone": {"equal": 3, "unequal": 0, "failed": 0}} +{"label": "c2-cand", "prompt": "code", "streams": 2, "aggregate_tps": 205.6, "end_to_end_tps": 201.3, "tokens_per_round": 2.813, "failed": 0, "alone": {"equal": 6, "unequal": 0, "failed": 0}} +{"label": "c2-cand", "prompt": "code", "streams": 4, "aggregate_tps": 310.3, "end_to_end_tps": 305.5, "tokens_per_round": 2.813, "failed": 0, "alone": {"equal": 12, "unequal": 0, "failed": 0}} +{"label": "c2-cand", "prompt": "code", "streams": 16, "aggregate_tps": 344.1, "end_to_end_tps": 343.7, "tokens_per_round": 2.813, "failed": 0, "alone": {"equal": 48, "unequal": 0, "failed": 0}} +{"label": "c2-cand", "prompt": "chat", "streams": 1, "aggregate_tps": 90.5, "end_to_end_tps": 88.1, "tokens_per_round": 2.37, "failed": 0, "alone": {"equal": 3, "unequal": 0, "failed": 0}} +{"label": "c2-cand", "prompt": "chat", "streams": 2, "aggregate_tps": 170.1, "end_to_end_tps": 166.0, "tokens_per_round": 2.327, "failed": 0, "alone": {"equal": 6, "unequal": 0, "failed": 0}} +{"label": "c2-cand", "prompt": "chat", "streams": 4, "aggregate_tps": 256.5, "end_to_end_tps": 251.9, "tokens_per_round": 2.327, "failed": 0, "alone": {"equal": 12, "unequal": 0, "failed": 0}} +{"label": "c2-cand", "prompt": "chat", "streams": 16, "aggregate_tps": 234.6, "end_to_end_tps": 234.2, "tokens_per_round": 2.327, "failed": 0, "alone": {"equal": 48, "unequal": 0, "failed": 0}} +{"label": "c2-ctl-b", "prompt": "code", "streams": 1, "aggregate_tps": 112.2, "end_to_end_tps": 109.0, "tokens_per_round": 3.325, "failed": 0, "alone": {"equal": 3, "unequal": 0, "failed": 0}} +{"label": "c2-ctl-b", "prompt": "code", "streams": 2, "aggregate_tps": 186.4, "end_to_end_tps": 180.8, "tokens_per_round": 2.813, "failed": 0, "alone": {"equal": 6, "unequal": 0, "failed": 0}} +{"label": "c2-ctl-b", "prompt": "code", "streams": 4, "aggregate_tps": 239.6, "end_to_end_tps": 235.9, "tokens_per_round": 2.813, "failed": 0, "alone": {"equal": 12, "unequal": 0, "failed": 0}} +{"label": "c2-ctl-b", "prompt": "code", "streams": 16, "aggregate_tps": 243.9, "end_to_end_tps": 243.9, "tokens_per_round": 2.813, "failed": 0, "alone": {"equal": 48, "unequal": 0, "failed": 0}} +{"label": "c2-ctl-b", "prompt": "chat", "streams": 1, "aggregate_tps": 82.4, "end_to_end_tps": 80.1, "tokens_per_round": 2.56, "failed": 0, "alone": {"equal": 3, "unequal": 0, "failed": 0}} +{"label": "c2-ctl-b", "prompt": "chat", "streams": 2, "aggregate_tps": 139.5, "end_to_end_tps": 133.6, "tokens_per_round": 2.327, "failed": 0, "alone": {"equal": 6, "unequal": 0, "failed": 0}} +{"label": "c2-ctl-b", "prompt": "chat", "streams": 4, "aggregate_tps": 187.8, "end_to_end_tps": 183.6, "tokens_per_round": 2.327, "failed": 0, "alone": {"equal": 12, "unequal": 0, "failed": 0}} +{"label": "c2-ctl-b", "prompt": "chat", "streams": 16, "aggregate_tps": 222.0, "end_to_end_tps": 221.6, "tokens_per_round": 2.327, "failed": 0, "alone": {"equal": 48, "unequal": 0, "failed": 0}} +{"label": "tensorfold", "prompt": "code", "streams": 1, "aggregate_tps": 116.2, "end_to_end_tps": 112.3, "tokens_per_round": 3.241, "failed": 0, "alone": null} +{"label": "tensorfold", "prompt": "code", "streams": 4, "aggregate_tps": 295.9, "end_to_end_tps": 292.0, "tokens_per_round": 2.813, "failed": 0, "alone": null} +{"label": "tensorfold", "prompt": "code", "streams": 64, "aggregate_tps": 340.9, "end_to_end_tps": 341.8, "tokens_per_round": 2.813, "failed": 0, "alone": null} +{"label": "tensorfold", "prompt": "chat", "streams": 1, "aggregate_tps": 93.8, "end_to_end_tps": 90.7, "tokens_per_round": 2.306, "failed": 0, "alone": null} +{"label": "tensorfold", "prompt": "chat", "streams": 4, "aggregate_tps": 261.4, "end_to_end_tps": 256.4, "tokens_per_round": 2.327, "failed": 0, "alone": null} +{"label": "tensorfold", "prompt": "chat", "streams": 64, "aggregate_tps": 232.2, "end_to_end_tps": 232.8, "tokens_per_round": 2.327, "failed": 0, "alone": null} +{"label": "omlx", "prompt": "code", "streams": 1, "aggregate_tps": 0.0, "end_to_end_tps": 45.1, "tokens_per_round": null, "failed": 0, "alone": null} +{"label": "omlx", "prompt": "code", "streams": 4, "aggregate_tps": 0.0, "end_to_end_tps": 107.0, "tokens_per_round": null, "failed": 0, "alone": null} +{"label": "omlx", "prompt": "code", "streams": 64, "aggregate_tps": 0.0, "end_to_end_tps": 209.3, "tokens_per_round": null, "failed": 0, "alone": null} +{"label": "omlx", "prompt": "chat", "streams": 1, "aggregate_tps": 8.4, "end_to_end_tps": 8.3, "tokens_per_round": 3.556, "failed": 0, "alone": null} +{"label": "omlx", "prompt": "chat", "streams": 4, "aggregate_tps": 86.5, "end_to_end_tps": 79.1, "tokens_per_round": 2.0, "failed": 0, "alone": null} +{"label": "omlx", "prompt": "chat", "streams": 64, "aggregate_tps": 229.3, "end_to_end_tps": 227.6, "tokens_per_round": 1.797, "failed": 0, "alone": null} diff --git a/docs/receipts/inkling-2-mini-metal-235/engines.sh b/docs/receipts/inkling-2-mini-metal-235/engines.sh new file mode 100755 index 00000000000..796651d326d --- /dev/null +++ b/docs/receipts/inkling-2-mini-metal-235/engines.sh @@ -0,0 +1,29 @@ +#!/bin/bash +# engines.sh TENSORFOLD_BINARY: the 1, 4 and 64-stream greedy receipt against oMLX on this Mac, 3 reps each. oMLX +# serves its own 4-bit MTP build (Inkling-2-Mini-oQ4e-mtp) from ~/.omlx/settings.json, MTP drafting on. Run it under +# `lockf -k /tmp/tensorfold-model.lock`; the two servers run one after the other. OMLX names the oMLX binary. +set -euo pipefail +bin=$1 +wt=$(git -C "$(dirname "$0")" rev-parse --show-toplevel) +model=${MODEL:-$HOME/models/Inkling-2-Mini} +omlx=${OMLX:-$HOME/work/inkling/.omlx/bin/omlx} +out=${OUT:-/tmp/ink2-bench} +mkdir -p "$out" +[ -e /Users/Shared/agent-work/mac-gpu-window ] || { echo "no Mac GPU window" >&2; exit 3; } + +measure() { # LABEL PORT MODEL COMMAND...: start the server, bench it, stop it + local label=$1 port=$2 name=$3 + shift 3 + "$@" >"$out/$label.server.log" 2>&1 & + local pid=$! + trap "kill -INT $pid 2>/dev/null; wait $pid 2>/dev/null" EXIT + for _ in $(seq 300); do curl -sf "http://127.0.0.1:$port/v1/models" >/dev/null && break; sleep 1; done + /opt/homebrew/bin/python3.13 "$wt/tools/bench_concurrent.py" "http://127.0.0.1:$port" "$name" \ + --levels 1,4,64 --reps 3 --tokens 256 --temperatures 0 --label "$label" --output "$out/$label.json" 2>&1 | cut -c1-200 + kill -INT $pid + wait $pid 2>/dev/null || true + trap - EXIT +} + +measure tensorfold 18235 Inkling-2-Mini "$bin" serve "$model" --port 18235 --context 65536 --drafter "$model" +measure omlx 8765 Inkling-2-Mini-oQ4e-mtp "$omlx" serve --host 127.0.0.1 --port 8765 --max-concurrent-requests 64 From 1de6b1c303b63fe735a617ca9272711aa7902a14 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:20:03 +0800 Subject: [PATCH 06/14] lanes: report head chain rows drafted and kept at each depth, summed per bench cell --- tools/bench_concurrent.py | 33 +++++++++++++++++++++++++++++- zig/src/core/engine_stats.zig | 3 +++ zig/src/core/lane_host.zig | 2 +- zig/src/core/lanes/engine.zig | 7 ++++++- zig/src/core/lanes/stream.zig | 2 ++ zig/src/server/chat_generation.zig | 11 ++++++++++ 6 files changed, 55 insertions(+), 3 deletions(-) diff --git a/tools/bench_concurrent.py b/tools/bench_concurrent.py index 5e6aa14fa82..11b7b3382e4 100644 --- a/tools/bench_concurrent.py +++ b/tools/bench_concurrent.py @@ -19,7 +19,9 @@ server with a small listen backlog resets simultaneous connections; those resets are reported, not hidden). Each request also carries bench_metrics' figures (prompt/TTFT tok/s, token ITL/TPOT, chunk estimates, round gaps) and bench_stream's boundaries and completion class (docs/cache-benchmarks.md defines them); each rep pools them over its -streams, and each cell gives medians ("request" and "pooled") and its completion classes. +streams, and each cell gives medians ("request" and "pooled") and its completion classes. ``drafts``: the cell's +speculative rounds, drafted and accepted tokens summed over its reps' requests, when the server reports them for all, +and ``depth_drafted``/``depth_accepted``, the head chain's drafted and kept rows at each depth, when it reports those. Every stream of a default cell sends the same prompt (greedy: and gets the same reply), so a mixture-of-experts model routes all of them to the same experts, which can flatter multi-stream rates. ``--prompts FILE`` (for example tools/bench_prompts.json) runs one "distinct" cell instead, where request i sends the file's item i (modulo its length). @@ -191,12 +193,33 @@ def overlapped(runs: list[dict]) -> bool | None: return any(b[0] < a[1] for a, b in zip(spans, spans[1:])) if len(spans) > 1 else None +DRAFT_KEYS = ("rounds", "drafted", "accepted") +DEPTH_KEYS = ("depth_drafted", "depth_accepted") + + def draft_count(run: dict, key: str) -> int | None: """A run's speculative count, None when the server reported none.""" value = (run.get("speculative") or {}).get(key) return value if type(value) is int and value >= 0 else None +def depth_counts(run: dict) -> tuple[list[int], list[int]] | None: + """A run's per-depth drafted and kept rows, None when the server reported none.""" + spec = run.get("speculative") or {} + pair = tuple(spec.get(k) for k in DEPTH_KEYS) + return pair if all(type(v) is list for v in pair) else None + + +def sum_depths(rows) -> list[int]: + """Element-wise sums of per-depth tallies of any lengths.""" + out: list[int] = [] + for row in rows: + out.extend([0] * (len(row) - len(out))) + for i, v in enumerate(row): + out[i] += v + return out + + def serial_evidence(alone: dict) -> dict: """Drafts the alone runs accepted and the ``"draft": false`` runs drafted; ``vacuous`` says why that proves none.""" accepted = [draft_count(r, "accepted") for r in alone.values()] @@ -324,6 +347,8 @@ def main() -> None: rep["ttft_s"] = [round(r["ttft_s"], 2) if r["ttft_s"] is not None else None for r in runs] rep["errors"] = [r["error"] for r in runs if r.get("error")] rep["thinking_modes"] = sorted({r["thinking"] for r in runs if "thinking" in r}) + rep["drafts"] = [[draft_count(r, k) for k in DRAFT_KEYS] for r in runs] + rep["depths"] = [depth_counts(r) for r in runs] rep["requests"] = [{k: r.get(k) for k in ("prompt_tokens", "ttft_s", "decode_tps", "thinking", "thinking_off_requested", "completion", "token_timing", *METRICS)} for r in runs] @@ -366,6 +391,12 @@ def main() -> None: cell[key] = statistics.median(r[key] for r in reps) if valid else None if all("steady_tps" in r for r in reps): cell["steady_tps"] = round(statistics.median(r["steady_tps"] for r in reps), 1) + counts = [c for r in reps for c in r["drafts"]] + if counts and all(None not in c for c in counts): + cell["drafts"] = dict(zip(DRAFT_KEYS, map(sum, zip(*counts)))) + depths = [d for r in reps for d in r["depths"]] + if all(d is not None for d in depths): + cell["drafts"].update(zip(DEPTH_KEYS, (sum_depths(d[i] for d in depths) for i in range(2)))) if alone: checks = [v for r in reps for v in r["equal_alone"]] cell["alone"] = {"equal": checks.count(True), "unequal": checks.count(False), diff --git a/zig/src/core/engine_stats.zig b/zig/src/core/engine_stats.zig index 5bc253e0a53..324cb06ad53 100644 --- a/zig/src/core/engine_stats.zig +++ b/zig/src/core/engine_stats.zig @@ -5,6 +5,9 @@ pub const Stats = struct { grammar: ?@import("lanes").grammar_time.Sum = null, drafted: u64 = 0, accepted: u64 = 0, + /// Head chain rows drafted and kept at each depth, the first depth first. + depth_drafted: [@import("lanes").shape.max_depth]u32 = @splat(0), + depth_accepted: [@import("lanes").shape.max_depth]u32 = @splat(0), /// The narrowest verify window of the reply's rounds (drafted replies: 2 or more). min_rows: u32 = 0, prefill_widths: []const u32 = &.{}, diff --git a/zig/src/core/lane_host.zig b/zig/src/core/lane_host.zig index 8187cf58406..10c0e903af6 100644 --- a/zig/src/core/lane_host.zig +++ b/zig/src/core/lane_host.zig @@ -320,7 +320,7 @@ pub const LaneHost = struct { h.gpa.free(job.marks); h.gpa.free(job.key); const s = &job.stream; - const stats: Stats = if (job.started) .{ .rounds = s.rounds, .grammar = if (s.grammar_time.windows > 0) s.grammar_time else null, .drafted = s.drafted, .accepted = s.accepted, .min_rows = s.min_rows, .prefill_widths = s.prefill_widths.items, .loop_period = s.loop_period, .gpu_seconds = s.gpu_seconds, .prefill_seconds = if (job.prefilled) |done| @as(f64, @floatFromInt(@as(i64, @intCast(@max(0, done - job.began))))) / 1e9 else null } else .{}; + const stats: Stats = if (job.started) .{ .rounds = s.rounds, .grammar = if (s.grammar_time.windows > 0) s.grammar_time else null, .drafted = s.drafted, .accepted = s.accepted, .depth_drafted = s.depth_drafted, .depth_accepted = s.depth_accepted, .min_rows = s.min_rows, .prefill_widths = s.prefill_widths.items, .loop_period = s.loop_period, .gpu_seconds = s.gpu_seconds, .prefill_seconds = if (job.prefilled) |done| @as(f64, @floatFromInt(@as(i64, @intCast(@max(0, done - job.began))))) / 1e9 else null } else .{}; var told = if (job.started) recalls.finished(h, job, reason, stats) else stats; told.queued_seconds = if (job.admitted_ns) |at| @as(f64, @floatFromInt(@max(0, at - job.submitted))) / 1e9 else 0; emit(job, .{ .finished = .{ .reason = reason, .stats = told, .message = message } }); diff --git a/zig/src/core/lanes/engine.zig b/zig/src/core/lanes/engine.zig index cdd10f432d1..f47625a6998 100644 --- a/zig/src/core/lanes/engine.zig +++ b/zig/src/core/lanes/engine.zig @@ -302,7 +302,12 @@ pub const Engine = struct { const chain = if (p.branch_from > 0) ds[0..p.branch_from] else ds[0..own_end]; var chain_kept: usize = 0; for (path[1..]) |r| chain_kept += @intFromBool((p.branch_from == 0 or r < p.branch_from) and r < own_end); - try e.rule.observeDepth(win.who(s), std.mem.max(u32, chain), @intCast(chain_kept)); + const deepest = std.mem.max(u32, chain); + try e.rule.observeDepth(win.who(s), deepest, @intCast(chain_kept)); + for (0..@min(deepest, s.depth_drafted.len)) |j| { + s.depth_drafted[j] += 1; + s.depth_accepted[j] += @intFromBool(j < chain_kept); + } } var kept_branch: u64 = 0; // the context's graft rows kept, then Recall's var kept_recall: u64 = 0; diff --git a/zig/src/core/lanes/stream.zig b/zig/src/core/lanes/stream.zig index 668b59e860a..561dfaf635c 100644 --- a/zig/src/core/lanes/stream.zig +++ b/zig/src/core/lanes/stream.zig @@ -219,6 +219,8 @@ pub const Stream = struct { copied_broke: [2]f64 = .{ 0, 0 }, // and its copies that broke before their end drafted: u64 = 0, accepted: u64 = 0, + depth_drafted: [shape.max_depth]u32 = @splat(0), // head chain rows drafted at each depth (1 first) + depth_accepted: [shape.max_depth]u32 = @splat(0), // and of those, kept branch_rows: u64 = 0, // suffix-match branch rows verified (lanes/fill.zig) branch_accepted: u64 = 0, // of those, rows on the accepted path graft_hit: f64 = 1, // recent share of grafted rows kept; a read of the chain that grafted none counts as a miss diff --git a/zig/src/server/chat_generation.zig b/zig/src/server/chat_generation.zig index 463888eb672..ba234a99da8 100644 --- a/zig/src/server/chat_generation.zig +++ b/zig/src/server/chat_generation.zig @@ -37,6 +37,15 @@ fn putRows(a: Allocator, d: Value, settled: Value, key: []const u8) Allocator.Er if (settled.get("positions")) |at| try d.object.put(a, "logprob_positions", try rowsOf(a, key, at.get(key).?)); } +/// A per-depth tally as a JSON array, the first depth first, through the deepest drafted. +fn depthCounts(a: Allocator, counts: []const u32) Allocator.Error!Value { + var n = counts.len; + while (n > 0 and counts[n - 1] == 0) n -= 1; + const out = try a.alloc(Value, n); + for (counts[0..n], out) |c, *slot| slot.* = try json.intValue(a, c); + return .{ .array = out }; +} + pub const Generation = struct { srv: *Server, a: Allocator, @@ -414,6 +423,8 @@ pub const Generation = struct { try spec.put(a, "rounds", try json.intValue(a, s.rounds)); try spec.put(a, "drafted", try json.intValue(a, s.drafted)); try spec.put(a, "accepted", try json.intValue(a, s.accepted)); + try spec.put(a, "depth_drafted", try depthCounts(a, &s.depth_drafted)); + try spec.put(a, "depth_accepted", try depthCounts(a, &s.depth_accepted)); try spec.put(a, "acceptance_rate", .{ .float = if (s.drafted > 0) @as(f64, @floatFromInt(s.accepted)) / @as(f64, @floatFromInt(s.drafted)) else 0 }); try spec.put(a, "tokens_per_round", .{ .float = if (s.rounds > 0) @as(f64, @floatFromInt(g.collected.items.len)) / @as(f64, @floatFromInt(s.rounds)) else 0 }); const counters = try a.dupe(u8, m.telemetry); // parsed strings point into it: it outlives the box From 0a05a58b17c0b3b7fff0538f75293f1eced44f9c Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:23:05 +0800 Subject: [PATCH 07/14] inkling2 metal: register and probe the five DSpark cohort launches against their solo twins --- .../inkling2_dspark_cohort_metal_records.zig | 18 + zig/src/core/contract/registry_joins.zig | 2 + zig/src/families/inkling2/metal/dspark.zig | 3 +- .../inkling2/metal/dspark_kernels.zig | 5 + .../contract/metal_inkling2_controls_host.zig | 1 + .../contract/metal_inkling2_dspark_cohort.zig | 313 ++++++++++++++++++ .../metal_inkling2_dspark_cohort_controls.zig | 61 ++++ zig/tests/contract/metal_inkling2_main.zig | 4 + zig/tests/contract/metal_mapping_test.zig | 2 +- 9 files changed, 407 insertions(+), 2 deletions(-) create mode 100644 zig/src/core/contract/inkling2_dspark_cohort_metal_records.zig create mode 100644 zig/tests/contract/metal_inkling2_dspark_cohort.zig create mode 100644 zig/tests/contract/metal_inkling2_dspark_cohort_controls.zig diff --git a/zig/src/core/contract/inkling2_dspark_cohort_metal_records.zig b/zig/src/core/contract/inkling2_dspark_cohort_metal_records.zig new file mode 100644 index 00000000000..5850e654641 --- /dev/null +++ b/zig/src/core/contract/inkling2_dspark_cohort_metal_records.zig @@ -0,0 +1,18 @@ +//! Mini DSpark's greedy cohort launches (zig/tests/contract/metal_inkling2_dspark_cohort.zig): up to 16 streams each. +const std = @import("std"); +const M = @import("limits.zig").MetalLaunch; + +pub const records = [_]M{ + .{ .name = "metal inkling2 dspark cohort_qkv tf_ink2_dspark_cohort_qkv", .threads = 128, .tg_memory = 16, .reserved = 128 }, + .{ .name = "metal inkling2 dspark cohort_step tf_ink2_dspark_cohort_step", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 dspark cohort_pick tf_ink2_dspark_cohort_pick", .threads = 1024, .tg_memory = 256, .reserved = 1024 }, + .{ .name = "metal inkling2 dspark cohort_logits tf_ink2_dspark_cohort_logits", .threads = 256, .tg_memory = 0, .reserved = 256 }, + .{ .name = "metal inkling2 dspark cohort_pack tf_ink2_dspark_cohort_pack", .threads = 256, .tg_memory = 0, .reserved = 256 }, +}; + +test "the cohort's launches reserve their threads" { + for (records) |record| { + try std.testing.expectEqual(record.threads, record.reserved); + try std.testing.expect(std.mem.startsWith(u8, record.name, "metal inkling2 dspark cohort_")); + } +} diff --git a/zig/src/core/contract/registry_joins.zig b/zig/src/core/contract/registry_joins.zig index 7a67b6166e5..bbc02a4040f 100644 --- a/zig/src/core/contract/registry_joins.zig +++ b/zig/src/core/contract/registry_joins.zig @@ -112,6 +112,7 @@ pub const all_metal = @import("penalties_records.zig").records ++ @import("inkling2_runtime_metal_records.zig").records ++ @import("inkling2_dspark_metal_records.zig").records ++ @import("inkling2_dspark_chain_metal_records.zig").records ++ + @import("inkling2_dspark_cohort_metal_records.zig").records ++ @import("inkling2_dspark_units_metal_records.zig").records ++ @import("flint_records.zig").records ++ @import("hy4_records.zig").metal ++ @@ -166,5 +167,6 @@ test { _ = @import("inkling2_runtime_metal_records.zig"); _ = @import("inkling2_dspark_metal_records.zig"); _ = @import("inkling2_dspark_chain_metal_records.zig"); + _ = @import("inkling2_dspark_cohort_metal_records.zig"); _ = @import("inkling2_dspark_units_metal_records.zig"); } diff --git a/zig/src/families/inkling2/metal/dspark.zig b/zig/src/families/inkling2/metal/dspark.zig index f7159ff70ec..ad372aaa52c 100644 --- a/zig/src/families/inkling2/metal/dspark.zig +++ b/zig/src/families/inkling2/metal/dspark.zig @@ -451,7 +451,8 @@ pub const Drafter = struct { } } - /// Every stream's block and first step in one command buffer, then one command buffer a later step for all of them. + /// A greedy hold of up to `cohort_streams` runs step-major in one command buffer; otherwise every stream's block and + /// first step in one command buffer, then one command buffer a later step for all of them. fn holdFn(ptr: *anyopaque, items: []const dr.Hold) anyerror!void { const d = cast(ptr); if (items.len == 0) return; diff --git a/zig/src/families/inkling2/metal/dspark_kernels.zig b/zig/src/families/inkling2/metal/dspark_kernels.zig index adc5dda4076..bdbe7c8fcc5 100644 --- a/zig/src/families/inkling2/metal/dspark_kernels.zig +++ b/zig/src/families/inkling2/metal/dspark_kernels.zig @@ -161,6 +161,11 @@ pub const Cohort = struct { logits: mtl.Pipeline, pack: mtl.Pipeline, + pub fn load(device: mtl.Device, text: []const u8) !Cohort { + const lib = try mtl.Library.fromSource(device, text, mtl.CompileOptions.mlx()); + defer lib.deinit(); + return fromLibrary(device, lib); + } pub fn fromLibrary(device: mtl.Device, lib: mtl.Library) !Cohort { const qkv = try mtl.Pipeline.init(device, lib, "tf_ink2_dspark_cohort_qkv", false); errdefer qkv.deinit(); diff --git a/zig/tests/contract/metal_inkling2_controls_host.zig b/zig/tests/contract/metal_inkling2_controls_host.zig index dddbd887d0b..14ef9f84eff 100644 --- a/zig/tests/contract/metal_inkling2_controls_host.zig +++ b/zig/tests/contract/metal_inkling2_controls_host.zig @@ -9,5 +9,6 @@ test { _ = @import("metal_inkling2_runtime_controls.zig"); _ = @import("metal_inkling2_dspark_controls.zig"); _ = @import("metal_inkling2_dspark_chain_controls.zig"); + _ = @import("metal_inkling2_dspark_cohort_controls.zig"); _ = @import("metal_inkling2_dspark_units_controls.zig"); } diff --git a/zig/tests/contract/metal_inkling2_dspark_cohort.zig b/zig/tests/contract/metal_inkling2_dspark_cohort.zig new file mode 100644 index 00000000000..ccd88116ee6 --- /dev/null +++ b/zig/tests/contract/metal_inkling2_dspark_cohort.zig @@ -0,0 +1,313 @@ +//! Mini DSpark's greedy cohort: each launch for `rows` streams against the solo launch it replaces, run a stream at a +//! time on the same inputs. Shape rows are streams; k is the depth row (step, pick) or the first base row (logits, +//! pack). +const std = @import("std"); +const mtl = @import("metal"); +const contract = @import("contract"); +const c = contract.spec; +const g = contract.gates; +const rig_ = @import("rig.zig"); +const host = @import("tensorfold").inkling2_dspark_host; +const controls = @import("metal_inkling2_dspark_cohort_controls.zig"); + +const RANK = host.rank; +const RNN = host.rnn_width; +const H = host.hidden; +const Q = host.query_width; +const KV = host.kv_width; +const V = host.vocab; +const BLOCK = host.block_rows; +const MOST = host.cohort_streams; + +const Kind = enum { qkv, step, pick, logits, pack }; + +fn noSums(_: c.Shape) usize { + return 1; +} +fn hr(b: rig_.Ref) host.Ref { + return .{ .buf = b.buf, .off = b.off }; +} +fn plus(b: rig_.Ref, bytes: usize) host.Ref { + return .{ .buf = b.buf, .off = b.off + bytes }; +} + +/// One cohort kernel's probe; `replaced` runs the solo kernel per stream into twin buffers laid out as the outputs. +pub const Probe = struct { + kind: Kind, + a: std.mem.Allocator, + arena: std.heap.ArenaAllocator, + rig: rig_.Rig, + cohort: host.Cohort, + chain: host.Chain, + pipes: host.Pipelines, + control: ?g.Gate, + shape: c.Shape = undefined, + ins: [6]rig_.Ref = undefined, + outs: [3]rig_.Ref = undefined, + twin: [3]rig_.Ref = undefined, + sizes: [3]usize = @splat(0), + want: std.ArrayList(u8) = .empty, + active: [host.steps]u32 = @splat(0), + msg: [160]u8 = undefined, + + fn mutation(kind: Kind) controls.Mutation { + return switch (kind) { + .qkv => .qkv_anchor, + .step => .step_token, + .pick => .pick_nan_row, + .logits => .logits_row, + .pack => .pack_prefix, + }; + } + fn label(kind: Kind, control: bool) []const u8 { + if (control) return mutation(kind).name(); + return switch (kind) { + inline else => |k| "metal inkling2 dspark cohort_" ++ @tagName(k) ++ " tf_ink2_dspark_cohort_" ++ @tagName(k), + }; + } + + pub fn init(a: std.mem.Allocator, device: mtl.Device, queue: mtl.Queue, kind: Kind, control: bool) !Probe { + const text = try controls.apply(a, if (control) mutation(kind) else .none); + defer a.free(text); + var cohort = try host.Cohort.load(device, text); + errdefer cohort.deinit(); + var chain = try host.Chain.load(device, @import("inkling2_metal").inkling2_dspark); + errdefer chain.deinit(); + return .{ .kind = kind, .a = a, .arena = .init(a), .rig = .{ .a = a, .device = device, .queue = queue }, .cohort = cohort, .chain = chain, .pipes = try host.Pipelines.load(device), .control = if (control) .shapes else null }; + } + pub fn deinit(t: *Probe) void { + t.want.deinit(t.a); + t.rig.deinit(); + t.arena.deinit(); + t.pipes.deinit(); + t.chain.deinit(); + t.cohort.deinit(); + } + + pub fn kernel(t: *Probe) g.Kernel { + const served: []const c.Shape = switch (t.kind) { + .qkv => &.{ .{ .rows = 1, .n = Q, .k = 0 }, .{ .rows = 3, .n = Q, .k = 0 }, .{ .rows = MOST, .n = Q, .k = 0 } }, + .step => &.{ .{ .rows = 1, .n = RNN, .k = 0 }, .{ .rows = 5, .n = RNN, .k = 3 }, .{ .rows = MOST, .n = RNN, .k = 6 } }, + .pick => &.{ .{ .rows = 1, .n = V, .k = 0 }, .{ .rows = 3, .n = V, .k = 2 }, .{ .rows = MOST, .n = V, .k = 6 } }, + // the kernel's three widths: up to 4, 8 and 16 streams, each from a later depth's base rows + .logits => &.{ .{ .rows = 3, .n = V, .k = 2 }, .{ .rows = 7, .n = V, .k = 5 }, .{ .rows = MOST, .n = V, .k = 1 } }, + .pack => &.{ .{ .rows = 1, .n = H, .k = 0 }, .{ .rows = 6, .n = H, .k = 4 }, .{ .rows = MOST, .n = H, .k = 9 } }, + }; + const nan: []const u8 = switch (t.kind) { + .qkv => "its bytes are tf_ink2_dspark_block_qkv's on each block at its own anchor", + .step => "its bytes are tf_ink2_dspark_recurrent's on each stream's state, kappa row and held token", + .pick => "its picks are tf_ink2_dspark_chain_pick's on each stream's row", + .logits => "its bytes are tf_ink2_dspark_logits' on each stream's base and lambda rows", + .pack => "its rows are copies of each stream's draft rows, NaNs included", + }; + return .{ .ctx = t, .vt = &vt, .control = t.control, .spec = .{ + .name = label(t.kind, t.control != null), + .accum = .none, + .depth = noSums, + .out = if (t.kind == .pick) .raw else .bf16, + .nan = .{ .stated = nan }, + .served = served, + .replaces = "the solo launch", + } }; + } + const vt = g.hooks(Probe); + + fn bf16(t: *Probe, n: usize, rng: std.Random) ![]u16 { + const bits = try t.arena.allocator().alloc(u16, n); + for (bits) |*b| b.* = c.toBf16(rng.float(f32) * 0.5 - 0.25); + return bits; + } + fn in(t: *Probe, i: usize, data: anytype) !void { + t.ins[i] = try t.rig.input(std.mem.sliceAsBytes(data)); + } + fn outputs(t: *Probe, sizes: []const usize) !void { + for (sizes, 0..) |bytes, i| { + t.sizes[i] = bytes; + t.outs[i] = try t.rig.output(bytes); + t.twin[i] = try t.rig.scratch(bytes); + } + } + + pub fn prepare(t: *Probe, shape: c.Shape, fill: g.Fill, seed: u64) !bool { + const n: u32 = switch (t.kind) { + .qkv => Q, + .step => RNN, + .pick, .logits => V, + .pack => H, + }; + const depth_ok = switch (t.kind) { + .step, .pick => shape.k < host.steps, + .logits => shape.k + shape.rows <= host.steps * MOST, + .pack => shape.k < host.steps * MOST, + .qkv => shape.k == 0, + }; + if (shape.n != n or shape.rows == 0 or shape.rows > MOST or !depth_ok) return false; + t.rig.reset(); + _ = t.arena.reset(.retain_capacity); + t.shape = shape; + t.sizes = @splat(0); + var prng = std.Random.DefaultPrng.init(seed); + const rng = prng.random(); + const s: usize = shape.rows; + const a = t.arena.allocator(); + switch (t.kind) { + .qkv => { + const q_raw = try t.bf16(s * BLOCK * Q, rng); + if (fill == .nonfinite) q_raw[Q + 5] = c.toBf16(std.math.nan(f32)); + const anchors = try a.alloc(u32, s); + for (anchors, 0..) |*p, i| p.* = @intCast(1 + 977 * i + rng.uintLessThan(u32, 500)); + try t.in(0, q_raw); + try t.in(1, try t.bf16(s * BLOCK * KV, rng)); + try t.in(2, try t.bf16(s * BLOCK * KV, rng)); + try t.in(3, try t.bf16(128, rng)); + try t.in(4, try t.bf16(128, rng)); + try t.in(5, anchors); + try t.outputs(&.{ s * BLOCK * Q * 2, s * BLOCK * KV * 2, s * BLOCK * KV * 2 }); + }, + .step => { + const state = try t.bf16(s * RANK, rng); + if (fill == .nonfinite) state[0] = c.toBf16(std.math.nan(f32)); + const kappa = try a.alloc(f32, s * host.steps * RNN); + for (kappa) |*v| v.* = rng.float(f32) * 0.5 - 0.25; + // Markov rows of tokens 0 and 1 differ; each stream's held token at the depth differs from stream 0's. + const held = try a.alloc(u32, s * 8); + for (held, 0..) |*h, i| h.* = @intFromBool((i / 8) % 2 == 1); + try t.in(0, state); + try t.in(1, kappa); + try t.in(2, try t.bf16(RNN * 5120, rng)); + try t.in(3, try t.bf16(2 * RANK, rng)); + try t.in(4, held); + try t.outputs(&.{ s * 3 * RANK * 2, s * RANK * 2, s * RANK * 2 }); + }, + .pick => { + const logits = try a.alloc(u16, s * V); + // few distinct values, so each row's greatest is tied many times + for (logits) |*v| v.* = c.toBf16(@as(f32, @floatFromInt(rng.uintLessThan(u32, 64))) / 4 - 8); + // a NaN at id 0 of a later row only: that row picks 0, the others do not + if (s > 1) logits[V] = c.toBf16(std.math.nan(f32)); + if (fill == .nonfinite) logits[V / 3] = c.toBf16(std.math.inf(f32)); + try t.in(0, logits); + try t.outputs(&.{s * 8 * @sizeOf(u32)}); + }, + .logits => { + const base = try t.bf16((shape.k + s) * V, rng); + if (fill == .nonfinite) base[shape.k * V + 9] = c.toBf16(std.math.nan(f32)); + try t.in(0, base); + try t.in(1, try t.bf16(V * RANK, rng)); + try t.in(2, try t.bf16(V, rng)); + try t.in(3, try t.bf16(s * RANK, rng)); + try t.outputs(&.{s * V * 2}); + }, + .pack => { + const x = try t.bf16(s * BLOCK * H, rng); + if (fill == .nonfinite) x[H + 3] = c.toBf16(std.math.nan(f32)); + // deepest first, one fewer stream at each later depth + var total: u32 = 0; + for (&t.active, 0..) |*v, j| { + v.* = @intCast(s -| j); + total += v.*; + } + if (shape.k >= total) return false; + try t.in(0, x); + try t.outputs(&.{(total - @as(u32, @intCast(shape.k))) * H * 2}); + }, + } + return true; + } + + fn packArgs(t: *const Probe) host.PackArgs { + var total: u32 = 0; + for (t.active) |v| total += v; + return .{ .active = t.active, .first = @intCast(t.shape.k), .count = total - @as(u32, @intCast(t.shape.k)) }; + } + + pub fn run(t: *Probe) !void { + const s: u32 = @intCast(t.shape.rows); + const k: u32 = @intCast(t.shape.k); + const pass = t.rig.begin(); + switch (t.kind) { + .qkv => host.cohortQkv(&t.cohort, pass.e, hr(t.ins[0]), hr(t.ins[1]), hr(t.ins[2]), hr(t.ins[3]), hr(t.ins[4]), hr(t.outs[0]), hr(t.outs[1]), hr(t.outs[2]), hr(t.ins[5]), s), + .step => host.cohortStep(&t.cohort, pass.e, hr(t.ins[0]), hr(t.ins[1]), hr(t.ins[2]), hr(t.ins[3]), hr(t.outs[0]), hr(t.outs[1]), hr(t.outs[2]), hr(t.ins[4]), k, s), + .pick => host.cohortPick(&t.cohort, pass.e, hr(t.ins[0]), hr(t.outs[0]), k, s), + .logits => host.cohortLogits(&t.cohort, pass.e, hr(t.ins[0]), hr(t.ins[1]), hr(t.ins[2]), hr(t.ins[3]), hr(t.outs[0]), k, s), + .pack => host.cohortPack(&t.cohort, pass.e, hr(t.ins[0]), hr(t.outs[0]), t.packArgs()), + } + try t.rig.finish(pass); + } + + /// The solo launches, a stream at a time, into the twins; returns their bytes in output order. + pub fn replaced(t: *Probe) ![]const u8 { + for (t.sizes, t.twin) |bytes, twin| if (bytes > 0) @memset(t.rig.bytes(twin, bytes), 0xff); + const k: u32 = @intCast(t.shape.k); + const pass = t.rig.begin(); + for (0..t.shape.rows) |si| { + const s: u32 = @intCast(si); + switch (t.kind) { + .qkv => { + const anchors = std.mem.bytesAsSlice(u32, t.rig.bytes(t.ins[5], t.shape.rows * 4)); + const rows = s * BLOCK; + host.blockQkv(&t.pipes, pass.e, plus(t.ins[0], rows * Q * 2), plus(t.ins[1], rows * KV * 2), plus(t.ins[2], rows * KV * 2), hr(t.ins[3]), hr(t.ins[4]), plus(t.twin[0], rows * Q * 2), plus(t.twin[1], rows * KV * 2), plus(t.twin[2], rows * KV * 2), anchors[s]); + }, + .step => { + const held = std.mem.bytesAsSlice(u32, t.rig.bytes(t.ins[4], t.shape.rows * 8 * 4)); + host.recurrentStep(&t.pipes, pass.e, plus(t.ins[0], s * RANK * 2), plus(t.ins[1], (s * host.steps + k) * RNN * 4), hr(t.ins[2]), hr(t.ins[3]), plus(t.twin[0], s * 3 * RANK * 2), plus(t.twin[1], s * RANK * 2), plus(t.twin[2], s * RANK * 2), held[s * 8 + k]); + }, + .pick => host.chainPick(&t.chain, pass.e, plus(t.ins[0], @as(usize, s) * V * 2), plus(t.twin[0], s * 8 * 4), k), + .logits => host.finalLogits(&t.pipes, pass.e, plus(t.ins[0], (@as(usize, k) + s) * V * 2), hr(t.ins[1]), hr(t.ins[2]), plus(t.ins[3], s * RANK * 2), plus(t.twin[0], @as(usize, s) * V * 2)), + .pack => {}, + } + } + try t.rig.finish(pass); + t.want.clearRetainingCapacity(); + if (t.kind == .pack) { + // the solo path's packed rows: depth j's draft row j + 1 of each of its active streams, from row `first` on + var row: usize = 0; + for (t.active, 0..) |streams, j| for (0..streams) |si| { + if (row >= t.shape.k) try t.want.appendSlice(t.a, t.rig.bytes(t.ins[0], (si * BLOCK + j + 2) * H * 2)[(si * BLOCK + j + 1) * H * 2 ..]); + row += 1; + }; + return t.want.items; + } + for (t.sizes, t.twin) |bytes, twin| if (bytes > 0) try t.want.appendSlice(t.a, t.rig.bytes(twin, bytes)); + return t.want.items; + } + + pub fn count(t: *Probe) usize { + var n: usize = 0; + for (t.sizes) |bytes| n += bytes; + return n; + } + pub fn reference(_: *Probe, _: []f64, _: []f64) !void { + return error.CheckedByItsOwnRule; + } + + pub fn check(t: *Probe, _: g.Gate) !?[]const u8 { + const got = try t.a.dupe(u8, try t.rig.outputBytes()); + defer t.a.free(got); + const want = try t.replaced(); + if (std.mem.indexOfDiff(u8, got, want)) |at| return try std.fmt.bufPrint(&t.msg, "differs from the solo launches from byte {d}", .{at}); + return null; + } +}; + +pub const Suite = struct { + a: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + kernels: *std.ArrayList(g.Kernel), + probes: [2 * std.enums.values(Kind).len]Probe = undefined, + used: usize = 0, + + pub fn deinit(s: *Suite) void { + for (s.probes[0..s.used]) |*t| t.deinit(); + } + + pub fn collect(s: *Suite, only: ?[]const u8) !void { + for ([_]bool{ false, true }) |control| for (std.enums.values(Kind)) |kind| { + if (only != null and std.mem.indexOf(u8, Probe.label(kind, control), only.?) == null) continue; + s.probes[s.used] = try Probe.init(s.a, s.device, s.queue, kind, control); + s.used += 1; + try s.kernels.append(s.a, s.probes[s.used - 1].kernel()); + }; + } +}; diff --git a/zig/tests/contract/metal_inkling2_dspark_cohort_controls.zig b/zig/tests/contract/metal_inkling2_dspark_cohort_controls.zig new file mode 100644 index 00000000000..6f518ea96dc --- /dev/null +++ b/zig/tests/contract/metal_inkling2_dspark_cohort_controls.zig @@ -0,0 +1,61 @@ +//! Count-checked mutations of Mini DSpark's five cohort kernels: each breaks one stream's or one row's indexing. +const std = @import("std"); +const src = @import("inkling2_metal"); +const g = @import("contract").gates; + +pub const Mutation = enum { + none, + qkv_anchor, + step_token, + pick_nan_row, + logits_row, + pack_prefix, + + pub fn name(m: Mutation) []const u8 { + return switch (m) { + .none => "", + .qkv_anchor => "control: metal inkling2 dspark cohort_qkv tf_ink2_dspark_cohort_qkv first anchor", + .step_token => "control: metal inkling2 dspark cohort_step tf_ink2_dspark_cohort_step first stream's token", + .pick_nan_row => "control: metal inkling2 dspark cohort_pick tf_ink2_dspark_cohort_pick first row's NaN", + .logits_row => "control: metal inkling2 dspark cohort_logits tf_ink2_dspark_cohort_logits depth row", + .pack_prefix => "control: metal inkling2 dspark cohort_pack tf_ink2_dspark_cohort_pack prefix", + }; + } + + pub fn gate(m: Mutation) ?g.Gate { + return if (m == .none) null else .shapes; + } + + const Edit = struct { from: []const u8, to: []const u8 }; + fn edit(m: Mutation) Edit { + return switch (m) { + .none => unreachable, + .qkv_anchor => .{ .from = "anchors[row / 8] + row % 8, work, d.x);", .to = "anchors[0] + row % 8, work, d.x);" }, + .step_token => .{ .from = "lambda + s * DSP_RANK, held[s * 8 + a.row], i);", .to = "lambda + s * DSP_RANK, held[a.row], i);" }, + .pick_nan_row => .{ .from = "if (t == 0) held[s * 8 + a.row + 1] = isnan(float(row[0])) ? 0u : at;", .to = "if (t == 0) held[s * 8 + a.row + 1] = isnan(float(logits[0])) ? 0u : at;" }, + .logits_row => .{ .from = "const device bfloat* rows = base + size_t(a.row) * 200058u;", .to = "const device bfloat* rows = base;" }, + .pack_prefix => .{ .from = "for (uint j = 0; j < tg.y; ++j) row += a.active[j];", .to = "for (uint j = 0; j < tg.y; ++j) row += a.active[0];" }, + }; + } +}; + +pub fn apply(a: std.mem.Allocator, m: Mutation) ![]u8 { + if (m == .none) return a.dupe(u8, src.inkling2_dspark); + const change = m.edit(); + if (std.mem.count(u8, src.inkling2_dspark, change.from) != 1) return error.ControlEditCount; + return std.mem.replaceOwned(u8, a, src.inkling2_dspark, change.from, change.to); +} + +test "each cohort control edits exactly its planted line" { + const a = std.testing.allocator; + for (std.enums.values(Mutation)) |m| { + if (m == .none) continue; + const edited = try apply(a, m); + defer a.free(edited); + try std.testing.expect(std.mem.indexOf(u8, edited, m.edit().to) != null); + try std.testing.expectEqual(g.Gate.shapes, m.gate().?); + try std.testing.expect(std.mem.startsWith(u8, m.name(), "control: metal inkling2 dspark cohort_")); + } + inline for (.{ "qkv", "step", "pick", "logits", "pack" }) |kernel| + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, src.inkling2_dspark, "tf_ink2_dspark_cohort_" ++ kernel ++ "(")); +} diff --git a/zig/tests/contract/metal_inkling2_main.zig b/zig/tests/contract/metal_inkling2_main.zig index 557538723e2..738db2da56c 100644 --- a/zig/tests/contract/metal_inkling2_main.zig +++ b/zig/tests/contract/metal_inkling2_main.zig @@ -14,6 +14,7 @@ pub const Suites = struct { runtime: @import("metal_inkling2_runtime.zig").Suite, dspark: @import("metal_inkling2_dspark.zig").Suite, chain: @import("metal_inkling2_dspark_chain.zig").Suite, + cohort: @import("metal_inkling2_dspark_cohort.zig").Suite, dspark_units: @import("metal_inkling2_dspark_units.zig").Suite, /// Built where it will live: each kernel's context points at a probe inside these suites. @@ -29,6 +30,7 @@ pub const Suites = struct { .runtime = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, .dspark = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, .chain = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, + .cohort = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, .dspark_units = .{ .a = a, .device = device, .queue = queue, .kernels = kernels }, }; errdefer s.deinit(); @@ -42,6 +44,7 @@ pub const Suites = struct { try s.runtime.collect(only); try s.dspark.collect(only); try s.chain.collect(only); + try s.cohort.collect(only); try s.dspark_units.collect(only); } @@ -56,6 +59,7 @@ pub const Suites = struct { s.runtime.deinit(); s.dspark.deinit(); s.chain.deinit(); + s.cohort.deinit(); s.dspark_units.deinit(); } }; diff --git a/zig/tests/contract/metal_mapping_test.zig b/zig/tests/contract/metal_mapping_test.zig index 1b5291d9dda..71dadb5abf9 100644 --- a/zig/tests/contract/metal_mapping_test.zig +++ b/zig/tests/contract/metal_mapping_test.zig @@ -22,7 +22,7 @@ test "Metal launch map: every DSpark limit pipeline has a resolver branch" { try launches.requireMapped(d); count += 1; } - try std.testing.expectEqual(@as(usize, 13), count); + try std.testing.expectEqual(@as(usize, 18), count); } test "Metal launch map: unknown registrations stay errors on every chip" { From 5faf93955f13e4258eab428cd4d3226091653d50 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:23:05 +0800 Subject: [PATCH 08/14] docs: card 235's benches admit every measured stream --- docs/receipts/inkling-2-mini-metal-235/bench.sh | 7 ++++--- docs/receipts/inkling-2-mini-metal-235/engines.sh | 9 +++++---- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/docs/receipts/inkling-2-mini-metal-235/bench.sh b/docs/receipts/inkling-2-mini-metal-235/bench.sh index f02e6ef5b33..d87980df60b 100755 --- a/docs/receipts/inkling-2-mini-metal-235/bench.sh +++ b/docs/receipts/inkling-2-mini-metal-235/bench.sh @@ -1,6 +1,7 @@ #!/bin/bash -# bench.sh LABEL BINARY: one DSpark server session from BINARY, bench_concurrent at 1, 2, 4 and 16 streams, greedy, -# 3 reps. Run it under `lockf -k /tmp/tensorfold-model.lock`, one at a time; LEVELS overrides the stream counts. +# bench.sh LABEL BINARY: one DSpark server session from BINARY admitting 16 lanes, bench_concurrent at 1, 2, 4 and 16 +# streams, greedy, 3 reps. Run it under `lockf -k /tmp/tensorfold-model.lock`, one at a time; LEVELS overrides the +# stream counts. set -euo pipefail label=$1 bin=$2 wt=$(git -C "$(dirname "$0")" rev-parse --show-toplevel) @@ -8,7 +9,7 @@ model=${MODEL:-$HOME/models/Inkling-2-Mini} out=${OUT:-/tmp/ink2-bench} mkdir -p "$out" [ -e /Users/Shared/agent-work/mac-gpu-window ] || { echo "no Mac GPU window" >&2; exit 3; } -"$bin" serve "$model" --port 18235 --context 65536 --drafter "$model" >"$out/$label.server.log" 2>&1 & +"$bin" serve "$model" --port 18235 --context 65536 --parallel 16 --drafter "$model" >"$out/$label.server.log" 2>&1 & pid=$! trap 'kill -INT $pid 2>/dev/null; wait $pid 2>/dev/null' EXIT for _ in $(seq 240); do curl -sf http://127.0.0.1:18235/v1/models >/dev/null && break; sleep 1; done diff --git a/docs/receipts/inkling-2-mini-metal-235/engines.sh b/docs/receipts/inkling-2-mini-metal-235/engines.sh index 796651d326d..1c35e6ce098 100755 --- a/docs/receipts/inkling-2-mini-metal-235/engines.sh +++ b/docs/receipts/inkling-2-mini-metal-235/engines.sh @@ -1,7 +1,8 @@ #!/bin/bash -# engines.sh TENSORFOLD_BINARY: the 1, 4 and 64-stream greedy receipt against oMLX on this Mac, 3 reps each. oMLX -# serves its own 4-bit MTP build (Inkling-2-Mini-oQ4e-mtp) from ~/.omlx/settings.json, MTP drafting on. Run it under -# `lockf -k /tmp/tensorfold-model.lock`; the two servers run one after the other. OMLX names the oMLX binary. +# engines.sh TENSORFOLD_BINARY: the 1, 4 and 64-stream greedy receipt against oMLX on this Mac, 3 reps each, both +# servers admitting 64 requests. oMLX serves its own 4-bit MTP build (Inkling-2-Mini-oQ4e-mtp) from +# ~/.omlx/settings.json, MTP drafting on. Run it under `lockf -k /tmp/tensorfold-model.lock`; the two servers run one +# after the other. OMLX names the oMLX binary; CONTEXT the TensorFold window (65536). set -euo pipefail bin=$1 wt=$(git -C "$(dirname "$0")" rev-parse --show-toplevel) @@ -25,5 +26,5 @@ measure() { # LABEL PORT MODEL COMMAND...: start the server, bench it, stop it trap - EXIT } -measure tensorfold 18235 Inkling-2-Mini "$bin" serve "$model" --port 18235 --context 65536 --drafter "$model" +measure tensorfold 18235 Inkling-2-Mini "$bin" serve "$model" --port 18235 --context "${CONTEXT:-65536}" --parallel 64 --drafter "$model" measure omlx 8765 Inkling-2-Mini-oQ4e-mtp "$omlx" serve --host 127.0.0.1 --port 8765 --max-concurrent-requests 64 From fc2e267bb423eac7f8923e0fb69b053d15d01c8c Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:00:41 +0800 Subject: [PATCH 09/14] docs: card 235's receipt at 16 admitted lanes, acceptance by depth, the other engines --- .../inkling-2-mini-metal-235/README.md | 93 +++++++++++++------ .../inkling-2-mini-metal-235/cells.jsonl | 72 +++++++------- .../inkling-2-mini-metal-235/engines.sh | 4 +- 3 files changed, 101 insertions(+), 68 deletions(-) diff --git a/docs/receipts/inkling-2-mini-metal-235/README.md b/docs/receipts/inkling-2-mini-metal-235/README.md index 0ed48c1ba6c..0340c5fb0f2 100644 --- a/docs/receipts/inkling-2-mini-metal-235/README.md +++ b/docs/receipts/inkling-2-mini-metal-235/README.md @@ -1,47 +1,71 @@ # Inkling 2 Mini on Metal, M5 Ultra: card 235's receipt Apple M5 Ultra, 256 GB, macOS 27.0; the official checkpoint (`Inkling-2-Mini`, its own `mtp.safetensors` as the -DSpark drafter); `tensorfold-native` from `zig build native -Doptimize=ReleaseFast`, `--context 65536`. Control is -card 210's head (781eeab52), candidate this branch. Every run held `/tmp/tensorfold-model.lock` inside the Desk's Mac -GPU window, one server at a time. Other agents' builds kept the load average between 14 and 40, which moves the -controls by up to 30%; the candidate ran between them. +DSpark drafter); `tensorfold-native` from `zig build native -Doptimize=ReleaseFast`. Control is card 210's head +(781eeab52), candidate this branch; both carry this branch's per-depth draft counters (1de6b1c30), which only report. +Every run held `/tmp/tensorfold-model.lock` inside the Desk's Mac GPU window, one server at a time. Other agents' +builds kept the load average between 50 and 90; the two controls differ by up to 40% (16 chat streams), so the +candidate ran between them. ## Step-major holds -`bench.sh` (`tools/bench_concurrent.py --levels 1,2,4,16 --reps 3 --tokens 256 --temperatures 0 --alone`), medians -of three reps, aggregate tok/s. Control, candidate, control: - -| code / chat | control | **candidate** | control again | tokens a round (all three) | -|---|---|---|---|---| -| 1 stream | 123.2 / 67.5 | **121.7 / 90.5** | 112.2 / 82.4 | 3.37 / 2.29-2.56 | -| 2 streams | 188.9 / 121.9 | **205.6 / 170.1** | 186.4 / 139.5 | 2.81 / 2.33 | -| 4 streams | 271.2 / 136.5 | **310.3 / 256.5** | 239.6 / 187.8 | 2.81 / 2.33 | -| 16 streams | 262.2 / 130.5 | **344.1 / 234.6** | 243.9 / 222.0 | 2.81 / 2.33 | - -- Against the better control: +8.8% / +21.9% at two streams, +14.4% / +36.6% at four, +31.2% / +5.7% at sixteen. One - stream keeps the solo chain (−1.2% on code, inside the controls' spread). -- Acceptance: at every depth the drafts equal the control's, so tokens a round agree cell for cell from two streams on - (one stream's chunking varies with timing). Accepted over drafted across each session: 21,844 / 42,709 (51.1%), - candidate 21,833 / 42,386 (51.5%), control 21,870 / 43,100 (50.7%). +`bench.sh` (`--context 65536 --parallel 16`; `tools/bench_concurrent.py --levels 1,2,4,16 --reps 3 --tokens 256 +--temperatures 0 --alone`), medians of three reps, aggregate tok/s. Control, candidate, control: + +| code / chat | control | **candidate** | control again | +|---|---|---|---| +| 1 stream | 119.7 / 93.9 | **121.9 / 93.4** | 125.7 / 94.0 | +| 2 streams | 192.9 / 159.2 | **209.8 / 172.8** | 196.0 / 157.6 | +| 4 streams | 278.3 / 228.3 | **317.2 / 259.5** | 277.6 / 225.2 | +| 16 streams | 284.1 / 266.8 | **372.2 / 348.9** | 267.4 / 190.9 | + +- Against the better control: +7.0% / +8.5% at two streams, +14.0% / +13.7% at four, +31.0% / +30.8% at sixteen. + One stream keeps the solo chain (−3.0% / −0.6%, inside the controls' spread). - 0 failed requests; every concurrent reply equal to its run alone (3, 6, 12 and 48 of each in every session). -## Against the fastest other engine here +Acceptance by depth, head chain rows kept over drafted, summed over each cell's three reps (`drafts.depth_accepted` +and `drafts.depth_drafted` in `cells.jsonl`). From two streams on the three sessions agree row for row; the later +depths' few rows are the first round's: -`engines.sh` (`--levels 1,4,64 --reps 3 --tokens 256 --temperatures 0`), end-to-end tok/s (a reply that arrives as -one text piece has no decode time, so the aggregate column reads 0 for it), medians of three: +| code | control | candidate | control again | +|---|---|---|---| +| 1 | 172/232 132/226 103/224 57/171 39/156 25/153 7/78 | 169/229 125/223 94/216 70/216 48/181 29/150 4/45 | 173/228 134/222 105/222 71/201 48/163 7/50 0/4 | +| 2 | 420/534 318/534 252/528 0/6 0/6 | 420/534 318/534 252/528 0/6 0/6 0/6 0/6 | 420/534 318/534 252/528 0/6 0/6 | +| 4 | 840/1068 636/1068 504/1056 0/12 0/12 | 840/1068 636/1068 504/1056 0/12 0/12 0/12 0/12 | 840/1068 636/1068 504/1056 0/12 0/12 | +| 16 | 5424/6720 | 5424/6720 | 5424/6720 | + +| chat | control | candidate | control again | +|---|---|---|---| +| 1 | 223/321 113/297 68/261 21/177 10/157 6/58 0/5 | 225/322 112/292 71/267 20/213 9/133 2/15 | 212/307 107/295 77/280 28/219 20/186 13/109 0/10 | +| 2 | 438/648 246/642 180/642 0/6 | 438/648 246/642 180/642 0/6 0/6 | 438/648 246/642 180/642 0/6 0/6 | +| 4 | 876/1296 492/1284 360/1284 0/12 | 876/1296 492/1284 360/1284 0/12 0/12 | 876/1296 492/1284 360/1284 0/12 0/12 | +| 16 | 5088/7008 | 5088/7008 | 5088/7008 | + +One stream's depths follow each round's timing, so they move between sessions in both arms; its kept rows (535, 539, +538 code; 441, 440, 457 chat) do not regress. At sixteen admitted streams the depth rule drafts one row. + +## Against the other engines + +`engines.sh` (`--levels 1,4,64 --reps 3 --tokens 256 --temperatures 0`; TensorFold `--context 16384 --parallel 64`, +the window that fits 64 lanes), end-to-end tok/s, medians of three (a reply that arrives as one text piece has no +decode time, so only end to end compares): | code / chat | TensorFold, DSpark | oMLX 0.8.2, MTP | ratio | |---|---|---|---| -| 1 stream | **112.3 / 90.7** | 45.1 / 8.3 | 2.5x / 10.9x | -| 4 streams | **292.0 / 256.4** | 107.0 / 79.1 | 2.7x / 3.2x | -| 64 streams | **341.8 / 232.8** | 209.3 / 227.6 | 1.6x / 1.02x | +| 1 stream | **113.7 / 86.2** | 13.5 / 36.2 | 8.4x / 2.4x | +| 4 streams | **293.9 / 240.0** | 39.2 / 48.3 | 7.5x / 5.0x | +| 64 streams | **344.3 / 236.2** | 200.0 / 184.5 | 1.7x / 1.3x | - oMLX serves its own 4-bit build (`Inkling-2-Mini-oQ4e-mtp`, about 17 GB) with MTP drafting on; TensorFold serves the - official NVFP4/MXFP8 checkpoint. oMLX's chat reps vary 4.5x at one stream (6.9-37.7); its best rep is still 2.4x - under ours. At 64 chat streams the two tie within the reps' spread (ours 210.9-277.3, oMLX 207.7-282.8). -- Not runnable here: Strata (no binary or weights; v0.2.19 publishes 108.9-114.5 tok/s at one stream on M5 Max), - llama.cpp (no `llama-server`, no Inkling GGUF), mlx-lm `mlx_lm.server` (installed with Inkling support, but oMLX - wraps the same kernels with batching, so it is the stronger of the two). + official NVFP4/MXFP8 checkpoint. oMLX ran at load average 70-90; in this branch's first session (load 14-40) it + reached 45.1 / 8.3, 107.0 / 79.1 and 209.3 / 227.6, still under ours at every cell but 64 chat streams (1.02x). +- #4618 on this Mac (its own clients, `--parallel 4 --context 16384`): oMLX 0.8.1 with DSpark 72.5 tok/s on one chat + stream and 126.6 on four; TensorFold's #4618 head 123.4 code / 91.5 chat on one stream, 281.1 / 223.0 on four. +- Strata and llama.cpp were not measured here: neither is installed, and running them needs their installers and + weights (Strata's app and SQ packs; an Inkling GGUF and a llama.cpp build with the looped-layer support) put on this + Mac, which is the owner's call. Strata's own model card publishes, for an M5 Max 128 GB, 100.0-114.5 tok/s on one + request and 597.2 with 64. The one-request figure is under ours; the 64-request figure is above ours (344.3 code / + 236.2 chat) on a smaller chip, so at 64 streams the fastest-engine line stays open until Strata runs on this Mac. ## Exactness @@ -54,6 +78,15 @@ binary runs on the device: token for token while a stream leaves and another joins; - `Mini Metal opt-in DSpark drafting preserves target tokens and rolls back exactly`. +## Kernel contract + +`tf-kernel-contract --only 'dspark cohort'` on this Mac: `SUMMARY 5 kernels: 5 pass gates 1-4, 0 fail, 0 known +findings; 5 controls: 5 red as planted, 0 missed; 0 limit problems`. Each cohort launch +(`zig/tests/contract/metal_inkling2_dspark_cohort.zig`, records in `inkling2_dspark_cohort_metal_records.zig`) is +checked byte for byte against the solo launches it replaces run a stream at a time on the same inputs: `block_qkv` +at each anchor, `recurrent` at each kappa row and held token, `chain_pick`, `logits` per base row, and the host's +row copies for `pack`. Each control plants one stream's or row's wrong index and turns red at `shapes`. + ## Files `cells.jsonl`: each cell of the five sessions; `bench.sh` and `engines.sh` reproduce them (`MODEL` names the diff --git a/docs/receipts/inkling-2-mini-metal-235/cells.jsonl b/docs/receipts/inkling-2-mini-metal-235/cells.jsonl index e3c6c83170c..68b5dc671bb 100644 --- a/docs/receipts/inkling-2-mini-metal-235/cells.jsonl +++ b/docs/receipts/inkling-2-mini-metal-235/cells.jsonl @@ -1,36 +1,36 @@ -{"label": "c2-ctl-a", "prompt": "code", "streams": 1, "aggregate_tps": 123.2, "end_to_end_tps": 120.0, "tokens_per_round": 3.368, "failed": 0, "alone": {"equal": 3, "unequal": 0, "failed": 0}} -{"label": "c2-ctl-a", "prompt": "code", "streams": 2, "aggregate_tps": 188.9, "end_to_end_tps": 185.2, "tokens_per_round": 2.813, "failed": 0, "alone": {"equal": 6, "unequal": 0, "failed": 0}} -{"label": "c2-ctl-a", "prompt": "code", "streams": 4, "aggregate_tps": 271.2, "end_to_end_tps": 267.6, "tokens_per_round": 2.813, "failed": 0, "alone": {"equal": 12, "unequal": 0, "failed": 0}} -{"label": "c2-ctl-a", "prompt": "code", "streams": 16, "aggregate_tps": 262.2, "end_to_end_tps": 262.0, "tokens_per_round": 2.813, "failed": 0, "alone": {"equal": 48, "unequal": 0, "failed": 0}} -{"label": "c2-ctl-a", "prompt": "chat", "streams": 1, "aggregate_tps": 67.5, "end_to_end_tps": 65.8, "tokens_per_round": 2.286, "failed": 0, "alone": {"equal": 3, "unequal": 0, "failed": 0}} -{"label": "c2-ctl-a", "prompt": "chat", "streams": 2, "aggregate_tps": 121.9, "end_to_end_tps": 118.7, "tokens_per_round": 2.327, "failed": 0, "alone": {"equal": 6, "unequal": 0, "failed": 0}} -{"label": "c2-ctl-a", "prompt": "chat", "streams": 4, "aggregate_tps": 136.5, "end_to_end_tps": 134.4, "tokens_per_round": 2.327, "failed": 0, "alone": {"equal": 12, "unequal": 0, "failed": 0}} -{"label": "c2-ctl-a", "prompt": "chat", "streams": 16, "aggregate_tps": 130.5, "end_to_end_tps": 130.5, "tokens_per_round": 2.327, "failed": 0, "alone": {"equal": 48, "unequal": 0, "failed": 0}} -{"label": "c2-cand", "prompt": "code", "streams": 1, "aggregate_tps": 121.7, "end_to_end_tps": 118.7, "tokens_per_round": 3.368, "failed": 0, "alone": {"equal": 3, "unequal": 0, "failed": 0}} -{"label": "c2-cand", "prompt": "code", "streams": 2, "aggregate_tps": 205.6, "end_to_end_tps": 201.3, "tokens_per_round": 2.813, "failed": 0, "alone": {"equal": 6, "unequal": 0, "failed": 0}} -{"label": "c2-cand", "prompt": "code", "streams": 4, "aggregate_tps": 310.3, "end_to_end_tps": 305.5, "tokens_per_round": 2.813, "failed": 0, "alone": {"equal": 12, "unequal": 0, "failed": 0}} -{"label": "c2-cand", "prompt": "code", "streams": 16, "aggregate_tps": 344.1, "end_to_end_tps": 343.7, "tokens_per_round": 2.813, "failed": 0, "alone": {"equal": 48, "unequal": 0, "failed": 0}} -{"label": "c2-cand", "prompt": "chat", "streams": 1, "aggregate_tps": 90.5, "end_to_end_tps": 88.1, "tokens_per_round": 2.37, "failed": 0, "alone": {"equal": 3, "unequal": 0, "failed": 0}} -{"label": "c2-cand", "prompt": "chat", "streams": 2, "aggregate_tps": 170.1, "end_to_end_tps": 166.0, "tokens_per_round": 2.327, "failed": 0, "alone": {"equal": 6, "unequal": 0, "failed": 0}} -{"label": "c2-cand", "prompt": "chat", "streams": 4, "aggregate_tps": 256.5, "end_to_end_tps": 251.9, "tokens_per_round": 2.327, "failed": 0, "alone": {"equal": 12, "unequal": 0, "failed": 0}} -{"label": "c2-cand", "prompt": "chat", "streams": 16, "aggregate_tps": 234.6, "end_to_end_tps": 234.2, "tokens_per_round": 2.327, "failed": 0, "alone": {"equal": 48, "unequal": 0, "failed": 0}} -{"label": "c2-ctl-b", "prompt": "code", "streams": 1, "aggregate_tps": 112.2, "end_to_end_tps": 109.0, "tokens_per_round": 3.325, "failed": 0, "alone": {"equal": 3, "unequal": 0, "failed": 0}} -{"label": "c2-ctl-b", "prompt": "code", "streams": 2, "aggregate_tps": 186.4, "end_to_end_tps": 180.8, "tokens_per_round": 2.813, "failed": 0, "alone": {"equal": 6, "unequal": 0, "failed": 0}} -{"label": "c2-ctl-b", "prompt": "code", "streams": 4, "aggregate_tps": 239.6, "end_to_end_tps": 235.9, "tokens_per_round": 2.813, "failed": 0, "alone": {"equal": 12, "unequal": 0, "failed": 0}} -{"label": "c2-ctl-b", "prompt": "code", "streams": 16, "aggregate_tps": 243.9, "end_to_end_tps": 243.9, "tokens_per_round": 2.813, "failed": 0, "alone": {"equal": 48, "unequal": 0, "failed": 0}} -{"label": "c2-ctl-b", "prompt": "chat", "streams": 1, "aggregate_tps": 82.4, "end_to_end_tps": 80.1, "tokens_per_round": 2.56, "failed": 0, "alone": {"equal": 3, "unequal": 0, "failed": 0}} -{"label": "c2-ctl-b", "prompt": "chat", "streams": 2, "aggregate_tps": 139.5, "end_to_end_tps": 133.6, "tokens_per_round": 2.327, "failed": 0, "alone": {"equal": 6, "unequal": 0, "failed": 0}} -{"label": "c2-ctl-b", "prompt": "chat", "streams": 4, "aggregate_tps": 187.8, "end_to_end_tps": 183.6, "tokens_per_round": 2.327, "failed": 0, "alone": {"equal": 12, "unequal": 0, "failed": 0}} -{"label": "c2-ctl-b", "prompt": "chat", "streams": 16, "aggregate_tps": 222.0, "end_to_end_tps": 221.6, "tokens_per_round": 2.327, "failed": 0, "alone": {"equal": 48, "unequal": 0, "failed": 0}} -{"label": "tensorfold", "prompt": "code", "streams": 1, "aggregate_tps": 116.2, "end_to_end_tps": 112.3, "tokens_per_round": 3.241, "failed": 0, "alone": null} -{"label": "tensorfold", "prompt": "code", "streams": 4, "aggregate_tps": 295.9, "end_to_end_tps": 292.0, "tokens_per_round": 2.813, "failed": 0, "alone": null} -{"label": "tensorfold", "prompt": "code", "streams": 64, "aggregate_tps": 340.9, "end_to_end_tps": 341.8, "tokens_per_round": 2.813, "failed": 0, "alone": null} -{"label": "tensorfold", "prompt": "chat", "streams": 1, "aggregate_tps": 93.8, "end_to_end_tps": 90.7, "tokens_per_round": 2.306, "failed": 0, "alone": null} -{"label": "tensorfold", "prompt": "chat", "streams": 4, "aggregate_tps": 261.4, "end_to_end_tps": 256.4, "tokens_per_round": 2.327, "failed": 0, "alone": null} -{"label": "tensorfold", "prompt": "chat", "streams": 64, "aggregate_tps": 232.2, "end_to_end_tps": 232.8, "tokens_per_round": 2.327, "failed": 0, "alone": null} -{"label": "omlx", "prompt": "code", "streams": 1, "aggregate_tps": 0.0, "end_to_end_tps": 45.1, "tokens_per_round": null, "failed": 0, "alone": null} -{"label": "omlx", "prompt": "code", "streams": 4, "aggregate_tps": 0.0, "end_to_end_tps": 107.0, "tokens_per_round": null, "failed": 0, "alone": null} -{"label": "omlx", "prompt": "code", "streams": 64, "aggregate_tps": 0.0, "end_to_end_tps": 209.3, "tokens_per_round": null, "failed": 0, "alone": null} -{"label": "omlx", "prompt": "chat", "streams": 1, "aggregate_tps": 8.4, "end_to_end_tps": 8.3, "tokens_per_round": 3.556, "failed": 0, "alone": null} -{"label": "omlx", "prompt": "chat", "streams": 4, "aggregate_tps": 86.5, "end_to_end_tps": 79.1, "tokens_per_round": 2.0, "failed": 0, "alone": null} -{"label": "omlx", "prompt": "chat", "streams": 64, "aggregate_tps": 229.3, "end_to_end_tps": 227.6, "tokens_per_round": 1.797, "failed": 0, "alone": null} +{"label": "c16-ctl-a", "prompt": "code", "streams": 1, "aggregate_tps": 119.7, "end_to_end_tps": 116.88543685775235, "failed": 0, "drafts": {"rounds": 233, "drafted": 1255, "accepted": 535, "depth_drafted": [232, 226, 224, 171, 156, 153, 78], "depth_accepted": [172, 132, 103, 57, 39, 25, 7]}, "alone": {"equal": 3, "unequal": 0, "failed": 0}} +{"label": "c16-ctl-a", "prompt": "code", "streams": 2, "aggregate_tps": 192.9, "end_to_end_tps": 189.231965025503, "failed": 0, "drafts": {"rounds": 540, "drafted": 1608, "accepted": 990, "depth_drafted": [534, 534, 528, 6, 6], "depth_accepted": [420, 318, 252]}, "alone": {"equal": 6, "unequal": 0, "failed": 0}} +{"label": "c16-ctl-a", "prompt": "code", "streams": 4, "aggregate_tps": 278.3, "end_to_end_tps": 275.10994491939044, "failed": 0, "drafts": {"rounds": 1080, "drafted": 3216, "accepted": 1980, "depth_drafted": [1068, 1068, 1056, 12, 12], "depth_accepted": [840, 636, 504]}, "alone": {"equal": 12, "unequal": 0, "failed": 0}} +{"label": "c16-ctl-a", "prompt": "code", "streams": 16, "aggregate_tps": 284.1, "end_to_end_tps": 283.96345011473045, "failed": 0, "drafts": {"rounds": 6816, "drafted": 6768, "accepted": 5424, "depth_drafted": [6720], "depth_accepted": [5424]}, "alone": {"equal": 48, "unequal": 0, "failed": 0}} +{"label": "c16-ctl-a", "prompt": "chat", "streams": 1, "aggregate_tps": 93.9, "end_to_end_tps": 91.38977157597242, "failed": 0, "drafts": {"rounds": 324, "drafted": 1321, "accepted": 441, "depth_drafted": [321, 297, 261, 177, 157, 58, 5], "depth_accepted": [223, 113, 68, 21, 10, 6]}, "alone": {"equal": 3, "unequal": 0, "failed": 0}} +{"label": "c16-ctl-a", "prompt": "chat", "streams": 2, "aggregate_tps": 159.2, "end_to_end_tps": 155.6431134964016, "failed": 0, "drafts": {"rounds": 654, "drafted": 2028, "accepted": 876, "depth_drafted": [648, 642, 642, 6], "depth_accepted": [438, 246, 180]}, "alone": {"equal": 6, "unequal": 0, "failed": 0}} +{"label": "c16-ctl-a", "prompt": "chat", "streams": 4, "aggregate_tps": 228.3, "end_to_end_tps": 224.64889015945306, "failed": 0, "drafts": {"rounds": 1308, "drafted": 3960, "accepted": 1752, "depth_drafted": [1296, 1284, 1284, 12], "depth_accepted": [876, 492, 360]}, "alone": {"equal": 12, "unequal": 0, "failed": 0}} +{"label": "c16-ctl-a", "prompt": "chat", "streams": 16, "aggregate_tps": 266.8, "end_to_end_tps": 266.3535516813391, "failed": 0, "drafts": {"rounds": 7104, "drafted": 7104, "accepted": 5136, "depth_drafted": [7008], "depth_accepted": [5088]}, "alone": {"equal": 48, "unequal": 0, "failed": 0}} +{"label": "c16-cand", "prompt": "code", "streams": 1, "aggregate_tps": 121.9, "end_to_end_tps": 119.32538271894245, "failed": 0, "drafts": {"rounds": 229, "drafted": 1260, "accepted": 539, "depth_drafted": [229, 223, 216, 216, 181, 150, 45], "depth_accepted": [169, 125, 94, 70, 48, 29, 4]}, "alone": {"equal": 3, "unequal": 0, "failed": 0}} +{"label": "c16-cand", "prompt": "code", "streams": 2, "aggregate_tps": 209.8, "end_to_end_tps": 205.71504794300844, "failed": 0, "drafts": {"rounds": 540, "drafted": 1620, "accepted": 990, "depth_drafted": [534, 534, 528, 6, 6, 6, 6], "depth_accepted": [420, 318, 252]}, "alone": {"equal": 6, "unequal": 0, "failed": 0}} +{"label": "c16-cand", "prompt": "code", "streams": 4, "aggregate_tps": 317.2, "end_to_end_tps": 313.0650068588643, "failed": 0, "drafts": {"rounds": 1080, "drafted": 3240, "accepted": 1980, "depth_drafted": [1068, 1068, 1056, 12, 12, 12, 12], "depth_accepted": [840, 636, 504]}, "alone": {"equal": 12, "unequal": 0, "failed": 0}} +{"label": "c16-cand", "prompt": "code", "streams": 16, "aggregate_tps": 372.2, "end_to_end_tps": 371.7421721646994, "failed": 0, "drafts": {"rounds": 6816, "drafted": 6768, "accepted": 5424, "depth_drafted": [6720], "depth_accepted": [5424]}, "alone": {"equal": 48, "unequal": 0, "failed": 0}} +{"label": "c16-cand", "prompt": "chat", "streams": 1, "aggregate_tps": 93.4, "end_to_end_tps": 91.0309139987294, "failed": 0, "drafts": {"rounds": 325, "drafted": 1287, "accepted": 440, "depth_drafted": [322, 292, 267, 213, 133, 15], "depth_accepted": [225, 112, 71, 20, 9, 2]}, "alone": {"equal": 3, "unequal": 0, "failed": 0}} +{"label": "c16-cand", "prompt": "chat", "streams": 2, "aggregate_tps": 172.8, "end_to_end_tps": 168.53290897738248, "failed": 0, "drafts": {"rounds": 654, "drafted": 2034, "accepted": 876, "depth_drafted": [648, 642, 642, 6, 6], "depth_accepted": [438, 246, 180]}, "alone": {"equal": 6, "unequal": 0, "failed": 0}} +{"label": "c16-cand", "prompt": "chat", "streams": 4, "aggregate_tps": 259.5, "end_to_end_tps": 255.12893928587093, "failed": 0, "drafts": {"rounds": 1308, "drafted": 3972, "accepted": 1752, "depth_drafted": [1296, 1284, 1284, 12, 12], "depth_accepted": [876, 492, 360]}, "alone": {"equal": 12, "unequal": 0, "failed": 0}} +{"label": "c16-cand", "prompt": "chat", "streams": 16, "aggregate_tps": 348.9, "end_to_end_tps": 347.74160865912006, "failed": 0, "drafts": {"rounds": 7104, "drafted": 7104, "accepted": 5136, "depth_drafted": [7008], "depth_accepted": [5088]}, "alone": {"equal": 48, "unequal": 0, "failed": 0}} +{"label": "c16-ctl-b", "prompt": "code", "streams": 1, "aggregate_tps": 125.7, "end_to_end_tps": 122.5636142797601, "failed": 0, "drafts": {"rounds": 230, "drafted": 1120, "accepted": 538, "depth_drafted": [228, 222, 222, 201, 163, 50, 4], "depth_accepted": [173, 134, 105, 71, 48, 7]}, "alone": {"equal": 3, "unequal": 0, "failed": 0}} +{"label": "c16-ctl-b", "prompt": "code", "streams": 2, "aggregate_tps": 196.0, "end_to_end_tps": 192.53329013059238, "failed": 0, "drafts": {"rounds": 540, "drafted": 1608, "accepted": 990, "depth_drafted": [534, 534, 528, 6, 6], "depth_accepted": [420, 318, 252]}, "alone": {"equal": 6, "unequal": 0, "failed": 0}} +{"label": "c16-ctl-b", "prompt": "code", "streams": 4, "aggregate_tps": 277.6, "end_to_end_tps": 274.6690769031714, "failed": 0, "drafts": {"rounds": 1080, "drafted": 3216, "accepted": 1980, "depth_drafted": [1068, 1068, 1056, 12, 12], "depth_accepted": [840, 636, 504]}, "alone": {"equal": 12, "unequal": 0, "failed": 0}} +{"label": "c16-ctl-b", "prompt": "code", "streams": 16, "aggregate_tps": 267.4, "end_to_end_tps": 266.9129804820544, "failed": 0, "drafts": {"rounds": 6816, "drafted": 6768, "accepted": 5424, "depth_drafted": [6720], "depth_accepted": [5424]}, "alone": {"equal": 48, "unequal": 0, "failed": 0}} +{"label": "c16-ctl-b", "prompt": "chat", "streams": 1, "aggregate_tps": 94.0, "end_to_end_tps": 91.0247506851077, "failed": 0, "drafts": {"rounds": 308, "drafted": 1421, "accepted": 457, "depth_drafted": [307, 295, 280, 219, 186, 109, 10], "depth_accepted": [212, 107, 77, 28, 20, 13]}, "alone": {"equal": 3, "unequal": 0, "failed": 0}} +{"label": "c16-ctl-b", "prompt": "chat", "streams": 2, "aggregate_tps": 157.6, "end_to_end_tps": 153.4496116937129, "failed": 0, "drafts": {"rounds": 654, "drafted": 2034, "accepted": 876, "depth_drafted": [648, 642, 642, 6, 6], "depth_accepted": [438, 246, 180]}, "alone": {"equal": 6, "unequal": 0, "failed": 0}} +{"label": "c16-ctl-b", "prompt": "chat", "streams": 4, "aggregate_tps": 225.2, "end_to_end_tps": 221.44720707479132, "failed": 0, "drafts": {"rounds": 1308, "drafted": 3972, "accepted": 1752, "depth_drafted": [1296, 1284, 1284, 12, 12], "depth_accepted": [876, 492, 360]}, "alone": {"equal": 12, "unequal": 0, "failed": 0}} +{"label": "c16-ctl-b", "prompt": "chat", "streams": 16, "aggregate_tps": 190.9, "end_to_end_tps": 190.63346263988035, "failed": 0, "drafts": {"rounds": 7104, "drafted": 7104, "accepted": 5136, "depth_drafted": [7008], "depth_accepted": [5088]}, "alone": {"equal": 48, "unequal": 0, "failed": 0}} +{"label": "tensorfold", "prompt": "code", "streams": 1, "aggregate_tps": 116.3, "end_to_end_tps": 113.7165267159262, "failed": 0, "drafts": {"rounds": 237, "drafted": 1059, "accepted": 531, "depth_drafted": [236, 231, 218, 213, 87, 39, 20], "depth_accepted": [181, 136, 104, 79, 24, 5, 2]}} +{"label": "tensorfold", "prompt": "code", "streams": 4, "aggregate_tps": 297.9, "end_to_end_tps": 293.91314907758107, "failed": 0, "drafts": {"rounds": 1080, "drafted": 3204, "accepted": 1980, "depth_drafted": [1068, 1068, 1056, 12], "depth_accepted": [840, 636, 504]}} +{"label": "tensorfold", "prompt": "code", "streams": 64, "aggregate_tps": 343.4, "end_to_end_tps": 344.26122726247877, "failed": 0, "drafts": {"rounds": 48960, "drafted": 0, "accepted": 0, "depth_drafted": [], "depth_accepted": []}} +{"label": "tensorfold", "prompt": "chat", "streams": 1, "aggregate_tps": 88.1, "end_to_end_tps": 86.20439036513953, "failed": 0, "drafts": {"rounds": 333, "drafted": 1249, "accepted": 432, "depth_drafted": [330, 263, 236, 234, 128, 13], "depth_accepted": [231, 94, 63, 28, 13, 1]}} +{"label": "tensorfold", "prompt": "chat", "streams": 4, "aggregate_tps": 244.2, "end_to_end_tps": 239.95424696743052, "failed": 0, "drafts": {"rounds": 1308, "drafted": 3972, "accepted": 1752, "depth_drafted": [1296, 1284, 1284, 12, 12], "depth_accepted": [876, 492, 360]}} +{"label": "tensorfold", "prompt": "chat", "streams": 64, "aggregate_tps": 235.6, "end_to_end_tps": 236.16095333117735, "failed": 0, "drafts": {"rounds": 48960, "drafted": 0, "accepted": 0, "depth_drafted": [], "depth_accepted": []}} +{"label": "omlx", "prompt": "code", "streams": 1, "aggregate_tps": 0.0, "end_to_end_tps": 13.463548904074338, "failed": 0} +{"label": "omlx", "prompt": "code", "streams": 4, "aggregate_tps": 0.0, "end_to_end_tps": 39.20085915878605, "failed": 0} +{"label": "omlx", "prompt": "code", "streams": 64, "aggregate_tps": 0.0, "end_to_end_tps": 200.03320690902405, "failed": 0} +{"label": "omlx", "prompt": "chat", "streams": 1, "aggregate_tps": 37.7, "end_to_end_tps": 36.2406493755635, "failed": 0} +{"label": "omlx", "prompt": "chat", "streams": 4, "aggregate_tps": 49.8, "end_to_end_tps": 48.29203390739297, "failed": 0} +{"label": "omlx", "prompt": "chat", "streams": 64, "aggregate_tps": 186.1, "end_to_end_tps": 184.5129861964711, "failed": 0} diff --git a/docs/receipts/inkling-2-mini-metal-235/engines.sh b/docs/receipts/inkling-2-mini-metal-235/engines.sh index 1c35e6ce098..81aec261766 100755 --- a/docs/receipts/inkling-2-mini-metal-235/engines.sh +++ b/docs/receipts/inkling-2-mini-metal-235/engines.sh @@ -2,7 +2,7 @@ # engines.sh TENSORFOLD_BINARY: the 1, 4 and 64-stream greedy receipt against oMLX on this Mac, 3 reps each, both # servers admitting 64 requests. oMLX serves its own 4-bit MTP build (Inkling-2-Mini-oQ4e-mtp) from # ~/.omlx/settings.json, MTP drafting on. Run it under `lockf -k /tmp/tensorfold-model.lock`; the two servers run one -# after the other. OMLX names the oMLX binary; CONTEXT the TensorFold window (65536). +# after the other. OMLX names the oMLX binary. 64 lanes take a 16384-token window to fit in memory. set -euo pipefail bin=$1 wt=$(git -C "$(dirname "$0")" rev-parse --show-toplevel) @@ -26,5 +26,5 @@ measure() { # LABEL PORT MODEL COMMAND...: start the server, bench it, stop it trap - EXIT } -measure tensorfold 18235 Inkling-2-Mini "$bin" serve "$model" --port 18235 --context "${CONTEXT:-65536}" --parallel 64 --drafter "$model" +measure tensorfold 18235 Inkling-2-Mini "$bin" serve "$model" --port 18235 --context 16384 --parallel 64 --drafter "$model" measure omlx 8765 Inkling-2-Mini-oQ4e-mtp "$omlx" serve --host 127.0.0.1 --port 8765 --max-concurrent-requests 64 From 185461e6a5416bc7e8df9e050fa56b39590a0cac Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:00:54 +0800 Subject: [PATCH 10/14] inkling2 metal: zig fmt dspark_state --- zig/src/families/inkling2/metal/dspark_state.zig | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/zig/src/families/inkling2/metal/dspark_state.zig b/zig/src/families/inkling2/metal/dspark_state.zig index d127e003708..8bbfc66428c 100644 --- a/zig/src/families/inkling2/metal/dspark_state.zig +++ b/zig/src/families/inkling2/metal/dspark_state.zig @@ -40,8 +40,8 @@ pub fn scratchBytes() usize { } const cohort_fields = [_][]const u8{ - "ids", "anchors", "state", "next_state", "z", "lambda", "x", "y", "resid", "next_resid", "q_raw", "k_raw", - "v_raw", "q", "kb", "vb", "attn", "gate", "up", "act", "kappa", "tile", "base", "logits", + "ids", "anchors", "state", "next_state", "z", "lambda", "x", "y", "resid", "next_resid", "q_raw", "k_raw", + "v_raw", "q", "kb", "vb", "attn", "gate", "up", "act", "kappa", "tile", "base", "logits", }; fn cohortSizes() [cohort_fields.len]usize { @@ -50,12 +50,12 @@ fn cohortSizes() [cohort_fields.len]usize { const drafts = s * (block - 1); const b = 2; return .{ - s * 4, s * 4, s * rank * b, s * rank * b, - s * 3 * rank * b, s * rank * b, rows * hidden * b, rows * hidden * b, - rows * hidden * b, rows * hidden * b, rows * query * b, rows * kv * b, - rows * kv * b, rows * query * b, rows * kv * b, rows * kv * b, - rows * query * b, rows * intermediate * b, rows * intermediate * b, rows * intermediate * b, - drafts * 3 * rank * 4, kernels.tile_rows * hidden * b, drafts * vocabulary * b, s * vocabulary * b, + s * 4, s * 4, s * rank * b, s * rank * b, + s * 3 * rank * b, s * rank * b, rows * hidden * b, rows * hidden * b, + rows * hidden * b, rows * hidden * b, rows * query * b, rows * kv * b, + rows * kv * b, rows * query * b, rows * kv * b, rows * kv * b, + rows * query * b, rows * intermediate * b, rows * intermediate * b, rows * intermediate * b, + drafts * 3 * rank * 4, kernels.tile_rows * hidden * b, drafts * vocabulary * b, s * vocabulary * b, }; } From 55875ebdb79a6dc5389fa5484893293ce4797fcc Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:24:46 +0800 Subject: [PATCH 11/14] server: report per-depth draft tallies only when a head chain drafted, so golden replies keep their shape --- zig/src/server/chat_generation.zig | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/zig/src/server/chat_generation.zig b/zig/src/server/chat_generation.zig index ba234a99da8..06feb2c74c0 100644 --- a/zig/src/server/chat_generation.zig +++ b/zig/src/server/chat_generation.zig @@ -37,12 +37,10 @@ fn putRows(a: Allocator, d: Value, settled: Value, key: []const u8) Allocator.Er if (settled.get("positions")) |at| try d.object.put(a, "logprob_positions", try rowsOf(a, key, at.get(key).?)); } -/// A per-depth tally as a JSON array, the first depth first, through the deepest drafted. -fn depthCounts(a: Allocator, counts: []const u32) Allocator.Error!Value { - var n = counts.len; - while (n > 0 and counts[n - 1] == 0) n -= 1; - const out = try a.alloc(Value, n); - for (counts[0..n], out) |c, *slot| slot.* = try json.intValue(a, c); +/// `counts` through the deepest head chain row drafted, as a JSON array, the first depth first. +fn depthCounts(a: Allocator, counts: []const u32, depths: usize) Allocator.Error!Value { + const out = try a.alloc(Value, depths); + for (counts[0..depths], out) |c, *slot| slot.* = try json.intValue(a, c); return .{ .array = out }; } @@ -423,8 +421,11 @@ pub const Generation = struct { try spec.put(a, "rounds", try json.intValue(a, s.rounds)); try spec.put(a, "drafted", try json.intValue(a, s.drafted)); try spec.put(a, "accepted", try json.intValue(a, s.accepted)); - try spec.put(a, "depth_drafted", try depthCounts(a, &s.depth_drafted)); - try spec.put(a, "depth_accepted", try depthCounts(a, &s.depth_accepted)); + const depths = std.mem.indexOfScalar(u32, &s.depth_drafted, 0) orelse s.depth_drafted.len; + if (depths > 0) { + try spec.put(a, "depth_drafted", try depthCounts(a, &s.depth_drafted, depths)); + try spec.put(a, "depth_accepted", try depthCounts(a, &s.depth_accepted, depths)); + } try spec.put(a, "acceptance_rate", .{ .float = if (s.drafted > 0) @as(f64, @floatFromInt(s.accepted)) / @as(f64, @floatFromInt(s.drafted)) else 0 }); try spec.put(a, "tokens_per_round", .{ .float = if (s.rounds > 0) @as(f64, @floatFromInt(g.collected.items.len)) / @as(f64, @floatFromInt(s.rounds)) else 0 }); const counters = try a.dupe(u8, m.telemetry); // parsed strings point into it: it outlives the box From 895bdaf0ebebacc0e35e89c683ff49c79cda2acb Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:47:55 +0800 Subject: [PATCH 12/14] inkling2 metal: say which DSpark holds take one command buffer; receipt compares one stream's acceptance by its total, names llama.cpp's Inkling release --- docs/receipts/inkling-2-mini-metal-235/README.md | 7 ++++--- zig/src/families/inkling2/metal/dspark.zig | 4 ++-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/receipts/inkling-2-mini-metal-235/README.md b/docs/receipts/inkling-2-mini-metal-235/README.md index 0340c5fb0f2..3bb10930a54 100644 --- a/docs/receipts/inkling-2-mini-metal-235/README.md +++ b/docs/receipts/inkling-2-mini-metal-235/README.md @@ -41,8 +41,9 @@ depths' few rows are the first round's: | 4 | 876/1296 492/1284 360/1284 0/12 | 876/1296 492/1284 360/1284 0/12 0/12 | 876/1296 492/1284 360/1284 0/12 0/12 | | 16 | 5088/7008 | 5088/7008 | 5088/7008 | -One stream's depths follow each round's timing, so they move between sessions in both arms; its kept rows (535, 539, -538 code; 441, 440, 457 chat) do not regress. At sixteen admitted streams the depth rule drafts one row. +One stream's depths follow each round's timing, so drafted rows per depth move between sessions in both arms and the +per-depth ratios do not compare; its total kept rows (535, 539, 538 code; 441, 440, 457 chat) do not regress. At +sixteen admitted streams the depth rule drafts one row. ## Against the other engines @@ -62,7 +63,7 @@ decode time, so only end to end compares): - #4618 on this Mac (its own clients, `--parallel 4 --context 16384`): oMLX 0.8.1 with DSpark 72.5 tok/s on one chat stream and 126.6 on four; TensorFold's #4618 head 123.4 code / 91.5 chat on one stream, 281.1 / 223.0 on four. - Strata and llama.cpp were not measured here: neither is installed, and running them needs their installers and - weights (Strata's app and SQ packs; an Inkling GGUF and a llama.cpp build with the looped-layer support) put on this + weights (Strata's app and SQ packs; llama.cpp b12406 or later, which added Inkling 2, and an Inkling GGUF) put on this Mac, which is the owner's call. Strata's own model card publishes, for an M5 Max 128 GB, 100.0-114.5 tok/s on one request and 597.2 with 64. The one-request figure is under ours; the 64-request figure is above ours (344.3 code / 236.2 chat) on a smaller chip, so at 64 streams the fastest-engine line stays open until Strata runs on this Mac. diff --git a/zig/src/families/inkling2/metal/dspark.zig b/zig/src/families/inkling2/metal/dspark.zig index ad372aaa52c..fea682881f9 100644 --- a/zig/src/families/inkling2/metal/dspark.zig +++ b/zig/src/families/inkling2/metal/dspark.zig @@ -451,8 +451,8 @@ pub const Drafter = struct { } } - /// A greedy hold of up to `cohort_streams` runs step-major in one command buffer; otherwise every stream's block and - /// first step in one command buffer, then one command buffer a later step for all of them. + /// A greedy hold of up to `cohort_streams` streams runs step-major, all depths in one command buffer. A sampled or + /// larger hold encodes one command buffer per depth for all its streams, with each block in the first. fn holdFn(ptr: *anyopaque, items: []const dr.Hold) anyerror!void { const d = cast(ptr); if (items.len == 0) return; From c478e1e84a8ea809af96261e976b8fb2e580ce11 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:53:13 +0800 Subject: [PATCH 13/14] docs: card 235's receipt compares only against #4618's published figures; the engine receipt moves to ink mac engines --- ...nkling-2-mini-on-mac-all-streams-dspark.md | 2 +- .../inkling-2-mini-metal-235/README.md | 30 +++++-------------- .../inkling-2-mini-metal-235/cells.jsonl | 12 -------- .../inkling-2-mini-metal-235/engines.sh | 30 ------------------- 4 files changed, 8 insertions(+), 66 deletions(-) delete mode 100755 docs/receipts/inkling-2-mini-metal-235/engines.sh diff --git a/changelog.d/235-inkling-2-mini-on-mac-all-streams-dspark.md b/changelog.d/235-inkling-2-mini-on-mac-all-streams-dspark.md index 9b0615b51f4..a93277e641a 100644 --- a/changelog.d/235-inkling-2-mini-on-mac-all-streams-dspark.md +++ b/changelog.d/235-inkling-2-mini-on-mac-all-streams-dspark.md @@ -2,4 +2,4 @@ - Schedule greedy DSpark holds by block and recurrent step across active streams, batching the unembedding weight read for each cohort rather than completing one stream's draft chain before starting the next; a lone stream keeps its solo chain. - Check greedy draft-token equality against solo holds with unequal depths, streams joining or leaving, and 16-stream cohorts. -- On the M5 Ultra, greedy DSpark reaches 310 / 257 tok/s at four streams (code / chat, up 14% / 37% on the better control) and 344 / 235 at sixteen, with acceptance unchanged; `docs/receipts/inkling-2-mini-metal-235` also holds the 1, 4 and 64-stream receipt against oMLX 0.8.2 on the same machine. +- On the M5 Ultra, greedy DSpark reaches 317 / 260 tok/s at four streams (code / chat, up 14% on the better control) and 372 / 349 at sixteen (up 31%), with acceptance unchanged; `docs/receipts/inkling-2-mini-metal-235` holds the control/candidate/control medians and acceptance by depth. diff --git a/docs/receipts/inkling-2-mini-metal-235/README.md b/docs/receipts/inkling-2-mini-metal-235/README.md index 3bb10930a54..ae05318cad2 100644 --- a/docs/receipts/inkling-2-mini-metal-235/README.md +++ b/docs/receipts/inkling-2-mini-metal-235/README.md @@ -45,28 +45,12 @@ One stream's depths follow each round's timing, so drafted rows per depth move b per-depth ratios do not compare; its total kept rows (535, 539, 538 code; 441, 440, 457 chat) do not regress. At sixteen admitted streams the depth rule drafts one row. -## Against the other engines +## Against #4618's published figures -`engines.sh` (`--levels 1,4,64 --reps 3 --tokens 256 --temperatures 0`; TensorFold `--context 16384 --parallel 64`, -the window that fits 64 lanes), end-to-end tok/s, medians of three (a reply that arrives as one text piece has no -decode time, so only end to end compares): - -| code / chat | TensorFold, DSpark | oMLX 0.8.2, MTP | ratio | -|---|---|---|---| -| 1 stream | **113.7 / 86.2** | 13.5 / 36.2 | 8.4x / 2.4x | -| 4 streams | **293.9 / 240.0** | 39.2 / 48.3 | 7.5x / 5.0x | -| 64 streams | **344.3 / 236.2** | 200.0 / 184.5 | 1.7x / 1.3x | - -- oMLX serves its own 4-bit build (`Inkling-2-Mini-oQ4e-mtp`, about 17 GB) with MTP drafting on; TensorFold serves the - official NVFP4/MXFP8 checkpoint. oMLX ran at load average 70-90; in this branch's first session (load 14-40) it - reached 45.1 / 8.3, 107.0 / 79.1 and 209.3 / 227.6, still under ours at every cell but 64 chat streams (1.02x). -- #4618 on this Mac (its own clients, `--parallel 4 --context 16384`): oMLX 0.8.1 with DSpark 72.5 tok/s on one chat - stream and 126.6 on four; TensorFold's #4618 head 123.4 code / 91.5 chat on one stream, 281.1 / 223.0 on four. -- Strata and llama.cpp were not measured here: neither is installed, and running them needs their installers and - weights (Strata's app and SQ packs; llama.cpp b12406 or later, which added Inkling 2, and an Inkling GGUF) put on this - Mac, which is the owner's call. Strata's own model card publishes, for an M5 Max 128 GB, 100.0-114.5 tok/s on one - request and 597.2 with 64. The one-request figure is under ours; the 64-request figure is above ours (344.3 code / - 236.2 chat) on a smaller chip, so at 64 streams the fastest-engine line stays open until Strata runs on this Mac. +#4618 published TensorFold's Inkling 2 Mini at 123.4 code / 91.5 chat tok/s on one stream and 281.1 / 223.0 on four, +on this Mac with its own clients; those are its published figures, not measured here. This branch's candidate gives +121.9 / 93.4 on one stream and 317.2 / 259.5 on four. Other engines at 1, 4 and 64 streams are card "ink mac +engines"'s receipt. ## Exactness @@ -90,5 +74,5 @@ row copies for `pack`. Each control plants one stream's or row's wrong index and ## Files -`cells.jsonl`: each cell of the five sessions; `bench.sh` and `engines.sh` reproduce them (`MODEL` names the -checkpoint, `OUT` the scratch folder, `OMLX` the oMLX binary). +`cells.jsonl`: each cell of the three sessions; `bench.sh` reproduces them (`MODEL` names the checkpoint, `OUT` the +scratch folder). diff --git a/docs/receipts/inkling-2-mini-metal-235/cells.jsonl b/docs/receipts/inkling-2-mini-metal-235/cells.jsonl index 68b5dc671bb..fab441488f4 100644 --- a/docs/receipts/inkling-2-mini-metal-235/cells.jsonl +++ b/docs/receipts/inkling-2-mini-metal-235/cells.jsonl @@ -22,15 +22,3 @@ {"label": "c16-ctl-b", "prompt": "chat", "streams": 2, "aggregate_tps": 157.6, "end_to_end_tps": 153.4496116937129, "failed": 0, "drafts": {"rounds": 654, "drafted": 2034, "accepted": 876, "depth_drafted": [648, 642, 642, 6, 6], "depth_accepted": [438, 246, 180]}, "alone": {"equal": 6, "unequal": 0, "failed": 0}} {"label": "c16-ctl-b", "prompt": "chat", "streams": 4, "aggregate_tps": 225.2, "end_to_end_tps": 221.44720707479132, "failed": 0, "drafts": {"rounds": 1308, "drafted": 3972, "accepted": 1752, "depth_drafted": [1296, 1284, 1284, 12, 12], "depth_accepted": [876, 492, 360]}, "alone": {"equal": 12, "unequal": 0, "failed": 0}} {"label": "c16-ctl-b", "prompt": "chat", "streams": 16, "aggregate_tps": 190.9, "end_to_end_tps": 190.63346263988035, "failed": 0, "drafts": {"rounds": 7104, "drafted": 7104, "accepted": 5136, "depth_drafted": [7008], "depth_accepted": [5088]}, "alone": {"equal": 48, "unequal": 0, "failed": 0}} -{"label": "tensorfold", "prompt": "code", "streams": 1, "aggregate_tps": 116.3, "end_to_end_tps": 113.7165267159262, "failed": 0, "drafts": {"rounds": 237, "drafted": 1059, "accepted": 531, "depth_drafted": [236, 231, 218, 213, 87, 39, 20], "depth_accepted": [181, 136, 104, 79, 24, 5, 2]}} -{"label": "tensorfold", "prompt": "code", "streams": 4, "aggregate_tps": 297.9, "end_to_end_tps": 293.91314907758107, "failed": 0, "drafts": {"rounds": 1080, "drafted": 3204, "accepted": 1980, "depth_drafted": [1068, 1068, 1056, 12], "depth_accepted": [840, 636, 504]}} -{"label": "tensorfold", "prompt": "code", "streams": 64, "aggregate_tps": 343.4, "end_to_end_tps": 344.26122726247877, "failed": 0, "drafts": {"rounds": 48960, "drafted": 0, "accepted": 0, "depth_drafted": [], "depth_accepted": []}} -{"label": "tensorfold", "prompt": "chat", "streams": 1, "aggregate_tps": 88.1, "end_to_end_tps": 86.20439036513953, "failed": 0, "drafts": {"rounds": 333, "drafted": 1249, "accepted": 432, "depth_drafted": [330, 263, 236, 234, 128, 13], "depth_accepted": [231, 94, 63, 28, 13, 1]}} -{"label": "tensorfold", "prompt": "chat", "streams": 4, "aggregate_tps": 244.2, "end_to_end_tps": 239.95424696743052, "failed": 0, "drafts": {"rounds": 1308, "drafted": 3972, "accepted": 1752, "depth_drafted": [1296, 1284, 1284, 12, 12], "depth_accepted": [876, 492, 360]}} -{"label": "tensorfold", "prompt": "chat", "streams": 64, "aggregate_tps": 235.6, "end_to_end_tps": 236.16095333117735, "failed": 0, "drafts": {"rounds": 48960, "drafted": 0, "accepted": 0, "depth_drafted": [], "depth_accepted": []}} -{"label": "omlx", "prompt": "code", "streams": 1, "aggregate_tps": 0.0, "end_to_end_tps": 13.463548904074338, "failed": 0} -{"label": "omlx", "prompt": "code", "streams": 4, "aggregate_tps": 0.0, "end_to_end_tps": 39.20085915878605, "failed": 0} -{"label": "omlx", "prompt": "code", "streams": 64, "aggregate_tps": 0.0, "end_to_end_tps": 200.03320690902405, "failed": 0} -{"label": "omlx", "prompt": "chat", "streams": 1, "aggregate_tps": 37.7, "end_to_end_tps": 36.2406493755635, "failed": 0} -{"label": "omlx", "prompt": "chat", "streams": 4, "aggregate_tps": 49.8, "end_to_end_tps": 48.29203390739297, "failed": 0} -{"label": "omlx", "prompt": "chat", "streams": 64, "aggregate_tps": 186.1, "end_to_end_tps": 184.5129861964711, "failed": 0} diff --git a/docs/receipts/inkling-2-mini-metal-235/engines.sh b/docs/receipts/inkling-2-mini-metal-235/engines.sh deleted file mode 100755 index 81aec261766..00000000000 --- a/docs/receipts/inkling-2-mini-metal-235/engines.sh +++ /dev/null @@ -1,30 +0,0 @@ -#!/bin/bash -# engines.sh TENSORFOLD_BINARY: the 1, 4 and 64-stream greedy receipt against oMLX on this Mac, 3 reps each, both -# servers admitting 64 requests. oMLX serves its own 4-bit MTP build (Inkling-2-Mini-oQ4e-mtp) from -# ~/.omlx/settings.json, MTP drafting on. Run it under `lockf -k /tmp/tensorfold-model.lock`; the two servers run one -# after the other. OMLX names the oMLX binary. 64 lanes take a 16384-token window to fit in memory. -set -euo pipefail -bin=$1 -wt=$(git -C "$(dirname "$0")" rev-parse --show-toplevel) -model=${MODEL:-$HOME/models/Inkling-2-Mini} -omlx=${OMLX:-$HOME/work/inkling/.omlx/bin/omlx} -out=${OUT:-/tmp/ink2-bench} -mkdir -p "$out" -[ -e /Users/Shared/agent-work/mac-gpu-window ] || { echo "no Mac GPU window" >&2; exit 3; } - -measure() { # LABEL PORT MODEL COMMAND...: start the server, bench it, stop it - local label=$1 port=$2 name=$3 - shift 3 - "$@" >"$out/$label.server.log" 2>&1 & - local pid=$! - trap "kill -INT $pid 2>/dev/null; wait $pid 2>/dev/null" EXIT - for _ in $(seq 300); do curl -sf "http://127.0.0.1:$port/v1/models" >/dev/null && break; sleep 1; done - /opt/homebrew/bin/python3.13 "$wt/tools/bench_concurrent.py" "http://127.0.0.1:$port" "$name" \ - --levels 1,4,64 --reps 3 --tokens 256 --temperatures 0 --label "$label" --output "$out/$label.json" 2>&1 | cut -c1-200 - kill -INT $pid - wait $pid 2>/dev/null || true - trap - EXIT -} - -measure tensorfold 18235 Inkling-2-Mini "$bin" serve "$model" --port 18235 --context 16384 --parallel 64 --drafter "$model" -measure omlx 8765 Inkling-2-Mini-oQ4e-mtp "$omlx" serve --host 127.0.0.1 --port 8765 --max-concurrent-requests 64 From baadcabcc84e958f66de2ea4e19370a097fd38f3 Mon Sep 17 00:00:00 2001 From: netrunner <299844489+plotarmordev@users.noreply.github.com> Date: Tue, 24 Nov 2026 10:49:03 +0800 Subject: [PATCH 14/14] bench: redact credentials inside tuples; depth tallies keep only nonnegative integers, as lists --- tools/bench_auth.py | 2 +- tools/bench_concurrent.py | 9 +++++---- tools/tests/test_bench_auth.py | 11 +++++++++++ 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/tools/bench_auth.py b/tools/bench_auth.py index 499f2c105b7..f7336d0e2d2 100644 --- a/tools/bench_auth.py +++ b/tools/bench_auth.py @@ -35,7 +35,7 @@ def redact(value, key: str | None): return value if isinstance(value, str): return value.replace(key, "[REDACTED]") - if isinstance(value, list): + if isinstance(value, (list, tuple)): return [redact(item, key) for item in value] if isinstance(value, dict): return {redact(name, key): redact(item, key) for name, item in value.items()} diff --git a/tools/bench_concurrent.py b/tools/bench_concurrent.py index 11b7b3382e4..c25fb0d67b7 100644 --- a/tools/bench_concurrent.py +++ b/tools/bench_concurrent.py @@ -203,11 +203,12 @@ def draft_count(run: dict, key: str) -> int | None: return value if type(value) is int and value >= 0 else None -def depth_counts(run: dict) -> tuple[list[int], list[int]] | None: - """A run's per-depth drafted and kept rows, None when the server reported none.""" +def depth_counts(run: dict) -> list[list[int]] | None: + """A run's per-depth drafted and kept rows, None unless the server reported both as nonnegative integers.""" spec = run.get("speculative") or {} - pair = tuple(spec.get(k) for k in DEPTH_KEYS) - return pair if all(type(v) is list for v in pair) else None + pair = [spec.get(k) for k in DEPTH_KEYS] + ok = all(type(v) is list and all(type(n) is int and n >= 0 for n in v) for v in pair) + return pair if ok else None def sum_depths(rows) -> list[int]: diff --git a/tools/tests/test_bench_auth.py b/tools/tests/test_bench_auth.py index 1dc5bd734b5..898e0aeaef3 100644 --- a/tools/tests/test_bench_auth.py +++ b/tools/tests/test_bench_auth.py @@ -13,6 +13,7 @@ from unittest.mock import patch sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +import bench_auth import bench_concurrent import bench_openai @@ -153,6 +154,16 @@ def test_stream_error_payload_does_not_expose_credentials(self): self.assertNotIn(KEY, stdout.getvalue() + stderr.getvalue()) self.assertIn("RuntimeError", stdout.getvalue() + stderr.getvalue()) + def test_credentials_nested_in_tuples_and_depth_tallies_are_redacted(self): + nested = {"depths": [([1, KEY], (KEY, {"note": KEY}))], KEY: (KEY,)} + self.assertNotIn(KEY, json.dumps(bench_auth.redact(nested, KEY))) + for drafted in ([2, KEY], [2, -1], [2, 1.5], [2, True]): + with self.subTest(drafted=drafted): + run = {"speculative": {"depth_drafted": drafted, "depth_accepted": [1, 0]}} + self.assertIsNone(bench_concurrent.depth_counts(run)) + run = {"speculative": {"depth_drafted": [4, 2], "depth_accepted": [3, 1]}} + self.assertEqual(bench_concurrent.depth_counts(run), [[4, 2], [3, 1]]) + @contextlib.contextmanager def serve(handler):