From b6e162b47789b84e5c5d891ec449b56782331f75 Mon Sep 17 00:00:00 2001 From: Petrus Pennanen <233579950+ThinkOffApp@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:08:59 +0100 Subject: [PATCH 01/12] Add layer traces to the Ling float64 reference --- zig/src/families/ling/oracle/ling_forward.py | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/zig/src/families/ling/oracle/ling_forward.py b/zig/src/families/ling/oracle/ling_forward.py index aab4c520286..6f2d520ba54 100644 --- a/zig/src/families/ling/oracle/ling_forward.py +++ b/zig/src/families/ling/oracle/ling_forward.py @@ -155,7 +155,7 @@ def moe(self, x, p, i): y[t] += self.mlp(x[t:t + 1], f"{p}experts.{int(idx[t, j])}.", le)[0] * w[t, j] return r(r(y) + self.mlp(x, p + "shared_experts.", ls)) - def logits(self, ids): + def logits(self, ids, trace=None): c, ck = self.c, self.ck x = ck.t("model.word_embeddings.weight").double()[ids] for i in range(c["num_hidden_layers"]): @@ -166,6 +166,8 @@ def logits(self, ids): x = self.r(x + (self.mla(h, p + "attention.") if mla else self.kda(h, p + "attention."))) h = self.norm(x, ck.t(p + "post_attention_layernorm.weight")) x = self.r(x + (self.moe(h, p + "mlp.", i) if i >= c["first_k_dense_replace"] else self.mlp(h, p + "mlp.", 0))) + if trace is not None: + trace(i, x) self.hidden = self.norm(x, ck.t("model.norm.weight")) return self.hidden @ ck.lin("lm_head").T @@ -192,6 +194,7 @@ def main(): a.add_argument("ckpt", help="a ling-synth directory (config.json, model.safetensors) or a sharded checkpoint's") a.add_argument("out", help="the reference file: ids, float64 and bf16-point logits, the picks it routed on") a.add_argument("--tokens", type=int, default=88) + a.add_argument("--layer-trace", help="write per-layer float64 and bf16-point hidden rows beside logits") a.add_argument("--picks", help="route on these picks (i32 [MoE layers][tokens][top_k], the graph's) instead") a.add_argument("--mtp", help="also the MTP layer's logits (float64, bf16 points) and its own picks, to this file") a.add_argument("--ids", help="these tokens (i32, ling-lanes' OUT.ids) instead of the fixed walk; --tokens follows") @@ -235,8 +238,17 @@ def main(): forced = torch.frombuffer(bytearray(open(o.picks, "rb").read()), dtype=torch.int32).view(nm, T, -1) with torch.no_grad(): exact = Model(ck, c, lambda z: z, forced) - l64 = exact.logits(ids) - lbf = Model(ck, c, bf16, forced).logits(ids) + traces = [[], []] + def capture(which): + return lambda layer, x: traces[which].append(x.clone()) + l64 = exact.logits(ids, capture(0) if o.layer_trace else None) + lbf = Model(ck, c, bf16, forced).logits(ids, capture(1) if o.layer_trace else None) + if o.layer_trace: + with open(o.layer_trace, "wb") as f: + f.write(b"TFLINGH1" + struct.pack("<3I", c["num_hidden_layers"], T, c["hidden_size"])) + for layers in traces: + for x in layers: + f.write(x.contiguous().numpy().tobytes()) if o.mtp: # the bf16-point model's own picks route its MTP layer; float64's are written for the flips rounded = Model(ck, c, bf16, forced) rounded.logits(ids) From 9d74f9704ae3ba26a884c5a32736a9d9486277db Mon Sep 17 00:00:00 2001 From: Petrus Pennanen <233579950+ThinkOffApp@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:08:59 +0100 Subject: [PATCH 02/12] Compose the Ling tiny bf16 backbone on existing Metal kernels --- zig/src/families/ling/checkpoint.zig | 85 ++++++++++++ zig/src/families/ling/metal_forward.zig | 168 ++++++++++++++++++++++++ zig/src/families/ling/metal_kda.zig | 121 +++++++++++++++++ zig/src/families/ling/metal_mla.zig | 140 ++++++++++++++++++++ zig/src/families/ling/metal_moe.zig | 97 ++++++++++++++ zig/src/families/ling/metal_rows.zig | 132 +++++++++++++++++++ 6 files changed, 743 insertions(+) create mode 100644 zig/src/families/ling/checkpoint.zig create mode 100644 zig/src/families/ling/metal_forward.zig create mode 100644 zig/src/families/ling/metal_kda.zig create mode 100644 zig/src/families/ling/metal_mla.zig create mode 100644 zig/src/families/ling/metal_moe.zig create mode 100644 zig/src/families/ling/metal_rows.zig diff --git a/zig/src/families/ling/checkpoint.zig b/zig/src/families/ling/checkpoint.zig new file mode 100644 index 00000000000..5a8441dac3b --- /dev/null +++ b/zig/src/families/ling/checkpoint.zig @@ -0,0 +1,85 @@ +//! Ling's bf16 checkpoint tensors, validated by the shared safetensors reader and mapped without weight copies. +const std = @import("std"); +const mtl = @import("metal"); +const st = @import("safetensors"); +const config = @import("config.zig"); + +pub const Tensor = struct { + buffer: mtl.Buffer, + offset: usize, + entry: st.Entry, +}; +const File = struct { + path: [:0]const u8, + map: ?mtl.MappedFile = null, + buffer: ?mtl.Buffer = null, + header: st.Header = .empty, + data: usize = 0, +}; +pub const Checkpoint = struct { + arena: std.heap.ArenaAllocator, + device: mtl.Device, + config: ?config.Config = null, + files: std.ArrayList(File) = .empty, + where: std.StringHashMapUnmanaged(u32) = .empty, + + pub fn open(gpa: std.mem.Allocator, io: std.Io, device: mtl.Device, dir: []const u8) !Checkpoint { + var self = Checkpoint{ .arena = std.heap.ArenaAllocator.init(gpa), .device = device }; + errdefer self.deinit(); + const a = self.arena.allocator(); + const config_path = try std.fs.path.join(a, &.{ dir, "config.json" }); + const config_text = try std.Io.Dir.cwd().readFileAlloc(io, config_path, a, .limited(16 << 20)); + var why: config.Why = .{}; + self.config = try config.parse(a, config_text, &why); + const path = try std.fs.path.join(a, &.{ dir, "model.safetensors.index.json" }); + const text = try std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(st.index.max_bytes)); + const parsed = try std.json.parseFromSliceLeaky(std.json.Value, a, text, .{}); + const index = try st.index.weightMap(parsed); + var file_of: std.StringHashMapUnmanaged(u32) = .empty; + for (index.keys(), index.values()) |name, value| { + const file = value.string; + if (std.fs.path.isAbsolute(file) or std.mem.indexOf(u8, file, "..") != null) return error.BadShardPath; + const slot = try file_of.getOrPut(a, file); + if (!slot.found_existing) { + slot.value_ptr.* = @intCast(self.files.items.len); + try self.files.append(a, .{ .path = try std.fs.path.joinZ(a, &.{ dir, file }) }); + } + try self.where.put(a, name, slot.value_ptr.*); + } + return self; + } + + pub fn get(self: *Checkpoint, name: []const u8, dtype: st.DType, shape: []const usize) !Tensor { + const id = self.where.get(name) orelse return error.MissingTensor; + const f = &self.files.items[id]; + if (f.buffer == null) { + const map = try mtl.MappedFile.open(f.path); + errdefer map.deinit(); + if (map.size < 8) return error.BadSafetensors; + const n = try st.headerSize(std.mem.readInt(u64, map.bytes[0..8], .little), map.size); + f.data = 8 + n; + f.header = try st.parseHeader(self.arena.allocator(), map.bytes[8..f.data], map.size - f.data); + for (f.header.values()) |entry| { + if (entry.dtype != .bf16 and entry.dtype != .f32) return error.UnsupportedDType; + if ((f.data + entry.begin) % entry.dtype.size() != 0) return error.MisalignedTensor; + } + f.buffer = try self.device.bufferNoCopy(map.bytes.ptr, map.bytes.len, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked); + f.map = map; + } + const entry = f.header.get(name) orelse return error.MissingTensor; + if (entry.dtype != dtype or entry.rank != shape.len or !std.mem.eql(usize, entry.shape[0..entry.rank], shape)) return error.TensorShape; + return .{ .buffer = f.buffer.?, .offset = f.data + entry.begin, .entry = entry }; + } + + pub fn deinit(self: *Checkpoint) void { + for (self.files.items) |file| { + if (file.buffer) |b| b.deinit(); + if (file.map) |m| m.deinit(); + } + self.arena.deinit(); + } +}; + +test { + std.testing.refAllDecls(Checkpoint); +} diff --git a/zig/src/families/ling/metal_forward.zig b/zig/src/families/ling/metal_forward.zig new file mode 100644 index 00000000000..c2a3539d0dc --- /dev/null +++ b/zig/src/families/ling/metal_forward.zig @@ -0,0 +1,168 @@ +//! Ling tiny's 24-layer bf16 backbone over the existing Metal row, KDA, MLA and route operations. +const std = @import("std"); +const mtl = @import("metal"); +const ck = @import("ling_checkpoint"); +const Rows = @import("ling_rows").Rows; +const Kda = @import("ling_kda").Kda; +const Mla = @import("ling_mla").Mla; +const Moe = @import("ling_moe").Moe; +const Attention = union(enum) { kda: Kda, mla: Mla }; + +pub const Forward = struct { + rows: *Rows, + model: *ck.Checkpoint, + attention: [24]Attention, + moe: Moe, + x: mtl.Buffer, + normed: mtl.Buffer, + delta: mtl.Buffer, + gate: mtl.Buffer, + up: mtl.Buffer, + activation: mtl.Buffer, + logits: mtl.Buffer, + picks: mtl.Buffer, + position: u32 = 0, + + pub fn init(rows: *Rows, model: *ck.Checkpoint, capacity: u32) !Forward { + const c = model.config orelse return error.MissingConfig; + if (c.quant != .bf16 or c.layers != 24 or c.hidden != 1536 or c.vocab != 157184 or c.group != 4 or + c.kda_heads != 16 or c.kda_dim != 128 or c.mla_heads != 16 or c.q_lora != 256 or c.kv_lora != 512 or + c.nope != 128 or c.rope_dim != 64 or c.v_dim != 128 or c.dense_layers != 1 or c.dense_inter != 4608 or + c.experts != 128 or c.topk != 8 or c.n_group != 8 or c.topk_group != 4 or c.moe_inter != 512 or + c.shared_inter != 512 or c.routed_scale != 2.5 or c.eps != 1e-6 or c.rope_theta != 6000000 or + c.lower_bound != -5 or c.mtp != 0 or !c.head_gate or c.tie or c.rope_style != .gptj or !c.norm_topk or !c.expert_bias) return error.UnsupportedLingGeometry; + for (0..24) |i| if (c.expert_limit[i] != 0 or c.shared_limit[i] != 0) return error.UnsupportedLingGeometry; + if (capacity == 0 or rows.max_rows == 0) return error.ContextCapacity; + var attention: [24]Attention = undefined; + var initialized: usize = 0; + errdefer for (attention[0..initialized]) |*a| switch (a.*) { + .mla => |*m| m.deinit(), + .kda => {}, + }; + for (&attention, 0..) |*a, i| { + const prefix = try std.fmt.allocPrint(rows.allocator, "model.layers.{d}.attention.", .{i}); + defer rows.allocator.free(prefix); + a.* = if (i % 4 == 3) .{ .mla = try Mla.init(rows, 16, capacity) } else .{ .kda = try Kda.init(rows, model, prefix, 16) }; + initialized += 1; + } + const r: usize = rows.max_rows; + return .{ + .rows = rows, + .model = model, + .attention = attention, + .moe = try Moe.init(rows, 1536, 512), + .x = try rows.buffer(r * 1536 * 2), + .normed = try rows.buffer(r * 1536 * 2), + .delta = try rows.buffer(r * 1536 * 2), + .gate = try rows.buffer(r * 4608 * 2), + .up = try rows.buffer(r * 4608 * 2), + .activation = try rows.buffer(r * 4608 * 2), + .logits = try rows.buffer(r * 157184 * 4), + .picks = try rows.buffer(23 * r * 8 * 4), + }; + } + + pub fn run(self: *Forward, ids: []const u32) ![]const f32 { + const r = self.rows; + if (ids.len == 0 or ids.len > r.max_rows) return error.RowCapacity; + const n: u32 = @intCast(ids.len); + for (&self.attention) |*a| if (a.* == .mla and (self.position > a.mla.capacity or n > a.mla.capacity - self.position)) return error.ContextCapacity; + + const embedding = try self.model.get("model.word_embeddings.weight", .bf16, &.{ 157184, 1536 }); + for (ids, 0..) |id, i| { + if (id >= 157184) return error.InvalidToken; + const offset = embedding.offset + @as(usize, id) * 1536 * 2; + @memcpy(self.x.contents()[i * 1536 * 2 ..][0 .. 1536 * 2], embedding.buffer.contents()[offset..][0 .. 1536 * 2]); + } + for (&self.attention, 0..) |*attention, i| { + const pre = try std.fmt.allocPrint(r.allocator, "model.layers.{d}.", .{i}); + defer r.allocator.free(pre); + const norm = try std.mem.concat(r.allocator, u8, &.{ pre, "input_layernorm.weight" }); + defer r.allocator.free(norm); + try r.norm(self.model, norm, .{ .buf = self.x }, .{ .buf = self.normed }, n, 1536, 1e-6); + const a = try std.mem.concat(r.allocator, u8, &.{ pre, "attention." }); + defer r.allocator.free(a); + switch (attention.*) { + .kda => |*k| try k.forward(r, self.model, a, .{ .buf = self.normed }, .{ .buf = self.delta }, n, 1536, -5, 1e-6), + .mla => |*m| try m.forward(r, self.model, a, .{ .buf = self.normed }, .{ .buf = self.delta }, n, 1536, 1e-6, 6000000), + } + try r.add(.{ .buf = self.x }, .{ .buf = self.delta }, .{ .buf = self.x }, n * 1536); + const post = try std.mem.concat(r.allocator, u8, &.{ pre, "post_attention_layernorm.weight" }); + defer r.allocator.free(post); + try r.norm(self.model, post, .{ .buf = self.x }, .{ .buf = self.normed }, n, 1536, 1e-6); + const mlp = try std.mem.concat(r.allocator, u8, &.{ pre, "mlp." }); + defer r.allocator.free(mlp); + if (i == 0) { + try r.mlp(self.model, mlp, .{ .buf = self.normed }, .{ .buf = self.delta }, .{ .buf = self.gate }, .{ .buf = self.up }, .{ .buf = self.activation }, n, 1536, 4608); + } else { + try self.moe.forward(r, self.model, mlp, .{ .buf = self.normed }, .{ .buf = self.delta }, n); + @memcpy(self.picks.contents()[(i - 1) * n * 8 * 4 ..][0 .. n * 8 * 4], self.moe.ids.contents()[0 .. n * 8 * 4]); + } + try r.add(.{ .buf = self.x }, .{ .buf = self.delta }, .{ .buf = self.x }, n * 1536); + } + try r.norm(self.model, "model.norm.weight", .{ .buf = self.x }, .{ .buf = self.normed }, n, 1536, 1e-6); + try r.linear(self.model, "lm_head.weight", .{ .buf = self.normed }, .{ .buf = self.logits }, n, 1536, 157184, true); + self.position += n; + return self.logits.slice(f32, n * 157184); + } + + fn stateBytes(position: u32) usize { + return 12 + 18 * (16 * 128 * 128 * 4 + 9 * 2048 * 2) + 6 * @as(usize, position) * 576 * 2; + } + + pub fn snapshot(self: *const Forward, allocator: std.mem.Allocator) ![]u8 { + const data = try allocator.alloc(u8, stateBytes(self.position)); + @memcpy(data[0..8], "TFLINGS1"); + std.mem.writeInt(u32, data[8..12], self.position, .little); + var at: usize = 12; + for (&self.attention) |*attention| switch (attention.*) { + .kda => |*k| { + const state = k.state.contents()[0 .. 16 * 128 * 128 * 4]; + const conv = k.conv.contents()[0 .. 9 * 2048 * 2]; + @memcpy(data[at..][0..state.len], state); + at += state.len; + @memcpy(data[at..][0..conv.len], conv); + at += conv.len; + }, + .mla => |*m| { + const cache = m.cache.contents()[0 .. @as(usize, self.position) * 576 * 2]; + @memcpy(data[at..][0..cache.len], cache); + at += cache.len; + }, + }; + return data; + } + + pub fn restore(self: *Forward, data: []const u8) !void { + if (data.len < 12 or !std.mem.eql(u8, data[0..8], "TFLINGS1")) return error.BadLingState; + const position = std.mem.readInt(u32, data[8..12], .little); + if (data.len != stateBytes(position)) return error.BadLingState; + for (&self.attention) |*a| if (a.* == .mla and position > a.mla.capacity) return error.ContextCapacity; + var at: usize = 12; + for (&self.attention) |*attention| switch (attention.*) { + .kda => |*k| { + const state = k.state.contents()[0 .. 16 * 128 * 128 * 4]; + const conv = k.conv.contents()[0 .. 9 * 2048 * 2]; + @memcpy(state, data[at..][0..state.len]); + at += state.len; + @memcpy(conv, data[at..][0..conv.len]); + at += conv.len; + }, + .mla => |*m| { + const cache = m.cache.contents()[0 .. @as(usize, position) * 576 * 2]; + @memcpy(cache, data[at..][0..cache.len]); + at += cache.len; + m.position = position; + }, + }; + self.position = position; + } + + pub fn deinit(self: *Forward) void { + for (&self.attention) |*a| switch (a.*) { + .mla => |*m| m.deinit(), + .kda => {}, + }; + self.moe.deinit(); + } +}; diff --git a/zig/src/families/ling/metal_kda.zig b/zig/src/families/ling/metal_kda.zig new file mode 100644 index 00000000000..e667b597ecc --- /dev/null +++ b/zig/src/families/ling/metal_kda.zig @@ -0,0 +1,121 @@ +//! Ling KDA state and unchanged k3_kda dispatch, with bf16 checkpoint vectors widened exactly to fp32. +const std = @import("std"); +const mtl = @import("metal"); +const kernels = @import("kimi_kernels"); +const ck = @import("ling_checkpoint"); +const Rows = @import("ling_rows").Rows; +const Ref = kernels.Ref; + +pub const Kda = struct { + state: mtl.Buffer, + conv: mtl.Buffer, + segment: mtl.Buffer, + dummy: mtl.Buffer, + weights: kernels.KdaWeights, + heads: u32, + readers: [6]Ref, + proj: mtl.Buffer, + f: mtl.Buffer, + b: mtl.Buffer, + g: mtl.Buffer, + y: mtl.Buffer, + + fn vector(rows: *Rows, model: *ck.Checkpoint, prefix: []const u8, name: []const u8, shape: []const usize, bf16: bool) !Ref { + const full = try std.mem.concat(rows.allocator, u8, &.{ prefix, name }); + defer rows.allocator.free(full); + const t = try model.get(full, if (bf16) .bf16 else .f32, shape); + if (!bf16) return .{ .buf = t.buffer, .off = t.offset }; + var count: usize = 1; + for (shape) |dim| count *= dim; + const out = try rows.buffer(count * 4); + const data = std.mem.bytesAsSlice(u16, t.buffer.contents()[t.offset..][0 .. count * 2]); + for (data, out.slice(f32, count)) |h, *f| f.* = @bitCast(@as(u32, h) << 16); + return .{ .buf = out }; + } + + pub fn init(rows: *Rows, model: *ck.Checkpoint, prefix: []const u8, heads: u32) !Kda { + const width = heads * 128; + const state = try rows.buffer(@as(usize, width) * 128 * 4); + const conv = try rows.buffer(9 * width * 2); + @memset(state.slice(f32, width * 128), 0); + @memset(conv.slice(u16, 9 * width), 0); + const readers = [6]Ref{ + try vector(rows, model, prefix, "q_conv1d.weight", &.{ width, 1, 4 }, true), + try vector(rows, model, prefix, "k_conv1d.weight", &.{ width, 1, 4 }, true), + try vector(rows, model, prefix, "v_conv1d.weight", &.{ width, 1, 4 }, true), + try vector(rows, model, prefix, "A_log", &.{heads}, false), + try vector(rows, model, prefix, "dt_bias", &.{width}, false), + try vector(rows, model, prefix, "o_norm.weight", &.{128}, true), + }; + return .{ + .state = state, + .conv = conv, + .segment = try rows.buffer(@sizeOf(kernels.KdaSeg)), + .dummy = try rows.buffer(16), + .heads = heads, + .proj = try rows.buffer(@as(usize, rows.max_rows) * 3 * width * 2), + .f = try rows.buffer(@as(usize, rows.max_rows) * width * 2), + .b = try rows.buffer(@as(usize, rows.max_rows) * heads * 2), + .g = try rows.buffer(@as(usize, rows.max_rows) * width * 2), + .y = try rows.buffer(@as(usize, rows.max_rows) * width * 2), + .readers = readers, + .weights = .{ .conv_q = kernels.addr(readers[0]), .conv_k = kernels.addr(readers[1]), .conv_v = kernels.addr(readers[2]), .A_log = kernels.addr(readers[3]), .dt_bias = kernels.addr(readers[4]), .o_norm = kernels.addr(readers[5]) }, + }; + } + + pub fn forward(self: *Kda, rows: *Rows, model: *ck.Checkpoint, prefix: []const u8, x: Ref, out: Ref, n: u32, hidden: u32, lower_bound: f32, eps: f32) !void { + const width = self.heads * 128; + for ([_][]const u8{ "q_proj.weight", "k_proj.weight", "v_proj.weight" }, 0..) |part, j| { + const name = try std.mem.concat(rows.allocator, u8, &.{ prefix, part }); + defer rows.allocator.free(name); + try rows.linearInto(model, name, x, .{ .buf = self.proj, .off = j * width * 2 }, n, hidden, width, hidden, 3 * width, false); + } + for ([_]struct { name: []const u8, buffer: mtl.Buffer, width: u32 }{ + .{ .name = "f_proj.weight", .buffer = self.f, .width = width }, + .{ .name = "b_proj.weight", .buffer = self.b, .width = self.heads }, + .{ .name = "g_proj.weight", .buffer = self.g, .width = width }, + }) |p| { + const name = try std.mem.concat(rows.allocator, u8, &.{ prefix, p.name }); + defer rows.allocator.free(name); + try rows.linear(model, name, x, .{ .buf = p.buffer }, n, hidden, p.width, false); + } + try self.mix(rows, .{ .buf = self.proj }, .{ .buf = self.f }, .{ .buf = self.b }, .{ .buf = self.g }, .{ .buf = self.y }, n, lower_bound, eps); + const name = try std.mem.concat(rows.allocator, u8, &.{ prefix, "o_proj.weight" }); + defer rows.allocator.free(name); + try rows.linear(model, name, .{ .buf = self.y }, out, n, width, hidden, false); + } + + pub fn mix(self: *Kda, rows: *Rows, qkv: Ref, f: Ref, b: Ref, g: Ref, out: Ref, n: u32, lower_bound: f32, eps: f32) !void { + if (n == 0 or n > rows.max_rows) return error.RowCapacity; + self.segment.slice(kernels.KdaSeg, 1)[0] = .{ .first = 0, .rows = n, .kept = 0, .flags = kernels.seg_commit, .slot = 0 }; + const state = kernels.KdaState{ + .S = self.state.gpuAddress(), + .conv = self.conv.gpuAddress(), + .log_a = self.dummy.gpuAddress(), + .log_k = self.dummy.gpuAddress(), + .log_u = self.dummy.gpuAddress(), + .log_x = self.dummy.gpuAddress(), + }; + const width = self.heads * 128; + const cb = rows.queue.commandBuffer(); + const e = cb.compute(.serial); + e.useResource(self.state, mtl.ResourceUsage.read | mtl.ResourceUsage.write); + e.useResource(self.conv, mtl.ResourceUsage.read | mtl.ResourceUsage.write); + e.useResource(self.dummy, mtl.ResourceUsage.read); + for (self.readers) |r| e.useResource(r.buf, mtl.ResourceUsage.read); + rows.k.kdaRound(e, qkv, f, b, g, out, .{ .buf = self.segment }, 1, state, self.weights, .{ + .heads = self.heads, + .head0 = 0, + .proj_stride = 3 * width, + .gate_stride = width, + .out_stride = width, + .log_rows = 1, + .lower_bound = lower_bound, + .eps = eps, + }); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure() != null) return error.GpuFailed; + } +}; diff --git a/zig/src/families/ling/metal_mla.zig b/zig/src/families/ling/metal_mla.zig new file mode 100644 index 00000000000..4c7d714dba9 --- /dev/null +++ b/zig/src/families/ling/metal_mla.zig @@ -0,0 +1,140 @@ +//! Ling MLA projections, latent cache and unchanged Kimi mixer with the three Ling RoPE/gate kernels. +const std = @import("std"); +const mtl = @import("metal"); +const kernels = @import("kimi_kernels"); +const ck = @import("ling_checkpoint"); +const Rows = @import("ling_rows").Rows; +const Ref = kernels.Ref; + +pub const Mla = struct { + library: mtl.Library, + rope_cache: mtl.Pipeline, + rope_q: mtl.Pipeline, + gate_expand: mtl.Pipeline, + cache: mtl.Buffer, + positions: mtl.Buffer, + angles: mtl.Buffer, + qa: mtl.Buffer, + qan: mtl.Buffer, + q: mtl.Buffer, + kv: mtl.Buffer, + gate: mtl.Buffer, + expanded: mtl.Buffer, + qlat: mtl.Buffer, + partial: mtl.Buffer, + olat: mtl.Buffer, + y: mtl.Buffer, + heads: u32, + capacity: u32, + position: u32 = 0, + + pub fn init(rows: *Rows, heads: u32, capacity: u32) !Mla { + const library = try mtl.Library.fromSource(rows.device, @import("ling_sources").mla, mtl.CompileOptions.mlx()); + errdefer library.deinit(); + const rope_cache = try mtl.Pipeline.init(rows.device, library, "tf_ling_mla_rope_cache", false); + errdefer rope_cache.deinit(); + const rope_q = try mtl.Pipeline.init(rows.device, library, "tf_ling_mla_rope_q", false); + errdefer rope_q.deinit(); + const gate_expand = try mtl.Pipeline.init(rows.device, library, "tf_ling_mla_gate_expand", false); + errdefer gate_expand.deinit(); + const r: usize = rows.max_rows; + const cache = try rows.buffer(@as(usize, capacity) * 576 * 2); + @memset(cache.slice(u16, capacity * 576), 0); + return .{ + .library = library, + .rope_cache = rope_cache, + .rope_q = rope_q, + .gate_expand = gate_expand, + .cache = cache, + .heads = heads, + .capacity = capacity, + .positions = try rows.buffer(r * @sizeOf(kernels.MlaRow)), + .angles = try rows.buffer(r * 64 * 4), + .qa = try rows.buffer(r * 256 * 2), + .qan = try rows.buffer(r * 256 * 2), + .q = try rows.buffer(r * heads * 192 * 2), + .kv = try rows.buffer(r * 576 * 2), + .gate = try rows.buffer(r * heads * 2), + .expanded = try rows.buffer(r * heads * 128 * 2), + .qlat = try rows.buffer(r * heads * 512 * 4), + .partial = try rows.buffer(r * heads * 16 * 514 * 4), + .olat = try rows.buffer(r * heads * 512 * 4), + .y = try rows.buffer(r * heads * 128 * 2), + }; + } + + fn name(rows: *Rows, prefix: []const u8, part: []const u8) ![]u8 { + return std.mem.concat(rows.allocator, u8, &.{ prefix, part }); + } + + fn project(self: *Mla, rows: *Rows, model: *ck.Checkpoint, prefix: []const u8, part: []const u8, x: Ref, y: mtl.Buffer, n: u32, width: u32, out_width: u32) !void { + _ = self; + const full = try name(rows, prefix, part); + defer rows.allocator.free(full); + try rows.linear(model, full, x, .{ .buf = y }, n, width, out_width, false); + } + + pub fn forward(self: *Mla, rows: *Rows, model: *ck.Checkpoint, prefix: []const u8, x: Ref, out: Ref, n: u32, hidden: u32, eps: f32, theta: f64) !void { + if (n == 0 or n > rows.max_rows or self.position > self.capacity or n > self.capacity - self.position) return error.ContextCapacity; + try self.project(rows, model, prefix, "q_a_proj.weight", x, self.qa, n, hidden, 256); + const qa_norm = try name(rows, prefix, "q_a_layernorm.weight"); + defer rows.allocator.free(qa_norm); + try rows.norm(model, qa_norm, .{ .buf = self.qa }, .{ .buf = self.qan }, n, 256, eps); + try self.project(rows, model, prefix, "q_b_proj.weight", .{ .buf = self.qan }, self.q, n, 256, self.heads * 192); + try self.project(rows, model, prefix, "kv_a_proj_with_mqa.weight", x, self.kv, n, hidden, 576); + try self.project(rows, model, prefix, "g_proj.weight", x, self.gate, n, hidden, self.heads); + const wn = try name(rows, prefix, "kv_a_layernorm.weight"); + defer rows.allocator.free(wn); + const w = try model.get(wn, .bf16, &.{512}); + const bn = try name(rows, prefix, "kv_b_proj.weight"); + defer rows.allocator.free(bn); + const b = try model.get(bn, .bf16, &.{ self.heads * 256, 512 }); + for (self.positions.slice(kernels.MlaRow, n), 0..) |*p, t| { + p.* = .{ .slot = 0, .pos = self.position + @as(u32, @intCast(t)) }; + for (0..32) |i| { + const angle = @as(f64, @floatFromInt(p.pos)) / std.math.pow(f64, theta, @as(f64, @floatFromInt(2 * i)) / 64.0); + self.angles.slice(f32, n * 64)[t * 64 + i * 2] = @floatCast(@cos(angle)); + self.angles.slice(f32, n * 64)[t * 64 + i * 2 + 1] = @floatCast(@sin(angle)); + } + } + const a = kernels.MlaArgs{ .cache = self.cache.gpuAddress(), .slot_keys = self.capacity, .heads = self.heads, .head0 = 0, .rows = n, .q_stride = self.heads * 192, .kv_stride = 576, .gate_stride = self.heads * 128, .out_stride = self.heads * 128, .eps = eps, .scale = 1.0 / @sqrt(@as(f32, 192)) }; + const cb = rows.queue.commandBuffer(); + const e = cb.compute(.serial); + e.useResource(self.cache, mtl.ResourceUsage.read | mtl.ResourceUsage.write); + rows.k.mlaCache(e, .{ .buf = self.kv }, .{ .buf = w.buffer, .off = w.offset }, .{ .buf = self.positions }, a); + e.setPipeline(self.rope_cache); + e.setBuffer(self.positions, 0, 0); + e.setValue(a, 1); + e.setBuffer(self.angles, 0, 2); + e.dispatchGroups(mtl.Size.of(n, 1, 1), mtl.Size.of(32, 1, 1)); + rows.k.mlaQlat(e, .{ .buf = self.q }, .{ .buf = b.buffer, .off = b.offset }, .{ .buf = self.qlat }, a); + e.setPipeline(self.rope_q); + e.setBuffer(self.q, 0, 0); + e.setValue(a, 1); + e.setBuffer(self.angles, 0, 2); + e.dispatchGroups(mtl.Size.of(self.heads, n, 1), mtl.Size.of(32, 1, 1)); + rows.k.mlaAttend(e, .{ .buf = self.q }, .{ .buf = self.qlat }, .{ .buf = self.positions }, .{ .buf = self.partial }, a); + rows.k.mlaMerge(e, .{ .buf = self.partial }, .{ .buf = self.positions }, .{ .buf = self.olat }, a); + e.setPipeline(self.gate_expand); + e.setBuffer(self.gate, 0, 0); + e.setBuffer(self.expanded, 0, 1); + e.setValue(a, 2); + e.dispatchThreads(mtl.Size.of(self.heads * 128, n, 1), mtl.Size.of(128, 1, 1)); + rows.k.mlaUv(e, .{ .buf = self.olat }, .{ .buf = b.buffer, .off = b.offset }, .{ .buf = self.expanded }, .{ .buf = self.y }, a); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure() != null) return error.GpuFailed; + const dense = try name(rows, prefix, "dense.weight"); + defer rows.allocator.free(dense); + try rows.linear(model, dense, .{ .buf = self.y }, out, n, self.heads * 128, hidden, false); + self.position += n; + } + + pub fn deinit(self: *Mla) void { + self.gate_expand.deinit(); + self.rope_q.deinit(); + self.rope_cache.deinit(); + self.library.deinit(); + } +}; diff --git a/zig/src/families/ling/metal_moe.zig b/zig/src/families/ling/metal_moe.zig new file mode 100644 index 00000000000..a95dd8af619 --- /dev/null +++ b/zig/src/families/ling/metal_moe.zig @@ -0,0 +1,97 @@ +//! Ling bf16 routed experts using the existing grouped router, row MLPs and Kimi weighted combine. +const std = @import("std"); +const mtl = @import("metal"); +const ck = @import("ling_checkpoint"); +const kernels = @import("kimi_kernels"); +const Rows = @import("ling_rows").Rows; +const Ref = kernels.Ref; +const RouteArgs = extern struct { rows: i32, ne: i32, topk: i32, ng: i32, keep: i32, scale: f32 }; + +pub const Moe = struct { + library: mtl.Library, + route: mtl.Pipeline, + logits: mtl.Buffer, + ids: mtl.Buffer, + weights: mtl.Buffer, + where: mtl.Buffer, + experts: mtl.Buffer, + routed: mtl.Buffer, + shared: mtl.Buffer, + gate: mtl.Buffer, + up: mtl.Buffer, + activation: mtl.Buffer, + hidden: u32, + inter: u32, + + pub fn init(rows: *Rows, hidden: u32, inter: u32) !Moe { + const library = try mtl.Library.fromSource(rows.device, @import("ling_sources").route, mtl.CompileOptions.mlx()); + errdefer library.deinit(); + const route = try mtl.Pipeline.init(rows.device, library, "tf_ling_route", false); + errdefer route.deinit(); + const r: usize = rows.max_rows; + return .{ + .library = library, + .route = route, + .hidden = hidden, + .inter = inter, + .logits = try rows.buffer(r * 128 * 4), + .ids = try rows.buffer(r * 8 * 4), + .weights = try rows.buffer(r * 8 * 4), + .where = try rows.buffer(r * 8 * 4), + .experts = try rows.buffer(r * 8 * hidden * 2), + .routed = try rows.buffer(r * hidden * 2), + .shared = try rows.buffer(r * hidden * 2), + .gate = try rows.buffer(r * inter * 2), + .up = try rows.buffer(r * inter * 2), + .activation = try rows.buffer(r * inter * 2), + }; + } + + pub fn forward(self: *Moe, rows: *Rows, model: *ck.Checkpoint, prefix: []const u8, x: Ref, out: Ref, n: u32) !void { + if (n == 0 or n > rows.max_rows) return error.RowCapacity; + const router = try std.mem.concat(rows.allocator, u8, &.{ prefix, "gate.weight" }); + defer rows.allocator.free(router); + try rows.linear(model, router, x, .{ .buf = self.logits }, n, self.hidden, 128, true); + const bias_name = try std.mem.concat(rows.allocator, u8, &.{ prefix, "gate.expert_bias" }); + defer rows.allocator.free(bias_name); + const bias = try model.get(bias_name, .f32, &.{128}); + const cb = rows.queue.commandBuffer(); + const e = cb.compute(.serial); + e.setPipeline(self.route); + e.setBuffer(self.logits, 0, 0); + e.setBuffer(bias.buffer, bias.offset, 1); + e.setValue(RouteArgs{ .rows = @intCast(n), .ne = 128, .topk = 8, .ng = 8, .keep = 4, .scale = 2.5 }, 2); + e.setBuffer(self.ids, 0, 3); + e.setBuffer(self.weights, 0, 4); + e.dispatchGroups(mtl.Size.of(n, 1, 1), mtl.Size.of(32, 1, 1)); + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure() != null) return error.GpuFailed; + for (0..n) |t| for (0..8) |j| { + const at = t * 8 + j; + const id = self.ids.slice(i32, n * 8)[at]; + if (id < 0 or id >= 128) return error.InvalidExpert; + const expert = try std.fmt.allocPrint(rows.allocator, "{s}experts.{d}.", .{ prefix, id }); + defer rows.allocator.free(expert); + try rows.mlp(model, expert, x.at(t * self.hidden * 2), .{ .buf = self.experts, .off = at * self.hidden * 2 }, .{ .buf = self.gate }, .{ .buf = self.up }, .{ .buf = self.activation }, 1, self.hidden, self.inter); + self.where.slice(u32, n * 8)[at] = @intCast(at); + }; + const shared = try std.mem.concat(rows.allocator, u8, &.{ prefix, "shared_experts." }); + defer rows.allocator.free(shared); + try rows.mlp(model, shared, x, .{ .buf = self.shared }, .{ .buf = self.gate }, .{ .buf = self.up }, .{ .buf = self.activation }, n, self.hidden, self.inter); + const sum_cb = rows.queue.commandBuffer(); + const sum_e = sum_cb.compute(.serial); + rows.k.combine(sum_e, .{ .buf = self.experts }, .{ .buf = self.where }, .{ .buf = self.weights }, .{ .buf = self.routed }, .{ .buf = self.ids }, n, false, 128, 0, 1, .{ .K = self.inter, .N = self.hidden, .topk = 8, .rows_max = rows.max_rows, .beta = 0, .lin = 0 }); + sum_e.end(); + sum_cb.commit(); + sum_cb.wait(); + if (sum_cb.failure() != null) return error.GpuFailed; + try rows.add(.{ .buf = self.routed }, .{ .buf = self.shared }, out, n * self.hidden); + } + + pub fn deinit(self: *Moe) void { + self.route.deinit(); + self.library.deinit(); + } +}; diff --git a/zig/src/families/ling/metal_rows.zig b/zig/src/families/ling/metal_rows.zig new file mode 100644 index 00000000000..69eac47cc96 --- /dev/null +++ b/zig/src/families/ling/metal_rows.zig @@ -0,0 +1,132 @@ +//! Ling's bf16 row operations over existing Kimi kernels, retaining checkpoint weights in mapped buffers. +const std = @import("std"); +const mtl = @import("metal"); +const kernels = @import("kimi_kernels"); +const ck = @import("ling_checkpoint"); +const Ref = kernels.Ref; + +pub const Rows = struct { + allocator: std.mem.Allocator, + device: mtl.Device, + queue: mtl.Queue, + library: mtl.Library, + glue: mtl.Library, + swiglu: mtl.Pipeline, + k: kernels.Kernels, + scratch: mtl.Buffer, + owned: std.ArrayList(mtl.Buffer) = .empty, + weights: std.StringHashMapUnmanaged(mtl.Buffer) = .empty, + max_rows: u32, + + pub fn init(a: std.mem.Allocator, device: mtl.Device, max_rows: u32) !Rows { + const library = try mtl.Library.fromBytes(device, @import("kimi_metallib").bytes); + errdefer library.deinit(); + var k = try kernels.Kernels.init(device, library); + errdefer k.deinit(); + const queue = try device.queue(); + errdefer queue.deinit(); + const glue = try mtl.Library.fromSource(device, @import("kernel_sources").lfm3, mtl.CompileOptions.mlx()); + errdefer glue.deinit(); + const swiglu = try mtl.Pipeline.init(device, glue, "lfm3_swiglu", false); + errdefer swiglu.deinit(); + const scratch = try device.buffer(kernels.partFloats(max_rows) * 4, mtl.ResourceOptions.shared); + return .{ .allocator = a, .device = device, .queue = queue, .library = library, .glue = glue, .swiglu = swiglu, .k = k, .scratch = scratch, .max_rows = max_rows }; + } + + pub fn buffer(self: *Rows, bytes: usize) !mtl.Buffer { + const b = try self.device.buffer(@max(bytes, 16), mtl.ResourceOptions.shared); + errdefer b.deinit(); + try self.owned.append(self.allocator, b); + return b; + } + + fn finish(cb: mtl.CommandBuffer, e: mtl.ComputeEncoder) !void { + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure() != null) return error.GpuFailed; + } + + pub fn weight(self: *Rows, model: *ck.Checkpoint, name: []const u8, n: u32, width: u32) !mtl.Buffer { + if (width % 64 != 0) return error.UnsupportedProjectionWidth; + const source = try model.get(name, .bf16, &.{ n, width }); + if (self.weights.get(name)) |w| return w; + const w = try self.buffer(@as(usize, n) * width * 2); + const cb = self.queue.commandBuffer(); + const e = cb.compute(.serial); + self.k.interleaved(e, .{ .buf = source.buffer, .off = source.offset }, .{ .buf = w }, n, width); + try finish(cb, e); + const key = try self.allocator.dupe(u8, name); + errdefer self.allocator.free(key); + try self.weights.put(self.allocator, key, w); + return w; + } + + pub fn linear(self: *Rows, model: *ck.Checkpoint, name: []const u8, x: Ref, y: Ref, rows: u32, width: u32, n: u32, fp32: bool) !void { + return self.linearInto(model, name, x, y, rows, width, n, width, n, fp32); + } + + pub fn linearInto(self: *Rows, model: *ck.Checkpoint, name: []const u8, x: Ref, y: Ref, rows: u32, width: u32, n: u32, x_stride: u32, y_stride: u32, fp32: bool) !void { + if (rows == 0 or rows > self.max_rows) return error.RowCapacity; + const w = try self.weight(model, name, n, width); + const cb = self.queue.commandBuffer(); + const e = cb.compute(.serial); + self.k.rows(e, x, .{ .buf = w }, y, .{ .buf = self.scratch }, fp32, .{ .K = width, .N = n, .rows = rows, .x_stride = x_stride, .y_stride = y_stride }); + try finish(cb, e); + } + + pub fn norm(self: *Rows, model: *ck.Checkpoint, name: []const u8, x: Ref, y: Ref, rows: u32, width: u32, eps: f32) !void { + if (rows == 0 or rows > self.max_rows) return error.RowCapacity; + const w = try model.get(name, .bf16, &.{width}); + const cb = self.queue.commandBuffer(); + const e = cb.compute(.serial); + self.k.rmsNorm(e, x, .{ .buf = w.buffer, .off = w.offset }, y, rows, .{ .D = width, .x_stride = width, .y_stride = width, .eps = eps }); + try finish(cb, e); + } + + pub fn add(self: *Rows, x: Ref, delta: Ref, out: Ref, count: u32) !void { + const cb = self.queue.commandBuffer(); + const e = cb.compute(.serial); + self.k.add(e, x, delta, out, count); + try finish(cb, e); + } + + pub fn mlp(self: *Rows, model: *ck.Checkpoint, prefix: []const u8, x: Ref, out: Ref, gate: Ref, up: Ref, activation: Ref, rows: u32, hidden: u32, inter: u32) !void { + const g = try std.fmt.allocPrint(self.allocator, "{s}gate_proj.weight", .{prefix}); + defer self.allocator.free(g); + const u = try std.fmt.allocPrint(self.allocator, "{s}up_proj.weight", .{prefix}); + defer self.allocator.free(u); + const d = try std.fmt.allocPrint(self.allocator, "{s}down_proj.weight", .{prefix}); + defer self.allocator.free(d); + try self.linear(model, g, x, gate, rows, hidden, inter, false); + try self.linear(model, u, x, up, rows, hidden, inter, false); + try self.siluMul(gate, up, activation, rows * inter); + try self.linear(model, d, activation, out, rows, inter, hidden, false); + } + + pub fn siluMul(self: *Rows, gate: Ref, up: Ref, out: Ref, count: u32) !void { + const cb = self.queue.commandBuffer(); + const e = cb.compute(.serial); + e.setPipeline(self.swiglu); + e.setBuffer(gate.buf, gate.off, 0); + e.setBuffer(up.buf, up.off, 1); + e.setBuffer(out.buf, out.off, 2); + e.setValue(count, 3); + e.dispatchThreads(mtl.Size.of((count + 7) / 8, 1, 1), mtl.Size.of(256, 1, 1)); + try finish(cb, e); + } + + pub fn deinit(self: *Rows) void { + var keys = self.weights.keyIterator(); + while (keys.next()) |key| self.allocator.free(key.*); + self.weights.deinit(self.allocator); + for (self.owned.items) |b| b.deinit(); + self.owned.deinit(self.allocator); + self.scratch.deinit(); + self.k.deinit(); + self.swiglu.deinit(); + self.glue.deinit(); + self.library.deinit(); + self.queue.deinit(); + } +}; From ee6a74842a9671922d1f58ffd83651beda9d23bd Mon Sep 17 00:00:00 2001 From: Petrus Pennanen <233579950+ThinkOffApp@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:08:59 +0100 Subject: [PATCH 03/12] Check Ling forward exactness and report paired precision distances --- docs/recipes/ling-bf16-forward.md | 69 +++++++++++++++ tools/zig/ling_forward_check.py | 93 +++++++++++++++++++ zig/build/kernel_contract.zig | 2 +- zig/build/ling_forward.zig | 81 +++++++++++++++++ zig/tests/ling_checkpoint.zig | 22 +++++ zig/tests/ling_forward.zig | 50 +++++++++++ zig/tests/ling_projection.zig | 142 ++++++++++++++++++++++++++++++ 7 files changed, 458 insertions(+), 1 deletion(-) create mode 100644 docs/recipes/ling-bf16-forward.md create mode 100644 tools/zig/ling_forward_check.py create mode 100644 zig/build/ling_forward.zig create mode 100644 zig/tests/ling_checkpoint.zig create mode 100644 zig/tests/ling_forward.zig create mode 100644 zig/tests/ling_projection.zig diff --git a/docs/recipes/ling-bf16-forward.md b/docs/recipes/ling-bf16-forward.md new file mode 100644 index 00000000000..c41d4703159 --- /dev/null +++ b/docs/recipes/ling-bf16-forward.md @@ -0,0 +1,69 @@ +# Ling tiny bf16 forward diagnostic + +This local step-3 diagnostic runs the 24-layer Ling-3.0-tiny backbone on Metal. +It reuses Kimi's row projections, RMS, residual add, KDA, MLA and expert combine; +Ling's grouped route and three MLA glue kernels; and LFM3's bf16-point SwiGLU. +No GPU kernel source or registration changes are introduced. `kernel_contract.zig` +only registers the separate diagnostic build module. + +The supported checkpoint is `inclusionAI/Ling-3.0-tiny`, revision +`9a98e35fe1c9ee255f78dd64771c7ae15a799481` (32 bf16/F32 shards). +The forward refuses incompatible config geometry, quantization and expert clamps. +Checkpoint tensors stay mapped; interleaved projection weights are cached separately. +This is a correctness diagnostic, not serving or a qualified performance path. + +## Run + +Use the repository's pinned Zig and build for the compatible Apple CPU target: + +```sh +zig build tf-ling-forward tf-ling-checkpoint tf-ling-projection -Dcpu=apple_m1 +export TF_LING_CHECKPOINT=/path/to/Ling-3.0-tiny +export TF_LING_PYTHON=/path/to/python-with-torch-and-safetensors +zig build test-ling-forward -Dcpu=apple_m1 +``` + +`TF_LING_PYTHON` takes precedence; otherwise the oracle uses `python3` on PATH. +Without the checkpoint or Python dependencies, the optional check prints an explicit +`SKIP`. It never downloads weights or changes another model service. +For persistent artifacts, run the wrapper directly: + +```sh +python3 tools/zig/ling_forward_check.py --binary zig-out/bin/ling-forward --out /tmp/ling-receipts +``` + +The fixed IDs are `(37*t + 11) % 157182`, at 2, 8 and 32 rows. +The native diagnostic compares whole execution with single-row chunks and a fresh +instance restored after token 1. It compares logits, KDA recurrent/conv state and +MLA cache bytes. A truncated snapshot must be rejected. +The snapshot is an internal same-checkpoint diagnostic format, not a serving or +portable checkpoint handover API. These receipts exercise in-process restoration. +The oracle remains `families/ling/oracle/ling_forward.py`, using native expert picks +for both its float64 and bf16-point runs. Its optional `--layer-trace` writes residual +hidden rows without changing logits. No second reference formula is introduced. + +## Measured numerical distances + +On an Apple M5 Metal device, all native logits were finite, all next-token argmaxes +agreed with both reference precisions, and all three whole/chunk/resume scenarios +completed with exact bytes. Numerical acceptance is **unresolved**, not passed. +The reference's rounding nodes include linears, SiLU, products, norms and residuals. + +| Rows | Metal RMS | bf16-point RMS | Metal maximum | bf16-point maximum | Rows with larger Metal RMS | +| --- | --- | --- | --- | --- | --- | +| 2 | 0.0317046309744 | 0.0298559560322 | 0.213487908284 | 0.185932075501 | 2/2 | +| 8 | 0.0292602858773 | 0.0310663639610 | 0.213487908284 | 0.217792950829 | 5/8 | +| 32 | 0.0200687156935 | 0.0205596869419 | 0.213487908284 | 0.217792950829 | 19/32 | + +These are distances from float64 on the same native route picks. The forced-route +selection gap is 0.00135229020 at 2/8 rows and 0.01254995249 at 32 rows. +The native route need not choose the reference's preferred set; forcing records that +difference instead of mixing reference routing with native routing. +Aggregate improvement at 8/32 rows does not establish a per-row or per-column bound. +The JSON receipts retain every row's RMS, maximum and argmax for both precisions. +Whether the maintainer's acceptance comparison is aggregate or row-wise remains a +review question; the implementation does not increase a tolerance to accept itself. + +Runs used one low-priority Ling GPU job at a time beside an existing model service; +no timing or isolated performance result is claimed. The wrapper refuses a macOS +run with system-wide free memory at or below 40%. diff --git a/tools/zig/ling_forward_check.py b/tools/zig/ling_forward_check.py new file mode 100644 index 00000000000..cc5b7c9f65c --- /dev/null +++ b/tools/zig/ling_forward_check.py @@ -0,0 +1,93 @@ +"""Run native Ling whole/chunk/resume checks beside the one FP64 oracle on identical routed picks.""" +import argparse +import array +import json +import math +import os +from pathlib import Path +import shutil +import struct +import sys +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] + + +def compare(native, reference): + data = reference.read_bytes() + if data[:8] != b"TFLINGF2": + raise ValueError("unexpected oracle format") + tokens, vocab, layers, topk = struct.unpack_from("<4I", data, 8) + at = 36 + tokens * 4 + exact = array.array("d", data[at:at + tokens * vocab * 8]) + rounded = array.array("d", data[at + tokens * vocab * 8:at + tokens * vocab * 16]) + metal = array.array("f", native.read_bytes()) + if len(metal) != tokens * vocab: + raise ValueError("native logits shape mismatch") + rows = [] + for row in range(tokens): + lo, hi = row * vocab, (row + 1) * vocab + a, b, g = exact[lo:hi], rounded[lo:hi], metal[lo:hi] + if not all(math.isfinite(v) for v in g): + raise ValueError("non-finite native logits") + pair = {} + for name, values in (("metal", g), ("bf16", b)): + errors = [x - y for x, y in zip(values, a)] + pair[name] = {"rms": math.sqrt(math.fsum(x*x for x in errors) / vocab), + "max": max(map(abs, errors)), "top": max(range(vocab), key=values.__getitem__)} + pair["top64"] = max(range(vocab), key=a.__getitem__) + rows.append(pair) + result = {"tokens": tokens, "moe_layers": layers, "top_k": topk, "rows": rows, + "forced_gap": struct.unpack_from(" r["bf16"]["rms"] for r in rows) + result["top_tokens_equal"] = all(r["metal"]["top"] == r["bf16"]["top"] == r["top64"] for r in rows) + result["accuracy_acceptance"] = "unresolved; distances reported without relaxing the reference bound" + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--binary", type=Path, required=True) + parser.add_argument("--counts", type=int, nargs="+", default=[2, 8, 32]) + parser.add_argument("--out", type=Path) + args = parser.parse_args() + checkpoint = os.environ.get("TF_LING_CHECKPOINT") + if not checkpoint or not (Path(checkpoint) / "model.safetensors.index.json").is_file(): + print("SKIP Ling full forward: set TF_LING_CHECKPOINT to the bf16 Ling-3.0-tiny checkpoint") + return + python = os.environ.get("TF_LING_PYTHON") or shutil.which("python3") + if not python: + print("SKIP Ling oracle: set TF_LING_PYTHON or install python3 on PATH") + return + probe = subprocess.run([python, "-c", "import torch, safetensors"], capture_output=True) + if probe.returncode: + print("SKIP Ling oracle: selected Python needs torch and safetensors") + return + with tempfile.TemporaryDirectory(prefix="ling-forward-") as temp: + out = args.out or Path(temp) + out.mkdir(parents=True, exist_ok=True) + for count in args.counts: + native, reference = out / f"native-{count}.f32", out / f"reference-{count}.bin" + if sys.platform == "darwin": + pressure = subprocess.check_output(["memory_pressure"], text=True) + free = int(pressure.split("System-wide memory free percentage:")[-1].strip().rstrip("%")) + if free <= 40: + raise RuntimeError("memory free is at or below 40%; refusing the Ling GPU run") + subprocess.run([str(args.binary.resolve()), checkpoint, str(native), str(count)], check=True) + oracle = ROOT / "zig/src/families/ling/oracle/ling_forward.py" + subprocess.run([python, str(oracle), checkpoint, str(reference), "--tokens", str(count), + "--picks", str(native) + ".picks"], check=True) + result = compare(native, reference) + (out / f"summary-{count}.json").write_text(json.dumps(result, indent=2) + "\n") + print(json.dumps(result), flush=True) + if not result["top_tokens_equal"]: + raise RuntimeError("top-token mismatch; inspect the numerical receipt") + print("Ling exactness checks completed; numerical acceptance remains a separate review decision") + + +if __name__ == "__main__": + main() diff --git a/zig/build/kernel_contract.zig b/zig/build/kernel_contract.zig index 1827336e568..540c3d95be8 100644 --- a/zig/build/kernel_contract.zig +++ b/zig/build/kernel_contract.zig @@ -129,7 +129,7 @@ pub fn hostTests(b: *std.Build, family: *std.Build.Step) void { /// macOS: tf-kernel-contract over the engine's Metal kernels; `kernel-contract` runs it on this Mac's GPU. pub fn metal(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal_mod: *std.Build.Module, engine: *std.Build.Module, sources: *std.Build.Module, kimi_metallib: *std.Build.Module) void { - @import("rotary_sweep.zig").steps(b, target, metal_mod); + @import("ling_forward.zig").steps(b, target, optimize, metal_mod, sources, kimi_metallib); const exe = b.addExecutable(.{ .name = "tf-kernel-contract", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/contract/metal_main.zig"), .target = target, diff --git a/zig/build/ling_forward.zig b/zig/build/ling_forward.zig new file mode 100644 index 00000000000..d99433b1b3f --- /dev/null +++ b/zig/build/ling_forward.zig @@ -0,0 +1,81 @@ +//! Local bf16 Ling forward diagnostics over existing registered Metal kernels. +const std = @import("std"); +pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal_mod: *std.Build.Module, sources: *std.Build.Module, kimi_metallib: *std.Build.Module) void { + const ling_ck = b.createModule(.{ + .root_source_file = b.path("zig/src/families/ling/checkpoint.zig"), + .target = target, + .imports = &.{ + .{ .name = "metal", .module = metal_mod }, + .{ .name = "safetensors", .module = b.createModule(.{ .root_source_file = b.path("zig/src/core/safetensors.zig"), .target = target }) }, + }, + }); + const ling_kernels = b.createModule(.{ .root_source_file = b.path("zig/src/families/kimi_k3/kernels.zig"), .target = target, .imports = &.{.{ .name = "metal", .module = metal_mod }} }); + const ling_rows = b.createModule(.{ .root_source_file = b.path("zig/src/families/ling/metal_rows.zig"), .target = target, .imports = &.{ + .{ .name = "metal", .module = metal_mod }, + .{ .name = "kernel_sources", .module = sources }, + .{ .name = "ling_checkpoint", .module = ling_ck }, + .{ .name = "kimi_kernels", .module = ling_kernels }, + .{ .name = "kimi_metallib", .module = kimi_metallib }, + } }); + const ling_kda = b.createModule(.{ .root_source_file = b.path("zig/src/families/ling/metal_kda.zig"), .target = target, .imports = &.{ + .{ .name = "metal", .module = metal_mod }, + .{ .name = "ling_checkpoint", .module = ling_ck }, + .{ .name = "kimi_kernels", .module = ling_kernels }, + .{ .name = "ling_rows", .module = ling_rows }, + } }); + const ling_sources = b.createModule(.{ .root_source_file = b.path("zig/kernels/metal/ling/sources.zig") }); + const ling_mla = b.createModule(.{ .root_source_file = b.path("zig/src/families/ling/metal_mla.zig"), .target = target, .imports = &.{ + .{ .name = "metal", .module = metal_mod }, .{ .name = "ling_checkpoint", .module = ling_ck }, + .{ .name = "kimi_kernels", .module = ling_kernels }, .{ .name = "ling_rows", .module = ling_rows }, + .{ .name = "ling_sources", .module = ling_sources }, + } }); + const ling_moe = b.createModule(.{ .root_source_file = b.path("zig/src/families/ling/metal_moe.zig"), .target = target, .imports = &.{ + .{ .name = "metal", .module = metal_mod }, .{ .name = "ling_checkpoint", .module = ling_ck }, + .{ .name = "kimi_kernels", .module = ling_kernels }, .{ .name = "ling_rows", .module = ling_rows }, + .{ .name = "ling_sources", .module = ling_sources }, + } }); + const ling_forward = b.createModule(.{ .root_source_file = b.path("zig/src/families/ling/metal_forward.zig"), .target = target, .imports = &.{ + .{ .name = "metal", .module = metal_mod }, .{ .name = "ling_checkpoint", .module = ling_ck }, + .{ .name = "ling_rows", .module = ling_rows }, .{ .name = "ling_kda", .module = ling_kda }, + .{ .name = "ling_mla", .module = ling_mla }, .{ .name = "ling_moe", .module = ling_moe }, + } }); + const ling_forward_tool = b.addExecutable(.{ .name = "ling-forward", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/ling_forward.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ .{ .name = "metal", .module = metal_mod }, .{ .name = "ling_checkpoint", .module = ling_ck }, .{ .name = "ling_rows", .module = ling_rows }, .{ .name = "ling_forward", .module = ling_forward } }, + }) }); + b.step("tf-ling-forward", "Build the native Ling bf16 full-forward diagnostic").dependOn(&b.addInstallArtifact(ling_forward_tool, .{}).step); + const python = b.graph.environ_map.get("TF_LING_PYTHON") orelse "python3"; + const full_check = b.addSystemCommand(&.{ python, "tools/zig/ling_forward_check.py", "--binary" }); + full_check.addArtifactArg(ling_forward_tool); + b.step("test-ling-forward", "Optional real-checkpoint Ling exactness and FP64 comparison receipts").dependOn(&full_check.step); + const ling_projection = b.addExecutable(.{ .name = "ling-projection", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/ling_projection.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ + .{ .name = "metal", .module = metal_mod }, + .{ .name = "ling_checkpoint", .module = ling_ck }, + .{ .name = "kimi_metallib", .module = kimi_metallib }, + .{ .name = "kimi_kernels", .module = ling_kernels }, + .{ .name = "ling_rows", .module = ling_rows }, + .{ .name = "ling_kda", .module = ling_kda }, + .{ .name = "ling_mla", .module = ling_mla }, + .{ .name = "ling_moe", .module = ling_moe }, + }, + }) }); + b.step("tf-ling-projection", "Build Ling's real bf16 projection diagnostic").dependOn(&b.addInstallArtifact(ling_projection, .{}).step); + const ling_checkpoint = b.addExecutable(.{ .name = "ling-checkpoint", .root_module = b.createModule(.{ + .root_source_file = b.path("zig/tests/ling_checkpoint.zig"), + .target = target, + .optimize = optimize, + .link_libc = true, + .imports = &.{ .{ .name = "metal", .module = metal_mod }, .{ .name = "ling_checkpoint", .module = ling_ck } }, + }) }); + b.step("tf-ling-checkpoint", "Build the native bf16 Ling checkpoint validator").dependOn(&b.addInstallArtifact(ling_checkpoint, .{}).step); + + @import("rotary_sweep.zig").steps(b, target, metal_mod); +} diff --git a/zig/tests/ling_checkpoint.zig b/zig/tests/ling_checkpoint.zig new file mode 100644 index 00000000000..3c06276d1a4 --- /dev/null +++ b/zig/tests/ling_checkpoint.zig @@ -0,0 +1,22 @@ +//! Read the real bf16 checkpoint through the native mapped source, including dtype and shape rejection. +const std = @import("std"); +const mtl = @import("metal"); +const ck = @import("ling_checkpoint"); + +pub fn main(init: std.process.Init) !void { + const args = try init.minimal.args.toSlice(init.arena.allocator()); + if (args.len != 2) return error.ModelDirectoryRequired; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const device = try mtl.Device.init(); + defer device.deinit(); + var model = try ck.Checkpoint.open(init.gpa, init.io, device, args[1]); + defer model.deinit(); + const embed = try model.get("model.word_embeddings.weight", .bf16, &.{ 157184, 1536 }); + _ = try model.get("model.layers.0.attention.q_proj.weight", .bf16, &.{ 2048, 1536 }); + _ = try model.get("model.norm.weight", .bf16, &.{1536}); + try std.testing.expectError(error.TensorShape, model.get("model.norm.weight", .f32, &.{1536})); + try std.testing.expectError(error.TensorShape, model.get("model.norm.weight", .bf16, &.{1535})); + try std.testing.expectError(error.MissingTensor, model.get("not.a.tensor", .bf16, &.{1})); + std.debug.print("Ling checkpoint: files={d} tensors={d} embedding_bytes={d}; 3 reads, 3 rejection checks passed\n", .{ model.files.items.len, model.where.count(), embed.entry.end - embed.entry.begin }); +} diff --git a/zig/tests/ling_forward.zig b/zig/tests/ling_forward.zig new file mode 100644 index 00000000000..2968d5f97b8 --- /dev/null +++ b/zig/tests/ling_forward.zig @@ -0,0 +1,50 @@ +//! Native bf16 Ling full-forward receipts with whole, chunked and snapshotted execution. +const std = @import("std"); +const mtl = @import("metal"); +const ck = @import("ling_checkpoint"); +const Rows = @import("ling_rows").Rows; +const Forward = @import("ling_forward").Forward; +pub fn main(init: std.process.Init) !void { + const args = try init.minimal.args.toSlice(init.arena.allocator()); + if (args.len < 3 or args.len > 4) return error.ModelAndOutputRequired; + const count = if (args.len == 4) try std.fmt.parseInt(u32, args[3], 10) else 2; + if (count < 2 or count > 32) return error.TokenCount; + const ids = try init.arena.allocator().alloc(u32, count); + for (ids, 0..) |*id, t| id.* = @intCast((37 * t + 11) % 157182); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const device = try mtl.Device.init(); + defer device.deinit(); + var model = try ck.Checkpoint.open(init.gpa, init.io, device, args[1]); + defer model.deinit(); + var rows = try Rows.init(init.gpa, device, count); + defer rows.deinit(); + var forward = try Forward.init(&rows, &model, 64); + defer forward.deinit(); + const logits = try forward.run(ids); + try std.Io.Dir.cwd().writeFile(init.io, .{ .sub_path = args[2], .data = std.mem.sliceAsBytes(logits) }); + const picks = try std.fmt.allocPrint(init.arena.allocator(), "{s}.picks", .{args[2]}); + try std.Io.Dir.cwd().writeFile(init.io, .{ .sub_path = picks, .data = forward.picks.contents()[0 .. 23 * count * 8 * 4] }); + std.debug.print("Ling full forward: 24 layers, {d} tokens, logits={d}; written with route picks\n", .{ count, logits.len }); + var split = try Forward.init(&rows, &model, 64); + defer split.deinit(); + const split_logits = try init.arena.allocator().alloc(f32, logits.len); + @memcpy(split_logits[0..157184], try split.run(ids[0..1])); + const saved = try split.snapshot(init.arena.allocator()); + var resumed = try Forward.init(&rows, &model, 64); + defer resumed.deinit(); + try std.testing.expectError(error.BadLingState, resumed.restore(saved[0 .. saved.len - 1])); + try resumed.restore(saved); + const resumed_logits = try resumed.run(ids[1..]); + try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(logits[157184..]), std.mem.sliceAsBytes(resumed_logits)); + for (1..count) |t| @memcpy(split_logits[t * 157184 ..][0..157184], try split.run(ids[t .. t + 1])); + try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(logits), std.mem.sliceAsBytes(split_logits)); + for (&forward.attention, &split.attention) |*whole, *part| switch (whole.*) { + .kda => |*k| { + try std.testing.expectEqualSlices(u8, k.state.contents()[0 .. 16 * 128 * 128 * 4], part.kda.state.contents()[0 .. 16 * 128 * 128 * 4]); + try std.testing.expectEqualSlices(u8, k.conv.contents()[0 .. 9 * 2048 * 2], part.kda.conv.contents()[0 .. 9 * 2048 * 2]); + }, + .mla => |*m| try std.testing.expectEqualSlices(u8, m.cache.contents()[0 .. count * 576 * 2], part.mla.cache.contents()[0 .. count * 576 * 2]), + }; + std.debug.print("Ling full forward whole/chunk/resume: logits/KDAstate/conv/MLAcache exact; truncated snapshot rejected\n", .{}); +} diff --git a/zig/tests/ling_projection.zig b/zig/tests/ling_projection.zig new file mode 100644 index 00000000000..a1546675045 --- /dev/null +++ b/zig/tests/ling_projection.zig @@ -0,0 +1,142 @@ +//! A real Ling bf16 projection through unchanged Kimi rows, with an independent float64 sum and row seam. +const std = @import("std"); +const mtl = @import("metal"); +const ck = @import("ling_checkpoint"); +const kernels = @import("kimi_kernels"); +fn f(h: u16) f64 { + return @as(f32, @bitCast(@as(u32, h) << 16)); +} +fn round(v: f64) f64 { + const bits: u32 = @bitCast(@as(f32, @floatCast(v))); + return f(@truncate((bits +% 0x7fff +% ((bits >> 16) & 1)) >> 16)); +} +pub fn main(init: std.process.Init) !void { + const args = try init.minimal.args.toSlice(init.arena.allocator()); + if (args.len < 2 or args.len > 3) return error.ModelDirectoryRequired; + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const device = try mtl.Device.init(); + defer device.deinit(); + const library = try mtl.Library.fromBytes(device, @import("kimi_metallib").bytes); + defer library.deinit(); + var k = try kernels.Kernels.init(device, library); + defer k.deinit(); + const queue = try device.queue(); + defer queue.deinit(); + var model = try ck.Checkpoint.open(init.gpa, init.io, device, args[1]); + defer model.deinit(); + const K = 1536; + const N = 2048; + const embed = try model.get("model.word_embeddings.weight", .bf16, &.{ 157184, K }); + const weight = try model.get("model.layers.0.attention.q_proj.weight", .bf16, &.{ N, K }); + const options = mtl.ResourceOptions.shared; + const x = try device.buffer(2 * K * 2, options); + defer x.deinit(); + const w = try device.buffer(N * K * 2, options); + defer w.deinit(); + const y = try device.buffer(2 * N * 2, options); + defer y.deinit(); + const split = try device.buffer(2 * N * 2, options); + defer split.deinit(); + const scratch = try device.buffer(kernels.partFloats(2) * 4, options); + defer scratch.deinit(); + for ([_]usize{ 11, 48 }, 0..) |id, row| { + const at = embed.offset + id * K * 2; + @memcpy(x.contents()[row * K * 2 ..][0 .. K * 2], embed.buffer.contents()[at..][0 .. K * 2]); + } + const cb = queue.commandBuffer(); + const e = cb.compute(.serial); + k.interleaved(e, .{ .buf = weight.buffer, .off = weight.offset }, .{ .buf = w }, N, K); + const a = kernels.RowsArgs{ .K = K, .N = N, .rows = 2, .x_stride = K, .y_stride = N }; + k.rows(e, .{ .buf = x }, .{ .buf = w }, .{ .buf = y }, .{ .buf = scratch }, false, a); + for (0..2) |row| { + var one = a; + one.rows = 1; + k.rows(e, .{ .buf = x, .off = row * K * 2 }, .{ .buf = w }, .{ .buf = split, .off = row * N * 2 }, .{ .buf = scratch }, false, one); + } + e.end(); + cb.commit(); + cb.wait(); + if (cb.failure() != null) return error.GpuFailed; + try std.testing.expectEqualSlices(u8, y.contents()[0 .. 2 * N * 2], split.contents()[0 .. 2 * N * 2]); + var rows = try @import("ling_rows").Rows.init(init.gpa, device, 2); + defer rows.deinit(); + try rows.linear(&model, "model.layers.0.attention.q_proj.weight", .{ .buf = x }, .{ .buf = split }, 2, K, N, false); + try std.testing.expectEqualSlices(u8, y.contents()[0 .. 2 * N * 2], split.contents()[0 .. 2 * N * 2]); + const xv = x.slice(u16, 2 * K); + const got = y.slice(u16, 2 * N); + const raw = std.mem.bytesAsSlice(u16, weight.buffer.contents()[weight.offset..][0 .. N * K * 2]); + var err: f64 = 0; + var baseline: f64 = 0; + var max_err: f64 = 0; + var max_round: f64 = 0; + for (0..2) |row| for (0..N) |n| { + var sum: f64 = 0; + for (0..K) |i| sum += f(xv[row * K + i]) * f(raw[n * K + i]); + const delta = f(got[row * N + n]) - sum; + const rounding = round(sum) - sum; + err += delta * delta; + baseline += rounding * rounding; + max_err = @max(max_err, @abs(delta)); + max_round = @max(max_round, @abs(rounding)); + }; + std.debug.print("Ling q projection rows=2 whole/split=exact Metal_rms={d} bf16_rms={d} Metal_max={d} bf16_max={d}\n", .{ @sqrt(err / (2 * N)), @sqrt(baseline / (2 * N)), max_err, max_round }); + if (err > baseline or max_err > max_round) return error.WorseThanBf16; + const activation = try rows.buffer(2 * N * 2); + try rows.siluMul(.{ .buf = y }, .{ .buf = split }, .{ .buf = activation }, 2 * N); + for (activation.slice(u16, 2 * N), got) |value, gate| { + const g = f(gate); + const expected = round(round(g / (1.0 + @exp(-g))) * g); + if (f(value) != expected) return error.SiluRoundingMismatch; + } + std.debug.print("Ling SiLU reused lfm3_swiglu: 4096 real projection values equal bf16-point FP64 formula\n", .{}); + const gate = try rows.buffer(2 * 4608 * 2); + const up = try rows.buffer(2 * 4608 * 2); + const act = try rows.buffer(2 * 4608 * 2); + const dense = try rows.buffer(2 * K * 2); + const chunked = try rows.buffer(2 * K * 2); + try rows.mlp(&model, "model.layers.0.mlp.", .{ .buf = x }, .{ .buf = dense }, .{ .buf = gate }, .{ .buf = up }, .{ .buf = act }, 2, K, 4608); + if (args.len == 3) { + for ([_]struct { suffix: []const u8, buffer: mtl.Buffer }{ + .{ .suffix = ".gate", .buffer = gate }, + .{ .suffix = ".up", .buffer = up }, + .{ .suffix = ".act", .buffer = act }, + }) |tap| { + const path = try std.fmt.allocPrint(init.arena.allocator(), "{s}{s}", .{ args[2], tap.suffix }); + try std.Io.Dir.cwd().writeFile(init.io, .{ .sub_path = path, .data = tap.buffer.contents()[0 .. 2 * 4608 * 2] }); + } + } + for (0..2) |row| try rows.mlp(&model, "model.layers.0.mlp.", .{ .buf = x, .off = row * K * 2 }, .{ .buf = chunked, .off = row * K * 2 }, .{ .buf = gate }, .{ .buf = up }, .{ .buf = act }, 1, K, 4608); + try std.testing.expectEqualSlices(u8, dense.contents()[0 .. 2 * K * 2], chunked.contents()[0 .. 2 * K * 2]); + if (args.len == 3) try std.Io.Dir.cwd().writeFile(init.io, .{ .sub_path = args[2], .data = dense.contents()[0 .. 2 * K * 2] }); + std.debug.print("Ling layer0 dense MLP two rows vs1+1: exact\n", .{}); + const Kda = @import("ling_kda").Kda; + var whole_kda = try Kda.init(&rows, &model, "model.layers.0.attention.", 16); + var split_kda = try Kda.init(&rows, &model, "model.layers.0.attention.", 16); + try whole_kda.forward(&rows, &model, "model.layers.0.attention.", .{ .buf = x }, .{ .buf = dense }, 2, K, -5, 1e-6); + for (0..2) |row| try split_kda.forward(&rows, &model, "model.layers.0.attention.", .{ .buf = x, .off = row * K * 2 }, .{ .buf = chunked, .off = row * K * 2 }, 1, K, -5, 1e-6); + try std.testing.expectEqualSlices(u8, dense.contents()[0 .. 2 * K * 2], chunked.contents()[0 .. 2 * K * 2]); + try std.testing.expectEqualSlices(u8, whole_kda.state.contents()[0 .. 16 * 128 * 128 * 4], split_kda.state.contents()[0 .. 16 * 128 * 128 * 4]); + try std.testing.expectEqualSlices(u8, whole_kda.conv.contents()[0 .. 9 * 2048 * 2], split_kda.conv.contents()[0 .. 9 * 2048 * 2]); + if (args.len == 3) { + const path = try std.fmt.allocPrint(init.arena.allocator(), "{s}.kda", .{args[2]}); + try std.Io.Dir.cwd().writeFile(init.io, .{ .sub_path = path, .data = dense.contents()[0 .. 2 * K * 2] }); + } + std.debug.print("Ling layer0 KDA full attention whole2 vs1+1: output/state/conv exact\n", .{}); + const Mla = @import("ling_mla").Mla; + var whole_mla = try Mla.init(&rows, 16, 16); + defer whole_mla.deinit(); + var split_mla = try Mla.init(&rows, 16, 16); + defer split_mla.deinit(); + try whole_mla.forward(&rows, &model, "model.layers.3.attention.", .{ .buf = x }, .{ .buf = dense }, 2, K, 1e-6, 6000000); + for (0..2) |row| try split_mla.forward(&rows, &model, "model.layers.3.attention.", .{ .buf = x, .off = row * K * 2 }, .{ .buf = chunked, .off = row * K * 2 }, 1, K, 1e-6, 6000000); + try std.testing.expectEqualSlices(u8, dense.contents()[0 .. 2 * K * 2], chunked.contents()[0 .. 2 * K * 2]); + try std.testing.expectEqualSlices(u8, whole_mla.cache.contents()[0 .. 2 * 576 * 2], split_mla.cache.contents()[0 .. 2 * 576 * 2]); + std.debug.print("Ling layer3 MLA whole2 vs1+1: output/cache exact\n", .{}); + var moe = try @import("ling_moe").Moe.init(&rows, K, 512); + defer moe.deinit(); + try moe.forward(&rows, &model, "model.layers.1.mlp.", .{ .buf = x }, .{ .buf = dense }, 2); + for (0..2) |row| try moe.forward(&rows, &model, "model.layers.1.mlp.", .{ .buf = x, .off = row * K * 2 }, .{ .buf = chunked, .off = row * K * 2 }, 1); + try std.testing.expectEqualSlices(u8, dense.contents()[0 .. 2 * K * 2], chunked.contents()[0 .. 2 * K * 2]); + std.debug.print("Ling layer1 MoE whole2 vs1+1: output exact\n", .{}); +} From 0cd25b7cb2d474d67cf64a8db813d7797c6d38a4 Mon Sep 17 00:00:00 2001 From: Petrus Pennanen <233579950+ThinkOffApp@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:48:34 +0100 Subject: [PATCH 04/12] Keep rotary sweep registration independent of Ling diagnostics --- zig/build/kernel_contract.zig | 1 + zig/build/ling_forward.zig | 4 +--- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/zig/build/kernel_contract.zig b/zig/build/kernel_contract.zig index 540c3d95be8..e33fe5fc528 100644 --- a/zig/build/kernel_contract.zig +++ b/zig/build/kernel_contract.zig @@ -129,6 +129,7 @@ pub fn hostTests(b: *std.Build, family: *std.Build.Step) void { /// macOS: tf-kernel-contract over the engine's Metal kernels; `kernel-contract` runs it on this Mac's GPU. pub fn metal(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, metal_mod: *std.Build.Module, engine: *std.Build.Module, sources: *std.Build.Module, kimi_metallib: *std.Build.Module) void { + @import("rotary_sweep.zig").steps(b, target, metal_mod); @import("ling_forward.zig").steps(b, target, optimize, metal_mod, sources, kimi_metallib); const exe = b.addExecutable(.{ .name = "tf-kernel-contract", .root_module = b.createModule(.{ .root_source_file = b.path("zig/tests/contract/metal_main.zig"), diff --git a/zig/build/ling_forward.zig b/zig/build/ling_forward.zig index d99433b1b3f..4851d0804c4 100644 --- a/zig/build/ling_forward.zig +++ b/zig/build/ling_forward.zig @@ -44,7 +44,7 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil .target = target, .optimize = optimize, .link_libc = true, - .imports = &.{ .{ .name = "metal", .module = metal_mod }, .{ .name = "ling_checkpoint", .module = ling_ck }, .{ .name = "ling_rows", .module = ling_rows }, .{ .name = "ling_forward", .module = ling_forward } }, + .imports = &.{ .{ .name = "metal", .module = metal_mod }, .{ .name = "ling_checkpoint", .module = ling_ck }, .{ .name = "ling_rows", .module = ling_rows }, .{ .name = "ling_forward", .module = ling_forward }, .{ .name = "ling_mla", .module = ling_mla } }, }) }); b.step("tf-ling-forward", "Build the native Ling bf16 full-forward diagnostic").dependOn(&b.addInstallArtifact(ling_forward_tool, .{}).step); const python = b.graph.environ_map.get("TF_LING_PYTHON") orelse "python3"; @@ -76,6 +76,4 @@ pub fn steps(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.buil .imports = &.{ .{ .name = "metal", .module = metal_mod }, .{ .name = "ling_checkpoint", .module = ling_ck } }, }) }); b.step("tf-ling-checkpoint", "Build the native bf16 Ling checkpoint validator").dependOn(&b.addInstallArtifact(ling_checkpoint, .{}).step); - - @import("rotary_sweep.zig").steps(b, target, metal_mod); } From 5c7fad8e30b7284da75bf2b8d0d64e86559a51f4 Mon Sep 17 00:00:00 2001 From: Petrus Pennanen <233579950+ThinkOffApp@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:48:34 +0100 Subject: [PATCH 05/12] Roll back Ling constructor resources on buffer allocation failure --- zig/src/families/ling/metal_forward.zig | 30 +++++++++++++------ zig/src/families/ling/metal_mla.zig | 38 +++++++++++++++++-------- zig/src/families/ling/metal_rows.zig | 7 +++++ 3 files changed, 54 insertions(+), 21 deletions(-) diff --git a/zig/src/families/ling/metal_forward.zig b/zig/src/families/ling/metal_forward.zig index c2a3539d0dc..5cb054fc664 100644 --- a/zig/src/families/ling/metal_forward.zig +++ b/zig/src/families/ling/metal_forward.zig @@ -24,6 +24,8 @@ pub const Forward = struct { position: u32 = 0, pub fn init(rows: *Rows, model: *ck.Checkpoint, capacity: u32) !Forward { + const buffer_mark = rows.owned.items.len; + errdefer rows.rollbackBuffers(buffer_mark); const c = model.config orelse return error.MissingConfig; if (c.quant != .bf16 or c.layers != 24 or c.hidden != 1536 or c.vocab != 157184 or c.group != 4 or c.kda_heads != 16 or c.kda_dim != 128 or c.mla_heads != 16 or c.q_lora != 256 or c.kv_lora != 512 or @@ -46,19 +48,29 @@ pub const Forward = struct { initialized += 1; } const r: usize = rows.max_rows; + var moe = try Moe.init(rows, 1536, 512); + errdefer moe.deinit(); + const x = try rows.buffer(r * 1536 * 2); + const normed = try rows.buffer(r * 1536 * 2); + const delta = try rows.buffer(r * 1536 * 2); + const gate = try rows.buffer(r * 4608 * 2); + const up = try rows.buffer(r * 4608 * 2); + const activation = try rows.buffer(r * 4608 * 2); + const logits = try rows.buffer(r * 157184 * 4); + const picks = try rows.buffer(23 * r * 8 * 4); return .{ .rows = rows, .model = model, .attention = attention, - .moe = try Moe.init(rows, 1536, 512), - .x = try rows.buffer(r * 1536 * 2), - .normed = try rows.buffer(r * 1536 * 2), - .delta = try rows.buffer(r * 1536 * 2), - .gate = try rows.buffer(r * 4608 * 2), - .up = try rows.buffer(r * 4608 * 2), - .activation = try rows.buffer(r * 4608 * 2), - .logits = try rows.buffer(r * 157184 * 4), - .picks = try rows.buffer(23 * r * 8 * 4), + .moe = moe, + .x = x, + .normed = normed, + .delta = delta, + .gate = gate, + .up = up, + .activation = activation, + .logits = logits, + .picks = picks, }; } diff --git a/zig/src/families/ling/metal_mla.zig b/zig/src/families/ling/metal_mla.zig index 4c7d714dba9..75c075f1bcf 100644 --- a/zig/src/families/ling/metal_mla.zig +++ b/zig/src/families/ling/metal_mla.zig @@ -29,6 +29,8 @@ pub const Mla = struct { position: u32 = 0, pub fn init(rows: *Rows, heads: u32, capacity: u32) !Mla { + const buffer_mark = rows.owned.items.len; + errdefer rows.rollbackBuffers(buffer_mark); const library = try mtl.Library.fromSource(rows.device, @import("ling_sources").mla, mtl.CompileOptions.mlx()); errdefer library.deinit(); const rope_cache = try mtl.Pipeline.init(rows.device, library, "tf_ling_mla_rope_cache", false); @@ -40,6 +42,18 @@ pub const Mla = struct { const r: usize = rows.max_rows; const cache = try rows.buffer(@as(usize, capacity) * 576 * 2); @memset(cache.slice(u16, capacity * 576), 0); + const positions = try rows.buffer(r * @sizeOf(kernels.MlaRow)); + const angles = try rows.buffer(r * 64 * 4); + const qa = try rows.buffer(r * 256 * 2); + const qan = try rows.buffer(r * 256 * 2); + const q = try rows.buffer(r * heads * 192 * 2); + const kv = try rows.buffer(r * 576 * 2); + const gate = try rows.buffer(r * heads * 2); + const expanded = try rows.buffer(r * heads * 128 * 2); + const qlat = try rows.buffer(r * heads * 512 * 4); + const partial = try rows.buffer(r * heads * 16 * 514 * 4); + const olat = try rows.buffer(r * heads * 512 * 4); + const y = try rows.buffer(r * heads * 128 * 2); return .{ .library = library, .rope_cache = rope_cache, @@ -48,18 +62,18 @@ pub const Mla = struct { .cache = cache, .heads = heads, .capacity = capacity, - .positions = try rows.buffer(r * @sizeOf(kernels.MlaRow)), - .angles = try rows.buffer(r * 64 * 4), - .qa = try rows.buffer(r * 256 * 2), - .qan = try rows.buffer(r * 256 * 2), - .q = try rows.buffer(r * heads * 192 * 2), - .kv = try rows.buffer(r * 576 * 2), - .gate = try rows.buffer(r * heads * 2), - .expanded = try rows.buffer(r * heads * 128 * 2), - .qlat = try rows.buffer(r * heads * 512 * 4), - .partial = try rows.buffer(r * heads * 16 * 514 * 4), - .olat = try rows.buffer(r * heads * 512 * 4), - .y = try rows.buffer(r * heads * 128 * 2), + .positions = positions, + .angles = angles, + .qa = qa, + .qan = qan, + .q = q, + .kv = kv, + .gate = gate, + .expanded = expanded, + .qlat = qlat, + .partial = partial, + .olat = olat, + .y = y, }; } diff --git a/zig/src/families/ling/metal_rows.zig b/zig/src/families/ling/metal_rows.zig index 69eac47cc96..2559bec6d22 100644 --- a/zig/src/families/ling/metal_rows.zig +++ b/zig/src/families/ling/metal_rows.zig @@ -17,6 +17,7 @@ pub const Rows = struct { owned: std.ArrayList(mtl.Buffer) = .empty, weights: std.StringHashMapUnmanaged(mtl.Buffer) = .empty, max_rows: u32, + fail_buffer_at: ?usize = null, pub fn init(a: std.mem.Allocator, device: mtl.Device, max_rows: u32) !Rows { const library = try mtl.Library.fromBytes(device, @import("kimi_metallib").bytes); @@ -34,12 +35,18 @@ pub const Rows = struct { } pub fn buffer(self: *Rows, bytes: usize) !mtl.Buffer { + if (self.fail_buffer_at) |at| if (self.owned.items.len >= at) return error.OutOfMemory; const b = try self.device.buffer(@max(bytes, 16), mtl.ResourceOptions.shared); errdefer b.deinit(); try self.owned.append(self.allocator, b); return b; } + pub fn rollbackBuffers(self: *Rows, mark: usize) void { + for (self.owned.items[mark..]) |b| b.deinit(); + self.owned.shrinkRetainingCapacity(mark); + } + fn finish(cb: mtl.CommandBuffer, e: mtl.ComputeEncoder) !void { e.end(); cb.commit(); From 4c7a829d6aad9ea876bcf821f1656dc56b8eea57 Mon Sep 17 00:00:00 2001 From: Petrus Pennanen <233579950+ThinkOffApp@users.noreply.github.com> Date: Wed, 18 Nov 2026 05:48:34 +0100 Subject: [PATCH 06/12] Check resumed Ling states and exercise constructor failure paths --- docs/recipes/ling-bf16-forward.md | 7 +++++++ zig/tests/ling_forward.zig | 22 ++++++++++++++++++++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/docs/recipes/ling-bf16-forward.md b/docs/recipes/ling-bf16-forward.md index c41d4703159..bc306095166 100644 --- a/docs/recipes/ling-bf16-forward.md +++ b/docs/recipes/ling-bf16-forward.md @@ -36,6 +36,13 @@ The fixed IDs are `(37*t + 11) % 157182`, at 2, 8 and 32 rows. The native diagnostic compares whole execution with single-row chunks and a fresh instance restored after token 1. It compares logits, KDA recurrent/conv state and MLA cache bytes. A truncated snapshot must be rejected. +Both the chunked and resumed instances' final recurrent states and caches are compared +with the whole run. A temporary one-byte corruption of the resumed final MLA slot +was planted after the logits check: the new state comparison failed, and the fault +was removed before the clean 2/8/32-row rerun. +Forced late-Forward and early-MLA buffer errors also test owned-buffer rollback. +Pipeline/library error cleanup is guarded by `errdefer`; driver object counts are +not independently instrumented by these allocator-failure checks. The snapshot is an internal same-checkpoint diagnostic format, not a serving or portable checkpoint handover API. These receipts exercise in-process restoration. The oracle remains `families/ling/oracle/ling_forward.py`, using native expert picks diff --git a/zig/tests/ling_forward.zig b/zig/tests/ling_forward.zig index 2968d5f97b8..0331e8c4ac9 100644 --- a/zig/tests/ling_forward.zig +++ b/zig/tests/ling_forward.zig @@ -19,7 +19,9 @@ pub fn main(init: std.process.Init) !void { defer model.deinit(); var rows = try Rows.init(init.gpa, device, count); defer rows.deinit(); + const init_mark = rows.owned.items.len; var forward = try Forward.init(&rows, &model, 64); + const init_buffers = rows.owned.items.len - init_mark; defer forward.deinit(); const logits = try forward.run(ids); try std.Io.Dir.cwd().writeFile(init.io, .{ .sub_path = args[2], .data = std.mem.sliceAsBytes(logits) }); @@ -39,12 +41,28 @@ pub fn main(init: std.process.Init) !void { try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(logits[157184..]), std.mem.sliceAsBytes(resumed_logits)); for (1..count) |t| @memcpy(split_logits[t * 157184 ..][0..157184], try split.run(ids[t .. t + 1])); try std.testing.expectEqualSlices(u8, std.mem.sliceAsBytes(logits), std.mem.sliceAsBytes(split_logits)); - for (&forward.attention, &split.attention) |*whole, *part| switch (whole.*) { + try sameState(&forward, &split, count); + try sameState(&forward, &resumed, count); + const mark = rows.owned.items.len; + rows.fail_buffer_at = mark + init_buffers - 1; + try std.testing.expectError(error.OutOfMemory, Forward.init(&rows, &model, 64)); + try std.testing.expectEqual(mark, rows.owned.items.len); + rows.fail_buffer_at = mark + 2; + try std.testing.expectError(error.OutOfMemory, @import("ling_mla").Mla.init(&rows, 16, 64)); + try std.testing.expectEqual(mark, rows.owned.items.len); + rows.fail_buffer_at = null; + std.debug.print("Ling init failures: Forward late-buffer and MLA early-buffer errors rolled back owned buffers\n", .{}); + + std.debug.print("Ling full forward whole/chunk/resume: logits/KDAstate/conv/MLAcache exact; truncated snapshot rejected\n", .{}); +} + +fn sameState(whole: *Forward, other: *Forward, count: u32) !void { + try std.testing.expectEqual(whole.position, other.position); + for (&whole.attention, &other.attention) |*attention, *part| switch (attention.*) { .kda => |*k| { try std.testing.expectEqualSlices(u8, k.state.contents()[0 .. 16 * 128 * 128 * 4], part.kda.state.contents()[0 .. 16 * 128 * 128 * 4]); try std.testing.expectEqualSlices(u8, k.conv.contents()[0 .. 9 * 2048 * 2], part.kda.conv.contents()[0 .. 9 * 2048 * 2]); }, .mla => |*m| try std.testing.expectEqualSlices(u8, m.cache.contents()[0 .. count * 576 * 2], part.mla.cache.contents()[0 .. count * 576 * 2]), }; - std.debug.print("Ling full forward whole/chunk/resume: logits/KDAstate/conv/MLAcache exact; truncated snapshot rejected\n", .{}); } From 32ff85ecf801e6fcb16f4d2ad6b629fe7f43dfa7 Mon Sep 17 00:00:00 2001 From: Petrus Pennanen <233579950+ThinkOffApp@users.noreply.github.com> Date: Wed, 18 Nov 2026 06:08:36 +0100 Subject: [PATCH 07/12] Describe the Ling forward diagnostic without local workflow wording --- docs/recipes/ling-bf16-forward.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/recipes/ling-bf16-forward.md b/docs/recipes/ling-bf16-forward.md index bc306095166..34ef30b949e 100644 --- a/docs/recipes/ling-bf16-forward.md +++ b/docs/recipes/ling-bf16-forward.md @@ -1,6 +1,6 @@ # Ling tiny bf16 forward diagnostic -This local step-3 diagnostic runs the 24-layer Ling-3.0-tiny backbone on Metal. +This diagnostic runs the 24-layer Ling-3.0-tiny backbone on Metal. It reuses Kimi's row projections, RMS, residual add, KDA, MLA and expert combine; Ling's grouped route and three MLA glue kernels; and LFM3's bf16-point SwiGLU. No GPU kernel source or registration changes are introduced. `kernel_contract.zig` From eea145974b7e3c26b6510c40534c8eabf0cf1b20 Mon Sep 17 00:00:00 2001 From: Petrus Pennanen <233579950+ThinkOffApp@users.noreply.github.com> Date: Thu, 19 Nov 2026 06:41:42 +0100 Subject: [PATCH 08/12] Record the Ling bf16 forward under Unreleased as #3919. --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 13dbd8a9c77..70b1f1b71df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -356,6 +356,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - DeepSeek-V4.1 on Metal: with `TF_DSV41_PREFILL_PIECES=1`, `TENSORFOLD_PREFILL_ORDER=srpt`, a prompt policy, share or budget, or `--decode-share` set, a prompt runs a chunk at a time between the other streams' rounds, so a short request no longer waits behind a long prompt; with none of them set, prompts run whole as before (#2950, refs #2984). Thanks to @gilby. - `tensorfold info` on Metal: `tensorfold info MODEL [--context N] [--parallel N|auto]` prints the startup budget `serve` charges a Qwen3.8-27B-class checkpoint (weights, each stream's KV and state, the prompt scratch; no drafter or images) and whether it fits this Mac's Metal working set beside the 8 GiB margin, in place of a memory floor that ignored the context; `info` also copies `model_type` out of the parse before freeing it (#3268, refs #2761). Thanks to @cshintov. +- Metal: Ling-3.0-tiny's published bf16 forward runs over all 24 layers on kernels that already exist and adds no GPU kernel source; nothing is served yet (#3919, part of #1247). Thanks to @ThinkOffApp. - Nemotron on HIP: a checkpoint whose token table (`backbone.embeddings`) is stored bf16 beside quantized matrices, marked `false` in config.json's quantization block or stored without scales, is admitted and loads; its rows are gathered as stored, the memory plan counts them at their stored bytes, and the startup label adds `+bf16-embed`; a bf16 `lm_head`, projection or other unquantized tensor is still refused by name (#3575, refs #3061). Thanks to @gilby. From 3b8d857cafc23c58707d25785d64bb330a366730 Mon Sep 17 00:00:00 2001 From: Petrus Pennanen <233579950+ThinkOffApp@users.noreply.github.com> Date: Sat, 21 Nov 2026 02:04:18 +0100 Subject: [PATCH 09/12] Probe for torch and safetensors before generating Ling MLA dumps The dump script imports both; an interpreter with torch alone passed the probe and then failed as DumpGen instead of skipping. The skip line now names both packages. --- zig/tests/ling_mla_gpu_dump.zig | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/zig/tests/ling_mla_gpu_dump.zig b/zig/tests/ling_mla_gpu_dump.zig index 9a94d0efd6f..fdde36f2458 100644 --- a/zig/tests/ling_mla_gpu_dump.zig +++ b/zig/tests/ling_mla_gpu_dump.zig @@ -123,10 +123,10 @@ fn fileOk(path: []const u8) bool { return true; } -fn hasTorch(py: []const u8) bool { +fn hasTorchAndSafetensors(py: []const u8) bool { const a = std.testing.allocator; const r = std.process.run(a, std.testing.io, .{ - .argv = &.{ py, "-c", "import torch" }, + .argv = &.{ py, "-c", "import torch, safetensors.torch" }, .stdout_limit = .limited(256), .stderr_limit = .limited(4096), }) catch return false; @@ -138,9 +138,9 @@ fn hasTorch(py: []const u8) bool { fn findPython() ?[]const u8 { if (std.c.getenv("TF_LING_PYTHON")) |p| { const s = std.mem.span(p); - if (hasTorch(s)) return s; + if (hasTorchAndSafetensors(s)) return s; } - if (hasTorch("python3")) return "python3"; + if (hasTorchAndSafetensors("python3")) return "python3"; return null; } @@ -151,7 +151,7 @@ fn ensureDumps() !void { return error.SkipZigTest; } const py = findPython() orelse { - std.debug.print("skip: no torch (set TF_LING_PYTHON or python3 on PATH); TFLINGA1 dumps come from ling_forward.py at test time\n", .{}); + std.debug.print("skip: no Python with both torch and safetensors (set TF_LING_PYTHON or put such a python3 on PATH); TFLINGA1 dumps come from ling_forward.py at test time\n", .{}); return error.SkipZigTest; }; const a = std.testing.allocator; From 5917e1a53880d592ac42ccc44f22a95fe4abee5a Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 03:29:34 +0000 Subject: [PATCH 10/12] changelog: #3919's line from lines/3919.txt in place of its own --- CHANGELOG.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 70b1f1b71df..56ba445b277 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Flash Next on HIP: on an integrated GPU that shares the host's pages (no firmware carve-out), the default kept-prompt cache takes no more than the memory the streams leave, at most 16 GiB and none when nothing is left; an explicit `--prompt-cache-gib` still sets it (#3645). - Tests: the Web loopback startup test sets its fixture ready before probing, so its health, model-list and relay checks no longer depend on warm-up timing (#3753, fixes #3752). Thanks to @AIFlowML. +- Ling-3.0-tiny on Metal: a bf16 forward diagnostic runs all 24 layers of the published checkpoint on kernels that already exist, with no new GPU kernel source; `zig build test-ling-forward`, given `TF_LING_CHECKPOINT` and a Python with torch and safetensors (`TF_LING_PYTHON`), checks whole, chunked and resumed runs byte for byte and reports the distance from float64. Nothing is served yet (#3919, part of #1247). Thanks to @ThinkOffApp. - Server: `TENSORFOLD_PARALLEL` sets the default lanes when `serve` has no `--parallel`: a whole number 1 to 4096 or `auto`; the flag wins when both are given, a blank value keeps the default, and any other value is refused by name at startup (#3685, for #3684). Thanks to @bikepresentball. @@ -40,8 +41,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Qwen3.5-2B on Metal: a new stream's prompt runs one chunk a call at the same cuts as before, so other streams' decode rounds run between its chunks instead of waiting for the whole prompt; a cancel between chunks keeps the state at the last chunk's end (#3090, refs #3021). - - - Tools: add tf-h3-image to compare MiniMax-H3-Image Metal transformer steps with exported picture cases (#2766). - Qwen3.8-27B on Metal with `TF_QWEN27_METAL_KV_PAGES=1`: a stream that opens a slot is promised the KV pages of its prompt and one widest pass instead of every slot being promised its whole window at load; a pass past that promises the rest before it takes a page and fails with `LaneMemory` before any page is taken when the pool cannot meet it, and a stream that leaves, a failed or requeued prompt pass, a reset and a move to slot 0 give back the slot's pages and promise. Without the flag nothing changes (#3377, refs #1293). Thanks to @CodingEmil. @@ -356,7 +355,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - DeepSeek-V4.1 on Metal: with `TF_DSV41_PREFILL_PIECES=1`, `TENSORFOLD_PREFILL_ORDER=srpt`, a prompt policy, share or budget, or `--decode-share` set, a prompt runs a chunk at a time between the other streams' rounds, so a short request no longer waits behind a long prompt; with none of them set, prompts run whole as before (#2950, refs #2984). Thanks to @gilby. - `tensorfold info` on Metal: `tensorfold info MODEL [--context N] [--parallel N|auto]` prints the startup budget `serve` charges a Qwen3.8-27B-class checkpoint (weights, each stream's KV and state, the prompt scratch; no drafter or images) and whether it fits this Mac's Metal working set beside the 8 GiB margin, in place of a memory floor that ignored the context; `info` also copies `model_type` out of the parse before freeing it (#3268, refs #2761). Thanks to @cshintov. -- Metal: Ling-3.0-tiny's published bf16 forward runs over all 24 layers on kernels that already exist and adds no GPU kernel source; nothing is served yet (#3919, part of #1247). Thanks to @ThinkOffApp. - Nemotron on HIP: a checkpoint whose token table (`backbone.embeddings`) is stored bf16 beside quantized matrices, marked `false` in config.json's quantization block or stored without scales, is admitted and loads; its rows are gathered as stored, the memory plan counts them at their stored bytes, and the startup label adds `+bf16-embed`; a bf16 `lm_head`, projection or other unquantized tensor is still refused by name (#3575, refs #3061). Thanks to @gilby. From f51f5c479bca52616fe358e724061e677ebb2086 Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 04:59:14 +0000 Subject: [PATCH 11/12] changelog: #3919's line from lines/3919.txt in place of its own --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 56ba445b277..c6f7fef2304 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased + + - GLM-5.3-Flash on CUDA: drafted decode after a 1,040,384-token prompt takes its DSA index scores from `tf_glm_index_scores`, 13.8% faster at TP=4 (172.39 against 151.51 tok/s median) with byte-identical scores and the same tokens; shorter windows keep `tf_glm_scores` (#3689). Thanks to @Bizuayeu. - GLM-5.3-Flash on CUDA: `TF_GLM_DRAFT_SPLIT=1` splits the DFlash2 drafter's MLP across three ranks or more where each share is 256-aligned, without `TF_ROCE=1`; the ranks must set it alike, two ranks split as before, and unset changes nothing. On three GB10s whose gathers stay on NCCL, decode with `--drafter` is about 5% faster at one stream (four streams within their start-to-start spread), with the same replies and the same tokens a round on the measured prompts. As with `TF_ROCE=1`, the split drafter adds its down projection's rank shares in another order, so its proposals can differ at near-ties (#3616, for #3581). @@ -15,6 +17,8 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Tests: the Web loopback startup test sets its fixture ready before probing, so its health, model-list and relay checks no longer depend on warm-up timing (#3753, fixes #3752). Thanks to @AIFlowML. - Ling-3.0-tiny on Metal: a bf16 forward diagnostic runs all 24 layers of the published checkpoint on kernels that already exist, with no new GPU kernel source; `zig build test-ling-forward`, given `TF_LING_CHECKPOINT` and a Python with torch and safetensors (`TF_LING_PYTHON`), checks whole, chunked and resumed runs byte for byte and reports the distance from float64. Nothing is served yet (#3919, part of #1247). Thanks to @ThinkOffApp. +- Tests: the Web loopback startup test sets its fixture ready before probing, so its health, model-list and relay checks no longer depend on warm-up timing (#3753, fixes #3752). Thanks to @AIFlowML. + - Server: `TENSORFOLD_PARALLEL` sets the default lanes when `serve` has no `--parallel`: a whole number 1 to 4096 or `auto`; the flag wins when both are given, a blank value keeps the default, and any other value is refused by name at startup (#3685, for #3684). Thanks to @bikepresentball. - Lane host: a streamed reply whose client falls 1,024 tokens behind sits out rounds until the reader is within 512 again, and one whose client reads nothing for 60 seconds is cancelled like a disconnect, so a stalled reader stops holding its lane; the text a reader receives is unchanged (#3234). From 18349246f6ac0e4e8544d8894c6458c80e2e044f Mon Sep 17 00:00:00 2001 From: ashhart <71890694+ashhart@users.noreply.github.com> Date: Sat, 21 Nov 2026 05:51:58 +0000 Subject: [PATCH 12/12] changelog: each line once under Unreleased --- CHANGELOG.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c6f7fef2304..827a14b1829 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,8 +17,6 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Tests: the Web loopback startup test sets its fixture ready before probing, so its health, model-list and relay checks no longer depend on warm-up timing (#3753, fixes #3752). Thanks to @AIFlowML. - Ling-3.0-tiny on Metal: a bf16 forward diagnostic runs all 24 layers of the published checkpoint on kernels that already exist, with no new GPU kernel source; `zig build test-ling-forward`, given `TF_LING_CHECKPOINT` and a Python with torch and safetensors (`TF_LING_PYTHON`), checks whole, chunked and resumed runs byte for byte and reports the distance from float64. Nothing is served yet (#3919, part of #1247). Thanks to @ThinkOffApp. -- Tests: the Web loopback startup test sets its fixture ready before probing, so its health, model-list and relay checks no longer depend on warm-up timing (#3753, fixes #3752). Thanks to @AIFlowML. - - Server: `TENSORFOLD_PARALLEL` sets the default lanes when `serve` has no `--parallel`: a whole number 1 to 4096 or `auto`; the flag wins when both are given, a blank value keeps the default, and any other value is refused by name at startup (#3685, for #3684). Thanks to @bikepresentball. - Lane host: a streamed reply whose client falls 1,024 tokens behind sits out rounds until the reader is within 512 again, and one whose client reads nothing for 60 seconds is cancelled like a disconnect, so a stalled reader stops holding its lane; the text a reader receives is unchanged (#3234).