Skip to content
Merged
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
2 changes: 2 additions & 0 deletions zig/src/families/nemotron/cuda.zig
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ test {
_ = @import("cuda_profile_window.zig");
_ = reuse;
_ = @import("learner.zig");
_ = @import("pocket_quiet.zig");
_ = @import("pocket_mark.zig");
_ = @import("subspace.zig");
_ = @import("cuda_train_back.zig");
}
5 changes: 5 additions & 0 deletions zig/src/families/nemotron/cuda_slide.zig
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,11 @@ const Host = struct {
try m.e.stream.synchronize();
return PocketShards.write(gpa, io, m.dir, m.e.c, moe, neurons, up, down);
}

/// One layer's pocket neurons rounded in place as pocketSave writes them.
pub fn pocketRound(gpa: std.mem.Allocator, neurons: usize, d: usize, up: []f32, down: []f32) !void {
return PocketShards.round(gpa, neurons, d, up, down);
}
};

pub const Learner = lessons.Learner(Host);
Expand Down
64 changes: 16 additions & 48 deletions zig/src/families/nemotron/pocket.zig
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ const joint = @import("pocket_joint.zig");
const pocket_dump = @import("pocket_dump.zig");
const clock = @import("pocket_clock.zig");
const reading = @import("pocket_read.zig");
const quieting = @import("pocket_quiet.zig");
const marks = @import("pocket_mark.zig");

const Example = examples.Example;
const Acting = lesson_route.Acting;
Expand All @@ -23,8 +25,6 @@ const fit_steps = pocket_fit.fit_steps;
pub const neurons = 64;
const per_fact = 10; // neurons a fact takes, at the layers that tell its questions apart best
const value_neurons = 4; // of those, the ones before its answer's value, when its answers show one
const kept_least: f32 = 0.5; // an earlier neuron refitted must still reach this on every one of its own fact's rows
const refit_above: f32 = 0.5; // an earlier neuron is refitted only where it fires above this on a new fact's rows

/// Where a neuron fires: the reply's first row, the named subject's last token, or the row before the answer's value.
pub const Key = enum(u2) { reply, subject, value };
Expand Down Expand Up @@ -134,6 +134,7 @@ pub fn Pocket(comptime T: type) type {
v: values.State = .{}, // the open fact's outputs as they are fitted
clock: clock.Clock = .{}, // where the open round's time goes
read: reading.Seen = .{}, // what the last read pass read, which a lesson begun again over the same keeps
snap: marks.Snap = .{}, // the pocket as the open fact's lesson found it, which taking the lesson out puts back

pub fn init(gpa: std.mem.Allocator) Self {
const asked: Mode = if (std.c.getenv("TF_SLIDE_POCKET_KEY")) |v| std.meta.stringToEnum(Mode, std.mem.span(v)) orelse .auto else .auto;
Expand All @@ -144,6 +145,12 @@ pub fn Pocket(comptime T: type) type {
inline for (.{ "moe", "up", "down", "used", "taken", "rows", "labels", "keeps", "refits", "refit_up", "retired_lessons", "retired", "retired_w", "joint", "joint_down", "joint_answers", "learned", "pos", "subjects", "leads" }) |f| @field(p, f).deinit(p.gpa);
p.read.deinit(p.gpa);
p.v.deinit(p.gpa);
p.snap.deinit(p.gpa);
}

/// The pocket as a new fact's lesson finds it: what taking that lesson out puts back, bit for bit.
pub fn mark(p: *Self) !void {
return marks.mark(p);
}

/// The fact's neurons per key: as asked, or by how many answers show a value and questions name the subject.
Expand Down Expand Up @@ -301,8 +308,12 @@ pub fn Pocket(comptime T: type) type {
p.next(.values);
}

/// The open fact's neurons back to zero and free, and the earlier neurons it fitted again as they were.
/// The pocket as the open fact's lesson found it; with no mark (a save since), its own neurons zero and free.
pub fn undo(p: *Self, t: *T, host: anytype) !void {
if (try marks.restore(p, t, host)) {
inline for (.{ "refits", "refit_up", "joint", "joint_down", "joint_answers", "taken" }) |f| @field(p, f).clearRetainingCapacity();
return;
}
const d = t.config().hidden;
p.learned.shrinkRetainingCapacity(p.learned_before);
p.pos.shrinkRetainingCapacity(p.pos_before);
Expand Down Expand Up @@ -394,7 +405,7 @@ pub fn Pocket(comptime T: type) type {
};
p.logSources(d, m, kinds);
try p.findKeeps(d);
try p.quiet(t, host);
try quieting.quiet(p, t, host);
std.log.info("slide pocket: {d} candidate neurons fitted on {d} read rows in {d:.1} s; earlier neurons checked in {d:.1} s", .{ fitted, m, t1 - t0, clock.now(host.io) - t1 });
try joint.find(p, d);
try p.v.begin(p.gpa, p.taken.items.len + p.joint.items.len, d, p.answered.len + p.joint_answers.items.len + p.keeps.items.len);
Expand Down Expand Up @@ -468,50 +479,6 @@ pub fn Pocket(comptime T: type) type {
std.log.info("slide pocket: {d} other answers name the fact's subject where its neurons fire; they are to stay as they were", .{p.keeps.items.len});
}

/// Earlier neurons firing on this fact's rows refitted silent there, undo copies kept; same-subject ones stay.
fn quiet(p: *Self, t: *T, host: anytype) !void {
const d = t.config().hidden;
const n = p.slots();
for (p.learned.items[0..p.learned_before]) |e| {
if (e.key == .subject and std.mem.indexOfScalar(u32, p.subjects.items, e.subject) != null) continue;
const u = p.neuron(p.up.items, e.slot, e.neuron, d);
var most: f32 = -std.math.inf(f32);
for (p.labels.items, 0..) |l, i| if (l.kind == .fact or l.kind == .held) {
most = @max(most, dotBf16(u, p.rows.items[(i * n + e.slot) * d ..][0..d]));
};
if (most <= refit_above) continue; // weak there: left exactly as it is, this fact's outputs fitted with it
try p.refits.append(p.gpa, .{ .slot = e.slot, .neuron = e.neuron });
try p.refit_up.appendSlice(p.gpa, u);
var xs: std.ArrayList([]const u16) = .empty;
defer xs.deinit(p.gpa);
var kinds: std.ArrayList(Kind) = .empty;
defer kinds.deinit(p.gpa);
for (0..e.count) |r| {
try xs.append(p.gpa, p.pos.items[(e.start + r) * d ..][0..d]);
try kinds.append(p.gpa, .fact);
}
for (p.labels.items, 0..) |l, i| {
try xs.append(p.gpa, p.rows.items[(i * n + e.slot) * d ..][0..d]);
try kinds.append(p.gpa, switch (l.kind) {
.fact, .held => .steady, // this fact's questions are another fact's to it
.none => .other,
else => l.kind,
});
}
const f = try fit(p.gpa, xs.items, kinds.items, d, u, true, fit_steps / 2, e.count);
if (f.fact_least < kept_least or @max(f.steady_most, f.other_most) > 0) {
// a refit that forgets its fact or spreads is undone; this fact's outputs are fitted with it firing
@memcpy(u, p.refit_up.items[p.refit_up.items.len - d ..]);
p.refits.shrinkRetainingCapacity(p.refits.items.len - 1);
p.refit_up.shrinkRetainingCapacity(p.refit_up.items.len - d);
std.log.info("slide pocket: layer {d}, neuron {d}, an earlier fact's, fires on this fact's questions (up to {d:.2}); fitted again its own would read at least {d:.2} and other rows at most {d:.2}, so it stays as it was", .{ p.moe.items[e.slot], e.neuron, most, f.fact_least, @max(f.steady_most, f.other_most) });
continue;
}
try p.upload(t, host, e.slot);
std.log.info("slide pocket: layer {d}, neuron {d}, an earlier fact's, fired on this fact's questions (up to {d:.2}); fitted again: there and elsewhere at most {d:.2}, its own questions' least {d:.2}", .{ p.moe.items[e.slot], e.neuron, most, @max(f.steady_most, f.other_most), f.fact_least });
}
}

/// Whether no neuron is in use at any layer.
pub fn empty(p: *const Self) bool {
for (p.used.items) |u| if (u > 0) return false;
Expand All @@ -522,6 +489,7 @@ pub fn Pocket(comptime T: type) type {
pub fn save(p: *Self, t: *T, host: anytype) !usize {
const bytes = try host.pocketSave(p.moe.items, neurons, p.up.items, p.down.items);
for (0..p.slots()) |j| if (p.used.items[j] > 0) try p.upload(t, host, j);
p.snap.valid = false;
return bytes;
}

Expand Down
157 changes: 157 additions & 0 deletions zig/src/families/nemotron/pocket_mark.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
//! The pocket as a lesson found it, put back bit for bit when the lesson is taken out; its layers rounded as saved.
const std = @import("std");
const neurons = @import("pocket.zig").neurons;

/// The pocket when a lesson began: every neuron's weights, the neurons in use, how much was learned before it.
pub const Snap = struct {
valid: bool = false, // false once a save has written the pocket: no lesson before it is put back
up: std.ArrayList(f32) = .empty,
down: std.ArrayList(f32) = .empty,
used: std.ArrayList(usize) = .empty,
learned: usize = 0,
pos: usize = 0,
hash: u64 = 0,

pub fn deinit(s: *Snap, gpa: std.mem.Allocator) void {
s.up.deinit(gpa);
s.down.deinit(gpa);
s.used.deinit(gpa);
}
};

/// The pocket's weights and neurons in use as one number: the same number, the same bits.
pub fn hash(p: anytype) u64 {
var h = std.hash.Wyhash.init(0);
h.update(std.mem.sliceAsBytes(p.up.items));
h.update(std.mem.sliceAsBytes(p.down.items));
h.update(std.mem.sliceAsBytes(p.used.items));
return h.final();
}

/// The pocket as a new fact's lesson finds it, which taking that lesson out puts back.
pub fn mark(p: anytype) !void {
const s = &p.snap;
inline for (.{ "up", "down", "used" }) |f| {
@field(s, f).clearRetainingCapacity();
try @field(s, f).appendSlice(p.gpa, @field(p, f).items);
}
s.learned = p.learned.items.len;
s.pos = p.pos.items.len;
s.hash = hash(p);
s.valid = true;
}

/// The pocket put back as the open lesson found it, each layer that changed handed to the forward; false with no mark.
pub fn restore(p: anytype, t: anytype, host: anytype) !bool {
const s = &p.snap;
if (!s.valid or s.up.items.len != p.up.items.len or s.used.items.len != p.used.items.len) return false;
const n = p.up.items.len / @max(p.used.items.len, 1);
const was = hash(p);
for (0..p.used.items.len) |j| {
const up = p.up.items[j * n ..][0..n];
const down = p.down.items[j * n ..][0..n];
const same = p.used.items[j] == s.used.items[j] and
std.mem.eql(u8, std.mem.sliceAsBytes(up), std.mem.sliceAsBytes(s.up.items[j * n ..][0..n])) and
std.mem.eql(u8, std.mem.sliceAsBytes(down), std.mem.sliceAsBytes(s.down.items[j * n ..][0..n]));
if (same) continue;
@memcpy(up, s.up.items[j * n ..][0..n]);
@memcpy(down, s.down.items[j * n ..][0..n]);
p.used.items[j] = s.used.items[j];
try p.upload(t, host, j);
}
p.learned.shrinkRetainingCapacity(s.learned);
p.pos.shrinkRetainingCapacity(s.pos);
const now = hash(p);
std.log.info("slide pocket: the lesson taken out: the pocket put back as the lesson found it ({x:0>16} -> {x:0>16}, {s})", .{ was, now, if (now == s.hash) "the same bits" else "NOT the same bits" });
return true;
}

/// The open fact's layers rounded as a save writes them (every neuron there shares the output's groups) and uploaded.
pub fn asWritten(p: anytype, t: anytype, host: anytype) !void {
const d = t.config().hidden;
const n = neurons * d;
var done: std.ArrayList(usize) = .empty;
defer done.deinit(p.gpa);
for (p.taken.items) |x| try once(p.gpa, &done, x.slot);
for (p.refits.items) |x| try once(p.gpa, &done, x.slot);
for (p.joint.items) |x| try once(p.gpa, &done, x.slot);
const was = hash(p);
for (done.items) |j| {
try host.pocketRound(neurons, d, p.up.items[j * n ..][0..n], p.down.items[j * n ..][0..n]);
try p.upload(t, host, j);
}
if (done.items.len > 0) std.log.info("slide pocket: {d} layers' neurons rounded as the shards hold them ({s})", .{ done.items.len, if (hash(p) == was) "already were" else "changed" });
}

fn once(gpa: std.mem.Allocator, list: *std.ArrayList(usize), j: usize) !void {
if (std.mem.indexOfScalar(usize, list.items, j) == null) try list.append(gpa, j);
}

test "a lesson taken out puts the pocket back bit for bit: its neurons, an earlier one it refitted, the rounding" {
const gpa = std.testing.allocator;
const d = 64;
const T = struct {
pub fn config(_: *const @This()) struct { hidden: usize } {
return .{ .hidden = d };
}
};
const Host = struct {
pub fn pocket(_: @This(), _: usize, _: []const f32, _: []const f32, _: usize) !void {}
pub fn pocketRound(_: @This(), k: usize, dd: usize, up: []f32, down: []f32) !void {
for (up) |*x| x.* = @round(x.* * 16) / 16;
// an output row's neurons share one step, as they share a 4-bit group in the shards
for (0..dd) |o| {
var most: f32 = 0;
for (0..k) |i| most = @max(most, @abs(down[i * dd + o]));
const step = if (most > 0) most / 7 else 1;
for (0..k) |i| down[i * dd + o] = @round(down[i * dd + o] / step) * step;
}
}
};
var prng = std.Random.DefaultPrng.init(3);
const r = prng.random();
var p: @import("pocket.zig").Pocket(T) = .{ .gpa = gpa, .mode = .reply };
defer p.deinit();
try p.moe.appendSlice(gpa, &.{ 3, 5 });
try p.up.appendNTimes(gpa, 0, 2 * neurons * d);
try p.down.appendNTimes(gpa, 0, 2 * neurons * d);
try p.used.appendSlice(gpa, &.{ 1, 0 });
// an earlier fact's neuron at the first layer, as a save left it
for (p.neuron(p.up.items, 0, 0, d), p.neuron(p.down.items, 0, 0, d)) |*u, *v| {
u.* = r.floatNorm(f32);
v.* = r.floatNorm(f32) * 0.01;
}
try Host.pocketRound(.{}, neurons, d, p.up.items[0 .. neurons * d], p.down.items[0 .. neurons * d]);
try p.learned.append(gpa, .{ .slot = 0, .neuron = 0, .key = .reply, .start = 0, .count = 0, .subject = 0, .lesson = 0 });
var t: T = .{};
try mark(&p);
p.learned_before = p.learned.items.len; // as begin() leaves it
const before = hash(&p);
// the lesson: a neuron of its own beside the earlier one and one at the second layer, the earlier one refitted
p.used.items[0] = 2;
p.used.items[1] = 1;
for ([_][2]usize{ .{ 0, 1 }, .{ 1, 0 } }) |at| {
for (p.neuron(p.up.items, at[0], at[1], d), p.neuron(p.down.items, at[0], at[1], d)) |*u, *v| {
u.* = r.floatNorm(f32);
v.* = r.floatNorm(f32);
}
try p.taken.append(gpa, .{ .slot = at[0], .neuron = at[1], .key = .reply });
}
try p.refits.append(gpa, .{ .slot = 0, .neuron = 0 });
try p.refit_up.appendSlice(gpa, p.neuron(p.up.items, 0, 0, d));
p.neuron(p.up.items, 0, 0, d)[0] += 1;
try p.learned.append(gpa, .{ .slot = 0, .neuron = 1, .key = .reply, .start = 0, .count = 0, .subject = 0, .lesson = 1 });
try asWritten(&p, &t, Host{});
try std.testing.expect(hash(&p) != before);
try p.undo(&t, Host{});
try std.testing.expectEqual(before, hash(&p));
try std.testing.expectEqualSlices(usize, &.{ 1, 0 }, p.used.items);
try std.testing.expectEqual(@as(usize, 1), p.learned.items.len);
// a save since the mark: no lesson before it is put back, and the undo takes out the open fact's neurons alone
p.snap.valid = false;
p.used.items[1] = 1;
try p.taken.append(gpa, .{ .slot = 1, .neuron = 0, .key = .reply });
@memset(p.neuron(p.up.items, 1, 0, d), 1);
try p.undo(&t, Host{});
try std.testing.expectEqual(before, hash(&p));
}
Loading
Loading