diff --git a/zig/build/cuda.zig b/zig/build/cuda.zig index 885ab97d45a..6ecae3f34ce 100644 --- a/zig/build/cuda.zig +++ b/zig/build/cuda.zig @@ -252,6 +252,7 @@ fn engines(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builti // the RDMA ring's verbs (rdma.zig) dsv41.addImport("fabric", b.createModule(.{ .root_source_file = b.path("zig/src/fabric/fabric.zig"), .target = target, .optimize = optimize, .link_libc = true })); const api = b.createModule(.{ .root_source_file = b.path("zig/src/core/engine_api.zig"), .target = target, .optimize = optimize, .link_libc = true, .imports = &.{.{ .name = "lanes", .module = lanes }} }); + dsv41.addImport("engine_api", api); const mod = b.createModule(.{ .root_source_file = b.path("zig/src/native/cuda.zig"), .target = target, diff --git a/zig/src/core/prompt_cache.zig b/zig/src/core/prompt_cache.zig index fffc2168fd0..659fc83049d 100644 --- a/zig/src/core/prompt_cache.zig +++ b/zig/src/core/prompt_cache.zig @@ -60,6 +60,8 @@ pub const Snapshots = struct { forget: ?*const fn (ptr: *anyopaque, dir: [:0]const u8, key: u64) void = null, /// --learn-conversations: the state's image as rows and parts, and copies out of and into kept states. rows: ?*const rows.Image = null, + /// A disk state's rows key stamped on `saved` so the family can name a peer's half file (null: none). + tag_disk: ?*const fn (ptr: *anyopaque, saved: Saved, name: u64) void = null, }; }; diff --git a/zig/src/core/rows_read.zig b/zig/src/core/rows_read.zig index f0d4bba8cb3..e65aff38165 100644 --- a/zig/src/core/rows_read.zig +++ b/zig/src/core/rows_read.zig @@ -21,6 +21,7 @@ pub fn read(r: *Rows, i: usize) !pc.Saved { defer wants.deinit(r.gpa); try r.blockNames(r.gpa, parts, s.tokens, s.spans, s.starts, s.at, &wants); const saved = try r.img.blank(r.family.ptr, s.at); + if (r.family.vtable.tag_disk) |t| t(r.family.ptr, saved, std.mem.readInt(u64, s.name[0..8], .little)); errdefer f.drop(r.family.ptr, saved); var ranges: std.ArrayList(image.Range) = .empty; defer ranges.deinit(r.gpa); diff --git a/zig/src/core/rows_write.zig b/zig/src/core/rows_write.zig index 96d3bf81da7..3c489f86159 100644 --- a/zig/src/core/rows_write.zig +++ b/zig/src/core/rows_write.zig @@ -130,6 +130,7 @@ fn prepare(r: *Rows, q: Queued) !?*Job { try image.ownRanges(parts, e.at, r.keying.block, &own, gpa); const j = try gpa.create(Job); j.* = .{ .entry = e, .starts = q.starts, .name = name, .parts = parts, .wants = &.{}, .own = &.{}, .began = nowNs() }; + if (r.family.vtable.tag_disk) |t| t(r.family.ptr, e.saved, std.mem.readInt(u64, name[0..8], .little)); j.wants = wants.toOwnedSlice(gpa) catch |err| { gpa.destroy(j); return err; diff --git a/zig/src/families/dsv41/disk.zig b/zig/src/families/dsv41/disk.zig new file mode 100755 index 00000000000..38e858c3138 --- /dev/null +++ b/zig/src/families/dsv41/disk.zig @@ -0,0 +1,184 @@ +//! DSV41 kept states on disk (--learn-conversations): the rows store serializes rank 0's image; rank 1 +//! keeps its half under a per-rank file named by the state's disk key, loaded on restore when its copy went. +const std = @import("std"); +const api = @import("engine_api"); +const lanes_mod = @import("lanes.zig"); +const cuda = @import("cuda"); +const rows = api.prompt_cache.rows; +const Lanes = lanes_mod.Lanes; +const Snap = lanes_mod.Snap; +const Allocator = std.mem.Allocator; + +const magic: u32 = 0x4453_5634; // "DSV4" +pub const Head = extern struct { magic: u32 = magic, version: u32 = 1, at: u64, disk_id: u64, bytes: u64, hash: u64 }; + +/// A rank's file for the disk state `key` (the rows state's name, low 64 bits) under `dir`. +pub fn path(buf: []u8, dir: []const u8, key: u64) ![:0]const u8 { + return std.fmt.bufPrintSentinel(buf, "{s}/ds41-{x:0>16}.snap", .{ dir, key }, 0); +} + +/// The disk state's bytes at `at` (one image part: the packed prefix, `at` tokens of this rank's rows). +pub fn snapBytes(m: anytype, at: u32) u64 { + return m.snapBytes(at); +} + +/// Write `payload` (this rank's half, `at` tokens) as `key`'s file under `dir`; partial writes never appear. +pub fn writeFile(dir: []const u8, key: u64, at: u64, payload: []const u8) !void { + var pbuf: [1200]u8 = undefined; + const file = try path(&pbuf, dir, key); + var tbuf: [1200]u8 = undefined; + const tmp = try std.fmt.bufPrintSentinel(&tbuf, "{s}.part", .{file}, 0); + const fd = std.c.open(tmp, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(std.c.mode_t, 0o600)); + if (fd < 0) return error.SnapshotWrite; + errdefer _ = std.c.unlink(tmp); + { + defer _ = std.c.close(fd); + const head: Head = .{ .at = at, .disk_id = key, .bytes = payload.len, .hash = std.hash.Wyhash.hash(0x6473, payload) }; + try put(fd, std.mem.asBytes(&head)); + try put(fd, payload); + if (std.c.fsync(fd) != 0) return error.SnapshotWrite; + } + if (std.c.rename(tmp, file) != 0) return error.SnapshotWrite; +} + +/// `key`'s file under `dir` into `out` (exactly `head.bytes` bytes): its header, checksum and length must agree. +pub fn readFile(dir: []const u8, key: u64, out: []u8) !void { + var pbuf: [1200]u8 = undefined; + const file = try path(&pbuf, dir, key); + const fd = std.c.open(file, .{ .ACCMODE = .RDONLY }, @as(std.c.mode_t, 0)); + if (fd < 0) return error.SnapshotRead; + defer _ = std.c.close(fd); + var head: Head = undefined; + if (std.c.pread(fd, std.mem.asBytes(&head).ptr, @sizeOf(Head), 0) != @sizeOf(Head)) return error.SnapshotRead; + if (head.magic != magic or head.version != 1 or head.disk_id != key or head.bytes != out.len) return error.SnapshotRead; + try get(fd, out, @sizeOf(Head)); + if (std.hash.Wyhash.hash(0x6473, out) != head.hash) return error.SnapshotRead; +} + +/// `key`'s file under `dir` removed (missing is fine). +pub fn unlinkFile(dir: []const u8, key: u64) void { + var pbuf: [1200]u8 = undefined; + const file = path(&pbuf, dir, key) catch return; + _ = std.c.unlink(file); +} + +/// This rank's spill files under `dir` trimmed to `cap` bytes, oldest modification first; `keep` stays. +pub fn trimDir(gpa: Allocator, dir: []const u8, cap: u64, keep: u64) void { + const Entry = struct { name: [64]u8, len: usize, bytes: u64, mtime: i64 }; + var list: std.ArrayList(Entry) = .empty; + defer list.deinit(gpa); + var dbuf: [1100]u8 = undefined; + const dz = std.fmt.bufPrintSentinel(&dbuf, "{s}", .{dir}, 0) catch return; + const d = std.c.opendir(dz) orelse return; + defer _ = std.c.closedir(d); + var total: u64 = 0; + while (std.c.readdir(d)) |ent| { + if (ent.type != std.c.DT.REG) continue; + const name = std.mem.sliceTo(&ent.name, 0); + if (!std.mem.startsWith(u8, name, "ds41-") or !std.mem.endsWith(u8, name, ".snap")) continue; + var fbuf: [1400]u8 = undefined; + const file = std.fmt.bufPrintSentinel(&fbuf, "{s}/{s}", .{ dir, name }, 0) catch continue; + var sx: std.os.linux.Statx = undefined; + if (std.c.statx(std.posix.AT.FDCWD, file, 0, .{ .MTIME = true, .SIZE = true }, &sx) != 0) continue; + var e: Entry = .{ .name = undefined, .len = name.len, .bytes = @intCast(@max(sx.size, 0)), .mtime = sx.mtime.sec }; + @memcpy(e.name[0..name.len], name); + list.append(gpa, e) catch return; + total += e.bytes; + } + if (total <= cap) return; + std.mem.sort(Entry, list.items, {}, struct { + fn lt(_: void, a: Entry, b: Entry) bool { + return a.mtime < b.mtime; + } + }.lt); + for (list.items) |e| { + if (total <= cap) break; + if (std.mem.eql(u8, e.name[0..e.len], "")) continue; + var kbuf: [24]u8 = undefined; + const ktext = e.name[5 .. 5 + 16]; + const key = std.fmt.parseInt(u64, ktext, 16) catch 0; + if (key == keep) continue; + var fbuf: [1400]u8 = undefined; + const file = std.fmt.bufPrintSentinel(&fbuf, "{s}/{s}", .{ dir, e.name[0..e.len] }, 0) catch continue; + _ = &kbuf; + if (std.c.unlink(file) == 0) total -= e.bytes; + } +} + +fn of(ptr: *anyopaque) *Lanes { + return @ptrCast(@alignCast(ptr)); +} + +fn savedOf(saved: api.prompt_cache.Saved) *Snap { + return @ptrCast(@alignCast(saved)); +} + +/// The store's view of a kept state: a single part, this rank's packed prefix of `at` tokens. +pub const image: rows.Image = .{ .parts = parts, .gather = gather, .blank = blank, .scatter = scatter, .whole = whole }; + +fn parts(ptr: *anyopaque, at: u32, out: *std.ArrayList(rows.image.Part), a: Allocator) anyerror!void { + try out.append(a, .{ .bytes = of(ptr).m.snapBytes(at) }); +} + +/// Ranges of a resident state out of its device buffer; the first gather after the state was stamped +/// publishes its disk key to the peer, which writes its own half's file in step. +fn gather(ptr: *anyopaque, saved: api.prompt_cache.Saved, ranges: []const rows.image.Range, out: []u8) anyerror!void { + const self = of(ptr); + const sn = savedOf(saved); + if (sn.disk_id != 0 and !sn.persisted) try self.publishPersist(sn); + var o: usize = 0; + for (ranges) |g| { + const len: usize = @intCast(g.len); + defer o += len; + try sn.buf.download(@intCast(g.off), out[o..][0..len]); + } +} + +/// A new kept state of `at` tokens for the store's disk reads: this rank's buffer registered, the peer's +/// half comes from its file on the restore that follows. +fn blank(ptr: *anyopaque, at: u32) anyerror!api.prompt_cache.Saved { + const self = of(ptr); + const sn = try self.gpa.create(Snap); + errdefer self.gpa.destroy(sn); + sn.* = .{ .id = self.next_snap, .at = at, .base = 0, .buf = try cuda.DeviceBuffer.alloc(self.m.ctx.d, self.m.snapBytes(at)), .backed = true }; + errdefer sn.buf.free(); + try self.snaps.append(self.gpa, sn); + self.next_snap += 1; + return sn; +} + +fn scatter(_: *anyopaque, saved: api.prompt_cache.Saved, ranges: []const rows.image.Range, in: []const u8) anyerror!void { + const sn = savedOf(saved); + var o: usize = 0; + for (ranges) |g| { + const len: usize = @intCast(g.len); + try sn.buf.upload(@intCast(g.off), in[o..][0..len]); + o += len; + } +} + +/// A state no longer resident (overwritten rows, dropped copy) cannot be read whole. +fn whole(ptr: *anyopaque, saved: api.prompt_cache.Saved) bool { + const sn = savedOf(saved); + return std.mem.indexOfScalar(*Snap, of(ptr).snaps.items, sn) != null and (sn.backed or !sn.stale); +} + +/// Every byte of `b` written, or a write error. +fn put(fd: c_int, b: []const u8) !void { + var off: usize = 0; + while (off < b.len) { + const n = std.c.write(fd, b.ptr + off, b.len - off); + if (n <= 0) return error.SnapshotWrite; + off += @intCast(n); + } +} + +/// Every byte of `out` read at `pos`, or a read error. +fn get(fd: c_int, out: []u8, pos: usize) !void { + var off: usize = 0; + while (off < out.len) { + const n = std.c.pread(fd, out.ptr + off, out.len - off, @intCast(pos + off)); + if (n <= 0) return error.SnapshotRead; + off += @intCast(n); + } +} diff --git a/zig/src/families/dsv41/lanes.zig b/zig/src/families/dsv41/lanes.zig index 9c3ce3eca83..d15b06120d4 100644 --- a/zig/src/families/dsv41/lanes.zig +++ b/zig/src/families/dsv41/lanes.zig @@ -23,6 +23,7 @@ const round = @import("round.zig"); const draft = @import("draft.zig"); const sampling = @import("sampling.zig"); const link = @import("link.zig"); +const disk_mod = @import("disk.zig"); const cuda = @import("cuda"); const be = lanes.backend; @@ -41,7 +42,7 @@ pub const image_piece = 32 << 10; pub var logits_sha = false; /// The primitives rank 0 sends rank 1 (each frame: kind u8, step u64, its fields little-endian). -pub const Kind = enum(u8) { fill_begin = 1, fill_chunk = 2, verify = 3, pass = 4, snap_save = 5, snap_restore = 6, snap_drop = 7, fill_images = 8, done = 9, fill_switch = 10 }; +pub const Kind = enum(u8) { fill_begin = 1, fill_chunk = 2, verify = 3, pass = 4, snap_save = 5, snap_restore = 6, snap_drop = 7, fill_images = 8, done = 9, fill_switch = 10, snap_persist = 11 }; /// A frame being written. pub const Wire = struct { @@ -98,6 +99,36 @@ pub const Reader = struct { } }; +/// Both snapshot operations describe the complete independent buffer on every rank. +const SnapshotView = struct { + id: u64, + slot: u32, + base: u64, + at: u64, + bytes: u64, + disk_id: u64 = 0, // the rows store key of a state read back from disk (0: resident only) + + fn write(v: SnapshotView, wire: *Wire, gpa: std.mem.Allocator) !void { + try wire.int(gpa, u64, v.id); + try wire.int(gpa, u32, v.slot); + try wire.int(gpa, u64, v.base); + try wire.int(gpa, u64, v.at); + try wire.int(gpa, u64, v.bytes); + try wire.int(gpa, u64, v.disk_id); + } + + fn read(reader: *Reader) !SnapshotView { + return .{ .id = try reader.int(u64), .slot = try reader.int(u32), .base = try reader.int(u64), + .at = try reader.int(u64), .bytes = try reader.int(u64), .disk_id = try reader.int(u64) }; + } + + fn validate(v: SnapshotView, m: *const Model) !void { + if (v.at == 0) return error.BadSnapshot; + try m.snapView(v.slot, @intCast(v.base), @intCast(v.at)); + if (v.bytes != m.snapBytes(@intCast(v.at))) return error.BadSnapshot; + } +}; + /// A window of a round as both ranks build it: its stream's slot and extent, its first position, whether its rows' /// taps go into the drafter, its rows' ids. pub const Win = struct { slot: usize, base: usize, end: usize, start: usize, absorb: bool, ids: []const i32 }; @@ -328,16 +359,17 @@ const Lane = struct { extern "c" fn exp(x: f64) f64; -/// A kept prompt state (the prompt cache's saved state, kept at a chunk end the prompt pass reached before its -/// replay): the slot's own part on the device (Model.snapCopy), and the extent its compressed rows stay in, -/// [base, base + at), held back from placement while it lives. Stale: a placement needed that room (its restore fails -/// and the prompt runs from 0). +/// A prompt-cache state before replay. Production saves own the slot and packed prefix in buf; +/// base/end describe their former working extent. Resident-only fixtures retain their stale/pinning controls. pub const Snap = struct { id: u64, at: usize, base: usize, buf: cuda.DeviceBuffer, - stale: bool = false, + stale: bool = false, // loss of resident-only working rows, not independent backing + backed: bool = false, // every production save owns the complete prefix + disk_id: u64 = 0, // the rows store's key stamped when the state heads for disk (0: not bound for it) + persisted: bool = false, // the peer already heard its half's disk key (one snap_persist a state) wanted: u64 = 0, // when a request first waited for the live stream that holds these rows (placeKept; 0: none) end: usize = 0, // the extent end of the stream that kept it (placement holds [base, end) back while room allows) }; @@ -746,7 +778,7 @@ pub const Lanes = struct { sn.wanted = 0; if (!moved) sn.end = @max(sn.end, base + size); // its extent now: the next resume in place finds it held } - if (kept) |sn| if (moved and sn.stale) { // the placement needed the kept rows' room: the prompt runs from 0 + if (kept) |sn| if (moved and sn.stale and !sn.backed) { // resident-only state lost its rows if (sn.at >= note_rows) std.log.info("dsv41: the kept state of {d} tokens at {d} found no room to move to ({d} positions); the prompt runs from 0", .{ sn.at, sn.base, size }); kept = null; s.reuse_failed = true; @@ -813,16 +845,20 @@ pub const Lanes = struct { const replay = len -| m.cfg.window; var start: usize = 0; if (kept) |sn| { - if (try self.begin(.snap_restore)) { - try self.wire.int(gpa, u64, sn.id); - try self.wire.int(gpa, u32, @intCast(slot)); - try self.wire.int(gpa, u64, sn.base); - try self.wire.int(gpa, u64, base); - try self.wire.int(gpa, u64, sn.at); - try self.flush(); + if (!sn.backed) return error.BadSnapshot; + if (self.peer != null) { + self.wire.begin(gpa, .snap_restore, self.step) catch |err| Model.snapshotFatal(err); + (SnapshotView{ .id = sn.id, .slot = @intCast(slot), .base = base, + .at = sn.at, .bytes = sn.buf.len, .disk_id = sn.disk_id }).write(&self.wire, gpa) catch |err| Model.snapshotFatal(err); + self.flush() catch |err| Model.snapshotFatal(err); + self.step += 1; + if (sn.disk_id != 0) { // the peer's half comes off its disk: it answers whether it could load it + var ack: [1]u8 = .{0}; + const got = self.peer.?.recvSpin(&ack, 120 * std.time.ns_per_s) catch |err| Model.snapshotFatal(err); + if (got.len != 1 or ack[0] != 1) return error.DiskRestoreRefused; + } } - if (base != sn.base) try m.copyExtent(sn.base, base, sn.at); - try m.snapCopy(slot, sn.buf.ptr, false); + m.snapCopy(slot, base, sn.at, sn.buf.ptr, false) catch |err| Model.snapshotFatal(err); start = sn.at; s.cached = @intCast(sn.at); } @@ -1052,7 +1088,7 @@ pub const Lanes = struct { /// pass of this prompt runs them). fn refusal(self: *const Lanes, sn: *const Snap, len: usize) ?Refusal { if (std.mem.indexOfScalar(*Snap, self.snaps.items, @constCast(sn)) == null) return .dropped; - if (sn.stale) return .stale; + if (sn.stale and !sn.backed) return .stale; if (sn.at == 0 or sn.at >= len) return .short; if (sn.at % model.resume_rows != 0) return .off_chunk; if (sn.at > len -| self.m.cfg.window) return .near_end; @@ -1074,12 +1110,12 @@ pub const Lanes = struct { defer kept.deinit(gpa); var rows: std.ArrayList([2]usize) = .empty; defer rows.deinit(gpa); - const held = if (source) |sn| !sn.stale and clashes(live, sn.base, sn.base + sn.at) else false; + const held = if (source) |sn| !sn.backed and !sn.stale and clashes(live, sn.base, sn.base + sn.at) else false; while (true) { kept.clearRetainingCapacity(); rows.clearRetainingCapacity(); try rows.appendSlice(gpa, live); - for (self.snaps.items) |sn| if (!sn.stale) { + for (self.snaps.items) |sn| if (!sn.backed and !sn.stale) { try kept.append(gpa, .{ sn.base, sn.at, sn.end }); try rows.append(gpa, .{ sn.base, sn.base + sn.at }); }; @@ -1089,9 +1125,10 @@ pub const Lanes = struct { return if (try roomAfter(gpa, rows.items, b, size, self.m.pool_cap)) b else error.ContextFull; } if (got) |b| return b; + if (place(live, size, self.m.pool_cap) == null) return error.ContextFull; const victim = for (self.snaps.items) |sn| { - if (!sn.stale and sn != source and !clashes(live, sn.base, sn.base + sn.at)) break sn; - } else if (source) |sn| (if (!sn.stale and !clashes(live, sn.base, sn.base + sn.at)) sn else return error.ContextFull) else return error.ContextFull; + if (!sn.backed and !sn.stale and sn != source and !clashes(live, sn.base, sn.base + sn.at)) break sn; + } else if (source) |sn| (if (!sn.backed and !sn.stale and !clashes(live, sn.base, sn.base + sn.at)) sn else return error.ContextFull) else return error.ContextFull; noteStale(victim, "a placement needed its room (oldest first)"); victim.stale = true; } @@ -1099,7 +1136,7 @@ pub const Lanes = struct { /// Whether a kept state other than `except` and its shorter siblings has rows in [lo, hi); a longer one may be another conversation's. fn keptOver(self: *const Lanes, lo: usize, hi: usize, except: *const Snap) bool { - for (self.snaps.items) |sn| if (sn != except and !sn.stale and (sn.base != except.base or sn.at > except.at) and sn.base < hi and lo < sn.base + sn.at) return true; + for (self.snaps.items) |sn| if (!sn.backed and sn != except and !sn.stale and (sn.base != except.base or sn.at > except.at) and sn.base < hi and lo < sn.base + sn.at) return true; return false; } @@ -1112,7 +1149,7 @@ pub const Lanes = struct { /// Kept states with rows in [lo, hi) go stale (a stream writes there), `except` aside. fn staleOver(self: *Lanes, lo: usize, hi: usize, except: ?*Snap) void { - for (self.snaps.items) |sn| if (sn != except and sn.base < hi and lo < sn.base + sn.at) { + for (self.snaps.items) |sn| if (!sn.backed and sn != except and sn.base < hi and lo < sn.base + sn.at) { if (!sn.stale) noteStale(sn, "a stream writes over its rows"); sn.stale = true; }; @@ -1120,28 +1157,36 @@ pub const Lanes = struct { /// The prompt cache's Snapshots functions (native.zig hands them to the CUDA host). pub fn snapBytesFn(ptr: *anyopaque, at: u32) u64 { - _ = at; - return of(ptr).m.snapBytes(); + return of(ptr).m.snapBytes(at); } - /// The live state at `at` (the pass stands at that chunk end): the slot's own part copied, the extent's rows kept. + /// Publish complete backing only after all recoverable local work succeeds. pub fn snapSaveFn(ptr: *anyopaque, owner: ?*anyopaque, at: u32) anyerror!*anyopaque { const self = of(ptr); const s: *const lanes.Stream = @ptrCast(@alignCast(owner orelse return error.NoStream)); const l = self.streams.getPtr(s) orelse return error.UnknownStream; if (at == 0 or at % model.resume_rows != 0 or at > s.prompt_len -| self.m.cfg.window) return error.NotAChunkEnd; + try self.m.snapView(l.slot, l.base, at); const sn = try self.gpa.create(Snap); errdefer self.gpa.destroy(sn); - sn.* = .{ .id = self.next_snap, .at = at, .base = l.base, .end = l.end, .buf = try cuda.DeviceBuffer.alloc(self.m.ctx.d, self.m.snapBytes()) }; + sn.* = .{ .id = self.next_snap, .at = at, .base = l.base, .end = l.end, .backed = true, + .buf = try cuda.DeviceBuffer.alloc(self.m.ctx.d, self.m.snapBytes(at)) }; errdefer sn.buf.free(); - try self.snaps.append(self.gpa, sn); - self.next_snap += 1; - if (try self.begin(.snap_save)) { - try self.wire.int(self.gpa, u64, sn.id); - try self.wire.int(self.gpa, u32, @intCast(l.slot)); - try self.flush(); + try self.snaps.ensureUnusedCapacity(self.gpa, 1); + // Build the frame without consuming a step; allocation/copy refusal leaves no published pointer. + if (self.peer != null) { + try self.wire.begin(self.gpa, .snap_save, self.step); + try (SnapshotView{ .id = sn.id, .slot = @intCast(l.slot), .base = l.base, + .at = at, .bytes = sn.buf.len }).write(&self.wire, self.gpa); } - try self.m.snapCopy(l.slot, sn.buf.ptr, true); + try self.m.snapCopy(l.slot, l.base, at, sn.buf.ptr, true); + try self.m.stream.synchronize(); // deferred local copy errors must precede peer publication + if (self.peer != null) { + self.flush() catch |err| Model.snapshotFatal(err); // delivery may already have reached some peers + self.step += 1; + } + self.snaps.appendAssumeCapacity(sn); + self.next_snap += 1; return sn; } @@ -1158,25 +1203,42 @@ pub const Lanes = struct { return false; } - /// Whether a kept state still holds its rows: one a stream wrote over leaves the prompt cache. + /// Independent backing remains live after its former working rows are overwritten. pub fn snapLiveFn(ptr: *anyopaque, saved: *anyopaque) bool { const sn: *Snap = @ptrCast(@alignCast(saved)); - return std.mem.indexOfScalar(*Snap, of(ptr).snaps.items, sn) != null and !sn.stale; + return std.mem.indexOfScalar(*Snap, of(ptr).snaps.items, sn) != null and (sn.backed or !sn.stale); } pub fn snapDropFn(ptr: *anyopaque, saved: *anyopaque) void { const self = of(ptr); const sn: *Snap = @ptrCast(@alignCast(saved)); const i = std.mem.indexOfScalar(*Snap, self.snaps.items, sn) orelse return; - _ = self.snaps.orderedRemove(i); - if (self.begin(.snap_drop) catch false) { - self.wire.int(self.gpa, u64, sn.id) catch {}; - self.flush() catch |err| std.log.err("dsv41: rank 1 kept a dropped prompt state: {s}", .{@errorName(err)}); + if (self.begin(.snap_drop) catch |err| Model.snapshotFatal(err)) { + self.wire.int(self.gpa, u64, sn.id) catch |err| Model.snapshotFatal(err); + self.flush() catch |err| Model.snapshotFatal(err); // peer buffers must not escape head accounting } + _ = self.snaps.orderedRemove(i); sn.buf.free(); self.gpa.destroy(sn); } + /// The peer writes its half of a state bound for disk, named by the rows store's key (once a state). + pub fn publishPersist(self: *Lanes, sn: *Snap) !void { + sn.persisted = true; + if (try self.begin(.snap_persist)) { + try self.wire.int(self.gpa, u64, sn.id); + try self.wire.int(self.gpa, u64, sn.disk_id); + try self.flush(); + } + } + + /// The rows store's key of the state heading for disk, for the peer half's file name. + pub fn snapTagDiskFn(ptr: *anyopaque, saved: *anyopaque, name: u64) void { + _ = ptr; + const sn: *Snap = @ptrCast(@alignCast(saved)); + sn.disk_id = name; + } + fn releaseFn(ptr: *anyopaque, s: *lanes.Stream) void { const self = of(ptr); if (self.fillOf(s)) |f| { @@ -1215,6 +1277,12 @@ pub var follow_prof: struct { rounds: u64 = 0, enqueue: u64 = 0, forward: u64 = /// Rank 1 (each of ranks 1-3 on the four-node split): the primitives rank 0 sends, run in order until it says done. pub fn follow(gpa: std.mem.Allocator, m: *Model) !void { const peer = m.peer(); + // the peer half's spill files under TF_DS_SPILL_DIR (its LRU by mtime, TF_DS_SPILL_GIB at most) + const spill_dir: ?[]const u8 = if (std.c.getenv("TF_DS_SPILL_DIR")) |v| if (std.mem.span(v).len > 0) std.mem.span(v) else null else null; + const spill_cap: u64 = blk: { + const v = std.c.getenv("TF_DS_SPILL_GIB") orelse break :blk 64 << 30; + break :blk (std.fmt.parseInt(u64, std.mem.span(v), 10) catch 64) << 30; + }; const buf = try gpa.alloc(u8, (m.pool_cap + 1) * 4 + (1 << 16)); defer gpa.free(buf); var seqs: [max_streams]std.ArrayList(i32) = @splat(.empty); @@ -1226,10 +1294,11 @@ pub fn follow(gpa: std.mem.Allocator, m: *Model) !void { var slot: usize = 0; var img_rows: std.ArrayList(u8) = .empty; // a prompt's image rows as their pieces come defer img_rows.deinit(gpa); - var kept: std.AutoHashMapUnmanaged(u64, cuda.DeviceBuffer) = .empty; // rank 0's kept states, this rank's part + const Kept = struct { buf: cuda.DeviceBuffer, at: usize }; + var kept: std.AutoHashMapUnmanaged(u64, Kept) = .empty; // complete mirrored prefix backing defer { var ki = kept.valueIterator(); - while (ki.next()) |b| b.free(); + while (ki.next()) |value| value.buf.free(); kept.deinit(gpa); } while (true) { @@ -1247,6 +1316,7 @@ pub fn follow(gpa: std.mem.Allocator, m: *Model) !void { 8 => .fill_images, 9 => .done, 10 => .fill_switch, + 11 => .snap_persist, else => return error.BadFrame, }; if (try r.int(u64) != step) return error.OutOfStep; @@ -1339,33 +1409,47 @@ pub fn follow(gpa: std.mem.Allocator, m: *Model) !void { } }, .snap_save => { - const id = try r.int(u64); - const s: usize = try r.int(u32); - if (s >= max_streams) return error.BadSlot; - var b = try cuda.DeviceBuffer.alloc(m.ctx.d, m.snapBytes()); - m.snapCopy(s, b.ptr, true) catch |err| { - b.free(); - try refused(m, err); - continue; - }; - try kept.put(gpa, id, b); + const view = SnapshotView.read(&r) catch |err| Model.snapshotFatal(err); + view.validate(m) catch |err| Model.snapshotFatal(err); + if (kept.contains(view.id) or r.at != r.b.len) Model.snapshotFatal(error.BadSnapshot); + const b = cuda.DeviceBuffer.alloc(m.ctx.d, @intCast(view.bytes)) catch |err| Model.snapshotFatal(err); + m.snapCopy(view.slot, @intCast(view.base), @intCast(view.at), b.ptr, true) catch |err| Model.snapshotFatal(err); + m.stream.synchronize() catch |err| Model.snapshotFatal(err); + kept.put(gpa, view.id, .{ .buf = b, .at = @intCast(view.at) }) catch |err| Model.snapshotFatal(err); }, .snap_restore => { - const id = try r.int(u64); - const s: usize = try r.int(u32); - if (s >= max_streams) return error.BadSlot; - const from: usize = @intCast(try r.int(u64)); - const to: usize = @intCast(try r.int(u64)); - const at: usize = @intCast(try r.int(u64)); - const b = kept.get(id) orelse return error.UnknownSnapshot; // rank 0 restores only states both ranks keep - if (from != to) m.copyExtent(from, to, at) catch |err| try refused(m, err); - m.snapCopy(s, b.ptr, false) catch |err| try refused(m, err); + const view = SnapshotView.read(&r) catch |err| Model.snapshotFatal(err); + view.validate(m) catch |err| Model.snapshotFatal(err); + if (r.at != r.b.len) Model.snapshotFatal(error.BadSnapshot); + var saved = kept.get(view.id); + if (saved == null and view.disk_id != 0 and spill_dir != null) { + const b = loadHalf(gpa, m, spill_dir.?, view.disk_id, view.bytes) catch { + peer.send(&.{0}) catch {}; + continue; + }; + kept.put(gpa, view.id, .{ .buf = b, .at = @intCast(view.at) }) catch |err| Model.snapshotFatal(err); + peer.send(&.{1}) catch |err| Model.snapshotFatal(err); // rank 0 waits on it before its own copy + saved = .{ .buf = b, .at = @intCast(view.at) }; + } + const sv = saved orelse Model.snapshotFatal(error.UnknownSnapshot); + if (sv.at != view.at or sv.buf.len != view.bytes) Model.snapshotFatal(error.BadSnapshot); + m.snapCopy(view.slot, @intCast(view.base), @intCast(view.at), sv.buf.ptr, false) catch |err| Model.snapshotFatal(err); + }, + .snap_persist => { + const snap_id = try r.int(u64); + const disk_id = try r.int(u64); + if (r.at != r.b.len) Model.snapshotFatal(error.BadFrame); + if (spill_dir) |dir| if (kept.get(snap_id)) |kh| { + persistHalf(gpa, kh.buf, dir, disk_id, kh.at) catch |err| + std.log.warn("dsv41: the peer half for {x} went unwritten: {s}", .{ disk_id, @errorName(err) }); + disk_mod.trimDir(gpa, dir, spill_cap, disk_id); + }; }, .snap_drop => { const id = try r.int(u64); if (kept.fetchRemove(id)) |kv| { - var b = kv.value; - b.free(); + var saved = kv.value; + saved.buf.free(); } }, .done => { @@ -1621,3 +1705,125 @@ test "passCap: resume_rows below pass_from, then pass_rows" { try std.testing.expectEqual(@as(usize, model.resume_rows), ln.passCap(3 * model.resume_rows)); try std.testing.expectEqual(@as(usize, model.chunk_rows), ln.passCap(4 * model.resume_rows)); } + +test "full prefix: backed snapshots survive overwrite and never pin live placement" { + var m: Model = undefined; + m.cfg.window = model.chunk_rows; + m.pool_cap = 16 * model.chunk_rows; + var ln: Lanes = .{ .gpa = std.testing.allocator, .m = &m, .peer = null }; + defer ln.snaps.deinit(std.testing.allocator); + var backed: Snap = .{ .id = 0, .at = 6 * model.chunk_rows, .base = 0, + .end = 12 * model.chunk_rows, .buf = undefined, .backed = true }; + try ln.snaps.append(std.testing.allocator, &backed); + ln.staleOver(0, m.pool_cap, null); + try std.testing.expect(!backed.stale); + backed.stale = true; // loss of the old working copy is irrelevant to independent backing + try std.testing.expect(ln.refusal(&backed, 8 * model.chunk_rows) == null); + try std.testing.expect(Lanes.snapLiveFn(&ln, &backed)); + try std.testing.expect(Lanes.snapResumesFn(&ln, &backed, 8 * model.chunk_rows)); + try std.testing.expect(!ln.keptOver(0, m.pool_cap, &backed)); + const live = [_][2]usize{.{ 8 * model.chunk_rows, 16 * model.chunk_rows }}; + try std.testing.expectEqual(@as(usize, 0), try ln.placeKept(&live, 8 * model.chunk_rows, &backed)); + try std.testing.expectEqual(@as(u64, 0), backed.wanted); + try std.testing.expectError(error.ContextFull, ln.placeKept(&live, 10 * model.chunk_rows, &backed)); + try std.testing.expect(ln.refusal(&backed, 8 * model.chunk_rows) == null); + try std.testing.expect(Lanes.snapLiveFn(&ln, &backed)); + try std.testing.expect(Lanes.snapResumesFn(&ln, &backed, 8 * model.chunk_rows)); +} + +test "full prefix: complete snapshot frames preserve base position and byte count" { + const view: SnapshotView = .{ .id = 0xabc, .slot = 7, .base = 172032, .at = 169856, .bytes = 157856512 }; + for ([_]Kind{ .snap_save, .snap_restore }) |kind| { + var wire: Wire = .{}; + defer wire.deinit(std.testing.allocator); + try wire.begin(std.testing.allocator, kind, 49); + try view.write(&wire, std.testing.allocator); + var reader: Reader = .{ .b = wire.buf.items }; + try std.testing.expectEqual(@backingInt(kind), try reader.int(u8)); + try std.testing.expectEqual(@as(u64, 49), try reader.int(u64)); + const result = try SnapshotView.read(&reader); + try std.testing.expectEqualDeep(view, result); + try std.testing.expectEqual(reader.b.len, reader.at); + reader.b = reader.b[0 .. reader.b.len - 1]; + reader.at = 9; + try std.testing.expectError(error.ShortFrame, SnapshotView.read(&reader)); + } +} + +const SaveRefusalCpu = struct { + var buffer: [65536]u8 = undefined; + var allocations: usize = 0; + var frees: usize = 0; + + fn allocate(out: *u64, bytes: usize) callconv(.c) c_int { + std.debug.assert(bytes <= buffer.len); + out.* = @intFromPtr(&buffer); + allocations += 1; + return 0; + } + fn free(_: u64) callconv(.c) c_int { frees += 1; return 0; } + fn refuseCopy(_: u64, _: u64, _: usize, _: cuda.abi.Stream) callconv(.c) c_int { return 600; } +}; + +test "full prefix: refused local save releases allocation without publishing pointer or wire step" { + var driver: cuda.Driver = undefined; + driver.api.cuMemAlloc_v2 = SaveRefusalCpu.allocate; + driver.api.cuMemFree_v2 = SaveRefusalCpu.free; + driver.api.cuMemcpyDtoDAsync_v2 = SaveRefusalCpu.refuseCopy; + const context: cuda.Context = .{ .d = &driver, .device = 0, .handle = null }; + var cfg: @import("config.zig").Config = undefined; + cfg.layers = 1; + cfg.head_dim = 32; + cfg.window = 128; + var weights: @import("weights.zig").Weights = undefined; + weights.layers = &.{}; + var m: Model = undefined; + m.ctx = &context; + m.stream = .{ .d = &driver, .handle = null }; + m.streams = 2; + m.pool_cap = 8192; + m.cfg = cfg; + m.eng.c = &cfg; + m.eng.w = &weights; + m.caches = .{}; + var rings = [_]u64{1}; // no copy dereferences this address: the fake driver refuses first + m.rings = &rings; + var ln: Lanes = .{ .gpa = std.testing.allocator, .m = &m, .peer = null }; + defer ln.snaps.deinit(std.testing.allocator); + defer ln.streams.deinit(std.testing.allocator); + const ids = try std.testing.allocator.alloc(u32, 4096); + defer std.testing.allocator.free(ids); + @memset(ids, 1); + var stream = try lanes.Stream.init(std.testing.allocator, .{ .id = "synthetic-save-refusal", .prompt = ids, .max_new = 400, .drafts = false }); + defer stream.deinit(std.testing.allocator); + try ln.streams.put(std.testing.allocator, &stream, .{ .slot = 0, .base = 0, .end = 8192 }); + SaveRefusalCpu.allocations = 0; + SaveRefusalCpu.frees = 0; + const before_id = ln.next_snap; + const before_step = ln.step; + try std.testing.expectError(error.NotReady, Lanes.snapSaveFn(&ln, &stream, 2048)); + try std.testing.expectEqual(@as(usize, 1), SaveRefusalCpu.allocations); + try std.testing.expectEqual(@as(usize, 1), SaveRefusalCpu.frees); + try std.testing.expectEqual(@as(usize, 0), ln.snaps.items.len); + try std.testing.expectEqual(before_id, ln.next_snap); + try std.testing.expectEqual(before_step, ln.step); +} + +/// A disk half of `key` under `dir` into new device storage (rank 1's part of a state rank 0 reads back). +fn loadHalf(gpa: std.mem.Allocator, m: *Model, dir: []const u8, key: u64, bytes: u64) !cuda.DeviceBuffer { + var b = try cuda.DeviceBuffer.alloc(m.ctx.d, @intCast(bytes)); + errdefer b.free(); + const host = try gpa.alloc(u8, @intCast(bytes)); + defer gpa.free(host); + try disk_mod.readFile(dir, key, host); + try b.upload(0, host); + return b; +} + +/// This rank's `buf` of `at` tokens as `key`'s spill file under `dir`. +fn persistHalf(gpa: std.mem.Allocator, buf: cuda.DeviceBuffer, dir: []const u8, key: u64, at: usize) !void { + const host = try gpa.alloc(u8, buf.len); + defer gpa.free(host); + try buf.download(0, host); + try disk_mod.writeFile(dir, key, at, host); +} diff --git a/zig/src/families/dsv41/model.zig b/zig/src/families/dsv41/model.zig index d2007ca822d..7039dc3d30e 100644 --- a/zig/src/families/dsv41/model.zig +++ b/zig/src/families/dsv41/model.zig @@ -514,6 +514,13 @@ pub const Model = struct { m.watch.stop(); } + /// A mirrored snapshot failure cannot be recovered by one rank alone. Closing this process's + /// links lets the existing peer watch stop the other ranks without waiting on a stuck GPU. + pub fn snapshotFatal(err: anyerror) noreturn { + std.log.err("dsv41: mirrored snapshot failed: {s}", .{@errorName(err)}); + std.c._exit(1); + } + /// Whether this rank's GPU context has failed for good: after a fault in a kernel (an illegal address, a trap) /// every later call returns that fault, the stream's query too (which logs it); a context that survived a failed /// call answers done or busy. @@ -535,21 +542,60 @@ pub const Model = struct { m.ahead = null; } - /// A kept prompt state's own bytes (the prompt cache's snapshots; the compressed plane stays in the stream's - /// extent): one slot's window ring of every layer and positional stores of every ratio-2 layer. - pub fn snapBytes(m: *const Model) usize { + /// A complete kept prompt: fixed slot state plus independent, byte-exact packed prefix planes. + /// The prompt cache charges this position-dependent allocation before either rank saves it. + pub fn snapBytes(m: *const Model, positions: usize) usize { const pb = prompt.raw_rows * m.eng.c.head_dim * 4; var n: usize = m.rings.len * m.eng.ringBytes(); for (m.caches.raw_kv[0..m.eng.c.layers], m.caches.raw_score[0..m.eng.c.layers]) |k, sc| { if (k != 0) n += pb; if (sc != 0) n += pb; } + for (m.eng.w.layers) |lay| { + if (lay.comp_wkv == null) continue; + const rows = positions / @as(usize, lay.ratio); + n += rows * (m.eng.c.head_dim / 2 + m.eng.c.head_dim / 16); + if (lay.idx_wk != null) n += rows * (m.eng.c.index_head_dim / 2 + m.eng.c.index_head_dim / 32); + } return n; } - /// Slot `slot`'s own state into `buf` (save: true) or back from it, in the stream's order (no wait): with the - /// extent's compressed rows, the state a prompt pass stands in at a chunk end. - pub fn snapCopy(m: *Model, slot: usize, buf: u64, save: bool) !void { + /// Validate the complete snapshot's view before allocation or any device copy. + pub fn snapView(m: *const Model, slot: usize, base: usize, positions: usize) !void { + if (slot >= m.streams) return error.BadSlot; + if (base > m.pool_cap or positions > m.pool_cap - base) return error.BadView; + for (m.eng.w.layers) |lay| { + if (lay.comp_wkv == null) continue; + const ratio: usize = lay.ratio; + if (ratio == 0 or base % ratio != 0 or positions % ratio != 0) return error.BadView; + } + } + + /// Save/restore the slot and full packed prefix in stream order, without requantization. + /// Restore always reads independent backing, even when its old working extent has the same base. + pub fn snapCopy(m: *Model, slot: usize, base: usize, positions: usize, buf: u64, save: bool) !void { + try m.snapView(slot, base, positions); + if (save) try m.snapSlotCopy(slot, buf, true); + var at = buf + m.snapBytes(0); + const c = m.eng.c; + for (m.eng.w.layers, 0..) |lay, i| { + if (lay.comp_wkv == null) continue; + const ratio: usize = lay.ratio; + const rows = positions / ratio; + const planes = [_]u64{ m.caches.comp_codes[i], m.caches.comp_scales[i], m.caches.idx_codes[i], m.caches.idx_scales[i] }; + const widths = [_]usize{ c.head_dim / 2, c.head_dim / 16, c.index_head_dim / 2, c.index_head_dim / 32 }; + const count: usize = if (lay.idx_wk != null) 4 else 2; + for (planes[0..count], widths[0..count]) |plane, width| { + const bytes = rows * width; + if (bytes > 0) try m.copyState(plane + base / ratio * width, at, bytes, save); + at += bytes; + } + } + std.debug.assert(at - buf == m.snapBytes(positions)); + if (!save) try m.snapSlotCopy(slot, buf, false); + } + + fn snapSlotCopy(m: *Model, slot: usize, buf: u64, save: bool) !void { const rb = m.eng.ringBytes(); const pb = prompt.raw_rows * m.eng.c.head_dim * 4; var at = buf; @@ -874,3 +920,160 @@ pub const Model = struct { try dr.pass(&m.eng, &m.ch, pool, tokens, q0, slots, steps, null); } }; + +// Appended only to isolated CPU test copies. These call the real model copy path with host-backed CUDA pointers. +const PrefixCpu = struct { + fn copy(dst: u64, src: u64, count: usize, _: cuda.abi.Stream) callconv(.c) c_int { + const to: [*]u8 = @ptrFromInt(dst); + const from: [*]const u8 = @ptrFromInt(src); + @memcpy(to[0..count], from[0..count]); + return 0; + } + + fn bytes(m: *const Model, at: usize) usize { + return if (@hasDecl(Model, "snapView")) m.snapBytes(at) else m.snapBytes(); + } + + fn transfer(m: *Model, slot: usize, base: usize, at: usize, buf: u64, save: bool) !void { + if (@hasDecl(Model, "snapView")) { + try m.snapCopy(slot, base, at, buf, save); + } else { + // The selected preimage restores from its old working extent, which the fixture deliberately overwrites. + if (!save and base != 0) try m.copyExtent(0, base, at); + try m.snapCopy(slot, buf, save); + } + } +}; + +test "full prefix: overwrite restores same-base and relocated codes scales raw and rings on both ranks" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for (0..2) |rank| { + var driver: cuda.Driver = undefined; + driver.api.cuMemcpyDtoDAsync_v2 = PrefixCpu.copy; + const context: cuda.Context = .{ .d = &driver, .device = 0, .handle = null }; + var cfg: Config = undefined; + cfg.layers = 3; + cfg.head_dim = 32; + cfg.index_head_dim = 32; + cfg.window = 2; + const linear: weights.Linear = .{ .words = 1, .suh = 0, .svh = 0, .k = 1, .n = 1, .k2 = 1 }; + var layers = [_]weights.Layer{ + .{ .idx = 0, .ratio = 2, .comp_wkv = linear, .idx_wk = linear }, + .{ .idx = 1, .ratio = 1, .comp_wkv = linear }, + .{ .idx = 2, .ratio = 1 }, + }; + var w: weights.Weights = undefined; + w.layers = &layers; + var m: Model = undefined; + m.ctx = &context; + m.stream = .{ .d = &driver, .handle = null }; + m.streams = 2; + m.pool_cap = 8; + m.eng.c = &cfg; + m.eng.w = &w; + m.caches = .{}; + var all: std.ArrayList([]u8) = .empty; + const rb = m.eng.ringBytes(); + const pb = prompt.raw_rows * cfg.head_dim * 4; + const ring_pointers = try a.alloc(u64, cfg.layers); + var fixed_expected: std.ArrayList(u8) = .empty; + for (ring_pointers, 0..) |*ptr, index| { + const storage = try a.alloc(u8, 2 * rb); + for (storage, 0..) |*byte, j| byte.* = @truncate(j + 31 * index + 7 * rank); + ptr.* = @intFromPtr(storage.ptr); + try all.append(a, storage); + try fixed_expected.appendSlice(a, storage[0..rb]); + } + m.rings = ring_pointers; + for (0..2) |raw| { + const storage = try a.alloc(u8, 2 * pb); + for (storage, 0..) |*byte, j| byte.* = @truncate(j * 3 + raw + 17 * rank); + if (raw == 0) m.caches.raw_kv[0] = @intFromPtr(storage.ptr) else m.caches.raw_score[0] = @intFromPtr(storage.ptr); + try all.append(a, storage); + try fixed_expected.appendSlice(a, storage[0..pb]); + } + var planes: std.ArrayList(struct { live: []u8, expected: []u8, ratio: usize, width: usize }) = .empty; + const widths = [_]usize{ cfg.head_dim / 2, cfg.head_dim / 16, cfg.index_head_dim / 2, cfg.index_head_dim / 32 }; + for (layers[0..2], 0..) |layer, i| { + const count: usize = if (layer.idx_wk != null) 4 else 2; + for (widths[0..count], 0..) |width, plane| { + const storage = try a.alloc(u8, (m.pool_cap / layer.ratio + 2) * width); + for (storage, 0..) |*byte, j| byte.* = @truncate(j * 5 + 13 * i + 19 * plane + 23 * rank); + const ptr = @intFromPtr(storage.ptr); + switch (plane) { + 0 => m.caches.comp_codes[i] = ptr, + 1 => m.caches.comp_scales[i] = ptr, + 2 => m.caches.idx_codes[i] = ptr, + 3 => m.caches.idx_scales[i] = ptr, + else => unreachable, + } + try planes.append(a, .{ .live = storage, .expected = try a.dupe(u8, storage[0 .. 4 / layer.ratio * width]), .ratio = layer.ratio, .width = width }); + try all.append(a, storage); + } + } + const saved = try a.alloc(u8, PrefixCpu.bytes(&m, 4)); + try PrefixCpu.transfer(&m, 0, 0, 4, @intFromPtr(saved.ptr), true); + for ([_]usize{ 0, 4 }) |destination| { + for (all.items) |storage| @memset(storage, 0xa5); + try PrefixCpu.transfer(&m, 1, destination, 4, @intFromPtr(saved.ptr), false); + // This is the real baseline failure: old snapshots cannot recover overwritten packed bytes. + for (planes.items) |plane| { + const start = destination / plane.ratio * plane.width; + try std.testing.expectEqualSlices(u8, plane.expected, plane.live[start..][0..plane.expected.len]); + for (plane.live[0..start]) |byte| try std.testing.expectEqual(@as(u8, 0xa5), byte); + for (plane.live[start + plane.expected.len ..]) |byte| try std.testing.expectEqual(@as(u8, 0xa5), byte); + } + var offset: usize = 0; + for (ring_pointers) |ptr| { + const data: [*]const u8 = @ptrFromInt(ptr + rb); + try std.testing.expectEqualSlices(u8, fixed_expected.items[offset..][0..rb], data[0..rb]); + offset += rb; + } + for ([_]u64{ m.caches.raw_kv[0], m.caches.raw_score[0] }) |ptr| { + const data: [*]const u8 = @ptrFromInt(ptr + pb); + try std.testing.expectEqualSlices(u8, fixed_expected.items[offset..][0..pb], data[0..pb]); + offset += pb; + } + } + if (@hasDecl(Model, "snapView")) { + try std.testing.expectError(error.BadSlot, m.snapView(2, 0, 4)); + try std.testing.expectError(error.BadView, m.snapView(0, 1, 4)); + try std.testing.expectError(error.BadView, m.snapView(0, 0, 3)); + try std.testing.expectError(error.BadView, m.snapView(0, 6, 4)); + var packed_bytes: usize = 0; + for (planes.items) |plane| packed_bytes += plane.expected.len; + try std.testing.expectEqual(fixed_expected.items.len + packed_bytes, m.snapBytes(4)); + try std.testing.expectEqual(fixed_expected.items.len, m.snapBytes(0)); + } + } +} + +test "full prefix: illustrative loaded layout charges fixed state plus every packed plane" { + if (!@hasDecl(Model, "snapView")) return; + var cfg: Config = undefined; + cfg.layers = 40; + cfg.head_dim = 512; + cfg.index_head_dim = 128; + cfg.window = 128; + const linear: weights.Linear = .{ .words = 1, .suh = 0, .svh = 0, .k = 1, .n = 1, .k2 = 1 }; + var layers = [_]weights.Layer{ + .{ .idx = 0, .ratio = 2, .comp_wkv = linear, .idx_wk = linear }, + .{ .idx = 1, .ratio = 2, .comp_wkv = linear, .idx_wk = linear }, + .{ .idx = 2, .ratio = 2, .comp_wkv = linear, .idx_wk = linear }, + .{ .idx = 3, .ratio = 1, .comp_wkv = linear, .idx_wk = linear }, + }; + var w: weights.Weights = undefined; + w.layers = &layers; + var m: Model = undefined; + m.eng.c = &cfg; + m.eng.w = &w; + m.caches = .{}; + var rings: [40]u64 = @splat(0); + m.rings = &rings; + for (0..3) |i| { m.caches.raw_kv[i] = 1; m.caches.raw_score[i] = 1; } + try std.testing.expectEqual(@as(usize, 6684672), m.snapBytes(0)); + try std.testing.expectEqual(@as(usize, 157856512), m.snapBytes(169856)); + try std.testing.expectEqual(@as(usize, 890 * 128), m.snapBytes(169984) - m.snapBytes(169856)); +} diff --git a/zig/src/families/dsv41/native.zig b/zig/src/families/dsv41/native.zig index e2e98328840..77ec969ccd5 100644 --- a/zig/src/families/dsv41/native.zig +++ b/zig/src/families/dsv41/native.zig @@ -53,6 +53,8 @@ const round = @import("round.zig"); const link = @import("link.zig"); const rank_cache = @import("rank_cache.zig"); const vision_mod = @import("vision.zig"); +const disk_mod = @import("disk.zig"); +const api = @import("engine_api"); pub const model_type = "deepseek_v41"; pub const formats: []const []const u8 = &.{"exl3-mul1"}; @@ -102,6 +104,9 @@ pub const Snaps = struct { /// Whether a kept state restores for a prompt of this many tokens, and whether it still holds its rows. resumes: *const fn (*anyopaque, *anyopaque, u32) bool, live: *const fn (*anyopaque, *anyopaque) bool, + /// --learn-conversations: the state's disk image, and the rows key stamped for a peer's half file. + rows: ?*const api.prompt_cache.rows.Image = null, + tag_disk: ?*const fn (*anyopaque, *anyopaque, u64) void = null, }; /// The rank's model and the backend over it (what `open` hands the server, freed by `deinit`). @@ -212,7 +217,7 @@ pub fn open(gpa: std.mem.Allocator, io: std.Io, ctx: *const cuda.Context, dir: [ st.lanes.vision = st.vision; // the pool is the model's (preallocated): a stream takes no device memory of its own const L = lanes_mod.Lanes; - const snaps: Snaps = .{ .ptr = &st.lanes, .bytes = L.snapBytesFn, .save = L.snapSaveFn, .restore = L.snapRestoreFn, .drop = L.snapDropFn, .resumes = L.snapResumesFn, .live = L.snapLiveFn }; + const snaps: Snaps = .{ .ptr = &st.lanes, .bytes = L.snapBytesFn, .save = L.snapSaveFn, .restore = L.snapRestoreFn, .drop = L.snapDropFn, .resumes = L.snapResumesFn, .live = L.snapLiveFn, .rows = &disk_mod.image, .tag_disk = L.snapTagDiskFn }; // a follower that stops stops this server too, with a line that names it, instead of a wait on it for good st.m.watchPeers() catch |err| std.log.warn("dsv41: rank 0 cannot watch its followers: {s}", .{@errorName(err)}); return .{ .backend = st.lanes.backend(), .facts = st.lanes.facts(), .rows = @intCast(st.m.eng.round_rows), .stream_bytes = 0, .ctx = st, .deinit = deinitFn, .snaps = snaps, .lane_vision = if (st.vision) |v| v.hook() else null, .fill_rounds = if (st.lanes.fill_chunks > 0) fill_rounds else 0, .fill_drain = if (st.lanes.fill_chunks > 0) fill_drain else 0 }; diff --git a/zig/src/native/cuda.zig b/zig/src/native/cuda.zig index 3bccedf37f6..3ff42a20a3a 100644 --- a/zig/src/native/cuda.zig +++ b/zig/src/native/cuda.zig @@ -428,10 +428,20 @@ fn openWith(comptime F: type, a: Allocator, gpa: Allocator, io: std.Io, o: api.O } // a family that keeps prompt states its own way (Loaded.snaps) gets a store over them, as before 1.0.12 if (h.store == null and cache > 0) if (@hasField(@TypeOf(loaded), "snaps")) if (loaded.snaps) |sn| { - h.snap_vt = .{ .bytes = sn.bytes, .save = sn.save, .restore = sn.restore, .drop = sn.drop, .resumes = if (@hasField(@TypeOf(sn), "resumes")) sn.resumes else null, .live = if (@hasField(@TypeOf(sn), "live")) sn.live else null }; + h.snap_vt = .{ .bytes = sn.bytes, .save = sn.save, .restore = sn.restore, .drop = sn.drop, .resumes = if (@hasField(@TypeOf(sn), "resumes")) sn.resumes else null, .live = if (@hasField(@TypeOf(sn), "live")) sn.live else null, .rows = if (@hasField(@TypeOf(sn), "rows")) sn.rows else null, .tag_disk = if (@hasField(@TypeOf(sn), "tag_disk")) sn.tag_disk else null }; const store = try gpa.create(api.prompt_cache.Store); store.* = api.prompt_cache.Store.init(gpa, .{ .ptr = sn.ptr, .vtable = &h.snap_vt }, .{}, cache); h.store = store; + // --learn-conversations: every kept state written behind to disk, read back where it pays + if (o.learn_conversations and sn.rows != null) { + const root = o.learn orelse return error.LearnNeedsDir; + var h64 = std.hash.Wyhash.init(0x6473_7634); + h64.update("dsv41"); + h64.update(o.dir); + const r = try api.prompt_cache.rows.Rows.open(gpa, store.family, .{ .root = root, .identity = h64.final(), .cap = @intFromFloat(o.learn_gib * gib), .floor = @intFromFloat(o.learn_min_free_gib * gib), .daily = @intFromFloat(o.learn_daily_gib * gib), .lookahead = store.rules.lookahead, .planned = store.rules.planned }); + store.disk = r; + std.log.info("dsv41: conversation states spill under {s} ({d} GiB cap)", .{ root, @as(u64, @intFromFloat(o.learn_gib)) }); + } }; errdefer if (h.store) |store| { store.deinit(); diff --git a/zig/src/native/cuda_refusal.zig b/zig/src/native/cuda_refusal.zig index 7cdf93f18f5..7832a2b3c71 100644 --- a/zig/src/native/cuda_refusal.zig +++ b/zig/src/native/cuda_refusal.zig @@ -2,6 +2,7 @@ const std = @import("std"); const api = @import("engine_api"); const nemotron = @import("nemotron"); +const dsv41 = @import("dsv41"); /// Flags refused whatever the family; null when `o` may open. pub fn backend(o: api.Open) ?[]const u8 { @@ -22,7 +23,7 @@ const lfm2_vision = "--vision: LFM2 reads the checkpoint's images through its ow /// A family takes --drafter only if it says so, and --learn-conversations only as Nemotron; null: `o` may open `F`. pub fn family(comptime F: type, o: api.Open) ?[]const u8 { if (o.drafter != null and !(@hasDecl(F, "takes_drafter") and F.takes_drafter)) return "--drafter loads a separate drafter, and this CUDA family drafts with its own MTP head: serve without --drafter"; - if (o.learn_conversations and F != nemotron.native) return "--learn-conversations keeps conversation states on disk for Nemotron only on CUDA: serve this model without it"; + if (o.learn_conversations and F != nemotron.native and F != dsv41.native) return "--learn-conversations keeps conversation states on disk for Nemotron only on CUDA: serve this model without it"; return null; }