Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions zig/src/core/prompt_cache.zig
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,18 @@ pub const Store = struct {
return if (s.family.vtable.spare) |f| f(s.family.ptr) else 0;
}

/// A kept state now takes `extra` more bytes (a family copied what it shared into the state's own storage): charged
/// when the budget leaves room for it, refused otherwise; nothing is evicted, since a prompt pass is under way.
pub fn grow(s: *Store, saved: Saved, extra: u64) bool {
for (s.entries.items) |e| if (e.tokens.len > 0 and e.saved == saved) {
if (extra > s.room()) return false;
e.bytes += extra;
s.held += extra;
return true;
};
return false;
}

/// What the budget leaves past the kept states and the spare storage: a family readies storage only inside it.
pub fn room(s: *const Store) u64 {
return s.budget -| s.held -| s.spare();
Expand Down
24 changes: 24 additions & 0 deletions zig/src/core/prompt_cache_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -569,3 +569,27 @@ test "under-cap disk pressure selects the same LRU victim before either half is
try std.testing.expectEqual(@as(usize, 1), fake.disk_peer_writes);
try std.testing.expect(!fake.disk_reserved);
}

test "a kept state grows only into what the budget leaves, and evicts nothing to do it" {
const gpa = std.testing.allocator;
var arena: std.heap.ArenaAllocator = .init(gpa);
defer arena.deinit();
const a = arena.allocator();
var f: Fake = .{ .gpa = gpa };
var s = Store.init(gpa, f.snapshots(), .{ .min_prompt = 0 }, 330); // fake bytes: 100 + at
defer s.deinit();
const t1 = [_]u32{ 1, 2, 3, 4, 5, 6 };
_ = f.pass(&s, &t1, try s.begin(a, &t1, 4, &.{}, &.{}, null, &.{})); // 104
const t2 = [_]u32{ 9, 9, 9, 9, 9, 9 };
_ = f.pass(&s, &t2, try s.begin(a, &t2, 5, &.{}, &.{}, null, &.{})); // 105: 209 held, 121 left
const e1 = s.find(&t1, &.{}, &.{}).?;
try std.testing.expect(s.grow(e1.saved, 100)); // 309 held
try std.testing.expectEqual(@as(u64, 204), e1.bytes);
try std.testing.expectEqual(@as(u64, 309), s.held);
try std.testing.expect(!s.grow(e1.saved, 22)); // 331 would pass the budget: refused, and both states stay
try std.testing.expectEqual(@as(usize, 2), s.entries.items.len);
try std.testing.expect(s.grow(e1.saved, 21)); // exactly the budget
try std.testing.expectEqual(s.budget, s.held);
var stranger: u8 = 0;
try std.testing.expect(!s.grow(&stranger, 0)); // a state the store doesn't hold
}
48 changes: 41 additions & 7 deletions zig/src/families/glm/slots.zig
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ pub const Slot = struct {
region: ?pool_mod.Region = null, // pooled: this stream's share of the MLA pool (pool.zig)
};

/// The prompt cache's leave for a kept state to take `extra` more bytes (Store.grow).
pub const Grow = struct {
ctx: *anyopaque,
f: *const fn (ctx: *anyopaque, saved: *anyopaque, extra: u64) bool,
};

pub const Slots = struct {
gpa: std.mem.Allocator,
e: *Engine,
Expand All @@ -55,6 +61,8 @@ pub const Slots = struct {
ahead: [2]f64 = .{ 0, 0 }, // the last launch's GPU start and end (0: none)
launched: ?mtl.CommandBuffer = null, // keeps and drafts committed ahead: the window after them encodes while they run
digest: u64 = 0, // the last window's picks hashed: a pair's ranks compare theirs
grow: ?Grow = null, // the prompt cache's leave to make a resident state whole before its slot writes below it
spilled: u64 = 0, // resident states made whole before their slots wrote below them
ring: Ref, // u32 [ring_len]: tokens by handle, a queued round's input read from its slot on the GPU
ring_at: u32 = 0,
ring_cb: [ring_len]?mtl.CommandBuffer = @splat(null), // the queued round writing each slot (retained) until read
Expand Down Expand Up @@ -120,8 +128,7 @@ pub const Slots = struct {
const slot = try sl.slotAt(i);
const snap = sl.snaps.get(id) orelse return error.SnapshotOutOfStep;
if (slot.s.pos != 0 or snap.at >= slot.prompt_len or snap.stale) return error.SnapshotOutOfStep;
if (snap.home) |h| if (h != i) sl.overwrite(i, 0); // another slot's prefixes copied over every one of this slot's
if (snap.held != null) sl.overwrite(i, 0); // copied from the pool's held blocks, the same
if (snap.home != i) try sl.overwrite(i, 0); // another slot's prefixes, or a whole state's, copied over every one of this slot's
try sl.copySnap(slot, snap, false);
}

Expand All @@ -130,14 +137,41 @@ pub const Slots = struct {
return sl.snaps.get(snap.id) == snap and !snap.stale;
}

/// Slot `i` writes its MLA rows from `at` on: its resident states past `at` lose their prefixes.
fn overwrite(sl: *Slots, i: u32, at: u32) void {
/// Slot `i` writes its MLA rows from `at` on: its resident states past `at` copy their prefixes out first when
/// the prompt cache's budget has room (they stay kept, whole), else they lose them (stale).
fn overwrite(sl: *Slots, i: u32, at: u32) !void {
var it = sl.snaps.valueIterator();
while (it.next()) |snap| if (snap.*.home == i and snap.*.at > at) {
snap.*.stale = true;
while (it.next()) |snap| if (snap.*.home == i and snap.*.at > at and !snap.*.stale) {
if (!try sl.spill(snap.*)) snap.*.stale = true;
};
}

/// A resident state made whole: a buffer for its MLA prefixes beside its KDA states, charged to the prompt cache,
/// filled from its slot before the slot writes. One Mac only: a pair's rank 1 holds its half resident still.
fn spill(sl: *Slots, snap: *snapshot.Snap) !bool {
const home = snap.home orelse return false;
const g = sl.grow orelse return false;
if (sl.e.ep != null) return false;
const whole = snapshot.bytes(&sl.e.c, snap.at, false);
if (!g.f(g.ctx, snap, whole - snap.bytes)) return false;
const buf = try sl.e.device.buffer(whole, mtl.ResourceOptions.shared | mtl.ResourceOptions.untracked);
errdefer buf.deinit();
try sl.flush();
const pool = mtl.objc.Pool.push();
defer pool.pop();
const x = sl.ctx(&sl.slots[home]);
const b = sl.e.begin();
snapshot.spill(&x, b.enc, .{ .buf = snap.buf }, .{ .buf = buf }, snap.at, &sl.slots[home].s);
try sl.e.finish(b.cb, b.enc);
snap.buf.deinit();
snap.buf = buf;
snap.bytes = whole;
snap.home = null;
sl.spilled += 1;
std.log.info("glm: a kept state of {d} tokens copied its prefixes out of slot {d} before the slot wrote below it ({d} MiB more)", .{ snap.at, home, (whole - snapshot.bytes(&sl.e.c, snap.at, true)) >> 20 });
return true;
}

/// A fixed prompt's state through slot 0, hashed: two builds agree only when their prompt passes give equal bits.
pub fn probe(sl: *Slots) !u64 {
var toks: [4096 + 40 + 7]u32 = undefined; // a full chunk past the sparse index's reach, a middle one, a short one
Expand Down Expand Up @@ -322,7 +356,7 @@ pub const Slots = struct {
const slot = try sl.slotAt(i);
const P = slot.prompt_len;
if (n == 0 or at != slot.s.pos or at + n > P or n > @max(e.chunk_rows, st.max_rows)) return error.ChunkOutOfStep;
sl.overwrite(i, at);
try sl.overwrite(i, at);
const D = e.c.hidden;
const last = at + n == P;
const absorb = if (last) n - 1 else n;
Expand Down
16 changes: 16 additions & 0 deletions zig/src/families/glm/snapshot.zig
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,22 @@ pub fn copy(x: *const fwd.Ctx, e: mtl.ComputeEncoder, s: *st.State, snap: Ref, a
s.mtp_pos = at;
}

/// A resident state made whole before its slot writes below it: its KDA states from `old`, then the MLA prefixes
/// from `home` (the slot's caches), into `whole` in a whole state's layout.
pub fn spill(x: *const fwd.Ctx, e: mtl.ComputeEncoder, old: Ref, whole: Ref, at: u32, home: *st.State) void {
const c = x.c;
var off = bytes(c, at, true);
words(x, e, old, whole, off);
for (home.mla[0..mlaCount(c)]) |*C| {
const sizes = [4]usize{ @as(usize, at) * c.kv_lora * 2, @as(usize, at) * c.i_dim * 2, @as(usize, at) * c.i_dim * 2, blocks(c, at) * c.i_dim * 2 };
for ([4]Ref{ C.keys, C.ik, C.ig, C.pool }, sizes) |src, n| {
words(x, e, src, whole.at(off), n);
off += n;
}
}
std.debug.assert(off == bytes(c, at, false));
}

/// A learned state's file for one rank of the pair: <dir>/<key>.r<rank>.bin.
pub fn path(buf: []u8, dir: []const u8, key: u64, rank: u32) ![:0]const u8 {
return std.fmt.bufPrintSentinel(buf, "{s}/{x:0>16}.r{d}.bin", .{ dir, key, rank }, 0);
Expand Down
7 changes: 7 additions & 0 deletions zig/src/native/glm_host.zig
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up:
h.cache = api.prompt_cache.Store.init(gpa, .{ .ptr = &h.back, .vtable = &.{ .bytes = B.snapBytes, .save = B.snapSave, .restore = B.snapRestore, .drop = B.snapDrop, .write = B.snapWrite, .read = B.snapRead, .forget = B.snapForget, .forget_checked = B.snapForgetChecked, .reclaim = B.snapReclaim, .peer_other_used = B.peerOtherUsed, .peer_other_next = B.peerOtherNext, .peer_other_bytes = B.peerOtherBytes, .peer_other_remove = B.peerOtherRemove, .peer_need = B.peerNeed, .peer_reclaim = B.peerReclaim, .peer_reserve = B.peerReserve, .peer_finish = B.peerFinish } }, cache_rules, budget);
h.host.cache = &h.cache.?;
h.host.info_.prompt_cache = true;
h.slots.grow = .{ .ctx = h, .f = growSnap }; // a resident state made whole before its slot writes below it
}
errdefer if (h.cache) |*store| store.deinit();
if (learn) |root| {
Expand All @@ -133,6 +134,12 @@ pub fn open(gpa: Allocator, io: std.Io, dir: []const u8, window: u32, speed_up:
return h;
}

/// Slots.grow: the prompt cache charges a kept state's prefixes when its budget has room (the host thread's store).
fn growSnap(ctx: *anyopaque, saved: *anyopaque, extra: u64) bool {
const h: *Host = @ptrCast(@alignCast(ctx));
return if (h.cache) |*store| store.grow(saved, extra) else false;
}

fn follow(h: *Host) void {
glm.mirror.follow(h.eng, &h.slots) catch |err| std.log.err("speed-up mode: following rank 0 ended: {s}", .{@errorName(err)});
}
Expand Down
Loading