Skip to content
Draft
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
1 change: 1 addition & 0 deletions build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ pub fn build(b: *std.Build) void {
@import("zig/build/metal_prompt_sources.zig").steps(b, budget_mods.metal, budget_mods.engine, test_step);
@import("zig/build/fsr.zig").deviceSteps(b, budget_mods.metal, budget_mods.engine, budget_mods.sources);
b.step("test-shared-head-cost-metal-host", "Metal family head-cost grants without device execution").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = budget_mods.engine, .filters = &.{"shared head costs:"} })).step);
b.step("test-token-ids-metal-host", "Drafted and fed ids past the embedding refused before any device work").dependOn(&b.addRunArtifact(b.addTest(.{ .root_module = budget_mods.engine, .filters = &.{"token ids:"} })).step);
@import("zig/build/flashnext_budget.zig").compileHost(b, budget_mods.metal, budget_mods.engine, budget_mods.lanes);
@import("zig/build/residency_host.zig").compileHost(b, budget_mods.metal, budget_mods.engine, budget_mods.lanes);
@import("zig/build/dsv41_metal.zig").steps(b, budget_mods.metal, budget_mods.sources, test_step);
Expand Down
1 change: 1 addition & 0 deletions zig/build/host_ci.zig
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,7 @@ const macos_adapters = [_][]const u8{
"test-shared-head-cost-metal-host",
"test-slide-metal-host",
"test-step5-host",
"test-token-ids-metal-host",
"test-verbs",
};

Expand Down
14 changes: 14 additions & 0 deletions zig/src/core/lanes/recall.zig
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub const Shared = struct {
io: std.Io,
mutex: std.Io.Mutex = .init,
record: Record,
vocab: u32 = 0, // a disk store sets its tokenizer cap; zero is a trusted in-memory record
rates: Rates = .{},

pub fn lock(s: *Shared) void {
Expand Down Expand Up @@ -104,6 +105,19 @@ pub const Reader = struct {
proposed: u64 = 0,
accepted: u64 = 0,

/// Admit a disk record once; a wider tokenizer may still contain only valid embedding ids.
pub fn checkVocabulary(x: *const Reader, rows: usize) error{TokenOutsideVocabulary}!void {
if (x.shared.vocab <= rows) return;
x.shared.lock();
defer x.shared.unlock();
const r = &x.shared.record;
var at = r.base();
while (at < r.end) : (at += 1) {
const id = r.id(at);
if (id != record.mark and id >= rows) return error.TokenOutsideVocabulary;
}
}

pub fn deinit(x: *Reader) void {
x.out.deinit(x.gpa);
}
Expand Down
2 changes: 1 addition & 1 deletion zig/src/core/lanes/recall_store.zig
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ pub const Store = struct {
const cap_chunks: usize = @max(2, o.cap_bytes / chunk_bytes);
s.* = .{
.gpa = gpa,
.shared = .{ .io = io, .record = try recall.Record.init(gpa, bucketBits(cap_chunks)) },
.shared = .{ .io = io, .record = try recall.Record.init(gpa, bucketBits(cap_chunks)), .vocab = identity.vocab },
.dir = dir,
.name = name,
.identity = identity,
Expand Down
39 changes: 39 additions & 0 deletions zig/src/core/lanes/recall_store_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -266,3 +266,42 @@ test "a disk-floor refusal writes no ids, then retries when space returns" {
try std.testing.expectEqual(@as(u8, 0), s.admission.failures);
try std.testing.expectEqual(@as(u64, 0), s.admission.reserved);
}

test "token ids: a reloaded Recall record must fit the target embedding before any draft" {
var d = try Dir.init();
defer d.deinit();
var prompt: [32]u32 = @splat(7);
prompt[31] = vocab - 1;
{
const s = try open(&d, identity(11, "recall-bound"), .{});
defer s.close();
s.readPrompt(&prompt, 0);
}
const s = try open(&d, identity(11, "recall-bound"), .{ .read_only = true });
defer s.close();
try std.testing.expect(s.shared.record.held() > 0);
try std.testing.expectEqual(vocab, s.shared.vocab);
var reader: @import("recall.zig").Reader = .{ .gpa = gpa, .shared = &s.shared };
defer reader.deinit();
try std.testing.expectError(error.TokenOutsideVocabulary, reader.checkVocabulary(vocab - 1));
try reader.checkVocabulary(vocab);
}

test "token ids: a reloaded Recall record with unused tokenizer ids stays usable" {
var d = try Dir.init();
defer d.deinit();
const prompt: [32]u32 = @splat(7);
{
const s = try open(&d, identity(12, "recall-subset"), .{});
defer s.close();
s.readPrompt(&prompt, 0);
}
const s = try open(&d, identity(12, "recall-subset"), .{ .read_only = true });
defer s.close();
try std.testing.expect(s.shared.record.held() > 0);
try std.testing.expectEqual(vocab, s.shared.vocab);
var reader: @import("recall.zig").Reader = .{ .gpa = gpa, .shared = &s.shared };
defer reader.deinit();
try reader.checkVocabulary(8);
try std.testing.expectError(error.TokenOutsideVocabulary, reader.checkVocabulary(7));
}
1 change: 1 addition & 0 deletions zig/src/families/flashnext/engine_generate.zig
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ pub fn generateFrom(e: *Engine, prompt: []const u32, from: usize, marks: []const
if (prompt.len == 0) return error.EmptyPrompt;
if (prompt.len + max_tokens + MARGIN > e.m.cap) return error.ContextFull;
if (from >= prompt.len or (from > 0 and m.pos != from)) return error.NotResumed;
if (!fz.Model.inVocab(prompt)) return error.TokenOutsideVocabulary; // before the other Mac hears of the prompt
for (marks, 0..) |mk, i| if (mk <= from or mk >= prompt.len or (i > 0 and mk <= marks[i - 1])) return error.Marks;
if (out.sampling != null and r.tp != null) return error.SpeedUpGreedyOnly; // each Mac holds half the logits
var watch = try think.Watch.init(budget);
Expand Down
5 changes: 5 additions & 0 deletions zig/src/families/flashnext/engine_load.zig
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,11 @@ fn finishLoad(context: Construction, r: *Run) !*Engine {
e.pr.* = try Prompt.init(r, pack_dir, r.xnew_header);
const uniform = try @import("engine_widths.zig").apply(arena, &cfg, index.object.get("weight_map").?.object, e.pr, m);
const tp_path: ?[]const u8 = speed_up orelse if (platform.c.getenv("TF_FLASHNEXT_TP")) |p| std.mem.span(p) else null;
const ew = m.embed_w orelse [2]usize{ 6, 32 }; // the embedding's bits and group: its kernel reads row id of each
for ([_][]const u8{ "weight", "scales", "biases" }, [_]usize{ D * ew[0] / 8, D / ew[1] * 2, D / ew[1] * 2 }) |part, row| {
const name = try std.fmt.allocPrint(arena, "language_model.model.embed_tokens.{s}", .{part});
if ((try r.entry(name)).len < VOCAB * row) return error.InvalidAffineShape; // fewer than VOCAB rows
}
e.pr2 = e.pr;
if (r.window.sibling(tp_path != null)) {
e.pr2 = try arena.create(Prompt);
Expand Down
2 changes: 2 additions & 0 deletions zig/src/families/flashnext/prefill_metal.zig
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ const Images = struct {
pub fn begin(b: anytype, stream: *lanes.Stream, preferred: ?usize) !fill.State {
const prompt = stream.prompt();
if (prompt.len == 0) return error.EmptyPrompt;
if (!fz.Model.inVocab(prompt) or !fz.Model.inVocab(stream.think_close)) return error.TokenOutsideVocabulary;
if (stream.recall) |reader| try reader.checkVocabulary(fz.VOCAB);
if (b.by.contains(stream)) return error.PromptAlreadyStarted;
const i = preferred orelse try b.slotFor(prompt.len, stream.max_new);
if (b.sessions[i].used) return error.NoFreeSlot;
Expand Down
6 changes: 6 additions & 0 deletions zig/src/families/flashnext/replay_model.zig
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,12 @@ pub const Model = struct {
kvm[0], kvm[2] = .{ @intCast(m.pos), @intCast(rows) };
}

/// Whether every token names a row of the embedding table: the kernels read row id with no bound of their own.
pub fn inVocab(tokens: []const u32) bool {
for (tokens) |t| if (t >= VOCAB) return false;
return true;
}

/// One forward over `tokens` (a window of up to MAXR rows from the cache's position): each row's argmax.
pub fn window(m: *Model, tokens: []const u32, picks: []u32) !void {
const r = m.r;
Expand Down
1 change: 1 addition & 0 deletions zig/src/families/flashnext/replay_prompt_chunks.zig
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,7 @@ pub fn chunkPair(p: *Prompt, m: *Model, gpa: std.mem.Allocator, tokens: []const
const n = tokens.len;
if (n < 2 or n > 2 * PMAX) return error.ChunkSize;
if (marks.len > MARKS or (marks.len > 0 and m.marks == null)) return error.Marks;
if (!Model.inVocab(tokens)) return error.TokenOutsideVocabulary; // both Macs refuse the same call: each preps half
const k: usize = tp.rank;
const a = m.state;
const at = segments.start(n, 2, k);
Expand Down
1 change: 1 addition & 0 deletions zig/src/families/flashnext/replay_prompt_segments.zig
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ pub fn bindMarks(p: *Prompt, m: *const Model, mk: [MARKS]i32, li: usize, rows_at
}

pub fn prep(p: *Prompt, m: *Model, gpa: std.mem.Allocator, tokens: []const u32, pos: usize, hist: [2]i64) !void {
if (!Model.inVocab(tokens)) return error.TokenOutsideVocabulary;
const b = &p.b;
const rows = tokens.len;
@memcpy(b.ids.b.slice(u32, rows), tokens);
Expand Down
1 change: 1 addition & 0 deletions zig/src/families/flashnext/think.zig
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ pub const Watch = struct {

pub fn init(t: Think) !Watch {
if (t.close.len > MAX_CLOSE) return error.ThinkCloseTooLong;
if (!fz.Model.inVocab(t.close)) return error.TokenOutsideVocabulary; // the close is forced into window ids on the GPU
return .{ .close = t.close, .end = t.end, .cut = t.budget -| 1, .armed = t.budget > 0 and t.close.len > 0 };
}

Expand Down
11 changes: 11 additions & 0 deletions zig/src/families/flashnext/tree.zig
Original file line number Diff line number Diff line change
Expand Up @@ -402,11 +402,22 @@ fn parse(a: std.mem.Allocator, text: []const u8) ![]const Entry {
l.* = try a.alloc(u32, k);
for (l.*) |*v| v.* = try std.fmt.parseInt(u32, it.next() orelse return error.BadFeed, 10);
}
for (lists[1]) |g| if (g >= replay.VOCAB) return error.BadFeed; // fz_tree_feed puts them in window ids, embedded unchecked
e.* = .{ .prompt = lists[0], .guesses = lists[1] };
}
return out;
}

test "token ids: a tree feed's guess past the vocabulary is refused when the feed is read" {
var arena: std.heap.ArenaAllocator = .init(std.testing.allocator);
defer arena.deinit();
const feed = "1\n2 5 6\n2 7 {d}\n";
const ok = try parse(arena.allocator(), std.fmt.comptimePrint(feed, .{replay.VOCAB - 1}));
try std.testing.expectEqualSlices(u32, &.{ 7, replay.VOCAB - 1 }, ok[0].guesses);
try std.testing.expectError(error.BadFeed, parse(arena.allocator(), std.fmt.comptimePrint(feed, .{replay.VOCAB})));
try std.testing.expectError(error.BadFeed, parse(arena.allocator(), "2\n1 5\n1 7\n1 5\n1 4294967295\n"));
}

test "a two-branch tree: the chain's rows, then the branch from the root" {
const t = table(2, 3);
try std.testing.expectEqualSlices(i32, &.{ -1, 0, 0 }, t[0..3]);
Expand Down
14 changes: 14 additions & 0 deletions zig/src/families/gemma4/assistant.zig
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,8 @@ pub const Drafter = struct {
fn holdFn(ptr: *anyopaque, holds: []const dr.Hold) anyerror!void {
const d = cast(ptr);
if (holds.len > max_items) return error.DraftTooManyStreams;
// gemma_assist_input reads the target's embedding at the pending id (clamped to its last row, not refused)
for (holds) |h| if (h.pending >= cfg.vocab) return error.InvalidGemmaToken;
const t0 = std.Io.Clock.awake.now(d.io);
var items: [max_items]Item = undefined;
var steps: u32 = 0;
Expand Down Expand Up @@ -547,6 +549,18 @@ test "a hold's key range and chunk counts follow the kept row's position" {
}
}

test "token ids: the Metal assistant refuses a pending id past the embedding before any stream's work" {
var d: Drafter = undefined; // the refusal reads nothing of it: no lane, cache, clock or device
var s: Stream = undefined;
const past: dr.Hold = .{ .stream = &s, .pending = cfg.vocab, .position = 2, .depth = 1 };
const last: dr.Hold = .{ .stream = &s, .pending = cfg.vocab - 1, .position = 2, .depth = 1 };
try std.testing.expectError(error.InvalidGemmaToken, d.drafter().hold(&.{past}));
try std.testing.expectError(error.InvalidGemmaToken, d.drafter().hold(&.{ last, past }));
var wide = past;
wide.pending = 0xffff_ffff;
try std.testing.expectError(error.InvalidGemmaToken, d.drafter().hold(&.{wide}));
}

test {
_ = @import("assistant_budget.zig").Cases(Drafter, Lane);
}
1 change: 1 addition & 0 deletions zig/src/families/gemma4/dflash.zig
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,7 @@ pub const Drafter = struct {
const it = items[at];
const l = d.lanes.get(it.stream) orelse return error.DraftStreamUnknown;
if (it.depth == 0 or it.depth >= block_rows or it.position == 0) return error.DraftDepth;
if (it.pending >= cfg.vocab) return error.InvalidGemmaToken; // gemma_embed reads row id unchecked
const anchor = it.position - 1;
if (l.end != anchor or anchor + block_rows > l.capacity + block_rows) return error.DraftContextGap;
if (rows + it.depth + 1 > hold_rows) break;
Expand Down
1 change: 1 addition & 0 deletions zig/src/families/gemma4/forward.zig
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ pub fn run(m: *Model, s: *state.Scratch, segments: []const Segment, ids: []const
rows += seg.rows;
}
if (rows == 0 or rows > state.prompt_rows or rows != ids.len) return error.BadWindow;
for (ids) |id| if (id >= cfg.vocab) return error.InvalidGemmaToken; // gemma_embed reads row id unchecked
var chunks: Chunks = undefined;
prepare(s, segments, ids, &chunks);
var at: usize = 0;
Expand Down
1 change: 1 addition & 0 deletions zig/src/families/gemma4/prompt.zig
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ pub fn run(m: *Model, s: *Scratch, c: *state.Cache, ids: []const u32, images: []
const rows = ids.len;
if (rows == 0 or rows > R) return error.BadChunk;
if (c.len + rows > c.capacity) return error.ContextFull;
for (ids) |id| if (id >= cfg.vocab) return error.InvalidGemmaToken; // gemma_embed reads row id unchecked
const p0 = c.len;
@memcpy(s.ids.slice(u32, rows), ids);
for (s.pos.slice(i32, rows), s.hi.slice(i32, rows), 0..) |*p, *h, i| {
Expand Down
1 change: 1 addition & 0 deletions zig/src/families/gemma4/weights.zig
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,7 @@ pub fn load(gpa: std.mem.Allocator, device: mtl.Device, c: *const ckpt.Checkpoin
@field(l, field) = try ref(c, try std.fmt.bufPrint(&name, "{s}{s}", .{ pre, t }));
}
w.head = try pack(gpa, device, r, &w.owned, geo, "language_model.model.", &.{"embed_tokens"}, ws.embed, false);
if (w.head.n != cfg.vocab or w.head.k != geo.hidden) return error.BadGemmaWeight; // gemma_embed reads it by id
w.embed_bits = ws.embed.bits;
w.embed_w = try ref(c, "language_model.model.embed_tokens.weight");
w.embed_s = try ref(c, "language_model.model.embed_tokens.scales");
Expand Down
5 changes: 4 additions & 1 deletion zig/src/families/glm/backend.zig
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,10 @@ pub const Backend = struct {
if (e.ep != null and s.sampling != null and s.sampling.?.temperature > 0) return error.SampledPeerUnsupported;
const prompt = s.prompt();
if (prompt.len == 0) return error.EmptyPrompt;
for (prompt) |t| if (t >= e.c.vocab) return error.TokenOutsideVocabulary; // before rank 1 hears of the prompt
for (s.think_close) |t| if (t >= e.c.vocab) return error.TokenOutsideVocabulary;
if (prompt.len + s.max_new + st.max_rows + 1 > pool.capacity(b.sl)) return error.ContextFull;
if (s.recall) |reader| try reader.checkVocabulary(e.c.vocab);
const reuse: ?*const snapshot.Snap = if (s.reuse.saved) |saved| @ptrCast(@alignCast(saved)) else null;
const i = b.sl.pick(reuse) orelse return error.NoFreeSlot;
try b.by.put(b.gpa, s, i);
Expand Down Expand Up @@ -362,7 +365,7 @@ pub const Backend = struct {
if (position != b.sl.length(i) + 1) return error.PositionMismatch;
const from = switch (feed) {
.handle => |h| @as(u32, @intCast(h)),
.value => |v| b.sl.ringPut(v),
.value => |v| if (v < b.sl.e.c.vocab) b.sl.ringPut(v) else return error.TokenOutsideVocabulary,
};
// The stream's sampling arms the queued round's keyed draw (a positive temperature); greedy streams stay plain.
return try b.sl.queueRound(i, from, s.sampling);
Expand Down
1 change: 1 addition & 0 deletions zig/src/families/glm/engine.zig
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,7 @@ pub const Engine = struct {
const P: u32 = @intCast(prompt.len);
if (e.ep != null and e.sampling != null and e.sampling.?.temperature > 0) return error.SampledPeerUnsupported; // the backend's refusal, before any state moves or the peer hears of it
if (prompt.len == 0) return error.EmptyPrompt;
for (prompt) |t| if (t >= c.vocab) return error.TokenOutsideVocabulary; // the embed reads w[id] unchecked
const d: u32 = @intCast(if (e.w.mtp == null) 0 else @min(depth, st.max_rows - 1));
if (prompt.len + max_tokens + d + 1 > e.s.cap) return error.ContextFull;
const pool = mtl.objc.Pool.push();
Expand Down
3 changes: 2 additions & 1 deletion zig/src/families/glm/mirror.zig
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,8 @@ pub fn follow(e: *Engine, sl: *Slots) !void {
const quiet: eng.Out = .{ .ctx = &dummy, .prefilled = eng.Quiet.prefilled, .tokens = eng.Quiet.tokens, .cancelled = eng.Quiet.cancelled };
while (try ep.ctl.waitCommand()) |cmd| switch (cmd) {
.request => |r| _ = e.generate(r.prompt, r.max_tokens, r.eos, r.depth, quiet) catch |err| switch (err) {
error.ContextFull, error.EmptyPrompt => continue, // refused before its first step, on rank 0 too
// refused before its first step, on rank 0 too
error.ContextFull, error.EmptyPrompt, error.TokenOutsideVocabulary => continue,
else => return err,
},
.lanes => |l| try apply(sl, l.kind, l.words, &wins, &drafts),
Expand Down
1 change: 1 addition & 0 deletions zig/src/families/glm/slots.zig
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,7 @@ pub const Slots = struct {
pub fn begin(sl: *Slots, i: u32, prompt: []const u32, drafts: bool) !void {
if (i >= sl.slots.len or sl.slots[i].used) return error.SlotOutOfStep;
if (prompt.len == 0 or prompt.len + st.max_rows + 1 > pool_mod.capacity(sl)) return error.ContextFull;
for (prompt) |t| if (t >= sl.e.c.vocab) return error.TokenOutsideVocabulary; // the embed reads w[id] unchecked
const least: u32 = @intCast(prompt.len + st.max_rows + 1);
if (sl.pool != null and sl.slots[i].region == null) try pool_mod.reserve(sl, i, least, null);
if (prompt.len + st.max_rows + 1 > sl.slots[i].s.cap) return error.ContextFull;
Expand Down
10 changes: 8 additions & 2 deletions zig/src/families/glm/vision_config.zig
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,19 @@ pub const Config = struct {
var c: Config = .{ .image_token = 0, .image_start = 0, .image_end = 0, .mean = .{ 0.48145466, 0.4578275, 0.40821073 }, .std = .{ 0.26862954, 0.26130258, 0.27577711 }, .min_tokens = 16, .max_tokens = 8000 };
if (vc.object.get("rms_norm_eps")) |v| c.eps = @floatCast(number(v) orelse return error.VisionConfig);
if (vc.object.get("swiglu_limit")) |v| c.limit = @floatCast(number(v) orelse return error.VisionConfig);
const text = doc.object.get("text_config") orelse doc; // where config.zig reads the vocabulary
const size = if (text == .object) text.object.get("vocab_size") else null;
const vocab = if (size != null and size.? == .integer) size.?.integer else return error.VisionConfig;
inline for (.{ .{ "image_token_id", "image_token" }, .{ "image_start_token_id", "image_start" }, .{ "image_end_token_id", "image_end" } }) |kv| {
const v = doc.object.get(kv[0]) orelse return error.VisionConfig;
if (v != .integer) return error.VisionConfig;
if (v != .integer or v.integer < 0 or v.integer >= vocab) return error.VisionConfig; // a prompt row's id
@field(c, kv[1]) = @intCast(v.integer);
}
if (doc.object.get("video_start_token_id")) |s| if (doc.object.get("video_token_id")) |t| if (doc.object.get("video_end_token_id")) |e| {
if (s == .integer and t == .integer and e == .integer) c.video = .{ @intCast(s.integer), @intCast(t.integer), @intCast(e.integer) };
if (s == .integer and t == .integer and e == .integer) {
for ([_]i64{ s.integer, t.integer, e.integer }) |id| if (id < 0 or id >= vocab) return error.VisionConfig;
c.video = .{ @intCast(s.integer), @intCast(t.integer), @intCast(e.integer) };
}
};
const pj = processor_json orelse return c;
const pdoc = try std.json.parseFromSliceLeaky(std.json.Value, arena, pj, .{});
Expand Down
2 changes: 2 additions & 0 deletions zig/src/families/glm_dsa/backend.zig
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,9 @@ pub const Backend = struct {
if (s.sampling) |p| if (p.temperature > 0) return error.GreedyOnly;
const prompt = s.prompt();
if (prompt.len == 0) return error.EmptyPrompt;
for (s.think_close) |t| if (t >= e.m.c.vocab) return error.TokenOutsideVocabulary;
if (prompt.len + s.max_new + eng.max_depth + R + 1 > e.context) return error.ContextFull;
if (s.recall) |reader| try reader.checkVocabulary(e.m.c.vocab);
const i = b.free() orelse return error.NoFreeSlot;
try b.by.put(b.gpa, s, i);
try fl.begin(e, i, prompt);
Expand Down
1 change: 1 addition & 0 deletions zig/src/families/glm_dsa/engine.zig
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ pub const Engine = struct {
/// A fresh stream in slot `i` with its prompt.
pub fn begin(e: *Engine, i: u32, prompt: []const u32) !void {
if (i >= e.slots.len or prompt.len == 0 or prompt.len + max_depth + R + 1 > e.context) return error.ContextFull;
for (prompt) |t| if (t >= e.m.c.vocab) return error.TokenOutsideVocabulary; // the embed reads w[id] unchecked
const s = &e.slots[i];
s.used = true;
s.len = 0;
Expand Down
Loading
Loading