From 4c80cbaabe6c8adb18442b2f7904fc268b0249a8 Mon Sep 17 00:00:00 2001 From: indexer-bf16 Date: Fri, 9 Oct 2026 21:00:58 -0500 Subject: [PATCH 1/3] GLM-5.3-Flash Living Weights: a low-rank change after layer 44's shared-expert down, loaded from append-only shards y += 10 (x a^T) b after the last layer's shared-expert down projection, in decode and prompt chunks, with the train.metal kernels Nemotron uses (rank 0 encodes nothing). Learned rows live beside the model as living-NNNN.safetensors listed in living_weights.index.json, summed in index order; each shard carries the site weight's sha256 and a mismatch is refused. A lone living_weights.safetensors loads as shard 1. Dropping the newest index entry undoes a lesson exactly. LW_TOPICS=a,b loads only those topics. GLM_LOAD_LIMIT_GB and GLM_MLOCK (both opt-in) let Flash load on one 256 GB Mac. Co-Authored-By: Claude Opus 5.5 --- zig/src/core/living_sidecar.zig | 512 +++++++++++++++++++++++++++++++ zig/src/core/root.zig | 2 + zig/src/families/glm/engine.zig | 55 +++- zig/src/families/glm/living.zig | 305 ++++++++++++++++++ zig/src/families/glm/moe.zig | 1 + zig/src/families/glm/prompt.zig | 1 + zig/src/families/glm/weights.zig | 16 +- 7 files changed, 890 insertions(+), 2 deletions(-) create mode 100644 zig/src/core/living_sidecar.zig create mode 100644 zig/src/families/glm/living.zig diff --git a/zig/src/core/living_sidecar.zig b/zig/src/core/living_sidecar.zig new file mode 100644 index 00000000000..e32cc8f906d --- /dev/null +++ b/zig/src/core/living_sidecar.zig @@ -0,0 +1,512 @@ +//! Living Weights on GLM-5.3-Flash: the sidecar file that keeps a model folder's committed low-rank change. +//! `living_weights.safetensors` beside the shards, never folded into the 4-bit weights (re-quantizing would erase it): +//! .lw_a bf16 [R, in], .lw_b bf16 [R, out], metadata format/scale/site/ranks/base_sha (all strings). +//! The forward adds scale * (x a^T) b after the site's projection. Absent file: the engine is the stock engine. +//! Host only (libc file calls, no Metal): the engine maps it, the learner writes it, the unit tests run anywhere. +const std = @import("std"); +const st = @import("safetensors.zig"); +const Allocator = std.mem.Allocator; +const Sha256 = std.crypto.hash.sha2.Sha256; + +pub const file_name = "living_weights.safetensors"; +pub const format = "tf-living-weights-glm/1"; +/// The one site: layer 44's shared-expert down projection (in 2048, out 4096). +pub const site = "model.layers.44.mlp.shared_experts.down_proj"; +pub const scale_text = "10"; +pub const scale: f32 = 10; +pub const in: usize = 2048; +pub const out: usize = 4096; +pub const block: usize = 16; // ranks a committed lesson adds +pub const max_rank: usize = 512; +pub const a_name = site ++ ".lw_a"; +pub const b_name = site ++ ".lw_b"; +/// The site's original weight as the checkpoint names it (MLX: under `model.language_model.`), then the plain name. +pub const weight_names = [_][]const u8{ "model.language_model.layers.44.mlp.shared_experts.down_proj.weight", site ++ ".weight" }; + +/// f32 to bf16 by round-to-nearest-even (Metal's `bfloat(float)`), NaN kept quiet. +pub fn toBf16(x: f32) u16 { + const u: u32 = @bitCast(x); + if (std.math.isNan(x)) return @intCast((u >> 16) | 0x40); + const lsb = (u >> 16) & 1; + return @intCast((u +% (0x7fff + lsb)) >> 16); +} + +pub fn fromBf16(h: u16) f32 { + return @bitCast(@as(u32, h) << 16); +} + +/// Each value replaced by the nearest bf16 (what the file keeps, so RAM and a reloaded folder compute the same bits). +pub fn roundSlice(v: []f32) void { + for (v) |*x| x.* = fromBf16(toBf16(x.*)); +} + +/// A parsed sidecar: views into its bytes (bf16, unaligned). +pub const View = struct { + ranks: usize, + a: []align(1) const u16, // [ranks, in] + b: []align(1) const u16, // [ranks, out] + base_sha: []const u8, // 64 hex digits + + pub fn aF32(v: View, dst: []f32) void { + for (dst[0 .. v.ranks * in], v.a) |*d, h| d.* = fromBf16(h); + } + pub fn bF32(v: View, dst: []f32) void { + for (dst[0 .. v.ranks * out], v.b) |*d, h| d.* = fromBf16(h); + } +}; + +/// The sidecar's bytes checked against the contract (format, site, scale, shapes, ranks a multiple of 16, at most 512). +pub fn decode(arena: Allocator, bytes: []const u8) !View { + if (bytes.len < 8) return error.BadLivingWeights; + const hl: usize = @intCast(std.mem.readInt(u64, bytes[0..8], .little)); + if (hl > bytes.len - 8) return error.BadLivingWeights; + const json = bytes[8..][0..hl]; + const data = bytes[8 + hl ..]; + const names = try st.parseHeader(arena, json, data.len); + const root = try std.json.parseFromSliceLeaky(std.json.Value, arena, json, .{}); + const meta = (root.object.get("__metadata__") orelse return error.BadLivingWeights); + if (meta != .object) return error.BadLivingWeights; + const text = struct { + fn of(m: std.json.Value, key: []const u8) ![]const u8 { + const v = m.object.get(key) orelse return error.BadLivingWeights; + return if (v == .string) v.string else error.BadLivingWeights; + } + }; + if (!std.mem.eql(u8, try text.of(meta, "format"), format)) return error.LivingFormat; + if (!std.mem.eql(u8, try text.of(meta, "site"), site)) return error.LivingSite; + if (!std.mem.eql(u8, try text.of(meta, "scale"), scale_text)) return error.LivingScale; + const ranks = std.fmt.parseInt(usize, try text.of(meta, "ranks"), 10) catch return error.BadLivingWeights; + const sha = try text.of(meta, "base_sha"); + if (sha.len != 64) return error.BadLivingWeights; + if (ranks == 0 or ranks % block != 0 or ranks > max_rank) return error.LivingRanks; + const ea = names.get(a_name) orelse return error.BadLivingWeights; + const eb = names.get(b_name) orelse return error.BadLivingWeights; + if (ea.dtype != .bf16 or ea.rank != 2 or ea.shape[0] != ranks or ea.shape[1] != in) return error.LivingShape; + if (eb.dtype != .bf16 or eb.rank != 2 or eb.shape[0] != ranks or eb.shape[1] != out) return error.LivingShape; + const a: []align(1) const u16 = std.mem.bytesAsSlice(u16, data[ea.begin..ea.end]); + const b: []align(1) const u16 = std.mem.bytesAsSlice(u16, data[eb.begin..eb.end]); + return .{ .ranks = ranks, .a = a, .b = b, .base_sha = sha }; +} + +/// The sidecar's bytes for `ranks` committed ranks (a [ranks, in], b [ranks, out], f32 rounded to bf16 here). +pub fn encode(gpa: Allocator, a: []const f32, b: []const f32, ranks: usize, base_sha: []const u8) ![]u8 { + if (ranks == 0 or ranks % block != 0 or ranks > max_rank) return error.LivingRanks; + if (a.len < ranks * in or b.len < ranks * out or base_sha.len != 64) return error.BadLivingWeights; + const a_bytes = ranks * in * 2; + const b_bytes = ranks * out * 2; + var head: std.ArrayList(u8) = .empty; + defer head.deinit(gpa); + try head.print(gpa, "{{\"__metadata__\":{{\"format\":\"{s}\",\"scale\":\"{s}\",\"site\":\"{s}\",\"ranks\":\"{d}\",\"base_sha\":\"{s}\"}}," ++ + "\"{s}\":{{\"dtype\":\"BF16\",\"shape\":[{d},{d}],\"data_offsets\":[0,{d}]}}," ++ + "\"{s}\":{{\"dtype\":\"BF16\",\"shape\":[{d},{d}],\"data_offsets\":[{d},{d}]}}}}", .{ format, scale_text, site, ranks, base_sha, a_name, ranks, in, a_bytes, b_name, ranks, out, a_bytes, a_bytes + b_bytes }); + while (head.items.len % 8 != 0) try head.append(gpa, ' '); + const total = 8 + head.items.len + a_bytes + b_bytes; + const buf = try gpa.alloc(u8, total); + std.mem.writeInt(u64, buf[0..8], head.items.len, .little); + @memcpy(buf[8..][0..head.items.len], head.items); + var at = 8 + head.items.len; + for (a[0 .. ranks * in]) |x| { + std.mem.writeInt(u16, buf[at..][0..2], toBf16(x), .little); + at += 2; + } + for (b[0 .. ranks * out]) |x| { + std.mem.writeInt(u16, buf[at..][0..2], toBf16(x), .little); + at += 2; + } + return buf; +} + +/// The whole file at `path` (libc), or null when it does not exist. +pub fn readFile(gpa: Allocator, path: []const u8) !?[]u8 { + const z = try gpa.dupeSentinel(u8, path, 0); + defer gpa.free(z); + const fd = std.c.open(z, .{ .ACCMODE = .RDONLY }); + if (fd < 0) return if (std.c._errno().* == @backingInt(std.c.E.NOENT)) null else error.LivingRead; + defer _ = std.c.close(fd); + const end = std.c.lseek(fd, 0, std.c.SEEK.END); + if (end < 0) return error.LivingRead; + const n: usize = @intCast(end); + const buf = try gpa.alloc(u8, n); + errdefer gpa.free(buf); + try preadAll(fd, buf, 0); + return buf; +} + +fn preadAll(fd: c_int, buf: []u8, offset: usize) !void { + var done: usize = 0; + while (done < buf.len) { + const r = std.c.pread(fd, buf.ptr + done, @min(buf.len - done, 1 << 30), @intCast(offset + done)); + if (r <= 0) return error.LivingRead; + done += @intCast(r); + } +} + +/// `bytes` to `path` through `path`.tmp, synced, renamed over it: a reader sees the old sidecar or the new one. +pub fn writeAtomic(gpa: Allocator, path: []const u8, bytes: []const u8) !void { + const tmp = try std.fmt.allocPrintSentinel(gpa, "{s}.tmp", .{path}, 0); + defer gpa.free(tmp); + const dest = try gpa.dupeSentinel(u8, path, 0); + defer gpa.free(dest); + const fd = std.c.open(tmp, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(std.c.mode_t, 0o644)); + if (fd < 0) return error.LivingWrite; + errdefer _ = std.c.unlink(tmp); + { + defer _ = std.c.close(fd); + var done: usize = 0; + while (done < bytes.len) { + const n = std.c.write(fd, bytes.ptr + done, @min(bytes.len - done, 1 << 30)); + if (n <= 0) return error.LivingWrite; + done += @intCast(n); + } + if (std.c.fsync(fd) != 0) return error.LivingWrite; + } + if (std.c.rename(tmp, dest) != 0) return error.LivingWrite; +} + +/// sha256 (hex) of the site's original `.weight` bytes in the checkpoint at `dir` (index -> shard -> the tensor's range). +pub fn siteSha(gpa: Allocator, dir: []const u8) ![64]u8 { + var arena_state = std.heap.ArenaAllocator.init(gpa); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const index_path = try std.fs.path.join(arena, &.{ dir, "model.safetensors.index.json" }); + var shard: []const u8 = "model.safetensors"; + var wname: []const u8 = weight_names[0]; + if (try readFile(arena, index_path)) |ix_bytes| { + const ix = try std.json.parseFromSliceLeaky(std.json.Value, arena, ix_bytes, .{}); + const map = (ix.object.get("weight_map") orelse return error.BadIndex).object; + const found = for (weight_names) |n| { + if (map.get(n)) |v| if (v == .string) break .{ n, v.string }; + } else return error.LivingSiteMissing; + wname, shard = found; + } + const path = try std.fs.path.joinZ(arena, &.{ dir, shard }); + const fd = std.c.open(path, .{ .ACCMODE = .RDONLY }); + if (fd < 0) return error.LivingRead; + defer _ = std.c.close(fd); + var lenb: [8]u8 = undefined; + try preadAll(fd, &lenb, 0); + const hl: usize = @intCast(std.mem.readInt(u64, &lenb, .little)); + if (hl > 1 << 28) return error.BadSafetensors; + const json = try arena.alloc(u8, hl); + try preadAll(fd, json, 8); + const end = std.c.lseek(fd, 0, std.c.SEEK.END); + if (end < 0) return error.LivingRead; + const names = try st.parseHeader(arena, json, @as(usize, @intCast(end)) - 8 - hl); + var e: ?st.Entry = names.get(wname); + if (e == null) for (weight_names) |n| if (names.get(n)) |x| { + e = x; + break; + }; + const ent = e orelse return error.LivingSiteMissing; + var h = Sha256.init(.{}); + const chunk = try arena.alloc(u8, 1 << 22); + var at: usize = ent.begin; + while (at < ent.end) { + const n = @min(chunk.len, ent.end - at); + try preadAll(fd, chunk[0..n], 8 + hl + at); + h.update(chunk[0..n]); + at += n; + } + var digest: [32]u8 = undefined; + h.final(&digest); + var hex: [64]u8 = undefined; + _ = std.fmt.bufPrint(&hex, "{x}", .{digest}) catch unreachable; + return hex; +} + +// ---- v2: spawned shards ---- +// `living_weights.index.json` {"format":"tf-living-weights-glm/2","site":...,"shards":[{"file","site","ranks","created", +// "topic","base_sha","sha256"}]} lists append-only shard files (`living-NNNN.safetensors`, each in the v1 file format); +// the engine sums every listed shard's ranks in index order. A v1 `living_weights.safetensors` with no index = shard 0001. +// Rollback = the newest entry dropped from the index (its file stays). LW_TOPICS=a,b loads only shards of those topics. + +pub const index_name = "living_weights.index.json"; +pub const format2 = "tf-living-weights-glm/2"; + +pub const Shard = struct { file: []const u8, ranks: usize, created: i64 = 0, topic: []const u8 = "", base_sha: []const u8, sha256: []const u8 }; + +/// The folder's shard list: the index's entries, else the v1 file as the one shard, else none (null). +pub fn listShards(arena: Allocator, dir: []const u8) !?[]Shard { + const ipath = try std.fs.path.join(arena, &.{ dir, index_name }); + if (try readFile(arena, ipath)) |bytes| { + const root = try std.json.parseFromSliceLeaky(std.json.Value, arena, bytes, .{}); + if (root != .object) return error.BadLivingIndex; + const f = root.object.get("format") orelse return error.BadLivingIndex; + if (f != .string or !std.mem.eql(u8, f.string, format2)) return error.LivingFormat; + const arr = root.object.get("shards") orelse return error.BadLivingIndex; + if (arr != .array) return error.BadLivingIndex; + const list = try arena.alloc(Shard, arr.array.items.len); + for (arr.array.items, list) |v, *o| { + if (v != .object) return error.BadLivingIndex; + const g = struct { + fn s(obj: std.json.Value, k: []const u8, need: bool) ![]const u8 { + const x = obj.object.get(k) orelse return if (need) error.BadLivingIndex else ""; + return if (x == .string) x.string else error.BadLivingIndex; + } + fn n(obj: std.json.Value, k: []const u8) !i64 { + const x = obj.object.get(k) orelse return 0; + return switch (x) { + .integer => |i| i, + .string => |t| std.fmt.parseInt(i64, t, 10) catch error.BadLivingIndex, + else => error.BadLivingIndex, + }; + } + }; + const site_v = try g.s(v, "site", true); + if (!std.mem.eql(u8, site_v, site)) return error.LivingSite; + const file = try g.s(v, "file", true); + if (std.mem.indexOfScalar(u8, file, '/') != null or std.mem.eql(u8, file, "..")) return error.BadLivingIndex; + o.* = .{ .file = file, .ranks = @intCast(try g.n(v, "ranks")), .created = try g.n(v, "created"), .topic = try g.s(v, "topic", false), .base_sha = try g.s(v, "base_sha", true), .sha256 = try g.s(v, "sha256", false) }; + } + return list; + } + const v1 = try std.fs.path.join(arena, &.{ dir, file_name }); + const bytes = (try readFile(arena, v1)) orelse return null; + const v = try decode(arena, bytes); + const one = try arena.alloc(Shard, 1); + one[0] = .{ .file = file_name, .ranks = v.ranks, .base_sha = try arena.dupe(u8, v.base_sha), .sha256 = "" }; + return one; +} + +/// Whether a shard's topic passes the allow-list (comma separated; null or empty: every shard). +pub fn topicAllowed(allow: ?[]const u8, topic: []const u8) bool { + const list = allow orelse return true; + if (list.len == 0) return true; + var it = std.mem.tokenizeScalar(u8, list, ','); + while (it.next()) |t| if (std.mem.eql(u8, std.mem.trim(u8, t, " "), topic)) return true; + return false; +} + +/// Every allowed shard's rows summed in index order: a [ranks, in], b [ranks, out] f32 (exact from bf16). +pub const Loaded = struct { a: []f32, b: []f32, ranks: usize, shards: usize, digest: [32]u8 }; + +/// The folder's change (null: no sidecar, no index). Each shard's sha256 (when listed) and base_sha are checked. +pub fn loadAll(arena: Allocator, dir: []const u8, base_sha: []const u8, allow: ?[]const u8) !?Loaded { + const shards = (try listShards(arena, dir)) orelse return null; + var total: usize = 0; + for (shards) |sh| if (topicAllowed(allow, sh.topic)) { + total += sh.ranks; + }; + if (total > max_rank) return error.LivingRanks; + var got: Loaded = .{ .a = try arena.alloc(f32, total * in), .b = try arena.alloc(f32, total * out), .ranks = 0, .shards = 0, .digest = undefined }; + var h = Sha256.init(.{}); + for (shards) |sh| { + if (!topicAllowed(allow, sh.topic)) continue; + const path = try std.fs.path.join(arena, &.{ dir, sh.file }); + const bytes = (try readFile(arena, path)) orelse return error.LivingShardMissing; + var d: [32]u8 = undefined; + Sha256.hash(bytes, &d, .{}); + var hex: [64]u8 = undefined; + _ = std.fmt.bufPrint(&hex, "{x}", .{d}) catch unreachable; + if (sh.sha256.len > 0 and !std.mem.eql(u8, sh.sha256, &hex)) return error.LivingShardChanged; + const v = try decode(arena, bytes); + if (v.ranks != sh.ranks) return error.LivingRanks; + if (!std.mem.eql(u8, v.base_sha, base_sha) or !std.mem.eql(u8, sh.base_sha, base_sha)) return error.LivingBaseMismatch; + v.aF32(got.a[got.ranks * in ..]); + v.bF32(got.b[got.ranks * out ..]); + got.ranks += v.ranks; + got.shards += 1; + h.update(&d); + } + h.final(&got.digest); + return got; +} + +/// rows [0, ranks) of a/b as a new append-only shard `living-NNNN.safetensors`, then the index (atomic rename). A v1 +/// file with no index becomes entry 0001 first. Returns the new shard's file name (in `gpa`, caller frees). +pub fn appendShard(gpa: Allocator, dir: []const u8, a: []const f32, b: []const f32, ranks: usize, topic: []const u8, base_sha: []const u8) ![]u8 { + var arena_state = std.heap.ArenaAllocator.init(gpa); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const old = (try listShards(arena, dir)) orelse &.{}; + var list: std.ArrayList(Shard) = .empty; + for (old) |sh| { + var e = sh; + if (e.sha256.len == 0) { // the v1 file joining the index: its hash recorded now + const bytes = (try readFile(arena, try std.fs.path.join(arena, &.{ dir, e.file }))).?; + var d: [32]u8 = undefined; + Sha256.hash(bytes, &d, .{}); + e.sha256 = try std.fmt.allocPrint(arena, "{x}", .{d}); + } + try list.append(arena, e); + } + // the next free number (never reuse a dropped shard's file) + var n: usize = list.items.len + 1; + while (true) : (n += 1) { + const name = try std.fmt.allocPrint(arena, "living-{d:0>4}.safetensors", .{n}); + const p = try std.fs.path.joinZ(arena, &.{ dir, name }); + if (std.c.access(p, std.c.F_OK) != 0) break; + } + const name = try std.fmt.allocPrint(gpa, "living-{d:0>4}.safetensors", .{n}); + errdefer gpa.free(name); + const bytes = try encode(gpa, a, b, ranks, base_sha); + defer gpa.free(bytes); + var d: [32]u8 = undefined; + Sha256.hash(bytes, &d, .{}); + try writeAtomic(gpa, try std.fs.path.join(arena, &.{ dir, name }), bytes); + try list.append(arena, .{ .file = name, .ranks = ranks, .created = now(), .topic = topic, .base_sha = base_sha, .sha256 = try std.fmt.allocPrint(arena, "{x}", .{d}) }); + try writeIndex(arena, dir, list.items); + return name; +} + +/// The newest entry dropped from the index (its file stays on disk): the state before that save. Returns the dropped file. +pub fn dropNewest(gpa: Allocator, dir: []const u8) ![]u8 { + var arena_state = std.heap.ArenaAllocator.init(gpa); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const old = (try listShards(arena, dir)) orelse return error.NothingLearned; + const ipath = try std.fs.path.join(arena, &.{ dir, index_name }); + if (try readFile(arena, ipath) == null) return error.LivingNoIndex; // a lone v1 file: no index to drop from + try writeIndex(arena, dir, old[0 .. old.len - 1]); + return gpa.dupe(u8, old[old.len - 1].file); +} + +extern "c" fn time(t: ?*i64) i64; +fn now() i64 { + return time(null); +} + +fn writeIndex(arena: Allocator, dir: []const u8, shards: []const Shard) !void { + var t: std.ArrayList(u8) = .empty; + try t.print(arena, "{{\n \"format\": \"{s}\",\n \"site\": \"{s}\",\n \"shards\": [", .{ format2, site }); + for (shards, 0..) |sh, i| { + try t.print(arena, "{s}\n {{\"file\": \"{s}\", \"site\": \"{s}\", \"ranks\": {d}, \"created\": {d}, \"topic\": ", .{ if (i > 0) "," else "", sh.file, site, sh.ranks, sh.created }); + try t.appendSlice(arena, try std.json.Stringify.valueAlloc(arena, sh.topic, .{})); + try t.print(arena, ", \"base_sha\": \"{s}\", \"sha256\": \"{s}\"}}", .{ sh.base_sha, sh.sha256 }); + } + try t.appendSlice(arena, "\n ]\n}\n"); + try writeAtomic(arena, try std.fs.path.join(arena, &.{ dir, index_name }), t.items); +} + +test "bf16 rounding is nearest-even and survives a round trip" { + try std.testing.expectEqual(@as(u16, 0x3f80), toBf16(1.0)); + try std.testing.expectEqual(@as(u16, 0x3f80), toBf16(@bitCast(@as(u32, 0x3f808000)))); // tie, even stays + try std.testing.expectEqual(@as(u16, 0x3f82), toBf16(@bitCast(@as(u32, 0x3f818000)))); // tie, odd rounds up + try std.testing.expectEqual(@as(u16, 0x3f81), toBf16(@bitCast(@as(u32, 0x3f808001)))); + var v = [_]f32{ 0.1, -3.3, 1e-20, 65504.5 }; + roundSlice(&v); + for (v) |x| try std.testing.expectEqual(x, fromBf16(toBf16(x))); +} + +test "a sidecar encodes and decodes to the same bf16 values, and refuses what breaks the contract" { + const gpa = std.testing.allocator; + var arena_state = std.heap.ArenaAllocator.init(gpa); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const R = 32; + const a = try arena.alloc(f32, R * in); + const b = try arena.alloc(f32, R * out); + var rng = std.Random.DefaultPrng.init(7); + for (a) |*x| x.* = rng.random().floatNorm(f32) * 0.02; + for (b) |*x| x.* = rng.random().floatNorm(f32) * 0.002; + const sha = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + const bytes = try encode(gpa, a, b, R, sha); + defer gpa.free(bytes); + const v = try decode(arena, bytes); + try std.testing.expectEqual(@as(usize, R), v.ranks); + try std.testing.expectEqualStrings(sha, v.base_sha); + const a2 = try arena.alloc(f32, R * in); + v.aF32(a2); + for (a, a2) |x, y| try std.testing.expectEqual(fromBf16(toBf16(x)), y); + const b2 = try arena.alloc(f32, R * out); + v.bF32(b2); + for (b, b2) |x, y| try std.testing.expectEqual(fromBf16(toBf16(x)), y); + // the reference reader's view: a plain safetensors file + const names = try st.parseHeader(arena, bytes[8..][0..std.mem.readInt(u64, bytes[0..8], .little)], bytes.len - 8 - std.mem.readInt(u64, bytes[0..8], .little)); + try std.testing.expectEqual(@as(usize, 2), names.count()); + try std.testing.expectError(error.LivingRanks, encode(gpa, a, b, 8, sha)); + try std.testing.expectError(error.LivingRanks, encode(gpa, a, b, 0, sha)); + const bad = try gpa.dupe(u8, bytes); + defer gpa.free(bad); + const at = std.mem.indexOf(u8, bad, "\"scale\":\"10\"").?; + bad[at + 10] = '9'; + try std.testing.expectError(error.LivingScale, decode(arena, bad)); +} + +test "the site's sha reads the original weight through the index; files write atomically" { + const gpa = std.testing.allocator; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const head = "{\"model.language_model.layers.44.mlp.shared_experts.down_proj.weight\":{\"dtype\":\"U32\",\"shape\":[2,2],\"data_offsets\":[0,16]},\"x\":{\"dtype\":\"U8\",\"shape\":[4],\"data_offsets\":[16,20]}}"; + var shard: [8 + head.len + 20]u8 = undefined; + std.mem.writeInt(u64, shard[0..8], head.len, .little); + @memcpy(shard[8..][0..head.len], head); + for (shard[8 + head.len ..], 0..) |*x, i| x.* = @intCast(i); + try tmp.dir.writeFile(io, .{ .sub_path = "model-00001-of-00001.safetensors", .data = &shard }); + try tmp.dir.writeFile(io, .{ .sub_path = "model.safetensors.index.json", .data = "{\"metadata\":{},\"weight_map\":{\"model.language_model.layers.44.mlp.shared_experts.down_proj.weight\":\"model-00001-of-00001.safetensors\"}}" }); + const dir = try std.fs.path.join(gpa, &.{ ".zig-cache", "tmp", &tmp.sub_path }); + defer gpa.free(dir); + const got = try siteSha(gpa, dir); + var digest: [32]u8 = undefined; + Sha256.hash(shard[8 + head.len ..][0..16], &digest, .{}); + var want: [64]u8 = undefined; + _ = try std.fmt.bufPrint(&want, "{x}", .{digest}); + try std.testing.expectEqualStrings(&want, &got); + const path = try std.fs.path.join(gpa, &.{ dir, file_name }); + defer gpa.free(path); + try std.testing.expect((try readFile(gpa, path)) == null); + try writeAtomic(gpa, path, "abc"); + const back = (try readFile(gpa, path)).?; + defer gpa.free(back); + try std.testing.expectEqualStrings("abc", back); +} + +test "v2 shards: two shards load as one merged shard, the newest dropped is the state before it, topics filter" { + const gpa = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try std.fs.path.join(gpa, &.{ ".zig-cache", "tmp", &tmp.sub_path }); + defer gpa.free(dir); + var arena_state = std.heap.ArenaAllocator.init(gpa); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const R = 32; + const a = try arena.alloc(f32, R * in); + const b = try arena.alloc(f32, R * out); + var rng = std.Random.DefaultPrng.init(3); + for (a) |*x| x.* = rng.random().floatNorm(f32) * 0.01; + for (b) |*x| x.* = rng.random().floatNorm(f32) * 0.01; + const sha = "1111111111111111111111111111111111111111111111111111111111111111"; + try std.testing.expect((try loadAll(arena, dir, sha, null)) == null); + // v1 file first: it becomes shard 0001 when the first v2 shard is appended + const v1 = try encode(gpa, a, b, 16, sha); + defer gpa.free(v1); + try writeAtomic(gpa, try std.fs.path.join(arena, &.{ dir, file_name }), v1); + const one = (try loadAll(arena, dir, sha, null)).?; + try std.testing.expectEqual(@as(usize, 16), one.ranks); + const n2 = try appendShard(gpa, dir, a[16 * in ..], b[16 * out ..], 16, "family", sha); + defer gpa.free(n2); + try std.testing.expectEqualStrings("living-0002.safetensors", n2); + const two = (try loadAll(arena, dir, sha, null)).?; + try std.testing.expectEqual(@as(usize, 2), two.shards); + // == one merged 32-rank shard + const merged = try encode(gpa, a, b, R, sha); + defer gpa.free(merged); + const mv = try decode(arena, merged); + const ma = try arena.alloc(f32, R * in); + const mb = try arena.alloc(f32, R * out); + mv.aF32(ma); + mv.bF32(mb); + try std.testing.expectEqualSlices(f32, ma, two.a); + try std.testing.expectEqualSlices(f32, mb, two.b); + // topics: only "family" → the second shard alone + const fam = (try loadAll(arena, dir, sha, "identity,family")).?; + try std.testing.expectEqual(@as(usize, 16), fam.ranks); + try std.testing.expectEqualSlices(f32, two.a[16 * in ..], fam.a); + // a changed shard file is refused + // drop the newest: back to the v1 state exactly, its file kept + const dropped = try dropNewest(gpa, dir); + defer gpa.free(dropped); + try std.testing.expectEqualStrings("living-0002.safetensors", dropped); + const back = (try loadAll(arena, dir, sha, null)).?; + try std.testing.expectEqual(@as(usize, 16), back.ranks); + try std.testing.expectEqualSlices(f32, one.a, back.a); + try std.testing.expectEqualSlices(f32, one.b, back.b); + try std.testing.expect((try readFile(arena, try std.fs.path.join(arena, &.{ dir, "living-0002.safetensors" }))) != null); + // the next save never reuses the dropped file's number + const n3 = try appendShard(gpa, dir, a[16 * in ..], b[16 * out ..], 16, "", sha); + defer gpa.free(n3); + try std.testing.expectEqualStrings("living-0003.safetensors", n3); + try std.testing.expectError(error.LivingBaseMismatch, loadAll(arena, dir, "2222222222222222222222222222222222222222222222222222222222222222", null)); +} diff --git a/zig/src/core/root.zig b/zig/src/core/root.zig index 92f4eeb367d..6b0083eaccd 100644 --- a/zig/src/core/root.zig +++ b/zig/src/core/root.zig @@ -11,6 +11,7 @@ pub const tokenizer = @import("tokenizer"); // a module of its own, so the nativ pub const ids_json = @import("ids_json.zig"); pub const affine4_host = @import("affine4_host.zig"); pub const shard_edit = @import("shard_edit.zig"); +pub const living_sidecar = @import("living_sidecar.zig"); test { _ = safetensors; @@ -18,6 +19,7 @@ test { _ = shard_edit; _ = exl3_format; _ = @import("exl3_rect_test.zig"); + _ = living_sidecar; _ = checkpoint; _ = direct_io; _ = draft_depth; diff --git a/zig/src/families/glm/engine.zig b/zig/src/families/glm/engine.zig index 0012e089801..583d905779b 100644 --- a/zig/src/families/glm/engine.zig +++ b/zig/src/families/glm/engine.zig @@ -11,6 +11,7 @@ const kernels = @import("kernels.zig"); const ep_mod = @import("ep.zig"); const CopyIndex = @import("../../core/copy_index.zig").CopyIndex; const checks = @import("checks.zig"); +const living_mod = @import("living.zig"); const Ref = wts.Ref; pub const Reason = enum { stop, length, cancelled }; @@ -84,6 +85,8 @@ pub const Engine = struct { fused_route: bool = true, // GLM_ROUTE=0: the Python family's cast, router and top-k launches draft_vocab: u32 = 154880, // GLM_DRAFT_VOCAB: the MTP head drafts from the vocabulary's first this many tokens committed: u64 = 0, // when the last command buffer was committed (mach ticks) + dir: []u8 = &.{}, // the checkpoint folder (a Living Weights save writes its sidecar here) + living: ?*living_mod.Living = null, // Living Weights: the low-rank change after layer 44's shared down /// The checkpoint in `dir`, caches for `cap` tokens; GLM_LAYERS=N: the first N layers only; GLM_EP=settings: half the experts. pub fn load(gpa: std.mem.Allocator, dir: []const u8, cap: u32) !*Engine { @@ -104,6 +107,9 @@ pub const Engine = struct { e.fused_route = if (std.c.getenv("GLM_ROUTE")) |v| v[0] != '0' else true; e.draft_vocab = if (std.c.getenv("GLM_DRAFT_VOCAB")) |v| std.fmt.parseInt(u32, std.mem.span(v), 10) catch 0 else 0; e.committed = 0; + e.living = null; + e.dir = try gpa.dupe(u8, dir); + errdefer gpa.free(e.dir); e.ep = null; e.pr = null; e.trace_last = null; @@ -128,7 +134,7 @@ pub const Engine = struct { e.c = try cfg.parse(gpa, f.bytes[0..f.size]); if (e.draft_vocab == 0 or e.draft_vocab > e.c.vocab) e.draft_vocab = e.c.vocab; e.draft_vocab -= e.draft_vocab % 4; // the head's kernel takes four rows a simdgroup - const model = try modelHash(gpa, dir, f.bytes[0..f.size]); + var model = try modelHash(gpa, dir, f.bytes[0..f.size]); e.model_hash = model; if (std.c.getenv("GLM_LAYERS")) |v| try cfg.subset(&e.c, std.fmt.parseInt(u32, std.mem.span(v), 10) catch return error.BadLayerCount); const link: ?ep_mod.Settings = if (ep_path) |sp| blk: { @@ -177,6 +183,18 @@ pub const Engine = struct { gpa.destroy(e.w); } try e.prepare(); + errdefer if (e.living) |l| l.deinit(); + // Living Weights: a folder's sidecar (or GLM_LW=1, the change in RAM for a learner) attached before the first reply + if (living_mod.present(gpa, dir) or std.c.getenv("GLM_LW") != null) { + const l = try e.livingOn(); + if (try l.loadDir(dir)) { + var h = std.hash.Wyhash.init(model); // the learned folder is another model: peers and kept states key on it + h.update(&l.loaded_sha.?); + model = h.final(); + e.model_hash = model; + std.log.info("glm: Living Weights: {d} committed ranks from {d} shards at layer {d}'s shared-expert down projection", .{ l.committed, l.shards, living_mod.layer }); + } + } if (link) |s| { const rows = e.c.byRows(); var me: ep_mod.Identity = .{ .layers = e.c.layers, .run = e.c.run, .mtp = @intFromBool(e.w.mtp != null), .experts = if (rows) e.c.moe_inter else e.c.experts, .own_lo = if (rows) e.c.inter[0] else e.c.own[0], .own_hi = if (rows) e.c.inter[1] else e.c.own[1], .cap = cap, .model = model }; @@ -222,6 +240,8 @@ pub const Engine = struct { /// The most this Mac may load: 70% of its RAM in GiB, read as GB (the floor's 179 GB on a 256 GiB Mac, the strict reading). pub fn loadLimit() usize { + // GLM_LOAD_LIMIT_GB=N: an explicit limit (a 256 GiB Mac holding Flash alone: 180.6 GB passes the 70% reading) + if (std.c.getenv("GLM_LOAD_LIMIT_GB")) |v| if (std.fmt.parseFloat(f64, std.mem.span(v))) |gb| return @intFromFloat(gb * 1e9) else |_| {}; var mem: u64 = 0; var len: usize = @sizeOf(u64); if (std.c.sysctlbyname("hw.memsize", &mem, &len, null, 0) != 0 or mem == 0) return 0; @@ -258,6 +278,8 @@ pub const Engine = struct { set.deinit(); } if (e.ep) |ep| ep.deinit(gpa); + if (e.living) |l| l.deinit(); + gpa.free(e.dir); e.ep_arena.deinit(); if (e.pr) |*p| p.deinit(); e.arena.deinit(); @@ -271,6 +293,37 @@ pub const Engine = struct { gpa.destroy(e); } + /// The Living Weights change, created (none in use: the stock forward) and attached to layer 44 on first call. + /// Call with nothing of the engine's in flight (between command buffers, e.g. from a learner's begin/step). + pub fn livingOn(e: *Engine) !*living_mod.Living { + if (e.living) |l| return l; + if (e.c.layers != living_mod.layer + 1) return error.LivingNeedsAllLayers; + const m = switch (e.w.layers[living_mod.layer].mlp) { + .moe => |*m| m, + .dense => return error.LivingSiteMissing, + }; + const l = try living_mod.Living.init(e.gpa, e.device); + m.living = l; + e.living = l; + return l; + } + + /// The change on (attached at layer 44) or off (the stock forward) without dropping it: a learner's private forward. + pub fn livingAttach(e: *Engine, on: bool) void { + const l = e.living orelse return; + switch (e.w.layers[living_mod.layer].mlp) { + .moe => |*m| m.living = if (on) l else null, + .dense => {}, + } + } + + /// The committed ranks written to this checkpoint's folder (living_weights.safetensors); the open block stays in RAM. + pub fn livingSave(e: *Engine) !void { + e.sync(); + const l = e.living orelse return error.NothingLearned; + try l.saveDir(e.dir, if (std.c.getenv("LW_TOPIC")) |t| std.mem.span(t) else ""); + } + pub fn hasMtp(e: *const Engine) bool { return e.w.mtp != null; } diff --git a/zig/src/families/glm/living.zig b/zig/src/families/glm/living.zig new file mode 100644 index 00000000000..f45ddc6f028 --- /dev/null +++ b/zig/src/families/glm/living.zig @@ -0,0 +1,305 @@ +//! Living Weights on GLM-5.3-Flash: one low-rank change after layer 44's shared-expert down projection. +//! y += 10 * (x a^T) b with x the projection's input [rows, 2048] and y its bf16 output [rows, 4096], in Nemotron's +//! arithmetic exactly (train.metal's tf_train_lora_in, tf_train_gate, tf_train_lora_out, f32 a and b): a row's sums +//! never depend on the window's other rows, so decode windows, prompt chunks and drafted rounds agree bit for bit. +//! Committed blocks are always on (gate -inf) and bf16-exact in RAM, so a saved and reloaded folder computes the same +//! bits; the open block (the lesson in progress) opens on a row only if its cosine with the block's first direction +//! reaches the block's tau. None in use: nothing is encoded at all, the stock engine's bits. +const std = @import("std"); +const mtl = @import("metal"); +const sources = @import("kernel_sources"); +pub const sidecar = @import("../../core/living_sidecar.zig"); +const wts = @import("weights.zig"); +const Ref = wts.Ref; + +pub const layer: usize = 44; +pub const in: usize = sidecar.in; +pub const out: usize = sidecar.out; +pub const block: usize = sidecar.block; +pub const max_rank: usize = sidecar.max_rank; +pub const max_blocks: usize = max_rank / block; +pub const scale: f32 = sidecar.scale; +/// Nemotron's a_norm squared (adapters.zig): a row's cosine with direction a is (x . a) / sqrt(unit |x|^2). +pub const unit: f32 = 0.577 * 0.577; +/// A gate above any cosine: the block stays shut. +pub const shut: f32 = 2; +/// The most rows one apply takes (a prompt chunk's, prompt.zig max_rows). +pub const max_rows: usize = 4096; + +const opts = mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked; + +pub const Living = struct { + gpa: std.mem.Allocator, + a: mtl.Buffer, // [max_rank, in] f32: every block's input directions + b: mtl.Buffer, // [max_rank, out] f32: every block's outputs (the open block's are what a learner trains) + tau: mtl.Buffer, // [max_blocks] f32: each block's gate (-inf: committed, always on) + xa: mtl.Buffer, // [max_rows, max_rank] f32 scratch: x a^T, closed blocks zeroed + xn: mtl.Buffer, // [max_rows] f32 scratch: |x|^2 + gates: mtl.Buffer, // [max_rows, max_blocks] f32 scratch: which blocks opened on each row + lora_in: mtl.Pipeline, + gate_p: mtl.Pipeline, + lora_out: mtl.Pipeline, + rank: usize = 0, // ranks in use: committed ones, then the open block's 16 if a lesson is open + committed: usize = 0, // always-on ranks (what a save keeps) + saved: usize = 0, // committed ranks already on disk (loaded shards, or saved): a save appends [saved, committed) + shards: usize = 0, // shards loaded + base_sha: [64]u8 = @splat('0'), // the site's original weight's sha256, hex (the folder's, set when known) + loaded_sha: ?[32]u8 = null, // the loaded sidecar file's own sha256 (part of the engine's model hash) + + /// Room for every block, none in use; the three kernels compiled from train.metal (Nemotron's learner's). + pub fn init(gpa: std.mem.Allocator, device: mtl.Device) !*Living { + const l = try gpa.create(Living); + errdefer gpa.destroy(l); + l.* = .{ .gpa = gpa, .a = undefined, .b = undefined, .tau = undefined, .xa = undefined, .xn = undefined, .gates = undefined, .lora_in = undefined, .gate_p = undefined, .lora_out = undefined }; + const sizes = [_]usize{ max_rank * in, max_rank * out, max_blocks, max_rows * max_rank, max_rows, max_rows * max_blocks }; + const fields = [_]*mtl.Buffer{ &l.a, &l.b, &l.tau, &l.xa, &l.xn, &l.gates }; + var got: usize = 0; + errdefer for (fields[0..got]) |f| f.deinit(); + for (fields, sizes) |f, n| { + f.* = try device.buffer(n * 4, opts); + @memset(f.slice(f32, n), 0); + got += 1; + } + @memset(l.tau.slice(f32, max_blocks), shut); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + const lib = try mtl.Library.fromSource(device, sources.train, mtl.CompileOptions.mlx()); + defer lib.deinit(); + l.lora_in = try mtl.Pipeline.init(device, lib, "tf_train_lora_in", false); + errdefer l.lora_in.deinit(); + l.gate_p = try mtl.Pipeline.init(device, lib, "tf_train_gate", false); + errdefer l.gate_p.deinit(); + l.lora_out = try mtl.Pipeline.init(device, lib, "tf_train_lora_out", false); + return l; + } + + pub fn deinit(l: *Living) void { + for ([_]*mtl.Buffer{ &l.a, &l.b, &l.tau, &l.xa, &l.xn, &l.gates }) |f| f.deinit(); + l.lora_in.deinit(); + l.gate_p.deinit(); + l.lora_out.deinit(); + l.gpa.destroy(l); + } + + // ---- views (shared memory: the host reads and writes them between command buffers) ---- + + /// Every block's input directions, [max_rank, in]. + pub fn aRows(l: *const Living) []f32 { + return l.a.slice(f32, max_rank * in); + } + /// Every block's outputs, [max_rank, out]. + pub fn bRows(l: *const Living) []f32 { + return l.b.slice(f32, max_rank * out); + } + /// Block k's gate. + pub fn gate(l: *const Living, k: usize) *f32 { + return &l.tau.slice(f32, max_blocks)[k]; + } + /// Whether a lesson's gated block is open (the last 16 ranks in use). + pub fn isOpen(l: *const Living) bool { + return l.rank > l.committed; + } + /// The open block's first rank (Nemotron's Sites.first). + pub fn first(l: *const Living) usize { + return l.rank - block; + } + /// The open block's outputs [block, out] (the bytes a learner's Adam updates: `b` at first() * out * 4). + pub fn openB(l: *const Living) []f32 { + return l.bRows()[l.first() * out ..][0 .. block * out]; + } + /// The open block's directions [block, in]. + pub fn openA(l: *const Living) []f32 { + return l.aRows()[l.first() * in ..][0 .. block * in]; + } + + // ---- the forward ---- + + /// After the site's projection: y [rows, out] (bf16) += scale (x [rows, in] (bf16) a^T) b, open block gated. + pub fn apply(l: *const Living, e: mtl.ComputeEncoder, x: Ref, y: Ref, rows: u32) void { + if (l.rank == 0 or rows == 0) return; + std.debug.assert(rows <= max_rows and l.rank % block == 0 and l.rank <= max_rank); + const R: u32 = @intCast(l.rank); + e.setPipeline(l.lora_in); + e.setBuffer(x.buf, x.off, 0); + e.setBuffer(l.a, 0, 1); + e.setBuffer(l.xa, 0, 2); + e.setValue([4]u32{ rows, @intCast(in), R, 0 }, 3); + e.setBuffer(l.xn, 0, 4); + e.dispatchThreads(mtl.Size.of(32 * R, rows, 1), mtl.Size.of(256, 1, 1)); + e.setPipeline(l.gate_p); + e.setBuffer(l.xa, 0, 0); + e.setBuffer(l.xn, 0, 1); + e.setBuffer(l.tau, 0, 2); + e.setBuffer(l.gates, 0, 3); + e.setValue([4]u32{ rows, R, R / 16, 0 }, 4); + e.setValue(unit, 5); + e.dispatchThreads(mtl.Size.of(R / 16, rows, 1), mtl.Size.of(R / 16, 1, 1)); + e.setPipeline(l.lora_out); + e.setBuffer(l.xa, 0, 0); + e.setBuffer(l.b, 0, 1); + e.setBuffer(y.buf, y.off, 2); + e.setValue([4]u32{ rows, @intCast(out), R, 0 }, 3); + e.setValue(scale, 4); + e.dispatchThreads(mtl.Size.of(out, rows, 1), mtl.Size.of(256, 1, 1)); + } + + // ---- the learner's runtime API (call between command buffers: nothing of the engine's in flight) ---- + + /// A new gated block after the committed ones: directions `dirs` [block, in] (taken as given), gate `tau`, b zero. + pub fn openBlock(l: *Living, dirs: []const f32, tau: f32) !void { + if (l.isOpen()) return error.LivingBlockOpen; + if (l.rank + block > max_rank) return error.LearnedChangeFull; + if (dirs.len != block * in) return error.LivingShape; + const at = l.rank; + @memcpy(l.aRows()[at * in ..][0 .. block * in], dirs); + @memset(l.bRows()[at * out ..][0 .. block * out], 0); + l.gate(at / block).* = tau; + l.rank += block; + } + + /// The open block's gate (a learner's tau = max keep cosine + 0.02, or -inf for a plain change before commit). + pub fn setOpenTau(l: *Living, tau: f32) void { + std.debug.assert(l.isOpen()); + l.gate(l.first() / block).* = tau; + } + + /// The open block made a committed, always-on change: gate -inf, its a and b rounded to bf16 (what a save keeps). + pub fn commitOpen(l: *Living) void { + std.debug.assert(l.isOpen()); + sidecar.roundSlice(l.openA()); + sidecar.roundSlice(l.openB()); + l.gate(l.first() / block).* = -std.math.inf(f32); + l.committed = l.rank; + } + + /// The open block taken back out (its lesson left nothing): rank back to the committed ones. + pub fn closeOpen(l: *Living) void { + if (!l.isOpen()) return; + const at = l.first(); + @memset(l.aRows()[at * in ..][0 .. block * in], 0); + @memset(l.bRows()[at * out ..][0 .. block * out], 0); + l.gate(at / block).* = shut; + l.rank = l.committed; + } + + /// Committed ranks appended as given (rounded to bf16), after any committed ones; refused while a block is open. + pub fn appendCommitted(l: *Living, a: []const f32, b: []const f32, n: usize) !void { + if (l.isOpen()) return error.LivingBlockOpen; + if (n == 0 or n % block != 0 or l.rank + n > max_rank) return error.LivingRanks; + if (a.len < n * in or b.len < n * out) return error.LivingShape; + const at = l.rank; + const da = l.aRows()[at * in ..][0 .. n * in]; + const db = l.bRows()[at * out ..][0 .. n * out]; + @memcpy(da, a[0 .. n * in]); + @memcpy(db, b[0 .. n * out]); + sidecar.roundSlice(da); + sidecar.roundSlice(db); + for (at / block..(at + n) / block) |k| l.gate(k).* = -std.math.inf(f32); + l.rank += n; + l.committed = l.rank; + } + + /// Every block dropped: the stock forward again. + pub fn clear(l: *Living) void { + @memset(l.aRows(), 0); + @memset(l.bRows(), 0); + @memset(l.tau.slice(f32, max_blocks), shut); + l.rank = 0; + l.committed = 0; + l.saved = 0; + l.shards = 0; + } + + // ---- the sidecar ---- + + /// The folder's change: every shard listed in living_weights.index.json summed in order (v2), or the lone v1 + /// living_weights.safetensors; LW_TOPICS=a,b keeps only shards of those topics. False: none, nothing changed. + /// Every shard's base_sha must match the folder's site weight, and its sha256 the index's. + pub fn loadDir(l: *Living, dir: []const u8) !bool { + var arena = std.heap.ArenaAllocator.init(l.gpa); + defer arena.deinit(); + if ((try sidecar.listShards(arena.allocator(), dir)) == null) return false; + l.base_sha = try sidecar.siteSha(l.gpa, dir); + const allow: ?[]const u8 = if (std.c.getenv("LW_TOPICS")) |v| std.mem.span(v) else null; + const got = (sidecar.loadAll(arena.allocator(), dir, &l.base_sha, allow) catch |err| { + if (err == error.LivingBaseMismatch) std.log.err("glm: {s}: a Living Weights shard was learned on another checkpoint (this folder's site {s})", .{ dir, &l.base_sha }); + return err; + }) orelse return false; + l.clear(); + if (got.ranks == 0) return false; + @memcpy(l.aRows()[0 .. got.ranks * in], got.a); + @memcpy(l.bRows()[0 .. got.ranks * out], got.b); + for (0..got.ranks / block) |k| l.gate(k).* = -std.math.inf(f32); + l.rank = got.ranks; + l.committed = got.ranks; + l.saved = got.ranks; + l.shards = got.shards; + l.loaded_sha = got.digest; + return true; + } + + /// The committed ranks not yet on disk appended as a new shard (living-NNNN.safetensors + the index, atomic); + /// earlier shards are never touched. `topic` names the shard ("" none). An open block is not kept. + pub fn saveDir(l: *Living, dir: []const u8, topic: []const u8) !void { + if (l.committed <= l.saved) return error.NothingLearned; + l.base_sha = try sidecar.siteSha(l.gpa, dir); + const n = l.committed - l.saved; + const name = try sidecar.appendShard(l.gpa, dir, l.aRows()[l.saved * in ..], l.bRows()[l.saved * out ..], n, topic, &l.base_sha); + defer l.gpa.free(name); + std.log.info("glm: Living Weights: {d} ranks saved as {s}/{s}", .{ n, dir, name }); + l.saved = l.committed; + l.shards += 1; + } +}; + +/// `ranks` NEW committed rows (a [ranks, in], b [ranks, out], f32, rounded to bf16 in the file) appended to +/// `dir` as a new shard (v2: living-NNNN.safetensors + living_weights.index.json, atomic; old shards untouched). +/// Returns the shard's file name (caller frees). Round your RAM rows with `sidecar.roundSlice` so RAM == reload. +pub fn saveRows(gpa: std.mem.Allocator, dir: []const u8, a: []const f32, b: []const f32, ranks: usize, topic: []const u8) ![]u8 { + const sha = try sidecar.siteSha(gpa, dir); + return sidecar.appendShard(gpa, dir, a, b, ranks, topic, &sha); +} + +/// `saveRows`, returning the new shard's bytes written (the learner's save). +pub fn spawnShard(gpa: std.mem.Allocator, dir: []const u8, a: []const f32, b: []const f32, n: usize, topic: []const u8) !usize { + const name = try saveRows(gpa, dir, a, b, n, topic); + defer gpa.free(name); + const path = try std.fs.path.join(gpa, &.{ dir, name }); + defer gpa.free(path); + const bytes = (try sidecar.readFile(gpa, path)) orelse return error.LivingWrite; + defer gpa.free(bytes); + return bytes.len; +} + +/// True when `dir` holds a sidecar (the engine then creates the change at load). +pub fn present(gpa: std.mem.Allocator, dir: []const u8) bool { + for ([_][]const u8{ sidecar.index_name, sidecar.file_name }) |f| { + const path = std.fs.path.joinZ(gpa, &.{ dir, f }) catch return false; + defer gpa.free(path); + if (std.c.access(path, std.c.F_OK) == 0) return true; + } + return false; +} + +/// The host reference of `apply` for one row: y + scale (x a^T) b in f32, NOT rounded to bf16 (the kernels' formula; +/// summation order differs, so compare the GPU's bf16 with one bf16 step at the value's size). +pub fn reference(a: []const f32, b: []const f32, tau: []const f32, rank: usize, x: []const f32, y: []f32) void { + var xa: [max_rank]f32 = undefined; + var xn: f32 = 0; + for (x) |v| xn += v * v; + for (0..rank) |q| { + var s: f32 = 0; + for (x, a[q * in ..][0..in]) |v, w| s += v * w; + xa[q] = s; + } + for (0..rank / block) |k| { + const n = unit * xn; + const open = n > 0 and xa[k * block] >= tau[k] * @sqrt(n); + if (!open) @memset(xa[k * block ..][0..block], 0); + } + for (y, 0..) |*yv, j| { + var s: f32 = 0; + for (0..rank) |q| s += xa[q] * b[q * out + j]; + yv.* = yv.* + scale * s; + } +} diff --git a/zig/src/families/glm/moe.zig b/zig/src/families/glm/moe.zig index 191ee3690cf..8564be57670 100644 --- a/zig/src/families/glm/moe.zig +++ b/zig/src/families/glm/moe.zig @@ -103,6 +103,7 @@ fn experts(x: *const Ctx, e: mtl.ComputeEncoder, w: *const wts.Moe, x_in: Ref, r shape(e, 1, .{ rows, slots, N }); bind(e, 2, .{ w.down.w, w.down.s, w.down.b, w.sh_down.w, w.sh_down.s, w.sh_down.b, group[0], group[1], group[2], if (part == 1) sc.ys else sc.ye }); e.dispatchThreads(size(32 * rows, D / 4, zs), size(32 * rows, 1, 1)); + if (part == 1) if (w.living) |lw| lw.apply(e, act, sc.ys, rows); // Living Weights after the shared expert's down } /// By rows: every routed pick's half (this Mac's intermediate rows), down's fp32 partials into `yp`. diff --git a/zig/src/families/glm/prompt.zig b/zig/src/families/glm/prompt.zig index 42e9f1d879d..905ba36c748 100644 --- a/zig/src/families/glm/prompt.zig +++ b/zig/src/families/glm/prompt.zig @@ -204,6 +204,7 @@ fn shared(p: *const Prompt, x: *const fwd.Ctx, e: mtl.ComputeEncoder, w: *const qmm(p, e, x_in, w.sh_gate_up, p.sgu, M); swiglu(x, e, p.sgu, p.sact, M, x.c.moe_inter); qmm(p, e, p.sact, w.sh_down, p.ys, M); + if (w.living) |lw| lw.apply(e, p.sact, p.ys, M); // Living Weights after the shared expert's down, as the decode's } /// The MoE block on M rows: shared expert, route, experts gathered by expert; by rows, this Mac's halves summed in slot order and swapped. diff --git a/zig/src/families/glm/weights.zig b/zig/src/families/glm/weights.zig index 4b6e0e7be5d..2139f7c02b0 100644 --- a/zig/src/families/glm/weights.zig +++ b/zig/src/families/glm/weights.zig @@ -42,7 +42,16 @@ pub const Mla = struct { x_proj: Q4, qr_proj: Q4, kv_b: Q4, o_proj: Q4, q_norm: pub const Dense = struct { gate_up: Q4, down: Q4 }; -pub const Moe = struct { router: Ref, bias: Ref, gate: Q4, up: Q4, down: Q4, sh_gate_up: Q4, sh_down: Q4 }; +pub const Moe = struct { + router: Ref, + bias: Ref, + gate: Q4, + up: Q4, + down: Q4, + sh_gate_up: Q4, + sh_down: Q4, + living: ?*const @import("living.zig").Living = null, // Living Weights: the change after sh_down (layer 44 only) +}; pub const Layer = struct { hc: ?[2]Hc, // attention's and the MLP's hyper-connections (none on the MTP layer) @@ -119,6 +128,11 @@ const Loader = struct { x.deinit(); return err; }; + // GLM_MLOCK=1: each weights buffer wired as it is made, so macOS never compresses the weights during a long load + // (a 256 GiB Mac with little swap kills the process holding >50% of compressed memory: "low-swap") + if (b) |x| if (std.c.getenv("GLM_MLOCK") != null) { + if (std.c.mlock(@ptrCast(@alignCast(x.contents())), @max(len, 16)) != 0) std.log.warn("glm: GLM_MLOCK: mlock of {d} bytes failed", .{len}); + }; l.cur = b; l.cur_len = len; l.cur_at = 0; From 062f8ca3c5ee0808912811fbc8853db0de070acb Mon Sep 17 00:00:00 2001 From: indexer-bf16 Date: Fri, 9 Oct 2026 21:01:08 -0500 Subject: [PATCH 2/3] GLM-5.3-Flash Living Weights: the --slide learner, Nemotron's slide machinery over the one GLM site The lane host's learn hook (glm_slide.zig) attached in glm_host as Nemotron's is in metal.zig. The learner reuses Sliding Weights' lesson, subspace choice, gate, gated rounds, commit, mining and guard (nemotron/choice.zig and subspace.zig unchanged), generic over its trainer. The Metal trainer caches one GPU capture per example (everything before layer 44's MLP is independent of the change) and runs the tail past the site and its backward to b on the CPU, exact through the last hyper-connection. Saves spawn a new shard holding only the new ranks. A chat template that closes no assistant turn (GLM-5.3) now ends each lesson's answer with the next turn's first token, so learned answers stop. --slide with --speed-up is refused. zig build test-lw: the CPU tail and its gradient against finite differences, the learner's state machine end to end on a host toy model, save rounding and undo; no GPU. Co-Authored-By: Claude Opus 5.5 --- build.zig | 10 + zig/src/families/glm/glm.zig | 3 + zig/src/families/glm/lw_learner.zig | 610 +++++++++++++++++++++++ zig/src/families/glm/lw_math.zig | 718 ++++++++++++++++++++++++++++ zig/src/families/glm/lw_sites.zig | 217 +++++++++ zig/src/families/glm/lw_train.zig | 316 ++++++++++++ zig/src/lw_glm_tests.zig | 6 + zig/src/native/glm_host.zig | 21 +- zig/src/native/glm_slide.zig | 64 +++ zig/src/native/metal.zig | 2 +- zig/src/server/slide_lesson.zig | 21 +- 11 files changed, 1985 insertions(+), 3 deletions(-) create mode 100644 zig/src/families/glm/lw_learner.zig create mode 100644 zig/src/families/glm/lw_math.zig create mode 100644 zig/src/families/glm/lw_sites.zig create mode 100644 zig/src/families/glm/lw_train.zig create mode 100644 zig/src/lw_glm_tests.zig create mode 100644 zig/src/native/glm_slide.zig diff --git a/build.zig b/build.zig index 94dbbd10950..048cc28f209 100644 --- a/build.zig +++ b/build.zig @@ -139,6 +139,16 @@ pub fn build(b: *std.Build) void { const cost_run = b.addRunArtifact(cost_cases); b.step("test-cost-rule", "CPU scripted window and interleaved head timing").dependOn(&cost_run.step); test_step.dependOn(&cost_run.step); + // Living Weights on GLM-5.3-Flash: the learner's host math (no GPU), on every OS + const lw_cases = b.addTest(.{ .root_module = b.createModule(.{ + .root_source_file = b.path("zig/src/lw_glm_tests.zig"), + .target = target, + .optimize = .Debug, + .link_libc = true, + }) }); + const lw_run = b.addRunArtifact(lw_cases); + b.step("test-lw", "Living Weights (GLM-5.3-Flash): host math and learner logic, no GPU").dependOn(&lw_run.step); + test_step.dependOn(&lw_run.step); switch (target.result.os.tag) { .macos => metalTargets(b, target, optimize, draft_ids, build_options, test_step), .linux => cuda_build.targets(b, target, optimize, draft_ids, build_options), diff --git a/zig/src/families/glm/glm.zig b/zig/src/families/glm/glm.zig index 2aad94c150c..9cebf840313 100644 --- a/zig/src/families/glm/glm.zig +++ b/zig/src/families/glm/glm.zig @@ -11,6 +11,9 @@ pub const ep = @import("ep.zig"); pub const slots = @import("slots.zig"); pub const backend = @import("backend.zig"); pub const mirror = @import("mirror.zig"); +pub const living = @import("living.zig"); +pub const lw_learner = @import("lw_learner.zig"); +pub const lw_train = @import("lw_train.zig"); test { _ = config; diff --git a/zig/src/families/glm/lw_learner.zig b/zig/src/families/glm/lw_learner.zig new file mode 100644 index 00000000000..a9061755dcf --- /dev/null +++ b/zig/src/families/glm/lw_learner.zig @@ -0,0 +1,610 @@ +//! GLM-5.3-Flash's Sliding Weights learner: Nemotron's state machine (families/nemotron/slide.zig) over one site, +//! layers.44's shared-expert down_proj. Generic over its trainer, so the machine is tested on the host with a fake one. +const std = @import("std"); +const lm = @import("lw_math.zig"); +const lw_sites = @import("lw_sites.zig"); +const choice = @import("../nemotron/choice.zig"); + +pub const block = lm.block; +pub const max_rank = lm.max_rank; +pub const candidates = lm.candidates; + +/// Rows a step reads at most (Nemotron's train.max_rows). +pub const max_rows = 256; + +/// A step's loss alone, with the open block's gradient, or with that and Adam; or the site's inputs sketched or projected. +pub const Mode = enum { loss, grad, learn, avoid, seek, project }; + +/// Token ids whose answer starts at `start`: the rows from start - 1 on predict it. +pub const Example = struct { ids: []const u32, start: u32 }; + +pub const Lesson = struct { + train: []const Example = &.{}, + held: []const Example = &.{}, + near: []const Example = &.{}, + keep: []const Example = &.{}, + undo: bool = false, + steps: u32 = max_steps, + more: bool = false, + commit: bool = false, + save: bool = false, +}; + +pub const Report = union(enum) { + learned: struct { recalled: bool, steps: u32, loss: f32 }, + failed: []const u8, +}; + +pub const Step = struct { done: bool, changed: bool = false, report: ?Report = null }; + +const max_steps = 400; +const check_every = 20; +const plain_steps = 60; +const replay_cap = 64; +const gate_margin: f32 = 0.02; +const hold: f64 = 1; + +const Phase = enum { idle, build, steps, undo, commit, save }; +const Turn = struct { ex: Example, fact: bool, last: bool }; + +/// The learner over trainer type T, which provides: `init(gpa, T.Ctx) !*T`, `deinit(gpa)`, fields `sites: lw_sites.Sites` +/// and `sketched: usize`, `step(ids, start, Mode) !lm.Result`, `projected(k, rows) []const f32`, `attach(on)`, `write(ranks) !usize`. +pub fn Learner(comptime T: type) type { + return struct { + const L = @This(); + + gpa: std.mem.Allocator, + ctx: T.Ctx, + trainer: ?*T = null, + lesson: Lesson = .{}, + phase: Phase = .idle, + plan: std.ArrayList(Turn) = .empty, + at: usize = 0, + taken: u32 = 0, + loss: f32 = 0, + replay: std.ArrayList(Example) = .empty, + last: []Example = &.{}, + kept_rounds: u32 = 0, + opened: bool = false, + built: usize = 0, + choice: ?choice.Choice = null, + answers: u32 = 0, + can_undo: bool = false, + plain: bool = false, + rounds: u64 = 0, + + pub fn init(gpa: std.mem.Allocator, ctx: T.Ctx) L { + return .{ .gpa = gpa, .ctx = ctx }; + } + + pub fn deinit(l: *L) void { + if (l.trainer) |t| t.deinit(l.gpa); + if (l.choice) |*c| c.deinit(); + l.plan.deinit(l.gpa); + disown(l.gpa, l.last); + for (l.replay.items) |ex| l.gpa.free(ex.ids); + l.replay.deinit(l.gpa); + } + + /// The trainer, made on the first lesson (it takes over a learned folder's committed blocks then). + pub fn ensure(l: *L) !*T { + if (l.trainer == null) { + l.choice = try choice.Choice.init(l.gpa, 1); + errdefer { + l.choice.?.deinit(); + l.choice = null; + } + l.trainer = try T.init(l.gpa, l.ctx); + } + return l.trainer.?; + } + + pub fn begin(l: *L, lesson: Lesson) !void { + std.debug.assert(l.phase == .idle); + l.lesson = lesson; + if (lesson.undo) { + l.phase = .undo; + return; + } + if (lesson.commit or lesson.save) { + l.phase = if (lesson.save) .save else .commit; + return; + } + if (lesson.train.len == 0) return; + for ([_][]const Example{ lesson.train, lesson.held, lesson.near, lesson.keep }) |xs| for (xs) |ex| { + if (ex.start < 1 or ex.start >= ex.ids.len or ex.ids.len - 1 > max_rows) return error.ExampleTooLong; + }; + const t = try l.ensure(); + if (lesson.more) { + if (!l.opened) return error.NothingToContinue; + return l.start(); + } + try l.settleLast(lesson.train); + if (t.sites.rank + block > max_rank) return error.LearnedChangeFull; + t.sites.clear(); + t.sketched = 0; + l.built = 0; + l.phase = .build; + } + + fn start(l: *L) !void { + const steps = @max(@min(l.lesson.steps, max_steps), 1); + if (l.plain) try l.schedulePlain(steps) else try l.schedule(steps); + l.trainer.?.sites.keep(); + l.can_undo = true; + l.at = 0; + l.taken = 0; + l.loss = 0; + l.phase = .steps; + } + + pub fn abort(l: *L) void { + l.phase = .idle; + } + + pub fn step(l: *L) Step { + return l.advance() catch |e| { + if (l.phase == .steps) l.trainer.?.sites.restore(); + l.phase = .idle; + return .{ .done = true, .changed = true, .report = .{ .failed = @errorName(e) } }; + }; + } + + fn advance(l: *L) !Step { + switch (l.phase) { + .idle => return .{ .done = true }, + .undo => { + l.phase = .idle; + const t = l.trainer orelse return .{ .done = true }; + if (l.plain) { + t.sites.close(); + t.attach(true); + l.plain = false; + l.opened = false; + l.kept_rounds = 0; + return .{ .done = true, .changed = true }; + } + if (!l.can_undo) return .{ .done = true }; + t.sites.restore(); + l.can_undo = false; + l.kept_rounds -|= 1; + return .{ .done = true, .changed = true }; + }, + .build => return l.buildOnce(), + .steps => return l.stepOnce(), + .commit => return l.commitOnce(), + .save => return l.saveOnce(), + } + } + + /// Every kept lesson's block into the model folder's sidecar (a still-gated open block stays out). + fn saveOnce(l: *L) !Step { + l.phase = .idle; + const t = l.trainer orelse return .{ .done = true }; + const ranks = t.sites.rank - @as(usize, if (l.opened and !l.plain) block else 0); + if (ranks == 0) return .{ .done = true }; + const bytes = try t.write(ranks); + t.sites.roundSaved(ranks); // what the sidecar holds, so this server and a reload of the folder agree + std.log.info("slide: {d} lessons written into the model folder's living weights ({d} KB)", .{ ranks / block, bytes >> 10 }); + return .{ .done = true, .changed = true }; + } + + fn commitOnce(l: *L) !Step { + l.phase = .idle; + if (!l.opened or l.kept_rounds == 0) return .{ .done = true }; + const t = l.trainer.?; + const c = &l.choice.?; + for (0..t.sites.list.len) |k| try c.refit(k, hold); + t.sites.plain(c.coef); + t.attach(true); + l.plain = true; + std.log.info("slide: lesson {d} is now a plain weight change; it learns on beside the answers it must keep", .{t.sites.first() / block + 1}); + try l.schedulePlain(plain_steps); + t.sites.keep(); + l.can_undo = false; + l.at = 0; + l.taken = 0; + l.loss = 0; + l.phase = .steps; + return .{ .done = false, .changed = true }; + } + + fn buildOnce(l: *L) !Step { + const t = l.trainer.?; + const c = &l.choice.?; + const facts = l.lesson.train; + const stay = [_][]const Example{ l.lesson.keep, l.lesson.near, l.replay.items }; + const steady = l.lesson.keep.len + l.lesson.near.len + l.replay.items.len; + var i = l.built; + l.built += 1; + if (i < steady) return l.sketch(pick(&stay, i), .avoid); + i -= steady; + if (i < facts.len) return l.sketch(facts[i], .seek); + i -= facts.len; + if (i == 0) { + t.sites.frame(); + c.reset(); + l.answers = 0; + } + if (i < steady) { + const ex = pick(&stay, i); + _ = try t.step(ex.ids, ex.start, .project); + for (0..t.sites.list.len) |k| try c.add(k, t.projected(k, ex.ids.len - 1), false, ex.start - 1, true); + return .{ .done = false }; + } + i -= steady; + if (i < facts.len) { + const ex = facts[i]; + _ = try t.step(ex.ids, ex.start, .project); + l.answers += @intCast(ex.ids.len - ex.start); + try c.head(); + for (0..t.sites.list.len) |k| try c.add(k, t.projected(k, ex.ids.len - 1)[(ex.start - 1) * candidates ..], true, 0, false); + return .{ .done = false }; + } + try c.choose(gate_margin); + try t.sites.open(c.coef); + t.attach(true); + l.opened = true; + l.gate(); + try l.start(); + return .{ .done = false, .changed = true }; + } + + fn sketch(l: *L, ex: Example, mode: Mode) !Step { + _ = try l.trainer.?.step(ex.ids, ex.start, mode); + return .{ .done = false }; + } + + fn gate(l: *L) void { + const sites = &l.trainer.?.sites; + const c = &l.choice.?; + const k = sites.first() / block; + for (sites.list, c.tau, c.hits, c.opens) |*site, tau, hits, opens| { + site.gate(k).* = tau; + std.log.info("slide: block {d} at layers.44 shared down_proj: gate {d:.3}, {s}, on {d} of the fact's {d} answer rows; first rows {d} of {d}", .{ k + 1, tau, if (hits > 0) "open" else "shut", hits, l.answers, opens, c.heads.items.len }); + } + } + + fn stepOnce(l: *L) !Step { + const t = l.trainer.?; + const turn = l.plan.items[l.at]; + const got = try t.step(turn.ex.ids, turn.ex.start, if (turn.last) .learn else .grad); + if (!std.math.isFinite(got.loss)) return error.NonfiniteStep; + l.at += 1; + if (turn.fact) l.loss += got.loss; + if (!turn.last) return .{ .done = false }; + l.taken += 1; + const end = l.at == l.plan.items.len; + if (l.plain and !end) return .{ .done = false, .changed = true }; + const back = (l.taken % check_every == 0 or end) and try l.recalled(); + if (!back and !end) return .{ .done = false, .changed = true }; + l.phase = .idle; + l.kept_rounds += 1; + const loss = l.loss / @as(f32, @floatFromInt(l.taken)); + return .{ .done = true, .changed = true, .report = .{ .learned = .{ .recalled = back, .steps = l.taken, .loss = loss } } }; + } + + fn recalled(l: *L) !bool { + if (l.lesson.held.len == 0) return false; + for (l.lesson.held) |ex| if (!(try l.trainer.?.step(ex.ids, ex.start, .loss)).recalled) return false; + return true; + } + + fn settleLast(l: *L, answers: []const Example) !void { + const now = try own(l.gpa, answers); + if (l.opened and l.kept_rounds == 0) { + l.trainer.?.sites.close(); + l.trainer.?.attach(true); + } + l.opened = false; + l.plain = false; + if (l.kept_rounds > 0) { + for (l.last) |ex| { + if (l.replay.items.len == replay_cap) l.gpa.free(l.replay.orderedRemove(0).ids); + try l.replay.append(l.gpa, ex); + } + l.gpa.free(l.last); + } else disown(l.gpa, l.last); + l.last = now; + l.kept_rounds = 0; + } + + fn schedulePlain(l: *L, steps: u32) !void { + l.rounds += 1; + var prng = std.Random.DefaultPrng.init(l.rounds); + var facts: Deck = try .init(l.gpa, &.{l.lesson.train}); + defer facts.deinit(l.gpa); + var steady: Deck = try .init(l.gpa, &.{ l.lesson.keep, l.lesson.near, l.lesson.near, l.replay.items }); + defer steady.deinit(l.gpa); + l.plan.clearRetainingCapacity(); + for (0..steps) |_| { + const alone = steady.cards.len == 0; + try l.plan.append(l.gpa, .{ .ex = facts.draw(prng.random()), .fact = true, .last = alone }); + if (!alone) try l.plan.append(l.gpa, .{ .ex = steady.draw(prng.random()), .fact = false, .last = false }); + if (!alone) try l.plan.append(l.gpa, .{ .ex = steady.draw(prng.random()), .fact = false, .last = true }); + } + } + + fn schedule(l: *L, steps: u32) !void { + l.rounds += 1; + var prng = std.Random.DefaultPrng.init(l.rounds); + var facts: Deck = try .init(l.gpa, &.{l.lesson.train}); + defer facts.deinit(l.gpa); + l.plan.clearRetainingCapacity(); + for (0..steps) |_| try l.plan.append(l.gpa, .{ .ex = facts.draw(prng.random()), .fact = true, .last = true }); + } + }; +} + +fn pick(lists: []const []const Example, i: usize) Example { + var at = i; + for (lists) |xs| { + if (at < xs.len) return xs[at]; + at -= xs.len; + } + unreachable; +} + +const Deck = struct { + cards: []Example, + next: usize, + + fn init(gpa: std.mem.Allocator, parts: []const []const Example) !Deck { + var n: usize = 0; + for (parts) |p| n += p.len; + const cards = try gpa.alloc(Example, n); + var at: usize = 0; + for (parts) |p| { + @memcpy(cards[at..][0..p.len], p); + at += p.len; + } + return .{ .cards = cards, .next = n }; + } + + fn deinit(d: *Deck, gpa: std.mem.Allocator) void { + gpa.free(d.cards); + } + + fn draw(d: *Deck, r: std.Random) Example { + if (d.next == d.cards.len) { + r.shuffle(Example, d.cards); + d.next = 0; + } + d.next += 1; + return d.cards[d.next - 1]; + } +}; + +fn own(gpa: std.mem.Allocator, xs: []const Example) ![]Example { + const out = try gpa.alloc(Example, xs.len); + var made: usize = 0; + errdefer { + for (out[0..made]) |x| gpa.free(x.ids); + gpa.free(out); + } + for (xs, out) |x, *o| { + o.* = .{ .ids = try gpa.dupe(u32, x.ids), .start = x.start }; + made += 1; + } + return out; +} + +fn disown(gpa: std.mem.Allocator, xs: []Example) void { + for (xs) |x| gpa.free(x.ids); + gpa.free(xs); +} + +// ================================================================ a host-only trainer: the whole learner, no GPU + +/// A trainer over the real CPU tail (lw_math.step) with a toy model: each example's "capture" is a fixed function of its +/// ids (site rows = token embeddings, the tail's fixed parts random), so learning, gates, undo and commit run for real. +pub const HostTrainer = struct { + pub const Ctx = *const HostModel; + model: *const HostModel, + sites: lw_sites.Sites, + sketched: usize = 0, + proj: []f32, + tmp: []f32, + a: []f32, + b: []f32, + tau: []f32, + attached: bool = false, + saved: usize = 0, + + pub fn init(gpa: std.mem.Allocator, m: *const HostModel) !*HostTrainer { + const t = try gpa.create(HostTrainer); + errdefer gpa.destroy(t); + t.* = .{ .model = m, .sites = undefined, .proj = try gpa.alloc(f32, max_rows * candidates), .tmp = try gpa.alloc(f32, m.in), .a = try gpa.alloc(f32, max_rank * m.in), .b = try gpa.alloc(f32, max_rank * m.d), .tau = try gpa.alloc(f32, lm.max_blocks) }; + t.sites = try lw_sites.Sites.init(gpa, m.in, m.d, .{ .a = t.a, .b = t.b, .tau = t.tau }); + return t; + } + + pub fn deinit(t: *HostTrainer, gpa: std.mem.Allocator) void { + t.sites.deinit(); + inline for (.{ "proj", "tmp", "a", "b", "tau" }) |f| gpa.free(@field(t, f)); + gpa.destroy(t); + } + + pub fn attach(t: *HostTrainer, on: bool) void { + t.attached = on and t.sites.rank > 0; + } + + pub fn write(t: *HostTrainer, ranks: usize) !usize { + t.saved = ranks; + return ranks * (t.model.in + t.model.d) * 2; + } + + pub fn projected(t: *const HostTrainer, k: usize, rows: usize) []const f32 { + _ = k; + return t.proj[0 .. rows * candidates]; + } + + pub fn step(t: *HostTrainer, ids: []const u32, start: usize, mode: Mode) !lm.Result { + const gpa = t.model.gpa; + var cap = try t.model.capture(ids, start); + defer cap.free(gpa); + const site = &t.sites.list[0]; + switch (mode) { + .avoid, .seek => { + const y = if (mode == .avoid) site.avoid else site.seek; + const k: usize = if (mode == .avoid) lm.avoid_dims else candidates; + const seed: u32 = if (mode == .avoid) 1 else 2; + const first = start - 1; + lm.sketch(cap.site, y, cap.rows, site.in, k, @intCast(t.sketched), seed, 1); + lm.sketch(cap.site[first * site.in ..], y, 1, site.in, k, @intCast((1 << 30) + t.sketched + first), seed, @floatFromInt(cap.rows - first)); + t.sketched += cap.rows; + return .{ .loss = 0, .recalled = false }; + }, + .project => { + lm.projectRows(cap.site, site.seek, t.proj, cap.rows, site.in, candidates, t.tmp); + return .{ .loss = 0, .recalled = false }; + }, + .loss => return lm.step(gpa, t.model.tail(), &cap, t.sites.lora(), null, 0), + .grad, .learn => { + if (t.sites.rank == 0) return error.NoOpenBlock; + const r = try lm.step(gpa, t.model.tail(), &cap, t.sites.lora(), site.gb, t.sites.first()); + if (mode == .learn) t.sites.adam(); + return r; + }, + } + } +}; + +/// The toy model behind HostTrainer: an embedding as the site's input, a random tail. +pub const HostModel = struct { + gpa: std.mem.Allocator, + in: usize = 32, + d: usize = 64, + vocab: usize = 48, + emb: []f32, // [vocab, in] + mix: []f32, // [in, d]: the routed + shared part of the branch, a fixed function of the site row + w: []u32, + s: []u16, + bb: []u16, + norm: []f32, + + pub fn init(gpa: std.mem.Allocator, seed: u64) !HostModel { + var prng = std.Random.DefaultPrng.init(seed); + const r = prng.random(); + var m: HostModel = .{ .gpa = gpa, .emb = &.{}, .mix = &.{}, .w = &.{}, .s = &.{}, .bb = &.{}, .norm = &.{} }; + m.emb = try gpa.alloc(f32, m.vocab * m.in); + m.mix = try gpa.alloc(f32, m.in * m.d); + m.w = try gpa.alloc(u32, m.vocab * m.d / 8); + m.s = try gpa.alloc(u16, m.vocab * m.d / 64); + m.bb = try gpa.alloc(u16, m.vocab * m.d / 64); + m.norm = try gpa.alloc(f32, m.d); + for (m.emb) |*v| v.* = r.floatNorm(f32); + for (m.mix) |*v| v.* = 0.2 * r.floatNorm(f32); + for (m.w) |*v| v.* = r.int(u32); + for (m.s, m.bb) |*x, *y| { + x.* = lm.bfBits(0.05); + y.* = lm.bfBits(-0.375); + } + @memset(m.norm, 1); + return m; + } + + pub fn deinit(m: *HostModel) void { + inline for (.{ "emb", "mix", "w", "s", "bb", "norm" }) |f| m.gpa.free(@field(m, f)); + } + + fn tail(m: *const HostModel) lm.Tail { + return .{ .norm = m.norm, .head = .{ .w = m.w, .s = m.s, .b = m.bb, .n = m.vocab, .k = m.d }, .eps = 1e-5 }; + } + + fn capture(m: *const HostModel, ids: []const u32, start: usize) !lm.Captured { + const rows = ids.len - 1; + var c = try lm.Captured.alloc(m.gpa, rows, start, m.in, m.d); + for (0..rows) |r| for (0..m.in) |i| { + // a row's input: its token's embedding plus a little of the one before (context) + const prev = if (r > 0) m.emb[ids[r - 1] * m.in + i] else 0; + c.site[r * m.in + i] = lm.bfBits(m.emb[ids[r] * m.in + i] + 0.3 * prev); + }; + for (0..c.answers()) |a| { + const r = start - 1 + a; + c.targets[a] = ids[r + 1]; + for (0..m.d) |j| { + var s: f32 = 0; + for (0..m.in) |i| s += lm.bfVal(c.site[r * m.in + i]) * m.mix[i * m.d + j]; + c.ys0[a * m.d + j] = lm.bf(0.5 * s); + c.branch0[a * m.d + j] = lm.bf(s); + for (0..4) |st| c.cold[(a * 4 + st) * m.d + j] = 0.1 * @as(f32, @floatFromInt(st)); + } + @memcpy(c.post[a * 4 ..][0..4], &[_]f32{ 1, 1, 1, 1 }); + } + return c; + } +}; + +test "the learner on the host: a fact learned in gated rounds, committed, saved, undone" { + const gpa = std.testing.allocator; + var model = try HostModel.init(gpa, 9); + defer model.deinit(); + var learner = Learner(HostTrainer).init(gpa, &model); + defer learner.deinit(); + // the fact "7 5 -> 11 3": its answer tokens 11 3 after a question 7 5 (start 2); a held-out variant with another lead + const fact = [_]u32{ 7, 5, 11, 3 }; + const held = [_]u32{ 8, 5, 11, 3 }; + const keeps = [_][4]u32{ .{ 1, 2, 3, 4 }, .{ 9, 9, 2, 6 }, .{ 20, 21, 22, 23 }, .{ 30, 31, 12, 13 }, .{ 40, 41, 42, 43 }, .{ 17, 18, 19, 16 } }; + var keep: [keeps.len]Example = undefined; + for (&keep, &keeps) |*k, *ids| k.* = .{ .ids = ids, .start = 2 }; + const train = [_]Example{.{ .ids = &fact, .start = 2 }}; + const helds = [_]Example{.{ .ids = &held, .start = 2 }}; + try learner.begin(.{ .train = &train, .held = &helds, .keep = &keep, .steps = 20 }); + var report: ?Report = null; + var n: usize = 0; + while (true) : (n += 1) { + const s = learner.step(); + if (s.report) |r| report = r; + if (s.done) break; + try std.testing.expect(n < 10_000); + } + const t = learner.trainer.?; + try std.testing.expect(report != null and report.? == .learned); + try std.testing.expectEqual(@as(usize, block), t.sites.rank); + try std.testing.expect(t.attached); + const before = report.?.learned.loss; + // a second round goes on from the first; the loss keeps falling + try learner.begin(.{ .train = &train, .held = &helds, .keep = &keep, .steps = 40, .more = true }); + while (true) { + const s = learner.step(); + if (s.report) |r| report = r; + if (s.done) break; + } + try std.testing.expect(report.? == .learned and report.?.learned.loss < before); + // undo takes the second round back: b equals what the first round left + const b_after = try gpa.dupe(f32, t.b[0 .. block * model.d]); + defer gpa.free(b_after); + try learner.begin(.{ .undo = true }); + _ = learner.step(); + try std.testing.expect(!std.mem.eql(f32, b_after, t.b[0 .. block * model.d])); + // commit: the block turns plain (always on) and trains beside the keep answers; save writes its ranks and rounds them + try learner.begin(.{ .train = &train, .held = &helds, .keep = &keep, .commit = true }); + while (!learner.step().done) {} + try std.testing.expectEqual(-std.math.inf(f32), t.tau[0]); + try learner.begin(.{ .save = true }); + _ = learner.step(); + try std.testing.expectEqual(@as(usize, block), t.saved); + for (t.b[0 .. block * model.d]) |v| try std.testing.expectEqual(lm.bf(v), v); + // undo of a plain lesson takes the whole block out + try learner.begin(.{ .undo = true }); + _ = learner.step(); + try std.testing.expectEqual(@as(usize, 0), t.sites.rank); + // an empty request is the server's probe: done at once, nothing moves + try learner.begin(.{}); + try std.testing.expect(learner.step().done); +} + +test "a gated block's gradient is zero on keep rows it shuts, and the probe is harmless before any lesson" { + const gpa = std.testing.allocator; + var model = try HostModel.init(gpa, 10); + defer model.deinit(); + var learner = Learner(HostTrainer).init(gpa, &model); + defer learner.deinit(); + try learner.begin(.{}); + try std.testing.expect(learner.step().done); + try std.testing.expect(learner.trainer == null); + const too_long: [max_rows + 2]u32 = @splat(0); + const bad = [_]Example{.{ .ids = &too_long, .start = 3 }}; + try std.testing.expectError(error.ExampleTooLong, learner.begin(.{ .train = &bad })); +} diff --git a/zig/src/families/glm/lw_math.zig b/zig/src/families/glm/lw_math.zig new file mode 100644 index 00000000000..5f215abf7a1 --- /dev/null +++ b/zig/src/families/glm/lw_math.zig @@ -0,0 +1,718 @@ +//! Living Weights on GLM-5.3-Flash: the CPU half of a step, after the site (layers.44 shared expert's down_proj). +//! The forward from the site on is row-local: the adapter on the shared expert's output, the MoE combine, the last +//! hyper-connection expand, the stream mean, the final RMSNorm, the 4-bit LM head, the softmax loss. Its backward reaches +//! only b of the open block. Everything here is plain host math over host slices (no GPU), so every op is tested on Linux. +const std = @import("std"); + +/// Ranks a lesson adds, the most a server life holds, the adapter's scale and its directions' squared length: Nemotron's values +/// (families/nemotron/adapters.zig:14-28), so a block, a gate and a sidecar mean the same thing in both families. +pub const block = 16; +pub const max_rank = 512; +pub const max_blocks = max_rank / block; +pub const scale: f32 = 10; +pub const a_norm: f32 = 0.577; +pub const unit = a_norm * a_norm; +pub const shut: f32 = 2; +pub const avoid_dims = 192; +pub const candidates = 64; +/// Adam: rate, decays, epsilon (adapters.zig:22). +pub const hyper = [4]f32{ 3e-4, 0.9, 0.999, 1e-8 }; + +// ---------------------------------------------------------------- bf16 + +pub fn bfBits(x: f32) u16 { + const u: u32 = @bitCast(x); + if (std.math.isNan(x)) return @intCast((u >> 16) | 0x40); + const lsb = (u >> 16) & 1; + return @intCast((u +% 0x7fff +% lsb) >> 16); +} + +pub fn bfVal(h: u16) f32 { + return @bitCast(@as(u32, h) << 16); +} + +/// x rounded to bf16 (nearest even), as an f32. +pub fn bf(x: f32) f32 { + return bfVal(bfBits(x)); +} + +// ---------------------------------------------------------------- the 4-bit LM head + +/// MLX affine 4-bit, groups of 64, row-major [n, k]: value i of the flat matrix at bits 4 (i % 8) of w[i / 8], +/// scale and bias at i / 64 (tf_train_head_t's reading, train.metal:25-35). +pub const Q4 = struct { + w: []const u32, + s: []const u16, + b: []const u16, + n: usize, + k: usize, + + /// Row v dequantized into out [k]. + pub fn row(q: Q4, v: usize, out: []f32) void { + const words = q.w[v * q.k / 8 ..][0 .. q.k / 8]; + const ss = q.s[v * q.k / 64 ..][0 .. q.k / 64]; + const bs = q.b[v * q.k / 64 ..][0 .. q.k / 64]; + for (0..q.k / 64) |g| { + const sc = bfVal(ss[g]); + const bi = bfVal(bs[g]); + for (0..8) |wi| { + const word = words[g * 8 + wi]; + inline for (0..8) |j| { + const code: f32 = @floatFromInt((word >> (4 * j)) & 0xf); + out[g * 64 + wi * 8 + j] = sc * code + bi; + } + } + } + } +}; + +/// Threads for the head's passes: up to 16, one per CPU. +fn threads() usize { + const n = std.Thread.getCpuCount() catch 1; + return std.math.clamp(n, 1, 16); +} + +/// Run f(ctx, t, n) on n threads (the calling thread takes its share when a spawn fails). +fn parallel(n: usize, ctx: anytype, comptime f: fn (@TypeOf(ctx), usize, usize) void) void { + var ts: [16]?std.Thread = @splat(null); + for (ts[0..n], 0..) |*t, i| t.* = if (i == 0) null else std.Thread.spawn(.{}, f, .{ ctx, i, n }) catch null; + f(ctx, 0, n); + for (ts[0..n], 0..) |t, i| if (i > 0) { + if (t) |th| th.join() else f(ctx, i, n); + }; +} + +fn dot(x: []const f32, y: []const f32) f32 { + const V = @Vector(8, f32); + var acc: V = @splat(0); + var i: usize = 0; + while (i + 8 <= x.len) : (i += 8) acc += @as(V, x[i..][0..8].*) * @as(V, y[i..][0..8].*); + var s = @reduce(.Add, acc); + while (i < x.len) : (i += 1) s += x[i] * y[i]; + return s; +} + +fn axpy(y: []f32, c: f32, x: []const f32) void { + const V = @Vector(8, f32); + const cv: V = @splat(c); + var i: usize = 0; + while (i + 8 <= x.len) : (i += 8) y[i..][0..8].* = @as(V, y[i..][0..8].*) + cv * @as(V, x[i..][0..8].*); + while (i < x.len) : (i += 1) y[i] += c * x[i]; +} + +/// logits [rows, n] = hidden [rows, k] W^T, every row of W dequantized once for all rows. +pub fn headLogits(gpa: std.mem.Allocator, q: Q4, hidden: []const f32, logits: []f32, rows: usize) !void { + const Ctx = struct { q: Q4, h: []const f32, l: []f32, rows: usize, bufs: []f32 }; + const n = threads(); + const bufs = try gpa.alloc(f32, n * q.k); + defer gpa.free(bufs); + const work = struct { + fn run(c: *const Ctx, t: usize, nt: usize) void { + const lo = c.q.n * t / nt; + const hi = c.q.n * (t + 1) / nt; + const wr = c.bufs[t * c.q.k ..][0..c.q.k]; + for (lo..hi) |v| { + c.q.row(v, wr); + for (0..c.rows) |r| c.l[r * c.q.n + v] = dot(c.h[r * c.q.k ..][0..c.q.k], wr); + } + } + }.run; + const ctx: Ctx = .{ .q = q, .h = hidden, .l = logits, .rows = rows, .bufs = bufs }; + parallel(n, &ctx, work); +} + +/// dh [rows, k] = g [rows, n] W: each thread a fixed run of W's rows into its own sums, added in thread order (deterministic). +pub fn headBack(gpa: std.mem.Allocator, q: Q4, g: []const f32, dh: []f32, rows: usize) !void { + const Ctx = struct { q: Q4, g: []const f32, acc: []f32, rows: usize, bufs: []f32 }; + const n = threads(); + const bufs = try gpa.alloc(f32, n * q.k); + defer gpa.free(bufs); + const acc = try gpa.alloc(f32, n * rows * q.k); + defer gpa.free(acc); + @memset(acc, 0); + const work = struct { + fn run(c: *const Ctx, t: usize, nt: usize) void { + const lo = c.q.n * t / nt; + const hi = c.q.n * (t + 1) / nt; + const wr = c.bufs[t * c.q.k ..][0..c.q.k]; + const mine = c.acc[t * c.rows * c.q.k ..][0 .. c.rows * c.q.k]; + for (lo..hi) |v| { + var any = false; + for (0..c.rows) |r| any = any or c.g[r * c.q.n + v] != 0; + if (!any) continue; + c.q.row(v, wr); + for (0..c.rows) |r| { + const gv = c.g[r * c.q.n + v]; + if (gv != 0) axpy(mine[r * c.q.k ..][0..c.q.k], gv, wr); + } + } + } + }.run; + const ctx: Ctx = .{ .q = q, .g = g, .acc = acc, .rows = rows, .bufs = bufs }; + parallel(n, &ctx, work); + @memcpy(dh[0 .. rows * q.k], acc[0 .. rows * q.k]); + for (1..n) |t| for (dh[0 .. rows * q.k], acc[t * rows * q.k ..][0 .. rows * q.k]) |*d, a| { + d.* += a; + }; +} + +/// A row's softmax loss against `target` (logits overwritten by (p - onehot) w): (loss, the target's probability). +pub fn softmaxCe(l: []f32, target: usize, w: f32) [2]f32 { + var m: f32 = -std.math.inf(f32); + for (l) |v| m = @max(m, v); + var s: f64 = 0; + for (l) |v| s += @exp(@as(f64, v - m)); + const lt = l[target]; + const ls: f32 = @floatCast(@log(s)); + const p_t: f32 = @floatCast(@exp(@as(f64, lt - m)) / s); + const inv: f32 = @floatCast(1 / s); + for (l, 0..) |*v, i| v.* = (@exp(v.* - m) * inv - @as(f32, if (i == target) 1 else 0)) * w; + return .{ ls + m - lt, p_t }; +} + +// ---------------------------------------------------------------- RMSNorm + +/// MLX RMSNorm: y = w x / sqrt(mean x^2 + eps), returns the inverse root. +pub fn rms(x: []const f32, w: []const f32, y: []f32, eps: f32, round: bool) f32 { + var sq: f32 = 0; + for (x) |v| sq += v * v; + const inv = 1 / @sqrt(sq / @as(f32, @floatFromInt(x.len)) + eps); + for (y, x, w) |*o, v, wv| o.* = if (round) bf(wv * (v * inv)) else wv * (v * inv); + return inv; +} + +/// dx = s w dy - s^3 x (w dy . x) / n, the backward of `rms` (tf_train_rms_back's arithmetic, train.metal:63-87). +pub fn rmsBack(x: []const f32, w: []const f32, dy: []const f32, dx: []f32, eps: f32) void { + var sq: f32 = 0; + var d: f32 = 0; + for (x, w, dy) |v, wv, g| { + sq += v * v; + d += wv * g * v; + } + const n: f32 = @floatFromInt(x.len); + const s = 1 / @sqrt(sq / n + eps); + const k = s * s * s * d / n; + for (dx, x, w, dy) |*o, v, wv, g| o.* = s * wv * g - k * v; +} + +// ---------------------------------------------------------------- the adapter at the site + +/// The live change at the site: y += scale (x a^T) b over every block in use, each block gated per row. +pub const Lora = struct { + a: []const f32, // [max_rank, in] + b: []const f32, // [max_rank, out] + tau: []const f32, // [max_blocks] + rank: usize, + in: usize, + out: usize, +}; + +/// xa [rank] = x a^T, closed blocks zeroed (tf_train_lora_in + tf_train_gate); returns |x|^2. +pub fn project(lo: Lora, x: []const f32, xa: []f32) f32 { + var n: f32 = 0; + for (x) |v| n += v * v; + for (0..lo.rank) |q| xa[q] = dot(x, lo.a[q * lo.in ..][0..lo.in]); + const len = unit * n; + var bk: usize = 0; + while (bk < lo.rank / block) : (bk += 1) { + const open = len > 0 and xa[bk * block] >= lo.tau[bk] * @sqrt(len); + if (!open) @memset(xa[bk * block ..][0..block], 0); + } + return n; +} + +/// s [out] = sum_q xa[q] b[q] (the change before its scale). +pub fn loraOut(lo: Lora, xa: []const f32, s: []f32) void { + @memset(s, 0); + for (0..lo.rank) |q| if (xa[q] != 0) axpy(s, xa[q], lo.b[q * lo.out ..][0..lo.out]); +} + +// ---------------------------------------------------------------- one example, captured past the site + +/// What the GPU forward left at layer 44 for one example (adapter off), host copies: the site's input on every row and, +/// on the answer rows (start - 1 ..), what the tail needs. Owned by the trainer's cache. +pub const Captured = struct { + rows: usize, // ids.len - 1 + start: usize, // the first answer token's place in ids + in: usize, + d: usize, + site: []u16, // bf16 [rows, in]: the shared expert's down_proj input + targets: []u32, // [A]: the next token of each answer row + branch0: []f32, // [A, d]: the MLP branch (shared + routed, bf16 values) without the change + ys0: []f32, // [A, d]: the shared expert's output without the change + post: []f32, // [A, 4]: the last expand's branch weights + cold: []f32, // [A, 4, d]: the last expand's mix of the old streams (sum_t comb[t, s] x_old[t]) + + pub fn answers(c: *const Captured) usize { + return c.rows + 1 - c.start; + } + + pub fn alloc(gpa: std.mem.Allocator, rows: usize, start: usize, in: usize, d: usize) !Captured { + const A = rows + 1 - start; + var c: Captured = .{ .rows = rows, .start = start, .in = in, .d = d, .site = &.{}, .targets = &.{}, .branch0 = &.{}, .ys0 = &.{}, .post = &.{}, .cold = &.{} }; + errdefer c.free(gpa); + c.site = try gpa.alloc(u16, rows * in); + c.targets = try gpa.alloc(u32, A); + c.branch0 = try gpa.alloc(f32, A * d); + c.ys0 = try gpa.alloc(f32, A * d); + c.post = try gpa.alloc(f32, A * 4); + c.cold = try gpa.alloc(f32, A * 4 * d); + return c; + } + + pub fn free(c: *Captured, gpa: std.mem.Allocator) void { + gpa.free(c.site); + gpa.free(c.targets); + gpa.free(c.branch0); + gpa.free(c.ys0); + gpa.free(c.post); + gpa.free(c.cold); + } + + pub fn bytes(c: *const Captured) usize { + const A = c.answers(); + return c.rows * c.in * 2 + A * (4 + 4 * (2 * c.d + 4 + 4 * c.d)); + } + + /// Row r's site input as f32. + pub fn siteRow(c: *const Captured, r: usize, out: []f32) void { + for (out, c.site[r * c.in ..][0..c.in]) |*o, h| o.* = bfVal(h); + } +}; + +/// The tail's fixed parts: the final norm's weight and the head. +pub const Tail = struct { + norm: []const f32, // [d] + head: Q4, // [vocab, d] + eps: f32, + round: bool = true, // bf16 rounding where the GPU rounds (off in gradient checks) +}; + +pub const Result = struct { loss: f32, recalled: bool }; + +/// Scratch for `step`, sized for `A` answer rows. +pub const Scratch = struct { + xa: []f32, + x: []f32, + s: []f32, + raw: []f32, + hidden: []f32, + logits: []f32, + dh: []f32, + dr: []f32, + + pub fn init(gpa: std.mem.Allocator, A: usize, in: usize, d: usize, vocab: usize) !Scratch { + var sc: Scratch = undefined; + sc.xa = try gpa.alloc(f32, A * max_rank); + sc.x = try gpa.alloc(f32, in); + sc.s = try gpa.alloc(f32, d); + sc.raw = try gpa.alloc(f32, A * d); + sc.hidden = try gpa.alloc(f32, A * d); + sc.logits = try gpa.alloc(f32, A * vocab); + sc.dh = try gpa.alloc(f32, A * d); + sc.dr = try gpa.alloc(f32, d); + return sc; + } + + pub fn deinit(sc: *Scratch, gpa: std.mem.Allocator) void { + inline for (.{ "xa", "x", "s", "raw", "hidden", "logits", "dh", "dr" }) |f| gpa.free(@field(sc, f)); + } +}; + +/// Every answer row from the site to the final norm: xa (gated), raw and hidden into the scratch. +fn forwardRows(tl: Tail, c: *const Captured, lo: Lora, sc: *Scratch) void { + const A = c.answers(); + const d = c.d; + const R = tl.round; + for (0..A) |i| { + const r = c.start - 1 + i; + c.siteRow(r, sc.x); + const xa = sc.xa[i * max_rank ..][0..max_rank]; + @memset(xa, 0); + if (lo.rank > 0) { + _ = project(lo, sc.x, xa); + loraOut(lo, xa, sc.s); + } else @memset(sc.s, 0); + const raw = sc.raw[i * d ..][0..d]; + const post = c.post[i * 4 ..][0..4]; + for (0..d) |j| { + const ys0 = c.ys0[i * d + j]; + const ys = if (R) bf(ys0 + scale * sc.s[j]) else ys0 + scale * sc.s[j]; + const br = if (R) bf(c.branch0[i * d + j] - ys0 + ys) else c.branch0[i * d + j] - ys0 + ys; + var sum: f32 = 0; + for (0..4) |s| { + const xn = post[s] * br + c.cold[(i * 4 + s) * d + j]; + sum += if (R) bf(xn) else xn; + } + raw[j] = if (R) bf(sum * 0.25) else sum * 0.25; + } + _ = rms(raw, tl.norm, sc.hidden[i * d ..][0..d], tl.eps, R); + } +} + +/// The answer rows' final-normed hidden states [A, d] with the change `lo` (for a check against the GPU's). +pub fn hiddenRows(gpa: std.mem.Allocator, tl: Tail, c: *const Captured, lo: Lora, out: []f32) !void { + var sc = try Scratch.init(gpa, c.answers(), c.in, c.d, 1); + defer sc.deinit(gpa); + forwardRows(tl, c, lo, &sc); + @memcpy(out[0 .. c.answers() * c.d], sc.hidden); +} + +/// The answer's mean loss with the change `lo` at the site; with `gb` ([block, out], for the open block from rank +/// `first`), its gradient added there. Returns the loss and whether every answer token had probability > 0.5. +pub fn step(gpa: std.mem.Allocator, tl: Tail, c: *const Captured, lo: Lora, gb: ?[]f32, first: usize) !Result { + const A = c.answers(); + const d = c.d; + const V = tl.head.n; + var sc = try Scratch.init(gpa, A, c.in, d, V); + defer sc.deinit(gpa); + const w: f32 = 1 / @as(f32, @floatFromInt(A)); + forwardRows(tl, c, lo, &sc); + try headLogits(gpa, tl.head, sc.hidden, sc.logits, A); + var out: Result = .{ .loss = 0, .recalled = true }; + for (0..A) |i| { + const st = softmaxCe(sc.logits[i * V ..][0..V], c.targets[i], w); + out.loss += st[0] * w; + out.recalled = out.recalled and st[1] > 0.5; + } + const g = gb orelse return out; + try headBack(gpa, tl.head, sc.logits, sc.dh, A); + for (0..A) |i| { + rmsBack(sc.raw[i * d ..][0..d], tl.norm, sc.dh[i * d ..][0..d], sc.dr, tl.eps); + const post = c.post[i * 4 ..][0..4]; + // raw = mean of the four streams, each stream post[s] branch + its old mix: d branch = (sum post) / 4 d raw + const k = scale * 0.25 * (post[0] + post[1] + post[2] + post[3]); + const xa = sc.xa[i * max_rank ..][first..][0..block]; + for (0..block) |q| if (xa[q] != 0) axpy(g[q * lo.out ..][0..lo.out], k * xa[q], sc.dr); + } + return out; +} + +/// One Adam step on p from its gradient g (cleared after), bias-corrected for step t (tf_train_adam's arithmetic). +pub fn adam(p: []f32, g: []f32, m: []f32, v: []f32, t: u64) void { + const tf: f32 = @floatFromInt(t); + const c1 = 1 / (1 - std.math.pow(f32, hyper[1], tf)); + const c2 = 1 / (1 - std.math.pow(f32, hyper[2], tf)); + for (p, g, m, v) |*pi, *gi, *mi, *vi| { + mi.* = hyper[1] * mi.* + (1 - hyper[1]) * gi.*; + vi.* = hyper[2] * vi.* + (1 - hyper[2]) * gi.* * gi.*; + pi.* -= hyper[0] * (mi.* * c1) / (@sqrt(vi.* * c2) + hyper[3]); + gi.* = 0; + } +} + +// ---------------------------------------------------------------- the sketches a new block is chosen from + +/// A sign from a row's place and a sketch column (train.metal's coin, bit for bit). +pub fn coin(row: u32, j: u32, seed: u32) f32 { + var h: u32 = row *% 0x9E3779B9 +% j *% 0x7FEB352D +% seed; + h ^= h >> 16; + h *%= 0x7FEB352D; + h ^= h >> 15; + h *%= 0x846CA68B; + h ^= h >> 16; + return if (h & 1 != 0) 1 else -1; +} + +/// y[j, i] += w sum_r coin(first + r, j) x[r, i] (tf_train_sketch). +pub fn sketch(x: []const u16, y: []f32, rows: usize, in: usize, k: usize, first: u32, seed: u32, w: f32) void { + for (0..k) |j| { + const yj = y[j * in ..][0..in]; + for (0..rows) |r| { + const cs = w * coin(first + @as(u32, @intCast(r)), @intCast(j), seed); + for (yj, x[r * in ..][0..in]) |*o, h| o.* += cs * bfVal(h); + } + } +} + +/// p[r, j] = f[j] . x[r] / |x[r]| (tf_train_project). +pub fn projectRows(x: []const u16, f: []const f32, p: []f32, rows: usize, in: usize, k: usize, tmp: []f32) void { + for (0..rows) |r| { + var n: f32 = 0; + for (tmp[0..in], x[r * in ..][0..in]) |*o, h| { + o.* = bfVal(h); + n += o.* * o.*; + } + const inv = if (n > 0) 1 / @sqrt(n) else 0; + for (0..k) |j| p[r * k + j] = dot(f[j * in ..][0..in], tmp[0..in]) * inv; + } +} + +// ================================================================ tests + +const testing = std.testing; + +/// A random 4-bit head [n, k] with its bf16 scales and biases. +const TestHead = struct { + w: []u32, + s: []u16, + b: []u16, + q: Q4, + + fn init(gpa: std.mem.Allocator, r: std.Random, n: usize, k: usize) !TestHead { + const w = try gpa.alloc(u32, n * k / 8); + const s = try gpa.alloc(u16, n * k / 64); + const b = try gpa.alloc(u16, n * k / 64); + for (w) |*x| x.* = r.int(u32); + for (s, b) |*x, *y| { + x.* = bfBits(0.02 + 0.02 * r.float(f32)); + y.* = bfBits(-0.15 + 0.05 * r.float(f32)); + } + return .{ .w = w, .s = s, .b = b, .q = .{ .w = w, .s = s, .b = b, .n = n, .k = k } }; + } + + fn deinit(h: *TestHead, gpa: std.mem.Allocator) void { + gpa.free(h.w); + gpa.free(h.s); + gpa.free(h.b); + } +}; + +test "the head's 4-bit rows read as tf_train_head_t reads them" { + const gpa = testing.allocator; + var prng = std.Random.DefaultPrng.init(7); + var h = try TestHead.init(gpa, prng.random(), 3, 128); + defer h.deinit(gpa); + var row: [128]f32 = undefined; + for (0..3) |v| { + h.q.row(v, &row); + for (0..128) |d| { + const i = v * 128 + d; + const code: f32 = @floatFromInt((h.w[i / 8] >> @intCast(4 * (i % 8))) & 0xf); + try testing.expectEqual(bfVal(h.s[i / 64]) * code + bfVal(h.b[i / 64]), row[d]); + } + } +} + +test "head logits and head backward equal the plain sums" { + const gpa = testing.allocator; + var prng = std.Random.DefaultPrng.init(11); + const r = prng.random(); + const n = 37; + const k = 128; + const rows = 3; + var h = try TestHead.init(gpa, r, n, k); + defer h.deinit(gpa); + var x: [rows * k]f32 = undefined; + for (&x) |*v| v.* = r.floatNorm(f32); + var l: [rows * n]f32 = undefined; + try headLogits(gpa, h.q, &x, &l, rows); + var g: [rows * n]f32 = undefined; + for (&g) |*v| v.* = r.floatNorm(f32); + var dh: [rows * k]f32 = undefined; + try headBack(gpa, h.q, &g, &dh, rows); + var wr: [k]f32 = undefined; + var want: [rows * k]f32 = @splat(0); + for (0..n) |v| { + h.q.row(v, &wr); + for (0..rows) |i| { + var s: f64 = 0; + for (0..k) |j| s += @as(f64, x[i * k + j]) * wr[j]; + try testing.expectApproxEqRel(@as(f32, @floatCast(s)), l[i * n + v], 1e-4); + for (0..k) |j| want[i * k + j] += g[i * n + v] * wr[j]; + } + } + for (want, dh) |a, b| try testing.expectApproxEqAbs(a, b, 1e-3); +} + +test "rmsBack is the gradient of rms (finite differences)" { + var prng = std.Random.DefaultPrng.init(3); + const r = prng.random(); + const n = 48; + var x: [n]f32 = undefined; + var w: [n]f32 = undefined; + var c: [n]f32 = undefined; // loss = c . rms(x) + for (&x, &w, &c) |*a, *b, *d| { + a.* = r.floatNorm(f32); + b.* = 0.5 + r.float(f32); + d.* = r.floatNorm(f32); + } + var dx: [n]f32 = undefined; + rmsBack(&x, &w, &c, &dx, 1e-5); + var y: [n]f32 = undefined; + for (0..n) |i| { + const h: f32 = 1e-2; + const keep = x[i]; + x[i] = keep + h; + _ = rms(&x, &w, &y, 1e-5, false); + const up = dot(&c, &y); + x[i] = keep - h; + _ = rms(&x, &w, &y, 1e-5, false); + const down = dot(&c, &y); + x[i] = keep; + try testing.expectApproxEqAbs((up - down) / (2 * h), dx[i], 2e-3); + } +} + +test "softmaxCe: loss, probability and (p - onehot) w" { + var l = [_]f32{ 1, 2, 0.5, -1 }; + const st = softmaxCe(&l, 1, 0.5); + const e = [_]f64{ @exp(1.0), @exp(2.0), @exp(0.5), @exp(-1.0) }; + const z = e[0] + e[1] + e[2] + e[3]; + try testing.expectApproxEqAbs(@as(f32, @floatCast(-@log(e[1] / z))), st[0], 1e-5); + try testing.expectApproxEqAbs(@as(f32, @floatCast(e[1] / z)), st[1], 1e-6); + try testing.expectApproxEqAbs(@as(f32, @floatCast((e[1] / z - 1) * 0.5)), l[1], 1e-6); + try testing.expectApproxEqAbs(@as(f32, @floatCast(e[3] / z * 0.5)), l[3], 1e-6); +} + +test "the gate opens a block on a row whose cosine with its first direction reaches tau" { + var a: [2 * block * 4]f32 = @splat(0); + a[0] = a_norm; // block 0's first direction: e0 + a[block * 4 + 1] = a_norm; // block 1's: e1 + a[4] = 0.1; // block 0 rank 1 reads e0 too + const b: [2 * block * 2]f32 = @splat(1); + var tau = [_]f32{ 0.5, -std.math.inf(f32) }; + const lo: Lora = .{ .a = &a, .b = &b, .tau = &tau, .rank = 2 * block, .in = 4, .out = 2 }; + var xa: [2 * block]f32 = undefined; + _ = project(lo, &[_]f32{ 1, 0, 0, 0 }, &xa); // cos 1 with e0: block 0 open; block 1 always + try testing.expectApproxEqAbs(a_norm, xa[0], 1e-6); + try testing.expectApproxEqAbs(@as(f32, 0.1), xa[1], 1e-6); + try testing.expectEqual(@as(f32, 0), xa[block]); + _ = project(lo, &[_]f32{ 0, 1, 0, 0 }, &xa); // cos 0 with e0: block 0 shut + try testing.expectEqual(@as(f32, 0), xa[0]); + try testing.expectEqual(@as(f32, 0), xa[1]); + try testing.expectApproxEqAbs(a_norm, xa[block], 1e-6); + _ = project(lo, &[_]f32{ 0, 0, 0, 0 }, &xa); // a zero row opens nothing (train.metal's n > 0) + for (xa) |v| try testing.expectEqual(@as(f32, 0), v); +} + +/// A small tail: in 64, d 64, vocab 40, a captured example of 7 rows with its answer from 4. +const Toy = struct { + head: TestHead, + norm: [64]f32, + cap: Captured, + a: []f32, + b: []f32, + tau: []f32, + + fn init(gpa: std.mem.Allocator, seed: u64) !Toy { + var prng = std.Random.DefaultPrng.init(seed); + const r = prng.random(); + var t: Toy = undefined; + t.head = try TestHead.init(gpa, r, 40, 64); + for (&t.norm) |*v| v.* = 0.5 + r.float(f32); + t.cap = try Captured.alloc(gpa, 7, 4, 64, 64); + for (t.cap.site) |*v| v.* = bfBits(r.floatNorm(f32)); + for (t.cap.targets) |*v| v.* = r.uintLessThan(u32, 40); + for (t.cap.branch0, t.cap.ys0) |*x, *y| { + y.* = r.floatNorm(f32); + x.* = y.* + r.floatNorm(f32); + } + for (t.cap.post) |*v| v.* = 0.2 + r.float(f32); + for (t.cap.cold) |*v| v.* = r.floatNorm(f32); + t.a = try gpa.alloc(f32, max_rank * 64); + t.b = try gpa.alloc(f32, max_rank * 64); + t.tau = try gpa.alloc(f32, max_blocks); + @memset(t.a, 0); + @memset(t.b, 0); + @memset(t.tau, shut); + for (t.a[0 .. 2 * block * 64]) |*v| v.* = 0.15 * r.floatNorm(f32); + for (t.b[0 .. 2 * block * 64]) |*v| v.* = 0.05 * r.floatNorm(f32); + t.tau[0] = -std.math.inf(f32); // a committed block + t.tau[1] = -0.3; // the open block, gated + return t; + } + + fn deinit(t: *Toy, gpa: std.mem.Allocator) void { + t.head.deinit(gpa); + t.cap.free(gpa); + gpa.free(t.a); + gpa.free(t.b); + gpa.free(t.tau); + } + + fn lora(t: *const Toy) Lora { + return .{ .a = t.a, .b = t.b, .tau = t.tau, .rank = 2 * block, .in = 64, .out = 64 }; + } + + fn tail(t: *const Toy) Tail { + return .{ .norm = &t.norm, .head = t.head.q, .eps = 1e-5, .round = false }; + } +}; + +test "the tail's gradient on the open block's b matches finite differences" { + const gpa = testing.allocator; + var t = try Toy.init(gpa, 21); + defer t.deinit(gpa); + const g = try gpa.alloc(f32, block * 64); + defer gpa.free(g); + @memset(g, 0); + const first = block; // the open block: ranks 16..32 + const base = try step(gpa, t.tail(), &t.cap, t.lora(), g, first); + try testing.expect(std.math.isFinite(base.loss)); + var nonzero: usize = 0; + var prng = std.Random.DefaultPrng.init(5); + for (0..40) |_| { + const q = prng.random().uintLessThan(usize, block); + const j = prng.random().uintLessThan(usize, 64); + const at = (first + q) * 64 + j; + const h: f32 = 1e-3; + const keep = t.b[at]; + t.b[at] = keep + h; + const up = (try step(gpa, t.tail(), &t.cap, t.lora(), null, first)).loss; + t.b[at] = keep - h; + const down = (try step(gpa, t.tail(), &t.cap, t.lora(), null, first)).loss; + t.b[at] = keep; + const fd = (up - down) / (2 * h); + const an = g[q * 64 + j]; + nonzero += @intFromBool(an != 0); + try testing.expectApproxEqAbs(fd, an, 2e-3 + 2e-2 * @abs(fd)); + } + try testing.expect(nonzero > 10); // the gate is open on some answer rows +} + +test "a closed block gets no gradient, and the committed block alone moves the loss" { + const gpa = testing.allocator; + var t = try Toy.init(gpa, 22); + defer t.deinit(gpa); + t.tau[1] = 1.5; // above any cosine: the open block shut on every row + const g = try gpa.alloc(f32, block * 64); + defer gpa.free(g); + @memset(g, 0); + const with = try step(gpa, t.tail(), &t.cap, t.lora(), g, block); + for (g) |v| try testing.expectEqual(@as(f32, 0), v); + var none = t.lora(); + none.rank = 0; + const without = try step(gpa, t.tail(), &t.cap, none, null, 0); + try testing.expect(with.loss != without.loss); +} + +test "Adam steps against the gradient and clears it" { + var p = [_]f32{ 1, -1 }; + var g = [_]f32{ 0.5, -0.25 }; + var m: [2]f32 = @splat(0); + var v: [2]f32 = @splat(0); + adam(&p, &g, &m, &v, 1); + try testing.expectApproxEqAbs(@as(f32, 1 - 3e-4), p[0], 1e-6); // first step: lr sign(g) + try testing.expectApproxEqAbs(@as(f32, -1 + 3e-4), p[1], 1e-6); + try testing.expectEqual(@as(f32, 0), g[0]); +} + +test "sketch and project: linear, signs even, projections unit" { + const in = 8; + var x: [3 * in]u16 = undefined; + for (&x, 0..) |*v, i| v.* = bfBits(@floatFromInt(@as(i32, @intCast(i % 5)) - 2)); + var y: [4 * in]f32 = @splat(0); + sketch(&x, &y, 3, in, 4, 0, 1, 1); + var y2: [4 * in]f32 = @splat(0); + for (0..3) |r| sketch(x[r * in ..][0..in], &y2, 1, in, 4, @intCast(r), 1, 1); // row by row = all at once + for (y, y2) |a, b| try testing.expectEqual(a, b); + var plus: usize = 0; + for (0..1000) |i| plus += @intFromBool(coin(@intCast(i), 3, 2) > 0); + try testing.expect(plus > 430 and plus < 570); + var f: [2 * in]f32 = @splat(0); + f[0] = 1; + f[in + 1] = 1; + var p: [3 * 2]f32 = undefined; + var tmp: [in]f32 = undefined; + projectRows(&x, &f, &p, 3, in, 2, &tmp); + var n: f32 = 0; + for (0..in) |i| n += bfVal(x[i]) * bfVal(x[i]); + try testing.expectApproxEqAbs(bfVal(x[0]) / @sqrt(n), p[0], 1e-6); +} + +test "bf16 rounding is nearest-even" { + try testing.expectEqual(@as(f32, 1.0), bf(1.0 + 1.0 / 256.0)); // halfway above an even mantissa: down + try testing.expectEqual(@as(f32, 1.015625), bf(1.0 + 3.0 / 256.0)); // halfway above an odd one: up + try testing.expectEqual(@as(f32, -2.5), bf(-2.5)); +} diff --git a/zig/src/families/glm/lw_sites.zig b/zig/src/families/glm/lw_sites.zig new file mode 100644 index 00000000000..33ec6c8be18 --- /dev/null +++ b/zig/src/families/glm/lw_sites.zig @@ -0,0 +1,217 @@ +//! The site's change, a block of ranks a lesson (Nemotron's adapters.Sites for one site: layers.44's shared-expert down_proj). +//! Host memory throughout; a, b and tau may live in GPU-shared buffers the engine's forward reads (unified memory). +const std = @import("std"); +const lm = @import("lw_math.zig"); +const subspace = @import("../nemotron/subspace.zig"); + +pub const block = lm.block; +pub const max_rank = lm.max_rank; +pub const max_blocks = lm.max_blocks; +pub const candidates = lm.candidates; +pub const avoid_dims = lm.avoid_dims; + +/// The change's live memory: a [max_rank, in], b [max_rank, out], tau [max_blocks], f32. +pub const Live = struct { a: []f32, b: []f32, tau: []f32 }; + +pub const Site = struct { + in: usize, + out: usize, + a: []f32, + b: []f32, + tau: []f32, + gb: []f32, // [block, out]: the open block's gradient + mb: []f32, // [block, out]: its Adam moments + vb: []f32, + kept: []f32, // [3, block, out]: the open block's b and moments as its round began + avoid: []f32, // [avoid_dims, in]: a sketch of the inputs the next block must leave alone + seek: []f32, // [candidates, in]: a sketch of the fact's inputs, then the candidate directions it frames + + pub fn gate(s: *const Site, k: usize) *f32 { + return &s.tau[k]; + } +}; + +pub const Sites = struct { + gpa: std.mem.Allocator, + list: []Site, // one site + rank: usize = 0, // ranks in use, the open block last + steps: u64 = 0, // the open block's Adam steps + kept_steps: u64 = 0, + + pub fn init(gpa: std.mem.Allocator, in: usize, out: usize, live: Live) !Sites { + std.debug.assert(live.a.len >= max_rank * in and live.b.len >= max_rank * out and live.tau.len >= max_blocks); + const list = try gpa.alloc(Site, 1); + errdefer gpa.free(list); + const s = &list[0]; + s.* = .{ .in = in, .out = out, .a = live.a, .b = live.b, .tau = live.tau, .gb = &.{}, .mb = &.{}, .vb = &.{}, .kept = &.{}, .avoid = &.{}, .seek = &.{} }; + const fields = [_]*[]f32{ &s.gb, &s.mb, &s.vb, &s.kept, &s.avoid, &s.seek }; + const sizes = [_]usize{ block * out, block * out, block * out, 3 * block * out, avoid_dims * in, candidates * in }; + var got: usize = 0; + errdefer for (fields[0..got]) |f| gpa.free(f.*); + for (fields, sizes) |f, n| { + f.* = try gpa.alloc(f32, n); + @memset(f.*, 0); + got += 1; + } + @memset(live.a, 0); + @memset(live.b, 0); + @memset(live.tau, lm.shut); + return .{ .gpa = gpa, .list = list }; + } + + pub fn deinit(s: *Sites) void { + for (s.list) |*site| for ([_][]f32{ site.gb, site.mb, site.vb, site.kept, site.avoid, site.seek }) |f| s.gpa.free(f); + s.gpa.free(s.list); + } + + /// Committed blocks from a learned folder (rows [0, ranks) of a and b): always on. + pub fn adopt(s: *Sites, a: []const f32, b: []const f32, ranks: usize) !void { + if (ranks % block != 0 or ranks > max_rank) return error.BadLearnedRanks; + const site = &s.list[0]; + @memcpy(site.a[0 .. ranks * site.in], a[0 .. ranks * site.in]); + @memcpy(site.b[0 .. ranks * site.out], b[0 .. ranks * site.out]); + for (0..ranks / block) |k| site.tau[k] = -std.math.inf(f32); + s.rank = ranks; + } + + pub fn lora(s: *const Sites) lm.Lora { + const site = &s.list[0]; + return .{ .a = site.a, .b = site.b, .tau = site.tau, .rank = s.rank, .in = site.in, .out = site.out }; + } + + pub fn first(s: *const Sites) usize { + return s.rank - block; + } + + /// The candidate directions: the fact's sketch with what must stay taken out, made orthonormal. + pub fn frame(s: *Sites) void { + for (s.list) |*site| { + subspace.orthonormal(site.avoid, avoid_dims, site.in); + subspace.remove(site.seek, candidates, site.avoid, avoid_dims, site.in); + subspace.orthonormal(site.seek, candidates, site.in); + } + } + + fn directions(site: *Site, at: usize, choice: []const f32, l: usize) void { + const a = site.a[at * site.in ..][0 .. block * site.in]; + @memset(a, 0); + for (0..block) |q| for (0..candidates) |j| { + subspace.axpy(a[q * site.in ..][0..site.in], lm.a_norm * choice[(l * block + q) * candidates + j], site.seek[j * site.in ..][0..site.in]); + }; + } + + /// A new block, shut, its directions `choice` [sites, block, candidates] of the candidates; b zero. + pub fn open(s: *Sites, choice: []const f32) !void { + if (s.rank + block > max_rank) return error.LearnedChangeFull; + const at = s.rank; + for (s.list, 0..) |*site, l| { + directions(site, at, choice, l); + site.gate(at / block).* = lm.shut; + @memset(site.b[at * site.out ..][0 .. block * site.out], 0); + for ([_][]f32{ site.gb, site.mb, site.vb }) |buf| @memset(buf, 0); + } + s.rank += block; + s.steps = 0; + } + + /// The open block's directions rebuilt from `choice`, its gate open on every row: a plain change. + pub fn plain(s: *Sites, choice: []const f32) void { + const at = s.first(); + for (s.list, 0..) |*site, l| { + const g = site.gate(at / block); + if (g.* >= lm.shut) continue; + directions(site, at, choice, l); + g.* = -std.math.inf(f32); + } + } + + /// The open block taken back out. + pub fn close(s: *Sites) void { + s.rank -= block; + for (s.list) |*site| { + @memset(site.b[s.rank * site.out ..][0 .. block * site.out], 0); + @memset(site.a[s.rank * site.in ..][0 .. block * site.in], 0); + site.gate(s.rank / block).* = lm.shut; + } + } + + /// One Adam step on the open block's outputs; the gradient is cleared. + pub fn adam(s: *Sites) void { + s.steps += 1; + for (s.list) |*site| lm.adam(site.b[s.first() * site.out ..][0 .. block * site.out], site.gb, site.mb, site.vb, s.steps); + } + + pub fn keep(s: *Sites) void { + s.kept_steps = s.steps; + for (s.list) |*site| { + const n = block * site.out; + @memcpy(site.kept[0..n], site.b[s.first() * site.out ..][0..n]); + @memcpy(site.kept[n .. 2 * n], site.mb); + @memcpy(site.kept[2 * n ..], site.vb); + } + } + + pub fn restore(s: *Sites) void { + s.steps = s.kept_steps; + for (s.list) |*site| { + const n = block * site.out; + @memcpy(site.b[s.first() * site.out ..][0..n], site.kept[0..n]); + @memcpy(site.mb, site.kept[n .. 2 * n]); + @memcpy(site.vb, site.kept[2 * n ..]); + @memset(site.gb, 0); + } + } + + pub fn clear(s: *Sites) void { + for (s.list) |*site| { + @memset(site.gb, 0); + @memset(site.avoid, 0); + @memset(site.seek, 0); + } + } + + /// Rows [0, ranks) of a and b rounded to bf16 in place: what a saved sidecar holds, so RAM and a reload agree. + pub fn roundSaved(s: *Sites, ranks: usize) void { + const site = &s.list[0]; + for (site.a[0 .. ranks * site.in]) |*v| v.* = lm.bf(v.*); + for (site.b[0 .. ranks * site.out]) |*v| v.* = lm.bf(v.*); + } +}; + +test "open, keep, restore, close, adopt" { + const gpa = std.testing.allocator; + const in = 8; + const out = 4; + const a = try gpa.alloc(f32, max_rank * in); + defer gpa.free(a); + const b = try gpa.alloc(f32, max_rank * out); + defer gpa.free(b); + var tau: [max_blocks]f32 = undefined; + var s = try Sites.init(gpa, in, out, .{ .a = a, .b = b, .tau = &tau }); + defer s.deinit(); + for (s.list[0].seek, 0..) |*v, i| v.* = if (i % (in + 1) == 0 and i < candidates * in) 1 else 0; // seek rows: unit vectors (8 of them) + var choice: [block * candidates]f32 = @splat(0); + choice[0] = 1; // rank 0 = candidate 0 + try s.open(&choice); + try std.testing.expectEqual(@as(usize, block), s.rank); + try std.testing.expectApproxEqAbs(lm.a_norm, a[0], 1e-6); + try std.testing.expectEqual(lm.shut, tau[0]); + s.keep(); + s.list[0].gb[0] = 1; + s.adam(); + try std.testing.expect(b[0] < 0); + s.restore(); + try std.testing.expectEqual(@as(f32, 0), b[0]); + tau[0] = 0.1; + s.plain(&choice); + try std.testing.expectEqual(-std.math.inf(f32), tau[0]); + s.close(); + try std.testing.expectEqual(@as(usize, 0), s.rank); + try std.testing.expectEqual(lm.shut, tau[0]); + const la: [block * in]f32 = @splat(0.5); + const lb: [block * out]f32 = @splat(0.25); + try s.adopt(&la, &lb, block); + try std.testing.expectEqual(-std.math.inf(f32), tau[0]); + try std.testing.expectEqual(@as(f32, 0.25), b[block * out - 1]); + try std.testing.expectError(error.BadLearnedRanks, s.adopt(&la, &lb, 3)); +} diff --git a/zig/src/families/glm/lw_train.zig b/zig/src/families/glm/lw_train.zig new file mode 100644 index 00000000000..e2f8402a84b --- /dev/null +++ b/zig/src/families/glm/lw_train.zig @@ -0,0 +1,316 @@ +//! GLM-5.3-Flash's Living Weights trainer: one GPU forward per example (the change off) captures what layer 44 +//! leaves (the site's input on every row; the shared expert's output, the MLP branch, the last expand's weights and old +//! streams on the answer rows), cached for the server's life (nothing before the site ever changes). Every learning step +//! then runs on the CPU past the site (lw_math.step): the change, the expand, the stream mean, the final norm, the 4-bit +//! head, the loss and its gradient to b. The change itself lives in the engine's Living buffers (living.zig), which +//! the served forward reads, so a step's b is what the next chat reply uses. +const std = @import("std"); +const mtl = @import("metal"); +const ge = @import("engine.zig"); +const fwd = @import("forward.zig"); +const prompt_mod = @import("prompt.zig"); +const st = @import("state.zig"); +const wts = @import("weights.zig"); +const living = @import("living.zig"); +const lm = @import("lw_math.zig"); +const lw_sites = @import("lw_sites.zig"); +const lw_learner = @import("lw_learner.zig"); +const Ref = wts.Ref; + +const max_rows = lw_learner.max_rows; +const Mode = lw_learner.Mode; + +/// The cache's room for captured examples; past it the cache starts over. +const cache_cap: usize = 3 << 30; + +pub const Learner = lw_learner.Learner(Trainer); +pub const lm_math = lm; + +pub const Trainer = struct { + pub const Ctx = *ge.Engine; + + gpa: std.mem.Allocator, + e: *ge.Engine, + lw: *living.Living, + sites: lw_sites.Sites, + sketched: usize = 0, + state: st.State, // the trainer's own caches: no slot's state is touched + ids: Ref, // u32 [max_rows] + cache: std.AutoHashMapUnmanaged(u64, lm.Captured) = .empty, + cache_bytes: usize = 0, + proj: []f32, // [max_rows, candidates] + tmp: []f32, + norm: []f32, // the final norm's weight, f32 + head: lm.Q4, + saved: usize = 0, // ranks already in the folder (loaded or written): a v2 save spawns a shard of the ranks after them + captures: u64 = 0, // GPU forwards run + seconds_gpu: f64 = 0, + seconds_cpu: f64 = 0, + + pub fn init(gpa: std.mem.Allocator, e: *ge.Engine) !*Trainer { + if (e.ep != null or e.c.tp > 1) return error.SlideNeedsOneMac; + if (e.c.run != e.c.layers) return error.LivingNeedsAllLayers; + e.sync(); + const l = try e.livingOn(); + const c = &e.c; + const t = try gpa.create(Trainer); + errdefer gpa.destroy(t); + t.* = .{ .gpa = gpa, .e = e, .lw = l, .sites = undefined, .state = undefined, .ids = undefined, .proj = &.{}, .tmp = &.{}, .norm = &.{}, .head = undefined }; + t.proj = try gpa.alloc(f32, max_rows * lm.candidates); + errdefer gpa.free(t.proj); + t.tmp = try gpa.alloc(f32, living.in); + errdefer gpa.free(t.tmp); + t.norm = try gpa.alloc(f32, c.hidden); + errdefer gpa.free(t.norm); + const nw: [*]const u16 = @ptrCast(@alignCast(e.w.norm.addr())); + for (t.norm, nw[0..c.hidden]) |*o, h| o.* = lm.bfVal(h); + const q = e.w.head; + if (q.n != c.vocab or q.k != c.hidden) return error.UnsupportedShape; + const n: usize = q.n; + const k: usize = q.k; + t.head = .{ + .w = @as([*]const u32, @ptrCast(@alignCast(q.w.addr())))[0 .. n * k / 8], + .s = @as([*]const u16, @ptrCast(@alignCast(q.s.addr())))[0 .. n * k / 64], + .b = @as([*]const u16, @ptrCast(@alignCast(q.b.addr())))[0 .. n * k / 64], + .n = n, + .k = k, + }; + t.state = try st.initState(&e.arena, c, max_rows + 64, null); + t.ids = try e.arena.buffer(max_rows * 4); + // a learned folder's committed blocks (loaded by the engine) carried over, then the learner's Sites own the buffers + const keep = l.committed; + const a0 = try gpa.dupe(f32, l.aRows()[0 .. keep * living.in]); + defer gpa.free(a0); + const b0 = try gpa.dupe(f32, l.bRows()[0 .. keep * living.out]); + defer gpa.free(b0); + t.sites = try lw_sites.Sites.init(gpa, living.in, living.out, .{ .a = l.aRows(), .b = l.bRows(), .tau = l.tau.slice(f32, living.max_blocks) }); + errdefer t.sites.deinit(); + if (keep > 0) try t.sites.adopt(a0, b0, keep); + t.saved = keep; + t.publish(); + std.log.info("slide: GLM-5.3-Flash learns at layers.44 shared-expert down_proj: {d} committed ranks carried over", .{keep}); + return t; + } + + pub fn deinit(t: *Trainer, gpa: std.mem.Allocator) void { + var it = t.cache.valueIterator(); + while (it.next()) |c| c.free(gpa); + t.cache.deinit(gpa); + t.sites.deinit(); + gpa.free(t.proj); + gpa.free(t.tmp); + gpa.free(t.norm); + gpa.destroy(t); + } + + /// The Sites' rank and committed ranks told to the engine's change (its forward reads l.rank). + fn publish(t: *Trainer) void { + t.lw.rank = t.sites.rank; + var plain: usize = 0; + while (plain < t.sites.rank and t.lw.gate(plain / lm.block).* == -std.math.inf(f32)) plain += lm.block; + t.lw.committed = plain; + } + + /// The change in the served forward from here on (off: the stock forward). + pub fn attach(t: *Trainer, on: bool) void { + t.e.sync(); + t.publish(); + t.e.livingAttach(on); + } + + /// Ranks [0, ranks) kept in the model folder. v2 (when the engine has `living.spawnShard`): only the + /// ranks after those already saved, as a NEW append-only living-NNNN.safetensors listed in the index; earlier shards + /// are never rewritten. v1 fallback: the single living_weights.safetensors with every rank. + pub fn write(t: *Trainer, ranks: usize) !usize { + t.e.sync(); + defer t.publish(); + if (comptime @hasDecl(living, "spawnShard")) { + if (ranks <= t.saved) return 0; + const n = ranks - t.saved; + const topic: []const u8 = if (std.c.getenv("LW_TOPIC")) |v| std.mem.span(v) else "chat"; + const bytes = try living.spawnShard(t.gpa, t.e.dir, t.lw.aRows()[t.saved * living.in ..][0 .. n * living.in], t.lw.bRows()[t.saved * living.out ..][0 .. n * living.out], n, topic); + t.saved = ranks; + return bytes; + } + const bytes = try living.saveRows(t.gpa, t.e.dir, t.lw.aRows(), t.lw.bRows(), ranks); + t.saved = ranks; + return bytes; + } + + pub fn projected(t: *const Trainer, k: usize, rows: usize) []const f32 { + _ = k; + return t.proj[0 .. rows * lm.candidates]; + } + + fn tail(t: *const Trainer) lm.Tail { + return .{ .norm = t.norm, .head = t.head, .eps = t.e.c.eps }; + } + + pub fn step(t: *Trainer, ids: []const u32, start: usize, mode: Mode) !lm.Result { + if (ids.len < 2 or start < 1 or start >= ids.len or ids.len - 1 > max_rows) return error.BadExample; + if ((mode == .grad or mode == .learn) and t.sites.rank == 0) return error.NoOpenBlock; + const cap = try t.captured(ids, start); + const site = &t.sites.list[0]; + const t0 = std.c.mach_absolute_time(); + defer t.seconds_cpu += @as(f64, @floatFromInt(std.c.mach_absolute_time() - t0)) / 24e6; + switch (mode) { + .avoid, .seek => { + const y = if (mode == .avoid) site.avoid else site.seek; + const k: usize = if (mode == .avoid) lm.avoid_dims else lm.candidates; + const seed: u32 = if (mode == .avoid) 1 else 2; + const first = start - 1; + lm.sketch(cap.site, y, cap.rows, site.in, k, @intCast(t.sketched), seed, 1); + lm.sketch(cap.site[first * site.in ..], y, 1, site.in, k, @intCast((1 << 30) + t.sketched + first), seed, @floatFromInt(cap.rows - first)); + t.sketched += cap.rows; + return .{ .loss = 0, .recalled = false }; + }, + .project => { + lm.projectRows(cap.site, site.seek, t.proj, cap.rows, site.in, lm.candidates, t.tmp); + return .{ .loss = 0, .recalled = false }; + }, + .loss => return lm.step(t.gpa, t.tail(), cap, t.sites.lora(), null, 0), + .grad, .learn => { + const r = try lm.step(t.gpa, t.tail(), cap, t.sites.lora(), site.gb, t.sites.first()); + if (mode == .learn) t.sites.adam(); + return r; + }, + } + } + + fn key(ids: []const u32, start: usize) u64 { + var h = std.hash.Wyhash.init(0x4c57); + h.update(std.mem.sliceAsBytes(ids)); + h.update(std.mem.asBytes(&start)); + return h.final(); + } + + /// The example's capture, from the cache or one GPU forward. + pub fn captured(t: *Trainer, ids: []const u32, start: usize) !*const lm.Captured { + const k = key(ids, start); + if (t.cache.getPtr(k)) |c| return c; + if (t.cache_bytes > cache_cap) { + var it = t.cache.valueIterator(); + while (it.next()) |c| c.free(t.gpa); + t.cache.clearRetainingCapacity(); + t.cache_bytes = 0; + } + var c = try lm.Captured.alloc(t.gpa, ids.len - 1, start, living.in, t.e.c.hidden); + errdefer c.free(t.gpa); + const t0 = std.c.mach_absolute_time(); + try t.forward(ids, &c); + targets(&c, ids); + t.seconds_gpu += @as(f64, @floatFromInt(std.c.mach_absolute_time() - t0)) / 24e6; + t.captures += 1; + try t.cache.put(t.gpa, k, c); + t.cache_bytes += c.bytes(); + return t.cache.getPtr(k).?; + } + + /// Where layer 44's values sit after a backbone pass (prompt chunk or decode window scratch). + const Places = struct { site: Ref, ys: Ref, branch: Ref, post: Ref, comb: Ref, old: Ref }; + + /// One forward of `ids` (the change off) through the backbone into `c`: a prompt chunk, or 16-row decode windows. + fn forward(t: *Trainer, ids: []const u32, c: *lm.Captured) !void { + const e = t.e; + const rows: u32 = @intCast(ids.len - 1); + const pool = mtl.objc.Pool.push(); + defer pool.pop(); + e.sync(); + e.livingAttach(false); + defer e.livingAttach(true); + t.state.reset(); + @memcpy(ge.Engine.u32s(t.ids, rows), ids[0..rows]); + var x = e.ctx(); + x.s = &t.state; + if (e.pr) |*pr| { + const b = e.begin(); + var px = x; + px.sc = &pr.streams; + prompt_mod.backbone(pr, &px, b.enc, t.ids, rows, 0); + try e.finish(b.cb, b.enc); + t.take(c, .{ .site = pr.sact, .ys = pr.ys, .branch = pr.streams.branch, .post = pr.streams.post, .comb = pr.streams.comb, .old = pr.streams.x[1 - px.xi] }, 0, rows); + return; + } + var at: u32 = 0; + while (at < rows) { + const n = @min(st.max_rows, rows - at); + const b = e.begin(); + fwd.backbone(&x, b.enc, t.ids.at(@as(usize, at) * 4), n, at); + fwd.flipKda(&x); + try e.finish(b.cb, b.enc); + t.take(c, .{ .site = e.sc.acts, .ys = e.sc.ys, .branch = e.sc.branch, .post = e.sc.post, .comb = e.sc.comb, .old = e.sc.x[1 - x.xi] }, at, n); + at += n; + } + } + + /// Rows [at, at + n) of the pass into the capture: every row's site input, the answer rows' tail inputs. + fn take(t: *Trainer, c: *lm.Captured, p: Places, at: u32, n: u32) void { + const D = c.d; + const in = c.in; + const site: [*]const u16 = @ptrCast(@alignCast(p.site.addr())); + @memcpy(c.site[@as(usize, at) * in ..][0 .. @as(usize, n) * in], site[0 .. @as(usize, n) * in]); + const ys: [*]const u16 = @ptrCast(@alignCast(p.ys.addr())); + const br: [*]const u16 = @ptrCast(@alignCast(p.branch.addr())); + const post: [*]const f32 = @ptrCast(@alignCast(p.post.addr())); + const comb: [*]const f32 = @ptrCast(@alignCast(p.comb.addr())); + const old: [*]const u16 = @ptrCast(@alignCast(p.old.addr())); + _ = t; + for (0..n) |j| { + const r = at + j; // the row in the example + if (r + 1 < c.start) continue; // a question row: no loss there + const i = r + 1 - c.start; // its answer row + for (0..D) |d| { + c.ys0[i * D + d] = lm.bfVal(ys[j * D + d]); + c.branch0[i * D + d] = lm.bfVal(br[j * D + d]); + } + @memcpy(c.post[i * 4 ..][0..4], post[j * 4 ..][0..4]); + const cm = comb[j * 16 ..][0..16]; + for (0..4) |s| for (0..D) |d| { + // the expand's mix of the old streams, in its order: c[0 s] x0, then fma c[t s] xt + var mm = cm[0 * 4 + s] * lm.bfVal(old[(j * 4 + 0) * D + d]); + inline for (1..4) |tt| mm = @mulAdd(f32, cm[tt * 4 + s], lm.bfVal(old[(j * 4 + tt) * D + d]), mm); + c.cold[(i * 4 + s) * D + d] = mm; + }; + } + } + + /// The answer rows' targets (kept apart from `take`, which sees only the pass's buffers). + fn targets(c: *lm.Captured, ids: []const u32) void { + for (0..c.answers()) |i| c.targets[i] = ids[c.start + i]; + } + + /// A check for the bench (tf-glm-lw-check): the GPU's final hidden rows with the change ON against the CPU tail's, + /// on the answer rows of `ids`; returns the largest absolute difference and the largest |value|. + pub fn checkTail(t: *Trainer, ids: []const u32, start: usize) ![2]f32 { + const e = t.e; + const cap = try t.captured(ids, start); + const A = cap.answers(); + const D = cap.d; + const cpu = try t.gpa.alloc(f32, A * D); + defer t.gpa.free(cpu); + try lm.hiddenRows(t.gpa, t.tail(), cap, t.sites.lora(), cpu); + const rows: u32 = @intCast(ids.len - 1); + e.sync(); + t.publish(); + e.livingAttach(true); + t.state.reset(); + @memcpy(ge.Engine.u32s(t.ids, rows), ids[0..rows]); + var x = e.ctx(); + x.s = &t.state; + const pr = &(e.pr orelse return error.NeedsPromptChunks); + const b = e.begin(); + var px = x; + px.sc = &pr.streams; + prompt_mod.backbone(pr, &px, b.enc, t.ids, rows, 0); + try e.finish(b.cb, b.enc); + const h: [*]const u16 = @ptrCast(@alignCast(pr.streams.hidden.addr())); + var worst: f32 = 0; + var big: f32 = 0; + for (0..A) |i| for (0..D) |d| { + const g = lm.bfVal(h[(start - 1 + i) * D + d]); + worst = @max(worst, @abs(g - cpu[i * D + d])); + big = @max(big, @abs(g)); + }; + return .{ worst, big }; + } +}; diff --git a/zig/src/lw_glm_tests.zig b/zig/src/lw_glm_tests.zig new file mode 100644 index 00000000000..2c5074952a5 --- /dev/null +++ b/zig/src/lw_glm_tests.zig @@ -0,0 +1,6 @@ +//! Living Weights (GLM-5.3-Flash): every host-only file's tests in one binary, run by `zig build test` on every OS. +test { + _ = @import("families/glm/lw_math.zig"); + _ = @import("families/glm/lw_sites.zig"); + _ = @import("families/glm/lw_learner.zig"); +} diff --git a/zig/src/native/glm_host.zig b/zig/src/native/glm_host.zig index dab885b4721..8ee8a2a201b 100644 --- a/zig/src/native/glm_host.zig +++ b/zig/src/native/glm_host.zig @@ -7,6 +7,7 @@ const lanes = tf.lanes; const glm = tf.glm; const ge = glm.engine; const Allocator = std.mem.Allocator; +const glm_slide = @import("glm_slide.zig"); /// The warm-up reply's draft depth: every rank of a pair pays a process's first-round costs at the same step. const DEPTH = 2; @@ -24,6 +25,7 @@ pub const Host = struct { learned: ?api.prompt_imprint.Imprint = null, // --learn: shared states on disk (rank 1 keeps its halves there) warm: mtl.keepalive.Target, follower: ?std.Thread = null, // speed-up mode's rank 1: the thread replaying rank 0's slot commands + slide: ?*glm_slide.Adapter = null, // Sliding Weights' learner, with --slide pub fn engine(h: *Host) api.Engine { return h.host.engine(); @@ -76,7 +78,8 @@ fn learnedStates(gpa: Allocator, eng: *const ge.Engine, sl: *glm.slots.Slots, ro } /// A GLM-5.3-Flash checkpoint served: `window` tokens of cache a stream, warmed first (the pair: `speed_up`). -pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up: ?[]const u8, streams: u32, fixed: bool, cache_gib: ?f64, learn: ?[]const u8, learn_cap: u64) !*Host { +pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up: ?[]const u8, streams: u32, fixed: bool, cache_gib: ?f64, learn: ?[]const u8, learn_cap: u64, slide: bool) !*Host { + if (slide and speed_up != null) return error.SlideNeedsOneMac; // the learner runs on one Mac; the pair would need b shipped to rank 1 const eng = try ge.Engine.loadWith(gpa, dir, window + 64, speed_up, learn != null); errdefer eng.deinit(); var toks: [96]u32 = undefined; @@ -89,6 +92,7 @@ pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up: h.eng = eng; h.follower = null; h.learned = null; + h.slide = null; h.slots = try glm.slots.Slots.init(gpa, eng, try fit(eng, streams, fixed)); errdefer h.slots.deinit(gpa); const n: u32 = @intCast(h.slots.slots.len); @@ -115,6 +119,17 @@ pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up: if (h.cache) |*store| store.imprint = &h.learned.?; } errdefer if (h.learned) |*m| m.deinit(); + if (slide) { + const s = try gpa.create(glm_slide.Adapter); + s.* = glm_slide.Adapter.init(gpa, eng); + h.slide = s; + h.host.learner = s.hook(); + std.log.info("glm: --slide: Living Weights learns into {s} (append-only living-NNNN.safetensors shards, layers.44 shared-expert down_proj)", .{dir}); + } + errdefer if (h.slide) |s| { + s.deinit(); + gpa.destroy(s); + }; h.host.explain = .{ .text = words }; h.warm = eng.keepalive_target; h.host.keepalive_target = .{ .ctx = &h.warm, .tick = mtl.keepalive.Target.tick }; @@ -133,6 +148,10 @@ fn follow(h: *Host) void { pub fn close(ctx: *anyopaque) void { const h: *Host = @ptrCast(@alignCast(ctx)); h.host.stop(); + if (h.slide) |s| { + s.deinit(); + h.gpa.destroy(s); + } if (h.cache) |*store| store.deinit(); if (h.follower) |th| { // rank 1: its wait for rank 0's next command ends, then the thread h.eng.stopFollowing(); diff --git a/zig/src/native/glm_slide.zig b/zig/src/native/glm_slide.zig new file mode 100644 index 00000000000..743782cc321 --- /dev/null +++ b/zig/src/native/glm_slide.zig @@ -0,0 +1,64 @@ +//! GLM-5.3-Flash's Sliding Weights learner (layers.44 shared-expert down_proj) behind the lane host's learn hook. +const std = @import("std"); +const api = @import("engine_api"); +const tf = @import("tensorfold"); +const lw = tf.glm.lw_train; +const lwl = tf.glm.lw_learner; +const Allocator = std.mem.Allocator; + +pub const Adapter = struct { + learner: lw.Learner, + arena: std.heap.ArenaAllocator, + sink: ?api.LearnSink = null, + + pub fn init(gpa: Allocator, eng: *tf.glm.engine.Engine) Adapter { + return .{ .learner = lw.Learner.init(gpa, eng), .arena = .init(gpa) }; + } + + pub fn deinit(a: *Adapter) void { + a.learner.deinit(); + a.arena.deinit(); + } + + pub fn hook(a: *Adapter) api.Learner { + return .{ .ctx = a, .begin = begin, .step = step, .abort = abort }; + } + + fn begin(ctx: *anyopaque, request: *const api.LearnRequest, sink: api.LearnSink) anyerror!void { + const a: *Adapter = @ptrCast(@alignCast(ctx)); + _ = a.arena.reset(.retain_capacity); + const al = a.arena.allocator(); + try a.learner.begin(.{ .train = try examples(al, request.train), .held = try examples(al, request.held), .near = try examples(al, request.near), .keep = try examples(al, request.keep), .undo = request.undo, .steps = request.steps, .more = request.more, .commit = request.commit, .save = request.save }); + a.sink = sink; + } + + fn step(ctx: *anyopaque) api.Learner.Step { + const a: *Adapter = @ptrCast(@alignCast(ctx)); + const s = a.learner.step(); + const failed = if (s.report) |r| r == .failed else false; + if (s.report) |r| a.emit(switch (r) { + .learned => |x| .{ .learned = .{ .recalled = x.recalled, .steps = x.steps, .loss = x.loss } }, + .failed => |message| .{ .done = .{ .message = message } }, + }); + if (s.done and !failed) a.emit(.{ .done = .{} }); + if (s.done) if (a.learner.trainer) |t| std.log.info("slide: {d} GPU captures ({d:.1} s), CPU tail {d:.1} s so far", .{ t.captures, t.seconds_gpu, t.seconds_cpu }); + return .{ .done = s.done, .changed = s.changed }; + } + + fn abort(ctx: *anyopaque) void { + const a: *Adapter = @ptrCast(@alignCast(ctx)); + a.learner.abort(); + a.emit(.{ .done = .{ .message = "the engine closed" } }); + } + + fn emit(a: *Adapter, event: api.LearnEvent) void { + const sink = a.sink orelse return; + sink.event(sink.ctx, &event); + } +}; + +fn examples(al: Allocator, xs: []const api.Example) ![]lwl.Example { + const out = try al.alloc(lwl.Example, xs.len); + for (xs, out) |x, *o| o.* = .{ .ids = x.ids, .start = x.start }; + return out; +} diff --git a/zig/src/native/metal.zig b/zig/src/native/metal.zig index 23febfa4176..c5f05c9222b 100644 --- a/zig/src/native/metal.zig +++ b/zig/src/native/metal.zig @@ -245,7 +245,7 @@ fn openGlm(a: Allocator, gpa: Allocator, io: std.Io, o: api.Open, problem: *[]co } const pool = mtl.objc.Pool.push(); defer pool.pop(); - const h = glm.open(gpa, io, o.dir, @intCast(window), o.speed_up, o.lanes, o.lanes_fixed, o.prompt_cache_gib, o.learn, @intFromFloat(o.learn_gib * (1 << 30))) catch |e| { + const h = glm.open(gpa, io, o.dir, @intCast(window), o.speed_up, o.lanes, o.lanes_fixed, o.prompt_cache_gib, o.learn, @intFromFloat(o.learn_gib * (1 << 30)), o.slide) catch |e| { problem.* = try std.fmt.allocPrint(a, "the native GLM-5.3-Flash engine cannot load {s} ({s})", .{ o.dir, @errorName(e) }); return null; }; diff --git a/zig/src/server/slide_lesson.zig b/zig/src/server/slide_lesson.zig index ddff1b6ea9b..6df48f268eb 100644 --- a/zig/src/server/slide_lesson.zig +++ b/zig/src/server/slide_lesson.zig @@ -455,11 +455,30 @@ fn turnEnd(srv: *Server, cx: *Cx, teacher: *Teacher) ![]const u32 { const text = srv.text.render(a, .{ .array = exchange }, .{ .add_generation_prompt = false }, &problem) catch |e| return if (e == error.OutOfMemory) error.OutOfMemory else cx.refuse("the chat template cannot render an exchange"); const at = std.mem.lastIndexOf(u8, text, marker) orelse return cx.refuse("the chat template drops the assistant's words"); const tail = std.mem.trimEnd(u8, text[at + marker.len ..], " \t\r\n"); - const ids = srv.text.encode(teacher.arena.allocator(), tail, false) catch |e| return if (e == error.OutOfMemory) error.OutOfMemory else cx.refuse("the tokenizer cannot encode the turn's end"); + var ids: []const u32 = srv.text.encode(teacher.arena.allocator(), tail, false) catch |e| return if (e == error.OutOfMemory) error.OutOfMemory else cx.refuse("the tokenizer cannot encode the turn's end"); + if (ids.len == 0) ids = try nextTurn(srv, cx, teacher, marker); // GLM: nothing closes a turn but the next one's opening teacher.turn_end = ids; return ids; } +/// A template that closes no assistant turn (GLM-5.3: the reply ends where `<|user|>` begins, an end-of-sequence token): +/// the first token of what follows the assistant's words when another user turn comes after them. +fn nextTurn(srv: *Server, cx: *Cx, teacher: *Teacher, marker: []const u8) ![]const u32 { + const a = cx.a; + const next = "\u{2063}next"; + const exchange = try a.dupe(Value, &.{ try message(a, "user", "Hello."), try message(a, "assistant", marker), try message(a, "user", next) }); + var problem: []const u8 = ""; + const text = srv.text.render(a, .{ .array = exchange }, .{ .add_generation_prompt = false }, &problem) catch return &.{}; + const at = std.mem.lastIndexOf(u8, text, marker) orelse return &.{}; + const to = std.mem.lastIndexOf(u8, text, next) orelse return &.{}; + if (to <= at + marker.len) return &.{}; + const between = std.mem.trim(u8, text[at + marker.len .. to], " \t\r\n"); + const ids = srv.text.encode(a, between, false) catch return &.{}; + if (ids.len == 0) return &.{}; + std.log.info("slide: the template closes no assistant turn; lessons end each answer with the next turn's first token {d} (\"{s}\")", .{ ids[0], between }); + return teacher.arena.allocator().dupe(u32, ids[0..1]); +} + /// One greedy reply without thinking to `user`, after a system note when given. fn ask(srv: *Server, cx: *Cx, system: ?[]const u8, user: []const u8, max_tokens: i64, gone: anytype) chat.Failure!chat.Reply { const a = cx.a; From 81dfd06b94aa2acda087cd92cf0ec7679bc3cb31 Mon Sep 17 00:00:00 2001 From: indexer-bf16 Date: Fri, 9 Oct 2026 21:01:08 -0500 Subject: [PATCH 3/3] docs: Living Weights on GLM-5.3-Flash (experimental), its shards and measured numbers Co-Authored-By: Claude Opus 5.5 --- docs/living-weights.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/docs/living-weights.md b/docs/living-weights.md index 091fd0f6f88..8f4219bb228 100644 --- a/docs/living-weights.md +++ b/docs/living-weights.md @@ -137,3 +137,26 @@ Living Weights is experimental. Measured on Nemotron 3.5 Lightning: Before keeping a fact, it checks related questions it never trained on. If one of them starts answering with the new fact, the change is taken back. Even so, it remembers short, distinct facts best, can miss facts in long documents, and a fact can occasionally bleed into a related question. Keep the original model for anything that matters. + +## GLM-5.3-Flash (experimental) + +`tensorfold serve --slide` learns into GLM-5.3-Flash on one Mac, with the same `/v1/slide/learn` +API and the same lesson, gate, guard and undo as Nemotron. It changes one site: a low-rank addition after the last +layer's shared-expert down projection (`layers.44`). The model's own files are never written. Learned weights live in +separate shard files beside the model, `living-0001.safetensors`, `living-0002.safetensors`, …, listed in order in +`living_weights.index.json`; the server sums them at load. Dropping the newest shard from the index undoes that lesson +exactly. A folder with no shards serves exactly as before. + +- `LW_TOPIC=name` labels the shard a save writes (default `chat`); `LW_TOPICS=a,b` loads only shards of those topics. +- Each shard records the hash of the weight it was learned on; a shard from another checkpoint is refused at load. +- `--slide` with `--speed-up` is refused: the pair would need the change shipped to the second Mac. +- On a 256 GB Mac, Flash needs `GLM_LOAD_LIMIT_GB=200` (its 180.6 GB is over the 70% default) and `GLM_MLOCK=1` (wires + the weights while they load, so macOS does not compress them and stop the process for low swap). + +Measured on an M3 Ultra with 256 GB: with no shard, 20 of 20 greedy replies match the stock engine token for token at +draft depth 0 and 3, and the last-row logits are byte-identical. A 32-rank shard saved and reloaded in a new process gives +the same tokens and logits as the change held in RAM (20 of 20), costs no measurable decode speed (49.0–49.4 tok/s +against 48.7–49.2), and keeps draft depth 3 equal to depth 0. A learn of "I like blue." runs end to end in about 7.5 +minutes and the model answers "You like blue", but the guard has not yet let a GLM fact stay: one site at the last layer +did not separate "which colour do you like best?" from "which colour do I like?". Thinking-on recall and several facts at +once are not tested yet.